Authors: show lines added/removed.
[gitstats.git] / gitstats
blob2012152bb6363c1bda657c7de83d009d991a3920
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 platform
9 import re
10 import shutil
11 import subprocess
12 import sys
13 import time
14 import zlib
16 GNUPLOT_COMMON = 'set terminal png transparent\nset size 0.5,0.5\n'
17 MAX_EXT_LENGTH = 10 # maximum file extension length
18 ON_LINUX = (platform.system() == 'Linux')
20 exectime_internal = 0.0
21 exectime_external = 0.0
22 time_start = time.time()
24 # By default, gnuplot is searched from path, but can be overridden with the
25 # environment variable "GNUPLOT"
26 gnuplot_cmd = 'gnuplot'
27 if 'GNUPLOT' in os.environ:
28 gnuplot_cmd = os.environ['GNUPLOT']
30 def getpipeoutput(cmds, quiet = False):
31 global exectime_external
32 start = time.time()
33 if not quiet and ON_LINUX and os.isatty(1):
34 print '>> ' + ' | '.join(cmds),
35 sys.stdout.flush()
36 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
37 p = p0
38 for x in cmds[1:]:
39 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
40 p0 = p
41 output = p.communicate()[0]
42 end = time.time()
43 if not quiet:
44 if ON_LINUX and os.isatty(1):
45 print '\r',
46 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
47 exectime_external += (end - start)
48 return output.rstrip('\n')
50 def getkeyssortedbyvalues(dict):
51 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
53 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
54 def getkeyssortedbyvaluekey(d, key):
55 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
57 VERSION = 0
58 def getversion():
59 global VERSION
60 if VERSION == 0:
61 VERSION = getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
62 return VERSION
64 class DataCollector:
65 """Manages data collection from a revision control repository."""
66 def __init__(self):
67 self.stamp_created = time.time()
68 self.cache = {}
71 # This should be the main function to extract data from the repository.
72 def collect(self, dir):
73 self.dir = dir
74 self.projectname = os.path.basename(os.path.abspath(dir))
77 # Load cacheable data
78 def loadCache(self, cachefile):
79 if not os.path.exists(cachefile):
80 return
81 print 'Loading cache...'
82 f = open(cachefile)
83 try:
84 self.cache = pickle.loads(zlib.decompress(f.read()))
85 except:
86 # temporary hack to upgrade non-compressed caches
87 f.seek(0)
88 self.cache = pickle.load(f)
89 f.close()
92 # Produce any additional statistics from the extracted data.
93 def refine(self):
94 pass
97 # : get a dictionary of author
98 def getAuthorInfo(self, author):
99 return None
101 def getActivityByDayOfWeek(self):
102 return {}
104 def getActivityByHourOfDay(self):
105 return {}
108 # Get a list of authors
109 def getAuthors(self):
110 return []
112 def getFirstCommitDate(self):
113 return datetime.datetime.now()
115 def getLastCommitDate(self):
116 return datetime.datetime.now()
118 def getStampCreated(self):
119 return self.stamp_created
121 def getTags(self):
122 return []
124 def getTotalAuthors(self):
125 return -1
127 def getTotalCommits(self):
128 return -1
130 def getTotalFiles(self):
131 return -1
133 def getTotalLOC(self):
134 return -1
137 # Save cacheable data
138 def saveCache(self, filename):
139 print 'Saving cache...'
140 f = open(cachefile, 'w')
141 #pickle.dump(self.cache, f)
142 data = zlib.compress(pickle.dumps(self.cache))
143 f.write(data)
144 f.close()
146 class GitDataCollector(DataCollector):
147 def collect(self, dir):
148 DataCollector.collect(self, dir)
150 try:
151 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
152 except:
153 self.total_authors = 0
154 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
156 self.activity_by_hour_of_day = {} # hour -> commits
157 self.activity_by_day_of_week = {} # day -> commits
158 self.activity_by_month_of_year = {} # month [1-12] -> commits
159 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
160 self.activity_by_hour_of_day_busiest = 0
161 self.activity_by_hour_of_week_busiest = 0
162 self.activity_by_year_week = {} # yy_wNN -> commits
163 self.activity_by_year_week_peak = 0
165 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
167 # author of the month
168 self.author_of_month = {} # month -> author -> commits
169 self.author_of_year = {} # year -> author -> commits
170 self.commits_by_month = {} # month -> commits
171 self.commits_by_year = {} # year -> commits
172 self.first_commit_stamp = 0
173 self.last_commit_stamp = 0
174 self.last_active_day = None
175 self.active_days = set()
177 # timezone
178 self.commits_by_timezone = {} # timezone -> commits
180 # tags
181 self.tags = {}
182 lines = getpipeoutput(['git show-ref --tags']).split('\n')
183 for line in lines:
184 if len(line) == 0:
185 continue
186 (hash, tag) = line.split(' ')
188 tag = tag.replace('refs/tags/', '')
189 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
190 if len(output) > 0:
191 parts = output.split(' ')
192 stamp = 0
193 try:
194 stamp = int(parts[0])
195 except ValueError:
196 stamp = 0
197 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
199 # collect info on tags, starting from latest
200 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
201 prev = None
202 for tag in reversed(tags_sorted_by_date_desc):
203 cmd = 'git shortlog -s "%s"' % tag
204 if prev != None:
205 cmd += ' "^%s"' % prev
206 output = getpipeoutput([cmd])
207 if len(output) == 0:
208 continue
209 prev = tag
210 for line in output.split('\n'):
211 parts = re.split('\s+', line, 2)
212 commits = int(parts[1])
213 author = parts[2]
214 self.tags[tag]['commits'] += commits
215 self.tags[tag]['authors'][author] = commits
217 # Collect revision statistics
218 # Outputs "<stamp> <author>"
219 lines = getpipeoutput(['git rev-list --pretty=format:"%at %ai %an" HEAD', 'grep -v ^commit']).split('\n')
220 for line in lines:
221 # linux-2.6 says "<unknown>" for one line O_o
222 parts = line.split(' ')
223 author = ''
224 try:
225 stamp = int(parts[0])
226 except ValueError:
227 stamp = 0
228 timezone = parts[3]
229 if len(parts) > 4:
230 author = ' '.join(parts[4:])
231 date = datetime.datetime.fromtimestamp(float(stamp))
233 # First and last commit stamp
234 if self.last_commit_stamp == 0:
235 self.last_commit_stamp = stamp
236 self.first_commit_stamp = stamp
238 # activity
239 # hour
240 hour = date.hour
241 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
242 # most active hour?
243 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
244 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
246 # day of week
247 day = date.weekday()
248 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
250 # hour of week
251 if day not in self.activity_by_hour_of_week:
252 self.activity_by_hour_of_week[day] = {}
253 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
254 # most active hour?
255 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
256 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
258 # month of year
259 month = date.month
260 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
262 # yearly/weekly activity
263 yyw = date.strftime('%Y-%W')
264 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
265 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
266 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
268 # author stats
269 if author not in self.authors:
270 self.authors[author] = {}
271 # commits
272 if 'last_commit_stamp' not in self.authors[author]:
273 self.authors[author]['last_commit_stamp'] = stamp
274 self.authors[author]['first_commit_stamp'] = stamp
275 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
277 # author of the month/year
278 yymm = date.strftime('%Y-%m')
279 if yymm in self.author_of_month:
280 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
281 else:
282 self.author_of_month[yymm] = {}
283 self.author_of_month[yymm][author] = 1
284 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
286 yy = date.year
287 if yy in self.author_of_year:
288 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
289 else:
290 self.author_of_year[yy] = {}
291 self.author_of_year[yy][author] = 1
292 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
294 # authors: active days
295 yymmdd = date.strftime('%Y-%m-%d')
296 if 'last_active_day' not in self.authors[author]:
297 self.authors[author]['last_active_day'] = yymmdd
298 self.authors[author]['active_days'] = 1
299 elif yymmdd != self.authors[author]['last_active_day']:
300 self.authors[author]['last_active_day'] = yymmdd
301 self.authors[author]['active_days'] += 1
303 # project: active days
304 if yymmdd != self.last_active_day:
305 self.last_active_day = yymmdd
306 self.active_days.add(yymmdd)
308 # timezone
309 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
311 # TODO Optimize this, it's the worst bottleneck
312 # outputs "<stamp> <files>" for each revision
313 self.files_by_stamp = {} # stamp -> files
314 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
315 lines = []
316 for revline in revlines:
317 time, rev = revline.split(' ')
318 linecount = self.getFilesInCommit(rev)
319 lines.append('%d %d' % (int(time), linecount))
321 self.total_commits = len(lines)
322 for line in lines:
323 parts = line.split(' ')
324 if len(parts) != 2:
325 continue
326 (stamp, files) = parts[0:2]
327 try:
328 self.files_by_stamp[int(stamp)] = int(files)
329 except ValueError:
330 print 'Warning: failed to parse line "%s"' % line
332 # extensions
333 self.extensions = {} # extension -> files, lines
334 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
335 self.total_files = len(lines)
336 for line in lines:
337 if len(line) == 0:
338 continue
339 parts = re.split('\s+', line, 4)
340 sha1 = parts[2]
341 filename = parts[3]
343 if filename.find('.') == -1 or filename.rfind('.') == 0:
344 ext = ''
345 else:
346 ext = filename[(filename.rfind('.') + 1):]
347 if len(ext) > MAX_EXT_LENGTH:
348 ext = ''
350 if ext not in self.extensions:
351 self.extensions[ext] = {'files': 0, 'lines': 0}
353 self.extensions[ext]['files'] += 1
354 try:
355 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
356 except:
357 print 'Warning: Could not count lines for file "%s"' % line
359 # line statistics
360 # outputs:
361 # N files changed, N insertions (+), N deletions(-)
362 # <stamp> <author>
363 self.changes_by_date = {} # stamp -> { files, ins, del }
364 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
365 lines.reverse()
366 files = 0; inserted = 0; deleted = 0; total_lines = 0
367 author = None
368 for line in lines:
369 if len(line) == 0:
370 continue
372 # <stamp> <author>
373 if line.find('files changed,') == -1:
374 pos = line.find(' ')
375 if pos != -1:
376 try:
377 (stamp, author) = (int(line[:pos]), line[pos+1:])
378 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
379 if author not in self.authors:
380 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
381 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
382 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
383 except ValueError:
384 print 'Warning: unexpected line "%s"' % line
385 else:
386 print 'Warning: unexpected line "%s"' % line
387 else:
388 numbers = re.findall('\d+', line)
389 if len(numbers) == 3:
390 (files, inserted, deleted) = map(lambda el : int(el), numbers)
391 total_lines += inserted
392 total_lines -= deleted
393 else:
394 print 'Warning: failed to handle line "%s"' % line
395 (files, inserted, deleted) = (0, 0, 0)
396 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
397 self.total_lines = total_lines
399 def refine(self):
400 # authors
401 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
402 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
403 authors_by_commits.reverse() # most first
404 for i, name in enumerate(authors_by_commits):
405 self.authors[name]['place_by_commits'] = i + 1
407 for name in self.authors.keys():
408 a = self.authors[name]
409 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
410 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
411 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
412 delta = date_last - date_first
413 a['date_first'] = date_first.strftime('%Y-%m-%d')
414 a['date_last'] = date_last.strftime('%Y-%m-%d')
415 a['timedelta'] = delta
417 def getActiveDays(self):
418 return self.active_days
420 def getActivityByDayOfWeek(self):
421 return self.activity_by_day_of_week
423 def getActivityByHourOfDay(self):
424 return self.activity_by_hour_of_day
426 def getAuthorInfo(self, author):
427 return self.authors[author]
429 def getAuthors(self):
430 return self.authors.keys()
432 def getCommitDeltaDays(self):
433 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
435 def getFilesInCommit(self, rev):
436 try:
437 res = self.cache['files_in_tree'][rev]
438 except:
439 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
440 if 'files_in_tree' not in self.cache:
441 self.cache['files_in_tree'] = {}
442 self.cache['files_in_tree'][rev] = res
444 return res
446 def getFirstCommitDate(self):
447 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
449 def getLastCommitDate(self):
450 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
452 def getTags(self):
453 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
454 return lines.split('\n')
456 def getTagDate(self, tag):
457 return self.revToDate('tags/' + tag)
459 def getTotalAuthors(self):
460 return self.total_authors
462 def getTotalCommits(self):
463 return self.total_commits
465 def getTotalFiles(self):
466 return self.total_files
468 def getTotalLOC(self):
469 return self.total_lines
471 def revToDate(self, rev):
472 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
473 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
475 class ReportCreator:
476 """Creates the actual report based on given data."""
477 def __init__(self):
478 pass
480 def create(self, data, path):
481 self.data = data
482 self.path = path
484 def html_linkify(text):
485 return text.lower().replace(' ', '_')
487 def html_header(level, text):
488 name = html_linkify(text)
489 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
491 class HTMLReportCreator(ReportCreator):
492 def create(self, data, path):
493 ReportCreator.create(self, data, path)
494 self.title = data.projectname
496 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
497 binarypath = os.path.dirname(os.path.abspath(__file__))
498 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
499 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
500 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
501 for base in basedirs:
502 src = base + '/' + file
503 if os.path.exists(src):
504 shutil.copyfile(src, path + '/' + file)
505 break
506 else:
507 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
509 f = open(path + "/index.html", 'w')
510 format = '%Y-%m-%d %H:%M:%S'
511 self.printHeader(f)
513 f.write('<h1>GitStats - %s</h1>' % data.projectname)
515 self.printNav(f)
517 f.write('<dl>')
518 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
519 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
520 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
521 f.write('<dt>Report Period</dt><dd>%s to %s (%d days, %d active days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays(), len(data.getActiveDays())))
522 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
523 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
524 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
525 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
526 f.write('</dl>')
528 f.write('</body>\n</html>')
529 f.close()
532 # Activity
533 f = open(path + '/activity.html', 'w')
534 self.printHeader(f)
535 f.write('<h1>Activity</h1>')
536 self.printNav(f)
538 #f.write('<h2>Last 30 days</h2>')
540 #f.write('<h2>Last 12 months</h2>')
542 # Weekly activity
543 WEEKS = 32
544 f.write(html_header(2, 'Weekly activity'))
545 f.write('<p>Last %d weeks</p>' % WEEKS)
547 # generate weeks to show (previous N weeks from now)
548 now = datetime.datetime.now()
549 deltaweek = datetime.timedelta(7)
550 weeks = []
551 stampcur = now
552 for i in range(0, WEEKS):
553 weeks.insert(0, stampcur.strftime('%Y-%W'))
554 stampcur -= deltaweek
556 # top row: commits & bar
557 f.write('<table class="noborders"><tr>')
558 for i in range(0, WEEKS):
559 commits = 0
560 if weeks[i] in data.activity_by_year_week:
561 commits = data.activity_by_year_week[weeks[i]]
563 percentage = 0
564 if weeks[i] in data.activity_by_year_week:
565 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
566 height = max(1, int(200 * percentage))
567 f.write('<td style="text-align: center; vertical-align: bottom">%d<div style="display: block; background-color: red; width: 20px; height: %dpx"></div></td>' % (commits, height))
569 # bottom row: year/week
570 f.write('</tr><tr>')
571 for i in range(0, WEEKS):
572 f.write('<td>%s</td>' % (WEEKS - i))
573 f.write('</tr></table>')
575 # Hour of Day
576 f.write(html_header(2, 'Hour of Day'))
577 hour_of_day = data.getActivityByHourOfDay()
578 f.write('<table><tr><th>Hour</th>')
579 for i in range(0, 24):
580 f.write('<th>%d</th>' % i)
581 f.write('</tr>\n<tr><th>Commits</th>')
582 fp = open(path + '/hour_of_day.dat', 'w')
583 for i in range(0, 24):
584 if i in hour_of_day:
585 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
586 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
587 fp.write('%d %d\n' % (i, hour_of_day[i]))
588 else:
589 f.write('<td>0</td>')
590 fp.write('%d 0\n' % i)
591 fp.close()
592 f.write('</tr>\n<tr><th>%</th>')
593 totalcommits = data.getTotalCommits()
594 for i in range(0, 24):
595 if i in hour_of_day:
596 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
597 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
598 else:
599 f.write('<td>0.00</td>')
600 f.write('</tr></table>')
601 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
602 fg = open(path + '/hour_of_day.dat', 'w')
603 for i in range(0, 24):
604 if i in hour_of_day:
605 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
606 else:
607 fg.write('%d 0\n' % (i + 1))
608 fg.close()
610 # Day of Week
611 f.write(html_header(2, 'Day of Week'))
612 day_of_week = data.getActivityByDayOfWeek()
613 f.write('<div class="vtable"><table>')
614 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
615 fp = open(path + '/day_of_week.dat', 'w')
616 for d in range(0, 7):
617 commits = 0
618 if d in day_of_week:
619 commits = day_of_week[d]
620 fp.write('%d %d\n' % (d + 1, commits))
621 f.write('<tr>')
622 f.write('<th>%d</th>' % (d + 1))
623 if d in day_of_week:
624 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
625 else:
626 f.write('<td>0</td>')
627 f.write('</tr>')
628 f.write('</table></div>')
629 f.write('<img src="day_of_week.png" alt="Day of Week" />')
630 fp.close()
632 # Hour of Week
633 f.write(html_header(2, 'Hour of Week'))
634 f.write('<table>')
636 f.write('<tr><th>Weekday</th>')
637 for hour in range(0, 24):
638 f.write('<th>%d</th>' % (hour))
639 f.write('</tr>')
641 for weekday in range(0, 7):
642 f.write('<tr><th>%d</th>' % (weekday + 1))
643 for hour in range(0, 24):
644 try:
645 commits = data.activity_by_hour_of_week[weekday][hour]
646 except KeyError:
647 commits = 0
648 if commits != 0:
649 f.write('<td')
650 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
651 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
652 f.write('>%d</td>' % commits)
653 else:
654 f.write('<td></td>')
655 f.write('</tr>')
657 f.write('</table>')
659 # Month of Year
660 f.write(html_header(2, 'Month of Year'))
661 f.write('<div class="vtable"><table>')
662 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
663 fp = open (path + '/month_of_year.dat', 'w')
664 for mm in range(1, 13):
665 commits = 0
666 if mm in data.activity_by_month_of_year:
667 commits = data.activity_by_month_of_year[mm]
668 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
669 fp.write('%d %d\n' % (mm, commits))
670 fp.close()
671 f.write('</table></div>')
672 f.write('<img src="month_of_year.png" alt="Month of Year" />')
674 # Commits by year/month
675 f.write(html_header(2, 'Commits by year/month'))
676 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
677 for yymm in reversed(sorted(data.commits_by_month.keys())):
678 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
679 f.write('</table></div>')
680 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
681 fg = open(path + '/commits_by_year_month.dat', 'w')
682 for yymm in sorted(data.commits_by_month.keys()):
683 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
684 fg.close()
686 # Commits by year
687 f.write(html_header(2, 'Commits by Year'))
688 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
689 for yy in reversed(sorted(data.commits_by_year.keys())):
690 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()))
691 f.write('</table></div>')
692 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
693 fg = open(path + '/commits_by_year.dat', 'w')
694 for yy in sorted(data.commits_by_year.keys()):
695 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
696 fg.close()
698 # Commits by timezone
699 f.write(html_header(2, 'Commits by Timezone'))
700 f.write('<table><tr>')
701 f.write('<th>Timezone</th><th>Commits</th>')
702 max_commits_on_tz = max(data.commits_by_timezone.values())
703 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
704 commits = data.commits_by_timezone[i]
705 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
706 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
707 f.write('</tr></table>')
709 f.write('</body></html>')
710 f.close()
713 # Authors
714 f = open(path + '/authors.html', 'w')
715 self.printHeader(f)
717 f.write('<h1>Authors</h1>')
718 self.printNav(f)
720 # Authors :: List of authors
721 f.write(html_header(2, 'List of Authors'))
723 f.write('<table class="authors sortable" id="authors">')
724 f.write('<tr><th>Author</th><th>Commits (%)</th><th>+ lines</th><th>- lines</th><th>First commit</th><th>Last commit</th><th class="unsortable">Age</th><th>Active days</th><th># by commits</th></tr>')
725 for author in sorted(data.getAuthors()):
726 info = data.getAuthorInfo(author)
727 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (author, info['commits'], info['lines_added'], info['lines_removed'], info['commits_frac'], info['date_first'], info['date_last'], info['timedelta'], info['active_days'], info['place_by_commits']))
728 f.write('</table>')
730 # Authors :: Author of Month
731 f.write(html_header(2, 'Author of Month'))
732 f.write('<table class="sortable" id="aom">')
733 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
734 for yymm in reversed(sorted(data.author_of_month.keys())):
735 authordict = data.author_of_month[yymm]
736 authors = getkeyssortedbyvalues(authordict)
737 authors.reverse()
738 commits = data.author_of_month[yymm][authors[0]]
739 next = ', '.join(authors[1:5])
740 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yymm, authors[0], commits, (100.0 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm], next))
742 f.write('</table>')
744 f.write(html_header(2, 'Author of Year'))
745 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>')
746 for yy in reversed(sorted(data.author_of_year.keys())):
747 authordict = data.author_of_year[yy]
748 authors = getkeyssortedbyvalues(authordict)
749 authors.reverse()
750 commits = data.author_of_year[yy][authors[0]]
751 next = ', '.join(authors[1:5])
752 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yy, authors[0], commits, (100.0 * commits) / data.commits_by_year[yy], data.commits_by_year[yy], next))
753 f.write('</table>')
755 f.write('</body></html>')
756 f.close()
759 # Files
760 f = open(path + '/files.html', 'w')
761 self.printHeader(f)
762 f.write('<h1>Files</h1>')
763 self.printNav(f)
765 f.write('<dl>\n')
766 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
767 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
768 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
769 f.write('</dl>\n')
771 # Files :: File count by date
772 f.write(html_header(2, 'File count by date'))
774 fg = open(path + '/files_by_date.dat', 'w')
775 for stamp in sorted(data.files_by_stamp.keys()):
776 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
777 fg.close()
779 f.write('<img src="files_by_date.png" alt="Files by Date" />')
781 #f.write('<h2>Average file size by date</h2>')
783 # Files :: Extensions
784 f.write(html_header(2, 'Extensions'))
785 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
786 for ext in sorted(data.extensions.keys()):
787 files = data.extensions[ext]['files']
788 lines = data.extensions[ext]['lines']
789 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))
790 f.write('</table>')
792 f.write('</body></html>')
793 f.close()
796 # Lines
797 f = open(path + '/lines.html', 'w')
798 self.printHeader(f)
799 f.write('<h1>Lines</h1>')
800 self.printNav(f)
802 f.write('<dl>\n')
803 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
804 f.write('</dl>\n')
806 f.write(html_header(2, 'Lines of Code'))
807 f.write('<img src="lines_of_code.png" />')
809 fg = open(path + '/lines_of_code.dat', 'w')
810 for stamp in sorted(data.changes_by_date.keys()):
811 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
812 fg.close()
814 f.write('</body></html>')
815 f.close()
818 # tags.html
819 f = open(path + '/tags.html', 'w')
820 self.printHeader(f)
821 f.write('<h1>Tags</h1>')
822 self.printNav(f)
824 f.write('<dl>')
825 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
826 if len(data.tags) > 0:
827 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
828 f.write('</dl>')
830 f.write('<table>')
831 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
832 # sort the tags by date desc
833 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
834 for tag in tags_sorted_by_date_desc:
835 authorinfo = []
836 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
837 for i in reversed(authors_by_commits):
838 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
839 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)))
840 f.write('</table>')
842 f.write('</body></html>')
843 f.close()
845 self.createGraphs(path)
847 def createGraphs(self, path):
848 print 'Generating graphs...'
850 # hour of day
851 f = open(path + '/hour_of_day.plot', 'w')
852 f.write(GNUPLOT_COMMON)
853 f.write(
855 set output 'hour_of_day.png'
856 unset key
857 set xrange [0.5:24.5]
858 set xtics 4
859 set ylabel "Commits"
860 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
861 """)
862 f.close()
864 # day of week
865 f = open(path + '/day_of_week.plot', 'w')
866 f.write(GNUPLOT_COMMON)
867 f.write(
869 set output 'day_of_week.png'
870 unset key
871 set xrange [0.5:7.5]
872 set xtics 1
873 set ylabel "Commits"
874 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
875 """)
876 f.close()
878 # Month of Year
879 f = open(path + '/month_of_year.plot', 'w')
880 f.write(GNUPLOT_COMMON)
881 f.write(
883 set output 'month_of_year.png'
884 unset key
885 set xrange [0.5:12.5]
886 set xtics 1
887 set ylabel "Commits"
888 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
889 """)
890 f.close()
892 # commits_by_year_month
893 f = open(path + '/commits_by_year_month.plot', 'w')
894 f.write(GNUPLOT_COMMON)
895 f.write(
897 set output 'commits_by_year_month.png'
898 unset key
899 set xdata time
900 set timefmt "%Y-%m"
901 set format x "%Y-%m"
902 set xtics rotate by 90 15768000
903 set bmargin 5
904 set ylabel "Commits"
905 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
906 """)
907 f.close()
909 # commits_by_year
910 f = open(path + '/commits_by_year.plot', 'w')
911 f.write(GNUPLOT_COMMON)
912 f.write(
914 set output 'commits_by_year.png'
915 unset key
916 set xtics 1
917 set ylabel "Commits"
918 set yrange [0:]
919 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
920 """)
921 f.close()
923 # Files by date
924 f = open(path + '/files_by_date.plot', 'w')
925 f.write(GNUPLOT_COMMON)
926 f.write(
928 set output 'files_by_date.png'
929 unset key
930 set xdata time
931 set timefmt "%Y-%m-%d"
932 set format x "%Y-%m-%d"
933 set ylabel "Files"
934 set xtics rotate by 90
935 set ytics 1
936 set bmargin 6
937 plot 'files_by_date.dat' using 1:2 w steps
938 """)
939 f.close()
941 # Lines of Code
942 f = open(path + '/lines_of_code.plot', 'w')
943 f.write(GNUPLOT_COMMON)
944 f.write(
946 set output 'lines_of_code.png'
947 unset key
948 set xdata time
949 set timefmt "%s"
950 set format x "%Y-%m-%d"
951 set ylabel "Lines"
952 set xtics rotate by 90
953 set bmargin 6
954 plot 'lines_of_code.dat' using 1:2 w lines
955 """)
956 f.close()
958 os.chdir(path)
959 files = glob.glob(path + '/*.plot')
960 for f in files:
961 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
962 if len(out) > 0:
963 print out
965 def printHeader(self, f, title = ''):
966 f.write(
967 """<?xml version="1.0" encoding="UTF-8"?>
968 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
969 <html xmlns="http://www.w3.org/1999/xhtml">
970 <head>
971 <title>GitStats - %s</title>
972 <link rel="stylesheet" href="gitstats.css" type="text/css" />
973 <meta name="generator" content="GitStats %s" />
974 <script type="text/javascript" src="sortable.js"></script>
975 </head>
976 <body>
977 """ % (self.title, getversion()))
979 def printNav(self, f):
980 f.write("""
981 <div class="nav">
982 <ul>
983 <li><a href="index.html">General</a></li>
984 <li><a href="activity.html">Activity</a></li>
985 <li><a href="authors.html">Authors</a></li>
986 <li><a href="files.html">Files</a></li>
987 <li><a href="lines.html">Lines</a></li>
988 <li><a href="tags.html">Tags</a></li>
989 </ul>
990 </div>
991 """)
994 usage = """
995 Usage: gitstats [options] <gitpath> <outputpath>
997 Options:
1000 if len(sys.argv) < 3:
1001 print usage
1002 sys.exit(0)
1004 gitpath = sys.argv[1]
1005 outputpath = os.path.abspath(sys.argv[2])
1006 rundir = os.getcwd()
1008 try:
1009 os.makedirs(outputpath)
1010 except OSError:
1011 pass
1012 if not os.path.isdir(outputpath):
1013 print 'FATAL: Output path is not a directory or does not exist'
1014 sys.exit(1)
1016 print 'Git path: %s' % gitpath
1017 print 'Output path: %s' % outputpath
1019 os.chdir(gitpath)
1021 cachefile = os.path.join(outputpath, 'gitstats.cache')
1023 print 'Collecting data...'
1024 data = GitDataCollector()
1025 data.loadCache(cachefile)
1026 data.collect(gitpath)
1027 print 'Refining data...'
1028 data.saveCache(cachefile)
1029 data.refine()
1031 os.chdir(rundir)
1033 print 'Generating report...'
1034 report = HTMLReportCreator()
1035 report.create(data, outputpath)
1037 time_end = time.time()
1038 exectime_internal = time_end - time_start
1039 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)