Optimization: get author stats in one run (same as author of month).
[gitstats.git] / statgit
blobb0eaa5731f146f6136a35dfa625c31e298e00d32
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 # TODO
77 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
79 # activity
80 lines = getoutput('git-rev-list HEAD --pretty=format:%at |grep -v ^commit').split('\n')
81 for stamp in lines:
82 date = datetime.datetime.fromtimestamp(float(stamp))
84 # hour
85 hour = date.hour
86 if hour in self.activity_by_hour_of_day:
87 self.activity_by_hour_of_day[hour] += 1
88 else:
89 self.activity_by_hour_of_day[hour] = 1
91 # day
92 day = date.weekday()
93 if day in self.activity_by_day_of_week:
94 self.activity_by_day_of_week[day] += 1
95 else:
96 self.activity_by_day_of_week[day] = 1
98 # TODO author of the month
99 self.author_of_month = {} # month -> author -> commits
100 self.author_of_year = {} # year -> author -> commits
101 self.commits_by_month = {} # month -> commits
102 self.first_commit_stamp = 0
103 self.last_commit_stamp = 0
105 lines = getoutput('git-rev-list --pretty=format:"%at %an" HEAD |grep -v ^commit').split('\n')
106 for line in lines:
107 parts = line.split(' ')
108 stamp = int(parts[0])
109 author = ' '.join(parts[1:])
111 # First and last commit stamp
112 if self.last_commit_stamp == 0:
113 self.last_commit_stamp = stamp
114 self.first_commit_stamp = stamp
116 # author stats
117 if author not in self.authors:
118 self.authors[author] = {}
119 # TODO commits
120 if 'last_commit_stamp' not in self.authors[author]:
121 self.authors[author]['last_commit_stamp'] = stamp
122 self.authors[author]['first_commit_stamp'] = stamp
123 if 'commits' in self.authors[author]:
124 self.authors[author]['commits'] += 1
125 else:
126 self.authors[author]['commits'] = 1
128 # author of the month/year
129 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
130 if yymm in self.author_of_month:
131 if author in self.author_of_month[yymm]:
132 self.author_of_month[yymm][author] += 1
133 else:
134 self.author_of_month[yymm][author] = 1
135 else:
136 self.author_of_month[yymm] = {}
137 self.author_of_month[yymm][author] = 1
138 if yymm in self.commits_by_month:
139 self.commits_by_month[yymm] += 1
140 else:
141 self.commits_by_month[yymm] = 1
143 yy = datetime.datetime.fromtimestamp(stamp).year
144 if yy in self.author_of_year:
145 if author in self.author_of_year[yy]:
146 self.author_of_year[yy][author] += 1
147 else:
148 self.author_of_year[yy][author] = 1
149 else:
150 self.author_of_year[yy] = {}
151 self.author_of_year[yy][author] = 1
153 def getActivityByDayOfWeek(self):
154 return self.activity_by_day_of_week
156 def getActivityByHourOfDay(self):
157 return self.activity_by_hour_of_day
159 def getAuthorInfo(self, author):
160 a = self.authors[author]
162 commits = a['commits']
163 commits_frac = (100 * float(commits)) / self.getTotalCommits()
164 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp']).strftime('%Y-%m-%d')
165 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp']).strftime('%Y-%m-%d')
167 res = { 'commits': commits, 'commits_frac': commits_frac, 'date_first': date_first, 'date_last': date_last }
168 return res
170 def getAuthors(self):
171 lines = getoutput('git-rev-list --all --pretty=format:%an |grep -v ^commit |sort |uniq')
172 return lines.split('\n')
174 def getFirstCommitDate(self):
175 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
177 def getLastCommitDate(self):
178 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
180 def getTags(self):
181 lines = getoutput('git-show-ref --tags |cut -d/ -f3')
182 return lines.split('\n')
184 def getTagDate(self, tag):
185 return self.revToDate('tags/' + tag)
187 def getTotalAuthors(self):
188 return self.total_authors
190 def getTotalCommits(self):
191 return self.total_commits
193 def getTotalFiles(self):
194 return self.total_files
196 def getTotalLOC(self):
197 return self.total_lines
199 def revToDate(self, rev):
200 stamp = int(getoutput('git-log --pretty=format:%%at "%s" -n 1' % rev))
201 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
203 class ReportCreator:
204 def __init__(self):
205 pass
207 def create(self, data, path):
208 self.data = data
209 self.path = path
211 class HTMLReportCreator(ReportCreator):
212 def create(self, data, path):
213 ReportCreator.create(self, data, path)
215 f = open(path + "/index.html", 'w')
216 format = '%Y-%m-%d %H:%m:%S'
217 self.printHeader(f)
219 f.write('<h1>StatGit</h1>')
221 f.write('<dl>');
222 f.write('<dt>Generated</dt><dd>%s</dd>' % datetime.datetime.now().strftime(format));
223 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
224 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
225 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
226 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
227 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
228 f.write('</dl>');
230 f.write("""<ul>
231 <li><a href="activity.html">Activity</a></li>
232 <li><a href="authors.html">Authors</a></li>
233 <li><a href="files.html">Files</a></li>
234 <li><a href="lines.html">Lines</a></li>
235 </ul>
236 """)
238 f.write('<h2>Tags</h2>')
239 f.write('<table>')
240 f.write('<tr><th>Name</th><th>Date</th><th>Developers</th></tr>')
241 for tag in data.getTags():
242 f.write('<tr><td>%s</td><td></td></tr>' % tag)
243 f.write('</table>')
245 f.write('</body>\n</html>');
246 f.close()
248 # activity.html
249 f = open(path + '/activity.html', 'w')
250 self.printHeader(f)
251 f.write('<h1>Activity</h1>')
253 f.write('<h2>Last 30 days</h2>')
255 f.write('<h2>Last 12 months</h2>')
257 f.write('\n<h2>Hour of Day</h2>\n\n')
258 hour_of_day = data.getActivityByHourOfDay()
259 f.write('<table><tr><th>Hour</th>')
260 for i in range(1, 25):
261 f.write('<th>%d</th>' % i)
262 f.write('</tr>\n<tr><th>Commits</th>')
263 for i in range(0, 24):
264 if i in hour_of_day:
265 f.write('<td>%d</td>' % hour_of_day[i])
266 else:
267 f.write('<td>0</td>')
268 f.write('</tr>\n<tr><th>%</th>')
269 totalcommits = data.getTotalCommits()
270 for i in range(0, 24):
271 if i in hour_of_day:
272 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
273 else:
274 f.write('<td>0.00</td>')
275 f.write('</tr></table>')
277 ### Day of Week
278 # TODO show also by hour of weekday?
279 f.write('\n<h2>Day of Week</h2>\n\n')
280 day_of_week = data.getActivityByDayOfWeek()
281 f.write('<table>')
282 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
283 for d in range(0, 7):
284 f.write('<tr>')
285 f.write('<th>%d</th>' % (d + 1))
286 if d in day_of_week:
287 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
288 else:
289 f.write('<td>0</td>')
290 f.write('</tr>')
291 f.write('</table>')
293 f.close()
295 # authors.html
296 f = open(path + '/authors.html', 'w')
297 self.printHeader(f)
299 f.write('<h1>Authors</h1>')
301 f.write('\n<h2>List of authors</h2>\n\n')
303 f.write('<table class="authors">')
304 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th></tr>')
305 for author in data.getAuthors():
306 info = data.getAuthorInfo(author)
307 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']))
308 f.write('</table>')
310 f.write('\n<h2>Author of Month</h2>\n\n')
311 f.write('<table>')
312 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th></tr>')
313 for yymm in reversed(sorted(data.author_of_month.keys())):
314 authordict = data.author_of_month[yymm]
315 authors = getkeyssortedbyvalues(authordict)
316 authors.reverse()
317 commits = data.author_of_month[yymm][authors[0]]
318 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]))
320 f.write('</table>')
322 f.write('\n<h2>Author of Year</h2>\n\n')
323 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th></tr>')
324 for yy in reversed(sorted(data.author_of_year.keys())):
325 authordict = data.author_of_year[yy]
326 authors = getkeyssortedbyvalues(authordict)
327 authors.reverse()
328 commits = data.author_of_year[yy][authors[0]]
329 f.write('<tr><td>%s</td><td>%s</td><td>%d</td></tr>' % (yy, authors[0], commits))
330 f.write('</table>')
332 f.write('</body></html>')
333 f.close()
334 pass
336 def printHeader(self, f):
337 f.write("""<html>
338 <head>
339 <title>StatGit</title>
340 <link rel="stylesheet" href="statgit.css" type="text/css" />
341 </head>
342 <body>
343 """)
346 usage = """
347 Usage: statgit [options] <gitpath> <outputpath>
349 Options:
350 -o html
353 if len(sys.argv) < 3:
354 print usage
355 sys.exit(0)
357 gitpath = sys.argv[1]
358 outputpath = sys.argv[2]
360 print 'Git path: %s' % gitpath
361 print 'Output path: %s' % outputpath
363 os.chdir(gitpath)
365 print 'Collecting data...'
366 data = GitDataCollector()
367 data.collect(gitpath)
369 print 'Generating report...'
370 report = HTMLReportCreator()
371 report.create(data, outputpath)