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