Add options for limiting stats to begin..end range.
[gitstats.git] / gitstats
blobadce52e8423c69b3c0d0b0d64af2abcbe5d68427
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2010 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
3 # GPLv2 / GPLv3
4 import datetime
5 import getopt
6 import glob
7 import os
8 import pickle
9 import platform
10 import re
11 import shutil
12 import subprocess
13 import sys
14 import time
15 import zlib
17 GNUPLOT_COMMON = 'set terminal png transparent\nset size 1.0,0.5\n'
18 ON_LINUX = (platform.system() == 'Linux')
19 WEEKDAYS = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
21 exectime_internal = 0.0
22 exectime_external = 0.0
23 time_start = time.time()
25 # By default, gnuplot is searched from path, but can be overridden with the
26 # environment variable "GNUPLOT"
27 gnuplot_cmd = 'gnuplot'
28 if 'GNUPLOT' in os.environ:
29 gnuplot_cmd = os.environ['GNUPLOT']
31 conf = {
32 'max_domains': 10,
33 'max_ext_length': 10,
34 'style': 'gitstats.css',
35 'max_authors': 20,
36 'authors_top': 5,
37 'commit_begin': '',
38 'commit_end': '',
41 def getpipeoutput(cmds, quiet = False):
42 global exectime_external
43 start = time.time()
44 if not quiet and ON_LINUX and os.isatty(1):
45 print '>> ' + ' | '.join(cmds),
46 sys.stdout.flush()
47 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
48 p = p0
49 for x in cmds[1:]:
50 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
51 p0 = p
52 output = p.communicate()[0]
53 end = time.time()
54 if not quiet:
55 if ON_LINUX and os.isatty(1):
56 print '\r',
57 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
58 exectime_external += (end - start)
59 return output.rstrip('\n')
61 def getcommitrange(defaultrange = '', end_only = False):
62 if len(conf['commit_end']) > 0:
63 if end_only or len(conf['commit_begin']) == 0:
64 return conf['commit_end']
65 return '%s..%s' % (conf['commit_begin'], conf['commit_end'])
66 return defaultrange
68 def getkeyssortedbyvalues(dict):
69 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
71 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
72 def getkeyssortedbyvaluekey(d, key):
73 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
75 VERSION = 0
76 def getversion():
77 global VERSION
78 if VERSION == 0:
79 VERSION = getpipeoutput(["git rev-parse --short %s" % getcommitrange('HEAD')]).split('\n')[0]
80 return VERSION
82 class DataCollector:
83 """Manages data collection from a revision control repository."""
84 def __init__(self):
85 self.stamp_created = time.time()
86 self.cache = {}
89 # This should be the main function to extract data from the repository.
90 def collect(self, dir):
91 self.dir = dir
92 self.projectname = os.path.basename(os.path.abspath(dir))
95 # Load cacheable data
96 def loadCache(self, cachefile):
97 if not os.path.exists(cachefile):
98 return
99 print 'Loading cache...'
100 f = open(cachefile, 'rb')
101 try:
102 self.cache = pickle.loads(zlib.decompress(f.read()))
103 except:
104 # temporary hack to upgrade non-compressed caches
105 f.seek(0)
106 self.cache = pickle.load(f)
107 f.close()
110 # Produce any additional statistics from the extracted data.
111 def refine(self):
112 pass
115 # : get a dictionary of author
116 def getAuthorInfo(self, author):
117 return None
119 def getActivityByDayOfWeek(self):
120 return {}
122 def getActivityByHourOfDay(self):
123 return {}
125 # : get a dictionary of domains
126 def getDomainInfo(self, domain):
127 return None
130 # Get a list of authors
131 def getAuthors(self):
132 return []
134 def getFirstCommitDate(self):
135 return datetime.datetime.now()
137 def getLastCommitDate(self):
138 return datetime.datetime.now()
140 def getStampCreated(self):
141 return self.stamp_created
143 def getTags(self):
144 return []
146 def getTotalAuthors(self):
147 return -1
149 def getTotalCommits(self):
150 return -1
152 def getTotalFiles(self):
153 return -1
155 def getTotalLOC(self):
156 return -1
159 # Save cacheable data
160 def saveCache(self, cachefile):
161 print 'Saving cache...'
162 f = open(cachefile, 'wb')
163 #pickle.dump(self.cache, f)
164 data = zlib.compress(pickle.dumps(self.cache))
165 f.write(data)
166 f.close()
168 class GitDataCollector(DataCollector):
169 def collect(self, dir):
170 DataCollector.collect(self, dir)
172 try:
173 self.total_authors = int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
174 except:
175 self.total_authors = 0
176 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
178 self.activity_by_hour_of_day = {} # hour -> commits
179 self.activity_by_day_of_week = {} # day -> commits
180 self.activity_by_month_of_year = {} # month [1-12] -> commits
181 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
182 self.activity_by_hour_of_day_busiest = 0
183 self.activity_by_hour_of_week_busiest = 0
184 self.activity_by_year_week = {} # yy_wNN -> commits
185 self.activity_by_year_week_peak = 0
187 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
189 # domains
190 self.domains = {} # domain -> commits
192 # author of the month
193 self.author_of_month = {} # month -> author -> commits
194 self.author_of_year = {} # year -> author -> commits
195 self.commits_by_month = {} # month -> commits
196 self.commits_by_year = {} # year -> commits
197 self.first_commit_stamp = 0
198 self.last_commit_stamp = 0
199 self.last_active_day = None
200 self.active_days = set()
202 # lines
203 self.total_lines = 0
204 self.total_lines_added = 0
205 self.total_lines_removed = 0
207 # timezone
208 self.commits_by_timezone = {} # timezone -> commits
210 # tags
211 self.tags = {}
212 lines = getpipeoutput(['git show-ref --tags']).split('\n')
213 for line in lines:
214 if len(line) == 0:
215 continue
216 (hash, tag) = line.split(' ')
218 tag = tag.replace('refs/tags/', '')
219 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
220 if len(output) > 0:
221 parts = output.split(' ')
222 stamp = 0
223 try:
224 stamp = int(parts[0])
225 except ValueError:
226 stamp = 0
227 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
229 # collect info on tags, starting from latest
230 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
231 prev = None
232 for tag in reversed(tags_sorted_by_date_desc):
233 cmd = 'git shortlog -s "%s"' % tag
234 if prev != None:
235 cmd += ' "^%s"' % prev
236 output = getpipeoutput([cmd])
237 if len(output) == 0:
238 continue
239 prev = tag
240 for line in output.split('\n'):
241 parts = re.split('\s+', line, 2)
242 commits = int(parts[1])
243 author = parts[2]
244 self.tags[tag]['commits'] += commits
245 self.tags[tag]['authors'][author] = commits
247 # Collect revision statistics
248 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
249 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%an <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
250 for line in lines:
251 parts = line.split(' ', 4)
252 author = ''
253 try:
254 stamp = int(parts[0])
255 except ValueError:
256 stamp = 0
257 timezone = parts[3]
258 author, mail = parts[4].split('<', 1)
259 author = author.rstrip()
260 mail = mail.rstrip('>')
261 domain = '?'
262 if mail.find('@') != -1:
263 domain = mail.rsplit('@', 1)[1]
264 date = datetime.datetime.fromtimestamp(float(stamp))
266 # First and last commit stamp
267 if self.last_commit_stamp == 0:
268 self.last_commit_stamp = stamp
269 self.first_commit_stamp = stamp
271 # activity
272 # hour
273 hour = date.hour
274 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
275 # most active hour?
276 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
277 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
279 # day of week
280 day = date.weekday()
281 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
283 # domain stats
284 if domain not in self.domains:
285 self.domains[domain] = {}
286 # commits
287 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
289 # hour of week
290 if day not in self.activity_by_hour_of_week:
291 self.activity_by_hour_of_week[day] = {}
292 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
293 # most active hour?
294 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
295 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
297 # month of year
298 month = date.month
299 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
301 # yearly/weekly activity
302 yyw = date.strftime('%Y-%W')
303 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
304 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
305 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
307 # author stats
308 if author not in self.authors:
309 self.authors[author] = {}
310 # commits
311 if 'last_commit_stamp' not in self.authors[author]:
312 self.authors[author]['last_commit_stamp'] = stamp
313 self.authors[author]['first_commit_stamp'] = stamp
314 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
316 # author of the month/year
317 yymm = date.strftime('%Y-%m')
318 if yymm in self.author_of_month:
319 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
320 else:
321 self.author_of_month[yymm] = {}
322 self.author_of_month[yymm][author] = 1
323 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
325 yy = date.year
326 if yy in self.author_of_year:
327 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
328 else:
329 self.author_of_year[yy] = {}
330 self.author_of_year[yy][author] = 1
331 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
333 # authors: active days
334 yymmdd = date.strftime('%Y-%m-%d')
335 if 'last_active_day' not in self.authors[author]:
336 self.authors[author]['last_active_day'] = yymmdd
337 self.authors[author]['active_days'] = 1
338 elif yymmdd != self.authors[author]['last_active_day']:
339 self.authors[author]['last_active_day'] = yymmdd
340 self.authors[author]['active_days'] += 1
342 # project: active days
343 if yymmdd != self.last_active_day:
344 self.last_active_day = yymmdd
345 self.active_days.add(yymmdd)
347 # timezone
348 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
350 # TODO Optimize this, it's the worst bottleneck
351 # outputs "<stamp> <files>" for each revision
352 self.files_by_stamp = {} # stamp -> files
353 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
354 lines = []
355 for revline in revlines:
356 time, rev = revline.split(' ')
357 linecount = self.getFilesInCommit(rev)
358 lines.append('%d %d' % (int(time), linecount))
360 self.total_commits = len(lines)
361 for line in lines:
362 parts = line.split(' ')
363 if len(parts) != 2:
364 continue
365 (stamp, files) = parts[0:2]
366 try:
367 self.files_by_stamp[int(stamp)] = int(files)
368 except ValueError:
369 print 'Warning: failed to parse line "%s"' % line
371 # extensions
372 self.extensions = {} # extension -> files, lines
373 lines = getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
374 self.total_files = len(lines)
375 for line in lines:
376 if len(line) == 0:
377 continue
378 parts = re.split('\s+', line, 4)
379 sha1 = parts[2]
380 filename = parts[3]
382 if filename.find('.') == -1 or filename.rfind('.') == 0:
383 ext = ''
384 else:
385 ext = filename[(filename.rfind('.') + 1):]
386 if len(ext) > conf['max_ext_length']:
387 ext = ''
389 if ext not in self.extensions:
390 self.extensions[ext] = {'files': 0, 'lines': 0}
392 self.extensions[ext]['files'] += 1
393 try:
394 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
395 except:
396 print 'Warning: Could not count lines for file "%s"' % line
398 # line statistics
399 # outputs:
400 # N files changed, N insertions (+), N deletions(-)
401 # <stamp> <author>
402 self.changes_by_date = {} # stamp -> { files, ins, del }
403 lines = getpipeoutput(['git log --shortstat --pretty=format:"%%at %%an" %s' % getcommitrange('HEAD')]).split('\n')
404 lines.reverse()
405 files = 0; inserted = 0; deleted = 0; total_lines = 0
406 author = None
407 for line in lines:
408 if len(line) == 0:
409 continue
411 # <stamp> <author>
412 if line.find('files changed,') == -1:
413 pos = line.find(' ')
414 if pos != -1:
415 try:
416 (stamp, author) = (int(line[:pos]), line[pos+1:])
417 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
418 if author not in self.authors:
419 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
420 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
421 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
422 files, inserted, deleted = 0, 0, 0
423 except ValueError:
424 print 'Warning: unexpected line "%s"' % line
425 else:
426 print 'Warning: unexpected line "%s"' % line
427 else:
428 numbers = re.findall('\d+', line)
429 if len(numbers) == 3:
430 (files, inserted, deleted) = map(lambda el : int(el), numbers)
431 total_lines += inserted
432 total_lines -= deleted
433 self.total_lines_added += inserted
434 self.total_lines_removed += deleted
435 else:
436 print 'Warning: failed to handle line "%s"' % line
437 (files, inserted, deleted) = (0, 0, 0)
438 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
439 self.total_lines = total_lines
441 def refine(self):
442 # authors
443 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
444 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
445 authors_by_commits.reverse() # most first
446 for i, name in enumerate(authors_by_commits):
447 self.authors[name]['place_by_commits'] = i + 1
449 for name in self.authors.keys():
450 a = self.authors[name]
451 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
452 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
453 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
454 delta = date_last - date_first
455 a['date_first'] = date_first.strftime('%Y-%m-%d')
456 a['date_last'] = date_last.strftime('%Y-%m-%d')
457 a['timedelta'] = delta
459 def getActiveDays(self):
460 return self.active_days
462 def getActivityByDayOfWeek(self):
463 return self.activity_by_day_of_week
465 def getActivityByHourOfDay(self):
466 return self.activity_by_hour_of_day
468 def getAuthorInfo(self, author):
469 return self.authors[author]
471 def getAuthors(self, limit = None):
472 res = getkeyssortedbyvaluekey(self.authors, 'commits')
473 res.reverse()
474 return res[:limit]
476 def getCommitDeltaDays(self):
477 return (self.last_commit_stamp - self.first_commit_stamp) / 86400 + 1
479 def getDomainInfo(self, domain):
480 return self.domains[domain]
482 def getDomains(self):
483 return self.domains.keys()
485 def getFilesInCommit(self, rev):
486 try:
487 res = self.cache['files_in_tree'][rev]
488 except:
489 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
490 if 'files_in_tree' not in self.cache:
491 self.cache['files_in_tree'] = {}
492 self.cache['files_in_tree'][rev] = res
494 return res
496 def getFirstCommitDate(self):
497 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
499 def getLastCommitDate(self):
500 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
502 def getLinesInBlob(self, sha1):
503 try:
504 res = self.cache['lines_in_blob'][sha1]
505 except:
506 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
507 if 'lines_in_blob' not in self.cache:
508 self.cache['lines_in_blob'] = {}
509 self.cache['lines_in_blob'][sha1] = res
510 return res
512 def getTags(self):
513 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
514 return lines.split('\n')
516 def getTagDate(self, tag):
517 return self.revToDate('tags/' + tag)
519 def getTotalAuthors(self):
520 return self.total_authors
522 def getTotalCommits(self):
523 return self.total_commits
525 def getTotalFiles(self):
526 return self.total_files
528 def getTotalLOC(self):
529 return self.total_lines
531 def revToDate(self, rev):
532 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
533 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
535 class ReportCreator:
536 """Creates the actual report based on given data."""
537 def __init__(self):
538 pass
540 def create(self, data, path):
541 self.data = data
542 self.path = path
544 def html_linkify(text):
545 return text.lower().replace(' ', '_')
547 def html_header(level, text):
548 name = html_linkify(text)
549 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
551 class HTMLReportCreator(ReportCreator):
552 def create(self, data, path):
553 ReportCreator.create(self, data, path)
554 self.title = data.projectname
556 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
557 binarypath = os.path.dirname(os.path.abspath(__file__))
558 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
559 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
560 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
561 for base in basedirs:
562 src = base + '/' + file
563 if os.path.exists(src):
564 shutil.copyfile(src, path + '/' + file)
565 break
566 else:
567 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
569 f = open(path + "/index.html", 'w')
570 format = '%Y-%m-%d %H:%M:%S'
571 self.printHeader(f)
573 f.write('<h1>GitStats - %s</h1>' % data.projectname)
575 self.printNav(f)
577 f.write('<dl>')
578 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
579 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
580 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
581 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
582 f.write('<dt>Age</dt><dd>%d days, %d active days (%3.2f%%)</dd>' % (data.getCommitDeltaDays(), len(data.getActiveDays()), (100.0 * len(data.getActiveDays()) / data.getCommitDeltaDays())))
583 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
584 f.write('<dt>Total Lines of Code</dt><dd>%s (%d added, %d removed)</dd>' % (data.getTotalLOC(), data.total_lines_added, data.total_lines_removed))
585 f.write('<dt>Total Commits</dt><dd>%s (average %.1f commits per active day, %.1f per all days)</dd>' % (data.getTotalCommits(), float(data.getTotalCommits()) / len(data.getActiveDays()), float(data.getTotalCommits()) / data.getCommitDeltaDays()))
586 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
587 f.write('</dl>')
589 f.write('</body>\n</html>')
590 f.close()
593 # Activity
594 f = open(path + '/activity.html', 'w')
595 self.printHeader(f)
596 f.write('<h1>Activity</h1>')
597 self.printNav(f)
599 #f.write('<h2>Last 30 days</h2>')
601 #f.write('<h2>Last 12 months</h2>')
603 # Weekly activity
604 WEEKS = 32
605 f.write(html_header(2, 'Weekly activity'))
606 f.write('<p>Last %d weeks</p>' % WEEKS)
608 # generate weeks to show (previous N weeks from now)
609 now = datetime.datetime.now()
610 deltaweek = datetime.timedelta(7)
611 weeks = []
612 stampcur = now
613 for i in range(0, WEEKS):
614 weeks.insert(0, stampcur.strftime('%Y-%W'))
615 stampcur -= deltaweek
617 # top row: commits & bar
618 f.write('<table class="noborders"><tr>')
619 for i in range(0, WEEKS):
620 commits = 0
621 if weeks[i] in data.activity_by_year_week:
622 commits = data.activity_by_year_week[weeks[i]]
624 percentage = 0
625 if weeks[i] in data.activity_by_year_week:
626 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
627 height = max(1, int(200 * percentage))
628 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))
630 # bottom row: year/week
631 f.write('</tr><tr>')
632 for i in range(0, WEEKS):
633 f.write('<td>%s</td>' % (WEEKS - i))
634 f.write('</tr></table>')
636 # Hour of Day
637 f.write(html_header(2, 'Hour of Day'))
638 hour_of_day = data.getActivityByHourOfDay()
639 f.write('<table><tr><th>Hour</th>')
640 for i in range(0, 24):
641 f.write('<th>%d</th>' % i)
642 f.write('</tr>\n<tr><th>Commits</th>')
643 fp = open(path + '/hour_of_day.dat', 'w')
644 for i in range(0, 24):
645 if i in hour_of_day:
646 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
647 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
648 fp.write('%d %d\n' % (i, hour_of_day[i]))
649 else:
650 f.write('<td>0</td>')
651 fp.write('%d 0\n' % i)
652 fp.close()
653 f.write('</tr>\n<tr><th>%</th>')
654 totalcommits = data.getTotalCommits()
655 for i in range(0, 24):
656 if i in hour_of_day:
657 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
658 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
659 else:
660 f.write('<td>0.00</td>')
661 f.write('</tr></table>')
662 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
663 fg = open(path + '/hour_of_day.dat', 'w')
664 for i in range(0, 24):
665 if i in hour_of_day:
666 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
667 else:
668 fg.write('%d 0\n' % (i + 1))
669 fg.close()
671 # Day of Week
672 f.write(html_header(2, 'Day of Week'))
673 day_of_week = data.getActivityByDayOfWeek()
674 f.write('<div class="vtable"><table>')
675 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
676 fp = open(path + '/day_of_week.dat', 'w')
677 for d in range(0, 7):
678 commits = 0
679 if d in day_of_week:
680 commits = day_of_week[d]
681 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
682 f.write('<tr>')
683 f.write('<th>%s</th>' % (WEEKDAYS[d]))
684 if d in day_of_week:
685 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
686 else:
687 f.write('<td>0</td>')
688 f.write('</tr>')
689 f.write('</table></div>')
690 f.write('<img src="day_of_week.png" alt="Day of Week" />')
691 fp.close()
693 # Hour of Week
694 f.write(html_header(2, 'Hour of Week'))
695 f.write('<table>')
697 f.write('<tr><th>Weekday</th>')
698 for hour in range(0, 24):
699 f.write('<th>%d</th>' % (hour))
700 f.write('</tr>')
702 for weekday in range(0, 7):
703 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
704 for hour in range(0, 24):
705 try:
706 commits = data.activity_by_hour_of_week[weekday][hour]
707 except KeyError:
708 commits = 0
709 if commits != 0:
710 f.write('<td')
711 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
712 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
713 f.write('>%d</td>' % commits)
714 else:
715 f.write('<td></td>')
716 f.write('</tr>')
718 f.write('</table>')
720 # Month of Year
721 f.write(html_header(2, 'Month of Year'))
722 f.write('<div class="vtable"><table>')
723 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
724 fp = open (path + '/month_of_year.dat', 'w')
725 for mm in range(1, 13):
726 commits = 0
727 if mm in data.activity_by_month_of_year:
728 commits = data.activity_by_month_of_year[mm]
729 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
730 fp.write('%d %d\n' % (mm, commits))
731 fp.close()
732 f.write('</table></div>')
733 f.write('<img src="month_of_year.png" alt="Month of Year" />')
735 # Commits by year/month
736 f.write(html_header(2, 'Commits by year/month'))
737 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
738 for yymm in reversed(sorted(data.commits_by_month.keys())):
739 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
740 f.write('</table></div>')
741 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
742 fg = open(path + '/commits_by_year_month.dat', 'w')
743 for yymm in sorted(data.commits_by_month.keys()):
744 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
745 fg.close()
747 # Commits by year
748 f.write(html_header(2, 'Commits by Year'))
749 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
750 for yy in reversed(sorted(data.commits_by_year.keys())):
751 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()))
752 f.write('</table></div>')
753 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
754 fg = open(path + '/commits_by_year.dat', 'w')
755 for yy in sorted(data.commits_by_year.keys()):
756 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
757 fg.close()
759 # Commits by timezone
760 f.write(html_header(2, 'Commits by Timezone'))
761 f.write('<table><tr>')
762 f.write('<th>Timezone</th><th>Commits</th>')
763 max_commits_on_tz = max(data.commits_by_timezone.values())
764 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
765 commits = data.commits_by_timezone[i]
766 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
767 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
768 f.write('</tr></table>')
770 f.write('</body></html>')
771 f.close()
774 # Authors
775 f = open(path + '/authors.html', 'w')
776 self.printHeader(f)
778 f.write('<h1>Authors</h1>')
779 self.printNav(f)
781 # Authors :: List of authors
782 f.write(html_header(2, 'List of Authors'))
784 f.write('<table class="authors sortable" id="authors">')
785 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>')
786 for author in data.getAuthors(conf['max_authors']):
787 info = data.getAuthorInfo(author)
788 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['commits_frac'], info['lines_added'], info['lines_removed'], info['date_first'], info['date_last'], info['timedelta'], info['active_days'], info['place_by_commits']))
789 f.write('</table>')
791 allauthors = data.getAuthors()
792 if len(allauthors) > conf['max_authors']:
793 rest = allauthors[conf['max_authors']:]
794 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
796 # Authors :: Author of Month
797 f.write(html_header(2, 'Author of Month'))
798 f.write('<table class="sortable" id="aom">')
799 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%%)</th><th class="unsortable">Next top %d</th><th>Number of authors</th></tr>' % conf['authors_top'])
800 for yymm in reversed(sorted(data.author_of_month.keys())):
801 authordict = data.author_of_month[yymm]
802 authors = getkeyssortedbyvalues(authordict)
803 authors.reverse()
804 commits = data.author_of_month[yymm][authors[0]]
805 next = ', '.join(authors[1:conf['authors_top']+1])
806 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td><td>%d</td></tr>' % (yymm, authors[0], commits, (100.0 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm], next, len(authors)))
808 f.write('</table>')
810 f.write(html_header(2, 'Author of Year'))
811 f.write('<table class="sortable" id="aoy"><tr><th>Year</th><th>Author</th><th>Commits (%%)</th><th class="unsortable">Next top %d</th><th>Number of authors</th></tr>' % conf['authors_top'])
812 for yy in reversed(sorted(data.author_of_year.keys())):
813 authordict = data.author_of_year[yy]
814 authors = getkeyssortedbyvalues(authordict)
815 authors.reverse()
816 commits = data.author_of_year[yy][authors[0]]
817 next = ', '.join(authors[1:conf['authors_top']+1])
818 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td><td>%d</td></tr>' % (yy, authors[0], commits, (100.0 * commits) / data.commits_by_year[yy], data.commits_by_year[yy], next, len(authors)))
819 f.write('</table>')
821 # Domains
822 f.write(html_header(2, 'Commits by Domains'))
823 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
824 domains_by_commits.reverse() # most first
825 f.write('<div class="vtable"><table>')
826 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
827 fp = open(path + '/domains.dat', 'w')
828 n = 0
829 for domain in domains_by_commits:
830 if n == conf['max_domains']:
831 break
832 commits = 0
833 n += 1
834 info = data.getDomainInfo(domain)
835 fp.write('%s %d %d\n' % (domain, n , info['commits']))
836 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
837 f.write('</table></div>')
838 f.write('<img src="domains.png" alt="Commits by Domains" />')
839 fp.close()
841 f.write('</body></html>')
842 f.close()
845 # Files
846 f = open(path + '/files.html', 'w')
847 self.printHeader(f)
848 f.write('<h1>Files</h1>')
849 self.printNav(f)
851 f.write('<dl>\n')
852 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
853 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
854 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
855 f.write('</dl>\n')
857 # Files :: File count by date
858 f.write(html_header(2, 'File count by date'))
860 # use set to get rid of duplicate/unnecessary entries
861 files_by_date = set()
862 for stamp in sorted(data.files_by_stamp.keys()):
863 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
865 fg = open(path + '/files_by_date.dat', 'w')
866 for line in sorted(list(files_by_date)):
867 fg.write('%s\n' % line)
868 #for stamp in sorted(data.files_by_stamp.keys()):
869 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
870 fg.close()
872 f.write('<img src="files_by_date.png" alt="Files by Date" />')
874 #f.write('<h2>Average file size by date</h2>')
876 # Files :: Extensions
877 f.write(html_header(2, 'Extensions'))
878 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
879 for ext in sorted(data.extensions.keys()):
880 files = data.extensions[ext]['files']
881 lines = data.extensions[ext]['lines']
882 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))
883 f.write('</table>')
885 f.write('</body></html>')
886 f.close()
889 # Lines
890 f = open(path + '/lines.html', 'w')
891 self.printHeader(f)
892 f.write('<h1>Lines</h1>')
893 self.printNav(f)
895 f.write('<dl>\n')
896 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
897 f.write('</dl>\n')
899 f.write(html_header(2, 'Lines of Code'))
900 f.write('<img src="lines_of_code.png" />')
902 fg = open(path + '/lines_of_code.dat', 'w')
903 for stamp in sorted(data.changes_by_date.keys()):
904 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
905 fg.close()
907 f.write('</body></html>')
908 f.close()
911 # tags.html
912 f = open(path + '/tags.html', 'w')
913 self.printHeader(f)
914 f.write('<h1>Tags</h1>')
915 self.printNav(f)
917 f.write('<dl>')
918 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
919 if len(data.tags) > 0:
920 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
921 f.write('</dl>')
923 f.write('<table class="tags">')
924 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
925 # sort the tags by date desc
926 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
927 for tag in tags_sorted_by_date_desc:
928 authorinfo = []
929 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
930 for i in reversed(authors_by_commits):
931 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
932 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)))
933 f.write('</table>')
935 f.write('</body></html>')
936 f.close()
938 self.createGraphs(path)
940 def createGraphs(self, path):
941 print 'Generating graphs...'
943 # hour of day
944 f = open(path + '/hour_of_day.plot', 'w')
945 f.write(GNUPLOT_COMMON)
946 f.write(
948 set output 'hour_of_day.png'
949 unset key
950 set xrange [0.5:24.5]
951 set xtics 4
952 set grid y
953 set ylabel "Commits"
954 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
955 """)
956 f.close()
958 # day of week
959 f = open(path + '/day_of_week.plot', 'w')
960 f.write(GNUPLOT_COMMON)
961 f.write(
963 set output 'day_of_week.png'
964 unset key
965 set xrange [0.5:7.5]
966 set xtics 1
967 set grid y
968 set ylabel "Commits"
969 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
970 """)
971 f.close()
973 # Domains
974 f = open(path + '/domains.plot', 'w')
975 f.write(GNUPLOT_COMMON)
976 f.write(
978 set output 'domains.png'
979 unset key
980 unset xtics
981 set grid y
982 set ylabel "Commits"
983 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
984 """)
985 f.close()
987 # Month of Year
988 f = open(path + '/month_of_year.plot', 'w')
989 f.write(GNUPLOT_COMMON)
990 f.write(
992 set output 'month_of_year.png'
993 unset key
994 set xrange [0.5:12.5]
995 set xtics 1
996 set grid y
997 set ylabel "Commits"
998 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
999 """)
1000 f.close()
1002 # commits_by_year_month
1003 f = open(path + '/commits_by_year_month.plot', 'w')
1004 f.write(GNUPLOT_COMMON)
1005 f.write(
1007 set output 'commits_by_year_month.png'
1008 unset key
1009 set xdata time
1010 set timefmt "%Y-%m"
1011 set format x "%Y-%m"
1012 set xtics rotate by 90 15768000
1013 set bmargin 5
1014 set grid y
1015 set ylabel "Commits"
1016 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1017 """)
1018 f.close()
1020 # commits_by_year
1021 f = open(path + '/commits_by_year.plot', 'w')
1022 f.write(GNUPLOT_COMMON)
1023 f.write(
1025 set output 'commits_by_year.png'
1026 unset key
1027 set xtics 1 rotate by 90
1028 set grid y
1029 set ylabel "Commits"
1030 set yrange [0:]
1031 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1032 """)
1033 f.close()
1035 # Files by date
1036 f = open(path + '/files_by_date.plot', 'w')
1037 f.write(GNUPLOT_COMMON)
1038 f.write(
1040 set output 'files_by_date.png'
1041 unset key
1042 set xdata time
1043 set timefmt "%Y-%m-%d"
1044 set format x "%Y-%m-%d"
1045 set grid y
1046 set ylabel "Files"
1047 set xtics rotate by 90
1048 set ytics autofreq
1049 set bmargin 6
1050 plot 'files_by_date.dat' using 1:2 w steps
1051 """)
1052 f.close()
1054 # Lines of Code
1055 f = open(path + '/lines_of_code.plot', 'w')
1056 f.write(GNUPLOT_COMMON)
1057 f.write(
1059 set output 'lines_of_code.png'
1060 unset key
1061 set xdata time
1062 set timefmt "%s"
1063 set format x "%Y-%m-%d"
1064 set grid y
1065 set ylabel "Lines"
1066 set xtics rotate by 90
1067 set bmargin 6
1068 plot 'lines_of_code.dat' using 1:2 w lines
1069 """)
1070 f.close()
1072 os.chdir(path)
1073 files = glob.glob(path + '/*.plot')
1074 for f in files:
1075 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1076 if len(out) > 0:
1077 print out
1079 def printHeader(self, f, title = ''):
1080 f.write(
1081 """<?xml version="1.0" encoding="UTF-8"?>
1082 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1083 <html xmlns="http://www.w3.org/1999/xhtml">
1084 <head>
1085 <title>GitStats - %s</title>
1086 <link rel="stylesheet" href="%s" type="text/css" />
1087 <meta name="generator" content="GitStats %s" />
1088 <script type="text/javascript" src="sortable.js"></script>
1089 </head>
1090 <body>
1091 """ % (self.title, conf['style'], getversion()))
1093 def printNav(self, f):
1094 f.write("""
1095 <div class="nav">
1096 <ul>
1097 <li><a href="index.html">General</a></li>
1098 <li><a href="activity.html">Activity</a></li>
1099 <li><a href="authors.html">Authors</a></li>
1100 <li><a href="files.html">Files</a></li>
1101 <li><a href="lines.html">Lines</a></li>
1102 <li><a href="tags.html">Tags</a></li>
1103 </ul>
1104 </div>
1105 """)
1108 class GitStats:
1109 def run(self, args_orig):
1110 optlist, args = getopt.getopt(args_orig, 'c:')
1111 for o,v in optlist:
1112 if o == '-c':
1113 key, value = v.split('=', 1)
1114 if key not in conf:
1115 raise 'Error: no such key "%s" in config' % key
1116 if isinstance(conf[key], int):
1117 conf[key] = int(value)
1118 else:
1119 conf[key] = value
1121 if len(args) < 2:
1122 print """
1123 Usage: gitstats [options] <gitpath> <outputpath>
1125 Options:
1126 -c key=value Override configuration value
1128 Default config values:
1130 """ % conf
1131 sys.exit(0)
1133 gitpath = args[0]
1134 outputpath = os.path.abspath(args[1])
1135 rundir = os.getcwd()
1137 try:
1138 os.makedirs(outputpath)
1139 except OSError:
1140 pass
1141 if not os.path.isdir(outputpath):
1142 print 'FATAL: Output path is not a directory or does not exist'
1143 sys.exit(1)
1145 print 'Git path: %s' % gitpath
1146 print 'Output path: %s' % outputpath
1148 os.chdir(gitpath)
1150 cachefile = os.path.join(outputpath, 'gitstats.cache')
1152 print 'Collecting data...'
1153 data = GitDataCollector()
1154 data.loadCache(cachefile)
1155 data.collect(gitpath)
1156 print 'Refining data...'
1157 data.saveCache(cachefile)
1158 data.refine()
1160 os.chdir(rundir)
1162 print 'Generating report...'
1163 report = HTMLReportCreator()
1164 report.create(data, outputpath)
1166 time_end = time.time()
1167 exectime_internal = time_end - time_start
1168 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1170 g = GitStats()
1171 g.run(sys.argv[1:])