Tags: show commits & authors for each tag.
[gitstats.git] / gitstats
blob70fe9104b88a1746cbedcf3a6fab6da29e582523
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2009 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
3 # GPLv2 / GPLv3
4 import datetime
5 import glob
6 import os
7 import pickle
8 import re
9 import shutil
10 import subprocess
11 import sys
12 import time
13 import zlib
15 GNUPLOT_COMMON = 'set terminal png transparent\nset size 0.5,0.5\n'
16 MAX_EXT_LENGTH = 10 # maximum file extension length
18 exectime_internal = 0.0
19 exectime_external = 0.0
20 time_start = time.time()
22 # By default, gnuplot is searched from path, but can be overridden with the
23 # environment variable "GNUPLOT"
24 gnuplot_cmd = 'gnuplot'
25 if 'GNUPLOT' in os.environ:
26 gnuplot_cmd = os.environ['GNUPLOT']
28 def getpipeoutput(cmds, quiet = False):
29 global exectime_external
30 start = time.time()
31 if not quiet:
32 print '>> ' + ' | '.join(cmds),
33 sys.stdout.flush()
34 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
35 p = p0
36 for x in cmds[1:]:
37 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
38 p0 = p
39 output = p.communicate()[0]
40 end = time.time()
41 if not quiet:
42 print '\r[%.5f] >> %s' % (end - start, ' | '.join(cmds))
43 exectime_external += (end - start)
44 return output.rstrip('\n')
46 def getkeyssortedbyvalues(dict):
47 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
49 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
50 def getkeyssortedbyvaluekey(d, key):
51 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
53 VERSION = 0
54 def getversion():
55 global VERSION
56 if VERSION == 0:
57 VERSION = getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
58 return VERSION
60 class DataCollector:
61 """Manages data collection from a revision control repository."""
62 def __init__(self):
63 self.stamp_created = time.time()
64 self.cache = {}
67 # This should be the main function to extract data from the repository.
68 def collect(self, dir):
69 self.dir = dir
70 self.projectname = os.path.basename(os.path.abspath(dir))
73 # Load cacheable data
74 def loadCache(self, cachefile):
75 if not os.path.exists(cachefile):
76 return
77 print 'Loading cache...'
78 f = open(cachefile)
79 try:
80 self.cache = pickle.loads(zlib.decompress(f.read()))
81 except:
82 # temporary hack to upgrade non-compressed caches
83 f.seek(0)
84 self.cache = pickle.load(f)
85 f.close()
88 # Produce any additional statistics from the extracted data.
89 def refine(self):
90 pass
93 # : get a dictionary of author
94 def getAuthorInfo(self, author):
95 return None
97 def getActivityByDayOfWeek(self):
98 return {}
100 def getActivityByHourOfDay(self):
101 return {}
104 # Get a list of authors
105 def getAuthors(self):
106 return []
108 def getFirstCommitDate(self):
109 return datetime.datetime.now()
111 def getLastCommitDate(self):
112 return datetime.datetime.now()
114 def getStampCreated(self):
115 return self.stamp_created
117 def getTags(self):
118 return []
120 def getTotalAuthors(self):
121 return -1
123 def getTotalCommits(self):
124 return -1
126 def getTotalFiles(self):
127 return -1
129 def getTotalLOC(self):
130 return -1
133 # Save cacheable data
134 def saveCache(self, filename):
135 print 'Saving cache...'
136 f = open(cachefile, 'w')
137 #pickle.dump(self.cache, f)
138 data = zlib.compress(pickle.dumps(self.cache))
139 f.write(data)
140 f.close()
142 class GitDataCollector(DataCollector):
143 def collect(self, dir):
144 DataCollector.collect(self, dir)
146 try:
147 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
148 except:
149 self.total_authors = 0
150 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
152 self.activity_by_hour_of_day = {} # hour -> commits
153 self.activity_by_day_of_week = {} # day -> commits
154 self.activity_by_month_of_year = {} # month [1-12] -> commits
155 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
156 self.activity_by_hour_of_day_busiest = 0
157 self.activity_by_hour_of_week_busiest = 0
159 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
161 # author of the month
162 self.author_of_month = {} # month -> author -> commits
163 self.author_of_year = {} # year -> author -> commits
164 self.commits_by_month = {} # month -> commits
165 self.commits_by_year = {} # year -> commits
166 self.first_commit_stamp = 0
167 self.last_commit_stamp = 0
169 # tags
170 self.tags = {}
171 lines = getpipeoutput(['git show-ref --tags']).split('\n')
172 for line in lines:
173 if len(line) == 0:
174 continue
175 (hash, tag) = line.split(' ')
177 tag = tag.replace('refs/tags/', '')
178 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
179 if len(output) > 0:
180 parts = output.split(' ')
181 stamp = 0
182 try:
183 stamp = int(parts[0])
184 except ValueError:
185 stamp = 0
186 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
188 # collect info on tags, starting from latest
189 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
190 prev = None
191 for tag in reversed(tags_sorted_by_date_desc):
192 #print prev, tag
193 cmd = 'git shortlog -s "%s"' % tag
194 if prev != None:
195 cmd += ' "^%s"' % prev
196 output = getpipeoutput([cmd])
197 prev = tag
198 for line in output.split('\n'):
199 parts = re.split('\s+', line, 2)
200 #print parts
201 commits = int(parts[1])
202 author = parts[2]
203 self.tags[tag]['commits'] += commits
204 self.tags[tag]['authors'][author] = commits
205 #print self.tags
207 # Collect revision statistics
208 # Outputs "<stamp> <author>"
209 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
210 for line in lines:
211 # linux-2.6 says "<unknown>" for one line O_o
212 parts = line.split(' ')
213 author = ''
214 try:
215 stamp = int(parts[0])
216 except ValueError:
217 stamp = 0
218 if len(parts) > 1:
219 author = ' '.join(parts[1:])
220 date = datetime.datetime.fromtimestamp(float(stamp))
222 # First and last commit stamp
223 if self.last_commit_stamp == 0:
224 self.last_commit_stamp = stamp
225 self.first_commit_stamp = stamp
227 # activity
228 # hour
229 hour = date.hour
230 if hour in self.activity_by_hour_of_day:
231 self.activity_by_hour_of_day[hour] += 1
232 else:
233 self.activity_by_hour_of_day[hour] = 1
234 # most active hour?
235 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
236 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
238 # day of week
239 day = date.weekday()
240 if day in self.activity_by_day_of_week:
241 self.activity_by_day_of_week[day] += 1
242 else:
243 self.activity_by_day_of_week[day] = 1
245 # hour of week
246 if day not in self.activity_by_hour_of_week:
247 self.activity_by_hour_of_week[day] = {}
248 if hour not in self.activity_by_hour_of_week[day]:
249 self.activity_by_hour_of_week[day][hour] = 1
250 else:
251 self.activity_by_hour_of_week[day][hour] += 1
252 # most active hour?
253 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
254 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
256 # month of year
257 month = date.month
258 if month in self.activity_by_month_of_year:
259 self.activity_by_month_of_year[month] += 1
260 else:
261 self.activity_by_month_of_year[month] = 1
263 # author stats
264 if author not in self.authors:
265 self.authors[author] = {}
266 # commits
267 if 'last_commit_stamp' not in self.authors[author]:
268 self.authors[author]['last_commit_stamp'] = stamp
269 self.authors[author]['first_commit_stamp'] = stamp
270 if 'commits' in self.authors[author]:
271 self.authors[author]['commits'] += 1
272 else:
273 self.authors[author]['commits'] = 1
275 # author of the month/year
276 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
277 if yymm in self.author_of_month:
278 if author in self.author_of_month[yymm]:
279 self.author_of_month[yymm][author] += 1
280 else:
281 self.author_of_month[yymm][author] = 1
282 else:
283 self.author_of_month[yymm] = {}
284 self.author_of_month[yymm][author] = 1
285 if yymm in self.commits_by_month:
286 self.commits_by_month[yymm] += 1
287 else:
288 self.commits_by_month[yymm] = 1
290 yy = datetime.datetime.fromtimestamp(stamp).year
291 if yy in self.author_of_year:
292 if author in self.author_of_year[yy]:
293 self.author_of_year[yy][author] += 1
294 else:
295 self.author_of_year[yy][author] = 1
296 else:
297 self.author_of_year[yy] = {}
298 self.author_of_year[yy][author] = 1
299 if yy in self.commits_by_year:
300 self.commits_by_year[yy] += 1
301 else:
302 self.commits_by_year[yy] = 1
304 # TODO Optimize this, it's the worst bottleneck
305 # outputs "<stamp> <files>" for each revision
306 self.files_by_stamp = {} # stamp -> files
307 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
308 lines = []
309 for revline in revlines:
310 time, rev = revline.split(' ')
311 #linecount = int(getpipeoutput(['git-ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
312 linecount = self.getFilesInCommit(rev)
313 lines.append('%d %d' % (int(time), linecount))
315 self.total_commits = len(lines)
316 for line in lines:
317 parts = line.split(' ')
318 if len(parts) != 2:
319 continue
320 (stamp, files) = parts[0:2]
321 try:
322 self.files_by_stamp[int(stamp)] = int(files)
323 except ValueError:
324 print 'Warning: failed to parse line "%s"' % line
326 # extensions
327 self.extensions = {} # extension -> files, lines
328 lines = getpipeoutput(['git ls-files']).split('\n')
329 self.total_files = len(lines)
330 for line in lines:
331 base = os.path.basename(line)
332 # Ignore extensionless (including .hidden files)
333 if base.find('.') == -1 or base.rfind('.') == 0:
334 ext = ''
335 else:
336 ext = base[(base.rfind('.') + 1):]
337 if len(ext) > MAX_EXT_LENGTH:
338 ext = ''
340 if ext not in self.extensions:
341 self.extensions[ext] = {'files': 0, 'lines': 0}
343 self.extensions[ext]['files'] += 1
344 try:
345 # Escaping could probably be improved here
346 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
347 except:
348 print 'Warning: Could not count lines for file "%s"' % line
350 # line statistics
351 # outputs:
352 # N files changed, N insertions (+), N deletions(-)
353 # <stamp> <author>
354 self.changes_by_date = {} # stamp -> { files, ins, del }
355 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
356 lines.reverse()
357 files = 0; inserted = 0; deleted = 0; total_lines = 0
358 for line in lines:
359 if len(line) == 0:
360 continue
362 # <stamp> <author>
363 if line.find('files changed,') == -1:
364 pos = line.find(' ')
365 if pos != -1:
366 try:
367 (stamp, author) = (int(line[:pos]), line[pos+1:])
368 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
369 except ValueError:
370 print 'Warning: unexpected line "%s"' % line
371 else:
372 print 'Warning: unexpected line "%s"' % line
373 else:
374 numbers = re.findall('\d+', line)
375 if len(numbers) == 3:
376 (files, inserted, deleted) = map(lambda el : int(el), numbers)
377 total_lines += inserted
378 total_lines -= deleted
379 else:
380 print 'Warning: failed to handle line "%s"' % line
381 (files, inserted, deleted) = (0, 0, 0)
382 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
383 self.total_lines = total_lines
385 def refine(self):
386 # authors
387 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
388 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
389 authors_by_commits.reverse() # most first
390 for i, name in enumerate(authors_by_commits):
391 self.authors[name]['place_by_commits'] = i + 1
393 for name in self.authors.keys():
394 a = self.authors[name]
395 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
396 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
397 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
398 delta = date_last - date_first
399 a['date_first'] = date_first.strftime('%Y-%m-%d')
400 a['date_last'] = date_last.strftime('%Y-%m-%d')
401 a['timedelta'] = delta
403 def getActivityByDayOfWeek(self):
404 return self.activity_by_day_of_week
406 def getActivityByHourOfDay(self):
407 return self.activity_by_hour_of_day
409 def getAuthorInfo(self, author):
410 return self.authors[author]
412 def getAuthors(self):
413 return self.authors.keys()
415 def getCommitDeltaDays(self):
416 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
418 def getFilesInCommit(self, rev):
419 try:
420 res = self.cache['files_in_tree'][rev]
421 except:
422 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
423 if 'files_in_tree' not in self.cache:
424 self.cache['files_in_tree'] = {}
425 self.cache['files_in_tree'][rev] = res
427 return res
429 def getFirstCommitDate(self):
430 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
432 def getLastCommitDate(self):
433 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
435 def getTags(self):
436 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
437 return lines.split('\n')
439 def getTagDate(self, tag):
440 return self.revToDate('tags/' + tag)
442 def getTotalAuthors(self):
443 return self.total_authors
445 def getTotalCommits(self):
446 return self.total_commits
448 def getTotalFiles(self):
449 return self.total_files
451 def getTotalLOC(self):
452 return self.total_lines
454 def revToDate(self, rev):
455 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
456 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
458 class ReportCreator:
459 """Creates the actual report based on given data."""
460 def __init__(self):
461 pass
463 def create(self, data, path):
464 self.data = data
465 self.path = path
467 def html_linkify(text):
468 return text.lower().replace(' ', '_')
470 def html_header(level, text):
471 name = html_linkify(text)
472 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
474 class HTMLReportCreator(ReportCreator):
475 def create(self, data, path):
476 ReportCreator.create(self, data, path)
477 self.title = data.projectname
479 # copy static files if they do not exist
480 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
481 basedir = os.path.dirname(os.path.abspath(__file__))
482 shutil.copyfile(basedir + '/' + file, path + '/' + file)
484 f = open(path + "/index.html", 'w')
485 format = '%Y-%m-%d %H:%M:%S'
486 self.printHeader(f)
488 f.write('<h1>GitStats - %s</h1>' % data.projectname)
490 self.printNav(f)
492 f.write('<dl>')
493 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
494 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
495 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
496 f.write('<dt>Report Period</dt><dd>%s to %s (%d days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays()))
497 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
498 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
499 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
500 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
501 f.write('</dl>')
503 f.write('</body>\n</html>')
504 f.close()
507 # Activity
508 f = open(path + '/activity.html', 'w')
509 self.printHeader(f)
510 f.write('<h1>Activity</h1>')
511 self.printNav(f)
513 #f.write('<h2>Last 30 days</h2>')
515 #f.write('<h2>Last 12 months</h2>')
517 # Hour of Day
518 f.write(html_header(2, 'Hour of Day'))
519 hour_of_day = data.getActivityByHourOfDay()
520 f.write('<table><tr><th>Hour</th>')
521 for i in range(0, 24):
522 f.write('<th>%d</th>' % i)
523 f.write('</tr>\n<tr><th>Commits</th>')
524 fp = open(path + '/hour_of_day.dat', 'w')
525 for i in range(0, 24):
526 if i in hour_of_day:
527 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
528 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
529 fp.write('%d %d\n' % (i, hour_of_day[i]))
530 else:
531 f.write('<td>0</td>')
532 fp.write('%d 0\n' % i)
533 fp.close()
534 f.write('</tr>\n<tr><th>%</th>')
535 totalcommits = data.getTotalCommits()
536 for i in range(0, 24):
537 if i in hour_of_day:
538 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
539 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
540 else:
541 f.write('<td>0.00</td>')
542 f.write('</tr></table>')
543 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
544 fg = open(path + '/hour_of_day.dat', 'w')
545 for i in range(0, 24):
546 if i in hour_of_day:
547 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
548 else:
549 fg.write('%d 0\n' % (i + 1))
550 fg.close()
552 # Day of Week
553 f.write(html_header(2, 'Day of Week'))
554 day_of_week = data.getActivityByDayOfWeek()
555 f.write('<div class="vtable"><table>')
556 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
557 fp = open(path + '/day_of_week.dat', 'w')
558 for d in range(0, 7):
559 commits = 0
560 if d in day_of_week:
561 commits = day_of_week[d]
562 fp.write('%d %d\n' % (d + 1, commits))
563 f.write('<tr>')
564 f.write('<th>%d</th>' % (d + 1))
565 if d in day_of_week:
566 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
567 else:
568 f.write('<td>0</td>')
569 f.write('</tr>')
570 f.write('</table></div>')
571 f.write('<img src="day_of_week.png" alt="Day of Week" />')
572 fp.close()
574 # Hour of Week
575 f.write(html_header(2, 'Hour of Week'))
576 f.write('<table>')
578 f.write('<tr><th>Weekday</th>')
579 for hour in range(0, 24):
580 f.write('<th>%d</th>' % (hour))
581 f.write('</tr>')
583 for weekday in range(0, 7):
584 f.write('<tr><th>%d</th>' % (weekday + 1))
585 for hour in range(0, 24):
586 try:
587 commits = data.activity_by_hour_of_week[weekday][hour]
588 except KeyError:
589 commits = 0
590 if commits != 0:
591 f.write('<td')
592 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
593 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
594 f.write('>%d</td>' % commits)
595 else:
596 f.write('<td></td>')
597 f.write('</tr>')
599 f.write('</table>')
601 # Month of Year
602 f.write(html_header(2, 'Month of Year'))
603 f.write('<div class="vtable"><table>')
604 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
605 fp = open (path + '/month_of_year.dat', 'w')
606 for mm in range(1, 13):
607 commits = 0
608 if mm in data.activity_by_month_of_year:
609 commits = data.activity_by_month_of_year[mm]
610 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
611 fp.write('%d %d\n' % (mm, commits))
612 fp.close()
613 f.write('</table></div>')
614 f.write('<img src="month_of_year.png" alt="Month of Year" />')
616 # Commits by year/month
617 f.write(html_header(2, 'Commits by year/month'))
618 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
619 for yymm in reversed(sorted(data.commits_by_month.keys())):
620 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
621 f.write('</table></div>')
622 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
623 fg = open(path + '/commits_by_year_month.dat', 'w')
624 for yymm in sorted(data.commits_by_month.keys()):
625 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
626 fg.close()
628 # Commits by year
629 f.write(html_header(2, 'Commits by Year'))
630 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
631 for yy in reversed(sorted(data.commits_by_year.keys())):
632 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td></tr>' % (yy, data.commits_by_year[yy], (100.0 * data.commits_by_year[yy]) / data.getTotalCommits()))
633 f.write('</table></div>')
634 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
635 fg = open(path + '/commits_by_year.dat', 'w')
636 for yy in sorted(data.commits_by_year.keys()):
637 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
638 fg.close()
640 f.write('</body></html>')
641 f.close()
644 # Authors
645 f = open(path + '/authors.html', 'w')
646 self.printHeader(f)
648 f.write('<h1>Authors</h1>')
649 self.printNav(f)
651 # Authors :: List of authors
652 f.write(html_header(2, 'List of Authors'))
654 f.write('<table class="authors sortable" id="authors">')
655 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th class="unsortable">Age</th><th># by commits</th></tr>')
656 for author in sorted(data.getAuthors()):
657 info = data.getAuthorInfo(author)
658 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td></tr>' % (author, info['commits'], info['commits_frac'], info['date_first'], info['date_last'], info['timedelta'], info['place_by_commits']))
659 f.write('</table>')
661 # Authors :: Author of Month
662 f.write(html_header(2, 'Author of Month'))
663 f.write('<table class="sortable" id="aom">')
664 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
665 for yymm in reversed(sorted(data.author_of_month.keys())):
666 authordict = data.author_of_month[yymm]
667 authors = getkeyssortedbyvalues(authordict)
668 authors.reverse()
669 commits = data.author_of_month[yymm][authors[0]]
670 next = ', '.join(authors[1:5])
671 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yymm, authors[0], commits, (100 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm], next))
673 f.write('</table>')
675 f.write(html_header(2, 'Author of Year'))
676 f.write('<table class="sortable" id="aoy"><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
677 for yy in reversed(sorted(data.author_of_year.keys())):
678 authordict = data.author_of_year[yy]
679 authors = getkeyssortedbyvalues(authordict)
680 authors.reverse()
681 commits = data.author_of_year[yy][authors[0]]
682 next = ', '.join(authors[1:5])
683 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yy, authors[0], commits, (100 * commits) / data.commits_by_year[yy], data.commits_by_year[yy], next))
684 f.write('</table>')
686 f.write('</body></html>')
687 f.close()
690 # Files
691 f = open(path + '/files.html', 'w')
692 self.printHeader(f)
693 f.write('<h1>Files</h1>')
694 self.printNav(f)
696 f.write('<dl>\n')
697 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
698 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
699 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
700 f.write('</dl>\n')
702 # Files :: File count by date
703 f.write(html_header(2, 'File count by date'))
705 fg = open(path + '/files_by_date.dat', 'w')
706 for stamp in sorted(data.files_by_stamp.keys()):
707 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
708 fg.close()
710 f.write('<img src="files_by_date.png" alt="Files by Date" />')
712 #f.write('<h2>Average file size by date</h2>')
714 # Files :: Extensions
715 f.write(html_header(2, 'Extensions'))
716 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
717 for ext in sorted(data.extensions.keys()):
718 files = data.extensions[ext]['files']
719 lines = data.extensions[ext]['lines']
720 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%d (%.2f%%)</td><td>%d</td></tr>' % (ext, files, (100.0 * files) / data.getTotalFiles(), lines, (100.0 * lines) / data.getTotalLOC(), lines / files))
721 f.write('</table>')
723 f.write('</body></html>')
724 f.close()
727 # Lines
728 f = open(path + '/lines.html', 'w')
729 self.printHeader(f)
730 f.write('<h1>Lines</h1>')
731 self.printNav(f)
733 f.write('<dl>\n')
734 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
735 f.write('</dl>\n')
737 f.write(html_header(2, 'Lines of Code'))
738 f.write('<img src="lines_of_code.png" />')
740 fg = open(path + '/lines_of_code.dat', 'w')
741 for stamp in sorted(data.changes_by_date.keys()):
742 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
743 fg.close()
745 f.write('</body></html>')
746 f.close()
749 # tags.html
750 f = open(path + '/tags.html', 'w')
751 self.printHeader(f)
752 f.write('<h1>Tags</h1>')
753 self.printNav(f)
755 f.write('<dl>')
756 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
757 if len(data.tags) > 0:
758 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
759 f.write('</dl>')
761 f.write('<table>')
762 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
763 # sort the tags by date desc
764 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
765 for tag in tags_sorted_by_date_desc:
766 authorinfo = []
767 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
768 for i in reversed(authors_by_commits):
769 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
770 f.write('<tr><td>%s</td><td>%s</td><td>%d</td><td>%s</td></tr>' % (tag, data.tags[tag]['date'], data.tags[tag]['commits'], ', '.join(authorinfo)))
771 f.write('</table>')
773 f.write('</body></html>')
774 f.close()
776 self.createGraphs(path)
778 def createGraphs(self, path):
779 print 'Generating graphs...'
781 # hour of day
782 f = open(path + '/hour_of_day.plot', 'w')
783 f.write(GNUPLOT_COMMON)
784 f.write(
786 set output 'hour_of_day.png'
787 unset key
788 set xrange [0.5:24.5]
789 set xtics 4
790 set ylabel "Commits"
791 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
792 """)
793 f.close()
795 # day of week
796 f = open(path + '/day_of_week.plot', 'w')
797 f.write(GNUPLOT_COMMON)
798 f.write(
800 set output 'day_of_week.png'
801 unset key
802 set xrange [0.5:7.5]
803 set xtics 1
804 set ylabel "Commits"
805 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
806 """)
807 f.close()
809 # Month of Year
810 f = open(path + '/month_of_year.plot', 'w')
811 f.write(GNUPLOT_COMMON)
812 f.write(
814 set output 'month_of_year.png'
815 unset key
816 set xrange [0.5:12.5]
817 set xtics 1
818 set ylabel "Commits"
819 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
820 """)
821 f.close()
823 # commits_by_year_month
824 f = open(path + '/commits_by_year_month.plot', 'w')
825 f.write(GNUPLOT_COMMON)
826 f.write(
828 set output 'commits_by_year_month.png'
829 unset key
830 set xdata time
831 set timefmt "%Y-%m"
832 set format x "%Y-%m"
833 set xtics rotate by 90 15768000
834 set bmargin 5
835 set ylabel "Commits"
836 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
837 """)
838 f.close()
840 # commits_by_year
841 f = open(path + '/commits_by_year.plot', 'w')
842 f.write(GNUPLOT_COMMON)
843 f.write(
845 set output 'commits_by_year.png'
846 unset key
847 set xtics 1
848 set ylabel "Commits"
849 set yrange [0:]
850 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
851 """)
852 f.close()
854 # Files by date
855 f = open(path + '/files_by_date.plot', 'w')
856 f.write(GNUPLOT_COMMON)
857 f.write(
859 set output 'files_by_date.png'
860 unset key
861 set xdata time
862 set timefmt "%Y-%m-%d"
863 set format x "%Y-%m-%d"
864 set ylabel "Files"
865 set xtics rotate by 90
866 set bmargin 6
867 plot 'files_by_date.dat' using 1:2 w histeps
868 """)
869 f.close()
871 # Lines of Code
872 f = open(path + '/lines_of_code.plot', 'w')
873 f.write(GNUPLOT_COMMON)
874 f.write(
876 set output 'lines_of_code.png'
877 unset key
878 set xdata time
879 set timefmt "%s"
880 set format x "%Y-%m-%d"
881 set ylabel "Lines"
882 set xtics rotate by 90
883 set bmargin 6
884 plot 'lines_of_code.dat' using 1:2 w lines
885 """)
886 f.close()
888 os.chdir(path)
889 files = glob.glob(path + '/*.plot')
890 for f in files:
891 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
892 if len(out) > 0:
893 print out
895 def printHeader(self, f, title = ''):
896 f.write(
897 """<?xml version="1.0" encoding="UTF-8"?>
898 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
899 <html xmlns="http://www.w3.org/1999/xhtml">
900 <head>
901 <title>GitStats - %s</title>
902 <link rel="stylesheet" href="gitstats.css" type="text/css" />
903 <meta name="generator" content="GitStats %s" />
904 <script type="text/javascript" src="sortable.js"></script>
905 </head>
906 <body>
907 """ % (self.title, getversion()))
909 def printNav(self, f):
910 f.write("""
911 <div class="nav">
912 <ul>
913 <li><a href="index.html">General</a></li>
914 <li><a href="activity.html">Activity</a></li>
915 <li><a href="authors.html">Authors</a></li>
916 <li><a href="files.html">Files</a></li>
917 <li><a href="lines.html">Lines</a></li>
918 <li><a href="tags.html">Tags</a></li>
919 </ul>
920 </div>
921 """)
924 usage = """
925 Usage: gitstats [options] <gitpath> <outputpath>
927 Options:
930 if len(sys.argv) < 3:
931 print usage
932 sys.exit(0)
934 gitpath = sys.argv[1]
935 outputpath = os.path.abspath(sys.argv[2])
936 rundir = os.getcwd()
938 try:
939 os.makedirs(outputpath)
940 except OSError:
941 pass
942 if not os.path.isdir(outputpath):
943 print 'FATAL: Output path is not a directory or does not exist'
944 sys.exit(1)
946 print 'Git path: %s' % gitpath
947 print 'Output path: %s' % outputpath
949 os.chdir(gitpath)
951 cachefile = os.path.join(outputpath, 'gitstats.cache')
953 print 'Collecting data...'
954 data = GitDataCollector()
955 data.loadCache(cachefile)
956 data.collect(gitpath)
957 print 'Refining data...'
958 data.saveCache(cachefile)
959 data.refine()
961 os.chdir(rundir)
963 print 'Generating report...'
964 report = HTMLReportCreator()
965 report.create(data, outputpath)
967 time_end = time.time()
968 exectime_internal = time_end - time_start
969 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)