123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. #!/usr/bin/python
  2. # Copyright (c) 2007 Heikki Hokkanen <hoxu@users.sf.net>
  3. # GPLv2
  4. import commands
  5. import datetime
  6. import os
  7. import re
  8. import sys
  9. def getoutput(cmd):
  10. print '>> %s' % cmd
  11. output = commands.getoutput(cmd)
  12. return output
  13. def getkeyssortedbyvalues(dict):
  14. return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
  15. class DataCollector:
  16. def __init__(self):
  17. pass
  18. ##
  19. # This should be the main function to extract data from the repository.
  20. def collect(self, dir):
  21. self.dir = dir
  22. ##
  23. # : get a dictionary of author
  24. def getAuthorInfo(self, author):
  25. return None
  26. def getActivityByDayOfWeek(self):
  27. return {}
  28. def getActivityByHourOfDay(self):
  29. return {}
  30. ##
  31. # Get a list of authors
  32. def getAuthors(self):
  33. return []
  34. def getFirstCommitDate(self):
  35. return datetime.datetime.now()
  36. def getLastCommitDate(self):
  37. return datetime.datetime.now()
  38. def getTags(self):
  39. return []
  40. def getTotalAuthors(self):
  41. return -1
  42. def getTotalCommits(self):
  43. return -1
  44. def getTotalFiles(self):
  45. return -1
  46. def getTotalLOC(self):
  47. return -1
  48. class GitDataCollector(DataCollector):
  49. def collect(self, dir):
  50. DataCollector.collect(self, dir)
  51. self.total_authors = int(getoutput('git-log |git-shortlog -s |wc -l'))
  52. self.total_commits = int(getoutput('git-rev-list HEAD |wc -l'))
  53. self.total_files = int(getoutput('git-ls-files |wc -l'))
  54. self.total_lines = int(getoutput('git-ls-files |xargs cat |wc -l'))
  55. self.activity_by_hour_of_day = {} # hour -> commits
  56. self.activity_by_day_of_week = {} # day -> commits
  57. self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
  58. # author of the month
  59. self.author_of_month = {} # month -> author -> commits
  60. self.author_of_year = {} # year -> author -> commits
  61. self.commits_by_month = {} # month -> commits
  62. self.first_commit_stamp = 0
  63. self.last_commit_stamp = 0
  64. # TODO also collect statistics for "last 30 days"/"last 12 months"
  65. lines = getoutput('git-rev-list --pretty=format:"%at %an" HEAD |grep -v ^commit').split('\n')
  66. for line in lines:
  67. # linux-2.6 says "<unknown>" for one line O_o
  68. parts = line.split(' ')
  69. author = ''
  70. try:
  71. stamp = int(parts[0])
  72. except ValueError:
  73. stamp = 0
  74. if len(parts) > 1:
  75. author = ' '.join(parts[1:])
  76. date = datetime.datetime.fromtimestamp(float(stamp))
  77. # First and last commit stamp
  78. if self.last_commit_stamp == 0:
  79. self.last_commit_stamp = stamp
  80. self.first_commit_stamp = stamp
  81. # activity
  82. # hour
  83. hour = date.hour
  84. if hour in self.activity_by_hour_of_day:
  85. self.activity_by_hour_of_day[hour] += 1
  86. else:
  87. self.activity_by_hour_of_day[hour] = 1
  88. # day
  89. day = date.weekday()
  90. if day in self.activity_by_day_of_week:
  91. self.activity_by_day_of_week[day] += 1
  92. else:
  93. self.activity_by_day_of_week[day] = 1
  94. # author stats
  95. if author not in self.authors:
  96. self.authors[author] = {}
  97. # TODO commits
  98. if 'last_commit_stamp' not in self.authors[author]:
  99. self.authors[author]['last_commit_stamp'] = stamp
  100. self.authors[author]['first_commit_stamp'] = stamp
  101. if 'commits' in self.authors[author]:
  102. self.authors[author]['commits'] += 1
  103. else:
  104. self.authors[author]['commits'] = 1
  105. # author of the month/year
  106. yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
  107. if yymm in self.author_of_month:
  108. if author in self.author_of_month[yymm]:
  109. self.author_of_month[yymm][author] += 1
  110. else:
  111. self.author_of_month[yymm][author] = 1
  112. else:
  113. self.author_of_month[yymm] = {}
  114. self.author_of_month[yymm][author] = 1
  115. if yymm in self.commits_by_month:
  116. self.commits_by_month[yymm] += 1
  117. else:
  118. self.commits_by_month[yymm] = 1
  119. yy = datetime.datetime.fromtimestamp(stamp).year
  120. if yy in self.author_of_year:
  121. if author in self.author_of_year[yy]:
  122. self.author_of_year[yy][author] += 1
  123. else:
  124. self.author_of_year[yy][author] = 1
  125. else:
  126. self.author_of_year[yy] = {}
  127. self.author_of_year[yy][author] = 1
  128. def getActivityByDayOfWeek(self):
  129. return self.activity_by_day_of_week
  130. def getActivityByHourOfDay(self):
  131. return self.activity_by_hour_of_day
  132. def getAuthorInfo(self, author):
  133. a = self.authors[author]
  134. commits = a['commits']
  135. commits_frac = (100 * float(commits)) / self.getTotalCommits()
  136. date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp']).strftime('%Y-%m-%d')
  137. date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp']).strftime('%Y-%m-%d')
  138. res = { 'commits': commits, 'commits_frac': commits_frac, 'date_first': date_first, 'date_last': date_last }
  139. return res
  140. def getAuthors(self):
  141. lines = getoutput('git-rev-list --all --pretty=format:%an |grep -v ^commit |sort |uniq')
  142. return lines.split('\n')
  143. def getFirstCommitDate(self):
  144. return datetime.datetime.fromtimestamp(self.first_commit_stamp)
  145. def getLastCommitDate(self):
  146. return datetime.datetime.fromtimestamp(self.last_commit_stamp)
  147. def getTags(self):
  148. lines = getoutput('git-show-ref --tags |cut -d/ -f3')
  149. return lines.split('\n')
  150. def getTagDate(self, tag):
  151. return self.revToDate('tags/' + tag)
  152. def getTotalAuthors(self):
  153. return self.total_authors
  154. def getTotalCommits(self):
  155. return self.total_commits
  156. def getTotalFiles(self):
  157. return self.total_files
  158. def getTotalLOC(self):
  159. return self.total_lines
  160. def revToDate(self, rev):
  161. stamp = int(getoutput('git-log --pretty=format:%%at "%s" -n 1' % rev))
  162. return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
  163. class ReportCreator:
  164. def __init__(self):
  165. pass
  166. def create(self, data, path):
  167. self.data = data
  168. self.path = path
  169. class HTMLReportCreator(ReportCreator):
  170. def create(self, data, path):
  171. ReportCreator.create(self, data, path)
  172. f = open(path + "/index.html", 'w')
  173. format = '%Y-%m-%d %H:%m:%S'
  174. self.printHeader(f)
  175. f.write('<h1>StatGit</h1>')
  176. self.printNav(f)
  177. f.write('<dl>');
  178. f.write('<dt>Generated</dt><dd>%s</dd>' % datetime.datetime.now().strftime(format));
  179. f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
  180. f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
  181. f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
  182. f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
  183. f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
  184. f.write('</dl>');
  185. #f.write('<h2>Tags</h2>')
  186. #f.write('<table>')
  187. #f.write('<tr><th>Name</th><th>Date</th><th>Developers</th></tr>')
  188. #for tag in data.getTags():
  189. # f.write('<tr><td>%s</td><td></td></tr>' % tag)
  190. #f.write('</table>')
  191. f.write('</body>\n</html>');
  192. f.close()
  193. # activity.html
  194. f = open(path + '/activity.html', 'w')
  195. self.printHeader(f)
  196. f.write('<h1>Activity</h1>')
  197. self.printNav(f)
  198. f.write('<h2>Last 30 days</h2>')
  199. f.write('<h2>Last 12 months</h2>')
  200. f.write('\n<h2>Hour of Day</h2>\n\n')
  201. hour_of_day = data.getActivityByHourOfDay()
  202. f.write('<table><tr><th>Hour</th>')
  203. for i in range(1, 25):
  204. f.write('<th>%d</th>' % i)
  205. f.write('</tr>\n<tr><th>Commits</th>')
  206. for i in range(0, 24):
  207. if i in hour_of_day:
  208. f.write('<td>%d</td>' % hour_of_day[i])
  209. else:
  210. f.write('<td>0</td>')
  211. f.write('</tr>\n<tr><th>%</th>')
  212. totalcommits = data.getTotalCommits()
  213. for i in range(0, 24):
  214. if i in hour_of_day:
  215. f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
  216. else:
  217. f.write('<td>0.00</td>')
  218. f.write('</tr></table>')
  219. ### Day of Week
  220. # TODO show also by hour of weekday?
  221. f.write('\n<h2>Day of Week</h2>\n\n')
  222. day_of_week = data.getActivityByDayOfWeek()
  223. f.write('<table>')
  224. f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
  225. for d in range(0, 7):
  226. f.write('<tr>')
  227. f.write('<th>%d</th>' % (d + 1))
  228. if d in day_of_week:
  229. f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
  230. else:
  231. f.write('<td>0</td>')
  232. f.write('</tr>')
  233. f.write('</table>')
  234. f.close()
  235. # authors.html
  236. f = open(path + '/authors.html', 'w')
  237. self.printHeader(f)
  238. f.write('<h1>Authors</h1>')
  239. self.printNav(f)
  240. f.write('\n<h2>List of authors</h2>\n\n')
  241. f.write('<table class="authors">')
  242. f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th></tr>')
  243. for author in data.getAuthors():
  244. info = data.getAuthorInfo(author)
  245. f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%s</td><td>%s</td></tr>' % (author, info['commits'], info['commits_frac'], info['date_first'], info['date_last']))
  246. f.write('</table>')
  247. f.write('\n<h2>Author of Month</h2>\n\n')
  248. f.write('<table>')
  249. f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th></tr>')
  250. for yymm in reversed(sorted(data.author_of_month.keys())):
  251. authordict = data.author_of_month[yymm]
  252. authors = getkeyssortedbyvalues(authordict)
  253. authors.reverse()
  254. commits = data.author_of_month[yymm][authors[0]]
  255. f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td></tr>' % (yymm, authors[0], commits, (100 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm]))
  256. f.write('</table>')
  257. f.write('\n<h2>Author of Year</h2>\n\n')
  258. f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th></tr>')
  259. for yy in reversed(sorted(data.author_of_year.keys())):
  260. authordict = data.author_of_year[yy]
  261. authors = getkeyssortedbyvalues(authordict)
  262. authors.reverse()
  263. commits = data.author_of_year[yy][authors[0]]
  264. f.write('<tr><td>%s</td><td>%s</td><td>%d</td></tr>' % (yy, authors[0], commits))
  265. f.write('</table>')
  266. f.write('</body></html>')
  267. f.close()
  268. pass
  269. def printHeader(self, f):
  270. f.write("""<html>
  271. <head>
  272. <title>StatGit</title>
  273. <link rel="stylesheet" href="statgit.css" type="text/css" />
  274. </head>
  275. <body>
  276. """)
  277. def printNav(self, f):
  278. f.write("""
  279. <div class="nav">
  280. <li><a href="index.html">General</a></li>
  281. <li><a href="activity.html">Activity</a></li>
  282. <li><a href="authors.html">Authors</a></li>
  283. <li><a href="files.html">Files</a></li>
  284. <li><a href="lines.html">Lines</a></li>
  285. </ul>
  286. </div>
  287. """)
  288. usage = """
  289. Usage: statgit [options] <gitpath> <outputpath>
  290. Options:
  291. -o html
  292. """
  293. if len(sys.argv) < 3:
  294. print usage
  295. sys.exit(0)
  296. gitpath = sys.argv[1]
  297. outputpath = sys.argv[2]
  298. print 'Git path: %s' % gitpath
  299. print 'Output path: %s' % outputpath
  300. os.chdir(gitpath)
  301. print 'Collecting data...'
  302. data = GitDataCollector()
  303. data.collect(gitpath)
  304. print 'Generating report...'
  305. report = HTMLReportCreator()
  306. report.create(data, outputpath)