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