Make project name configurable (-c project_name=foo).
[gitstats.git] / gitstats
blob7675f5860c25249c1c5d0dde885cf1c66c427bfa
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': '',
39 'linear_linestats': 1,
40 'project_name': '',
43 def getpipeoutput(cmds, quiet = False):
44 global exectime_external
45 start = time.time()
46 if not quiet and ON_LINUX and os.isatty(1):
47 print '>> ' + ' | '.join(cmds),
48 sys.stdout.flush()
49 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
50 p = p0
51 for x in cmds[1:]:
52 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
53 p0 = p
54 output = p.communicate()[0]
55 end = time.time()
56 if not quiet:
57 if ON_LINUX and os.isatty(1):
58 print '\r',
59 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
60 exectime_external += (end - start)
61 return output.rstrip('\n')
63 def getcommitrange(defaultrange = 'HEAD', end_only = False):
64 if len(conf['commit_end']) > 0:
65 if end_only or len(conf['commit_begin']) == 0:
66 return conf['commit_end']
67 return '%s..%s' % (conf['commit_begin'], conf['commit_end'])
68 return defaultrange
70 def getkeyssortedbyvalues(dict):
71 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
73 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
74 def getkeyssortedbyvaluekey(d, key):
75 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
77 VERSION = 0
78 def getversion():
79 global VERSION
80 if VERSION == 0:
81 VERSION = getpipeoutput(["git rev-parse --short %s" % getcommitrange('HEAD')]).split('\n')[0]
82 return VERSION
84 class DataCollector:
85 """Manages data collection from a revision control repository."""
86 def __init__(self):
87 self.stamp_created = time.time()
88 self.cache = {}
91 # This should be the main function to extract data from the repository.
92 def collect(self, dir):
93 self.dir = dir
94 if len(conf['project_name']) == 0:
95 self.projectname = os.path.basename(os.path.abspath(dir))
96 else:
97 self.projectname = conf['project_name']
100 # Load cacheable data
101 def loadCache(self, cachefile):
102 if not os.path.exists(cachefile):
103 return
104 print 'Loading cache...'
105 f = open(cachefile, 'rb')
106 try:
107 self.cache = pickle.loads(zlib.decompress(f.read()))
108 except:
109 # temporary hack to upgrade non-compressed caches
110 f.seek(0)
111 self.cache = pickle.load(f)
112 f.close()
115 # Produce any additional statistics from the extracted data.
116 def refine(self):
117 pass
120 # : get a dictionary of author
121 def getAuthorInfo(self, author):
122 return None
124 def getActivityByDayOfWeek(self):
125 return {}
127 def getActivityByHourOfDay(self):
128 return {}
130 # : get a dictionary of domains
131 def getDomainInfo(self, domain):
132 return None
135 # Get a list of authors
136 def getAuthors(self):
137 return []
139 def getFirstCommitDate(self):
140 return datetime.datetime.now()
142 def getLastCommitDate(self):
143 return datetime.datetime.now()
145 def getStampCreated(self):
146 return self.stamp_created
148 def getTags(self):
149 return []
151 def getTotalAuthors(self):
152 return -1
154 def getTotalCommits(self):
155 return -1
157 def getTotalFiles(self):
158 return -1
160 def getTotalLOC(self):
161 return -1
164 # Save cacheable data
165 def saveCache(self, cachefile):
166 print 'Saving cache...'
167 f = open(cachefile, 'wb')
168 #pickle.dump(self.cache, f)
169 data = zlib.compress(pickle.dumps(self.cache))
170 f.write(data)
171 f.close()
173 class GitDataCollector(DataCollector):
174 def collect(self, dir):
175 DataCollector.collect(self, dir)
177 try:
178 self.total_authors = int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
179 except:
180 self.total_authors = 0
181 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
183 self.activity_by_hour_of_day = {} # hour -> commits
184 self.activity_by_day_of_week = {} # day -> commits
185 self.activity_by_month_of_year = {} # month [1-12] -> commits
186 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
187 self.activity_by_hour_of_day_busiest = 0
188 self.activity_by_hour_of_week_busiest = 0
189 self.activity_by_year_week = {} # yy_wNN -> commits
190 self.activity_by_year_week_peak = 0
192 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
194 # domains
195 self.domains = {} # domain -> commits
197 # author of the month
198 self.author_of_month = {} # month -> author -> commits
199 self.author_of_year = {} # year -> author -> commits
200 self.commits_by_month = {} # month -> commits
201 self.commits_by_year = {} # year -> commits
202 self.first_commit_stamp = 0
203 self.last_commit_stamp = 0
204 self.last_active_day = None
205 self.active_days = set()
207 # lines
208 self.total_lines = 0
209 self.total_lines_added = 0
210 self.total_lines_removed = 0
212 # timezone
213 self.commits_by_timezone = {} # timezone -> commits
215 # tags
216 self.tags = {}
217 lines = getpipeoutput(['git show-ref --tags']).split('\n')
218 for line in lines:
219 if len(line) == 0:
220 continue
221 (hash, tag) = line.split(' ')
223 tag = tag.replace('refs/tags/', '')
224 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
225 if len(output) > 0:
226 parts = output.split(' ')
227 stamp = 0
228 try:
229 stamp = int(parts[0])
230 except ValueError:
231 stamp = 0
232 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
234 # collect info on tags, starting from latest
235 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
236 prev = None
237 for tag in reversed(tags_sorted_by_date_desc):
238 cmd = 'git shortlog -s "%s"' % tag
239 if prev != None:
240 cmd += ' "^%s"' % prev
241 output = getpipeoutput([cmd])
242 if len(output) == 0:
243 continue
244 prev = tag
245 for line in output.split('\n'):
246 parts = re.split('\s+', line, 2)
247 commits = int(parts[1])
248 author = parts[2]
249 self.tags[tag]['commits'] += commits
250 self.tags[tag]['authors'][author] = commits
252 # Collect revision statistics
253 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
254 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
255 for line in lines:
256 parts = line.split(' ', 4)
257 author = ''
258 try:
259 stamp = int(parts[0])
260 except ValueError:
261 stamp = 0
262 timezone = parts[3]
263 author, mail = parts[4].split('<', 1)
264 author = author.rstrip()
265 mail = mail.rstrip('>')
266 domain = '?'
267 if mail.find('@') != -1:
268 domain = mail.rsplit('@', 1)[1]
269 date = datetime.datetime.fromtimestamp(float(stamp))
271 # First and last commit stamp
272 if self.last_commit_stamp == 0:
273 self.last_commit_stamp = stamp
274 self.first_commit_stamp = stamp
276 # activity
277 # hour
278 hour = date.hour
279 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
280 # most active hour?
281 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
282 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
284 # day of week
285 day = date.weekday()
286 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
288 # domain stats
289 if domain not in self.domains:
290 self.domains[domain] = {}
291 # commits
292 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
294 # hour of week
295 if day not in self.activity_by_hour_of_week:
296 self.activity_by_hour_of_week[day] = {}
297 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
298 # most active hour?
299 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
300 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
302 # month of year
303 month = date.month
304 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
306 # yearly/weekly activity
307 yyw = date.strftime('%Y-%W')
308 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
309 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
310 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
312 # author stats
313 if author not in self.authors:
314 self.authors[author] = {}
315 # commits
316 if 'last_commit_stamp' not in self.authors[author]:
317 self.authors[author]['last_commit_stamp'] = stamp
318 self.authors[author]['first_commit_stamp'] = stamp
319 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
321 # author of the month/year
322 yymm = date.strftime('%Y-%m')
323 if yymm in self.author_of_month:
324 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
325 else:
326 self.author_of_month[yymm] = {}
327 self.author_of_month[yymm][author] = 1
328 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
330 yy = date.year
331 if yy in self.author_of_year:
332 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
333 else:
334 self.author_of_year[yy] = {}
335 self.author_of_year[yy][author] = 1
336 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
338 # authors: active days
339 yymmdd = date.strftime('%Y-%m-%d')
340 if 'last_active_day' not in self.authors[author]:
341 self.authors[author]['last_active_day'] = yymmdd
342 self.authors[author]['active_days'] = 1
343 elif yymmdd != self.authors[author]['last_active_day']:
344 self.authors[author]['last_active_day'] = yymmdd
345 self.authors[author]['active_days'] += 1
347 # project: active days
348 if yymmdd != self.last_active_day:
349 self.last_active_day = yymmdd
350 self.active_days.add(yymmdd)
352 # timezone
353 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
355 # TODO Optimize this, it's the worst bottleneck
356 # outputs "<stamp> <files>" for each revision
357 self.files_by_stamp = {} # stamp -> files
358 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
359 lines = []
360 for revline in revlines:
361 time, rev = revline.split(' ')
362 linecount = self.getFilesInCommit(rev)
363 lines.append('%d %d' % (int(time), linecount))
365 self.total_commits = len(lines)
366 for line in lines:
367 parts = line.split(' ')
368 if len(parts) != 2:
369 continue
370 (stamp, files) = parts[0:2]
371 try:
372 self.files_by_stamp[int(stamp)] = int(files)
373 except ValueError:
374 print 'Warning: failed to parse line "%s"' % line
376 # extensions
377 self.extensions = {} # extension -> files, lines
378 lines = getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
379 self.total_files = len(lines)
380 for line in lines:
381 if len(line) == 0:
382 continue
383 parts = re.split('\s+', line, 4)
384 sha1 = parts[2]
385 filename = parts[3]
387 if filename.find('.') == -1 or filename.rfind('.') == 0:
388 ext = ''
389 else:
390 ext = filename[(filename.rfind('.') + 1):]
391 if len(ext) > conf['max_ext_length']:
392 ext = ''
394 if ext not in self.extensions:
395 self.extensions[ext] = {'files': 0, 'lines': 0}
397 self.extensions[ext]['files'] += 1
398 try:
399 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
400 except:
401 print 'Warning: Could not count lines for file "%s"' % line
403 # line statistics
404 # outputs:
405 # N files changed, N insertions (+), N deletions(-)
406 # <stamp> <author>
407 self.changes_by_date = {} # stamp -> { files, ins, del }
408 extra = ''
409 if conf['linear_linestats']:
410 extra = '--first-parent -m'
411 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
412 lines.reverse()
413 files = 0; inserted = 0; deleted = 0; total_lines = 0
414 author = None
415 for line in lines:
416 if len(line) == 0:
417 continue
419 # <stamp> <author>
420 if line.find('files changed,') == -1:
421 pos = line.find(' ')
422 if pos != -1:
423 try:
424 (stamp, author) = (int(line[:pos]), line[pos+1:])
425 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
426 if author not in self.authors:
427 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
428 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
429 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
430 files, inserted, deleted = 0, 0, 0
431 except ValueError:
432 print 'Warning: unexpected line "%s"' % line
433 else:
434 print 'Warning: unexpected line "%s"' % line
435 else:
436 numbers = re.findall('\d+', line)
437 if len(numbers) == 3:
438 (files, inserted, deleted) = map(lambda el : int(el), numbers)
439 total_lines += inserted
440 total_lines -= deleted
441 self.total_lines_added += inserted
442 self.total_lines_removed += deleted
443 else:
444 print 'Warning: failed to handle line "%s"' % line
445 (files, inserted, deleted) = (0, 0, 0)
446 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
447 self.total_lines = total_lines
449 def refine(self):
450 # authors
451 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
452 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
453 authors_by_commits.reverse() # most first
454 for i, name in enumerate(authors_by_commits):
455 self.authors[name]['place_by_commits'] = i + 1
457 for name in self.authors.keys():
458 a = self.authors[name]
459 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
460 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
461 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
462 delta = date_last - date_first
463 a['date_first'] = date_first.strftime('%Y-%m-%d')
464 a['date_last'] = date_last.strftime('%Y-%m-%d')
465 a['timedelta'] = delta
466 if 'lines_added' not in a: a['lines_added'] = 0
467 if 'lines_removed' not in a: a['lines_removed'] = 0
469 def getActiveDays(self):
470 return self.active_days
472 def getActivityByDayOfWeek(self):
473 return self.activity_by_day_of_week
475 def getActivityByHourOfDay(self):
476 return self.activity_by_hour_of_day
478 def getAuthorInfo(self, author):
479 return self.authors[author]
481 def getAuthors(self, limit = None):
482 res = getkeyssortedbyvaluekey(self.authors, 'commits')
483 res.reverse()
484 return res[:limit]
486 def getCommitDeltaDays(self):
487 return (self.last_commit_stamp - self.first_commit_stamp) / 86400 + 1
489 def getDomainInfo(self, domain):
490 return self.domains[domain]
492 def getDomains(self):
493 return self.domains.keys()
495 def getFilesInCommit(self, rev):
496 try:
497 res = self.cache['files_in_tree'][rev]
498 except:
499 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
500 if 'files_in_tree' not in self.cache:
501 self.cache['files_in_tree'] = {}
502 self.cache['files_in_tree'][rev] = res
504 return res
506 def getFirstCommitDate(self):
507 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
509 def getLastCommitDate(self):
510 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
512 def getLinesInBlob(self, sha1):
513 try:
514 res = self.cache['lines_in_blob'][sha1]
515 except:
516 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
517 if 'lines_in_blob' not in self.cache:
518 self.cache['lines_in_blob'] = {}
519 self.cache['lines_in_blob'][sha1] = res
520 return res
522 def getTags(self):
523 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
524 return lines.split('\n')
526 def getTagDate(self, tag):
527 return self.revToDate('tags/' + tag)
529 def getTotalAuthors(self):
530 return self.total_authors
532 def getTotalCommits(self):
533 return self.total_commits
535 def getTotalFiles(self):
536 return self.total_files
538 def getTotalLOC(self):
539 return self.total_lines
541 def revToDate(self, rev):
542 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
543 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
545 class ReportCreator:
546 """Creates the actual report based on given data."""
547 def __init__(self):
548 pass
550 def create(self, data, path):
551 self.data = data
552 self.path = path
554 def html_linkify(text):
555 return text.lower().replace(' ', '_')
557 def html_header(level, text):
558 name = html_linkify(text)
559 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
561 class HTMLReportCreator(ReportCreator):
562 def create(self, data, path):
563 ReportCreator.create(self, data, path)
564 self.title = data.projectname
566 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
567 binarypath = os.path.dirname(os.path.abspath(__file__))
568 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
569 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
570 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
571 for base in basedirs:
572 src = base + '/' + file
573 if os.path.exists(src):
574 shutil.copyfile(src, path + '/' + file)
575 break
576 else:
577 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
579 f = open(path + "/index.html", 'w')
580 format = '%Y-%m-%d %H:%M:%S'
581 self.printHeader(f)
583 f.write('<h1>GitStats - %s</h1>' % data.projectname)
585 self.printNav(f)
587 f.write('<dl>')
588 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
589 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
590 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
591 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
592 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())))
593 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
594 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))
595 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()))
596 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
597 f.write('</dl>')
599 f.write('</body>\n</html>')
600 f.close()
603 # Activity
604 f = open(path + '/activity.html', 'w')
605 self.printHeader(f)
606 f.write('<h1>Activity</h1>')
607 self.printNav(f)
609 #f.write('<h2>Last 30 days</h2>')
611 #f.write('<h2>Last 12 months</h2>')
613 # Weekly activity
614 WEEKS = 32
615 f.write(html_header(2, 'Weekly activity'))
616 f.write('<p>Last %d weeks</p>' % WEEKS)
618 # generate weeks to show (previous N weeks from now)
619 now = datetime.datetime.now()
620 deltaweek = datetime.timedelta(7)
621 weeks = []
622 stampcur = now
623 for i in range(0, WEEKS):
624 weeks.insert(0, stampcur.strftime('%Y-%W'))
625 stampcur -= deltaweek
627 # top row: commits & bar
628 f.write('<table class="noborders"><tr>')
629 for i in range(0, WEEKS):
630 commits = 0
631 if weeks[i] in data.activity_by_year_week:
632 commits = data.activity_by_year_week[weeks[i]]
634 percentage = 0
635 if weeks[i] in data.activity_by_year_week:
636 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
637 height = max(1, int(200 * percentage))
638 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))
640 # bottom row: year/week
641 f.write('</tr><tr>')
642 for i in range(0, WEEKS):
643 f.write('<td>%s</td>' % (WEEKS - i))
644 f.write('</tr></table>')
646 # Hour of Day
647 f.write(html_header(2, 'Hour of Day'))
648 hour_of_day = data.getActivityByHourOfDay()
649 f.write('<table><tr><th>Hour</th>')
650 for i in range(0, 24):
651 f.write('<th>%d</th>' % i)
652 f.write('</tr>\n<tr><th>Commits</th>')
653 fp = open(path + '/hour_of_day.dat', 'w')
654 for i in range(0, 24):
655 if i in hour_of_day:
656 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
657 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
658 fp.write('%d %d\n' % (i, hour_of_day[i]))
659 else:
660 f.write('<td>0</td>')
661 fp.write('%d 0\n' % i)
662 fp.close()
663 f.write('</tr>\n<tr><th>%</th>')
664 totalcommits = data.getTotalCommits()
665 for i in range(0, 24):
666 if i in hour_of_day:
667 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
668 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
669 else:
670 f.write('<td>0.00</td>')
671 f.write('</tr></table>')
672 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
673 fg = open(path + '/hour_of_day.dat', 'w')
674 for i in range(0, 24):
675 if i in hour_of_day:
676 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
677 else:
678 fg.write('%d 0\n' % (i + 1))
679 fg.close()
681 # Day of Week
682 f.write(html_header(2, 'Day of Week'))
683 day_of_week = data.getActivityByDayOfWeek()
684 f.write('<div class="vtable"><table>')
685 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
686 fp = open(path + '/day_of_week.dat', 'w')
687 for d in range(0, 7):
688 commits = 0
689 if d in day_of_week:
690 commits = day_of_week[d]
691 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
692 f.write('<tr>')
693 f.write('<th>%s</th>' % (WEEKDAYS[d]))
694 if d in day_of_week:
695 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
696 else:
697 f.write('<td>0</td>')
698 f.write('</tr>')
699 f.write('</table></div>')
700 f.write('<img src="day_of_week.png" alt="Day of Week" />')
701 fp.close()
703 # Hour of Week
704 f.write(html_header(2, 'Hour of Week'))
705 f.write('<table>')
707 f.write('<tr><th>Weekday</th>')
708 for hour in range(0, 24):
709 f.write('<th>%d</th>' % (hour))
710 f.write('</tr>')
712 for weekday in range(0, 7):
713 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
714 for hour in range(0, 24):
715 try:
716 commits = data.activity_by_hour_of_week[weekday][hour]
717 except KeyError:
718 commits = 0
719 if commits != 0:
720 f.write('<td')
721 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
722 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
723 f.write('>%d</td>' % commits)
724 else:
725 f.write('<td></td>')
726 f.write('</tr>')
728 f.write('</table>')
730 # Month of Year
731 f.write(html_header(2, 'Month of Year'))
732 f.write('<div class="vtable"><table>')
733 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
734 fp = open (path + '/month_of_year.dat', 'w')
735 for mm in range(1, 13):
736 commits = 0
737 if mm in data.activity_by_month_of_year:
738 commits = data.activity_by_month_of_year[mm]
739 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
740 fp.write('%d %d\n' % (mm, commits))
741 fp.close()
742 f.write('</table></div>')
743 f.write('<img src="month_of_year.png" alt="Month of Year" />')
745 # Commits by year/month
746 f.write(html_header(2, 'Commits by year/month'))
747 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
748 for yymm in reversed(sorted(data.commits_by_month.keys())):
749 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
750 f.write('</table></div>')
751 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
752 fg = open(path + '/commits_by_year_month.dat', 'w')
753 for yymm in sorted(data.commits_by_month.keys()):
754 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
755 fg.close()
757 # Commits by year
758 f.write(html_header(2, 'Commits by Year'))
759 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
760 for yy in reversed(sorted(data.commits_by_year.keys())):
761 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()))
762 f.write('</table></div>')
763 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
764 fg = open(path + '/commits_by_year.dat', 'w')
765 for yy in sorted(data.commits_by_year.keys()):
766 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
767 fg.close()
769 # Commits by timezone
770 f.write(html_header(2, 'Commits by Timezone'))
771 f.write('<table><tr>')
772 f.write('<th>Timezone</th><th>Commits</th>')
773 max_commits_on_tz = max(data.commits_by_timezone.values())
774 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
775 commits = data.commits_by_timezone[i]
776 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
777 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
778 f.write('</tr></table>')
780 f.write('</body></html>')
781 f.close()
784 # Authors
785 f = open(path + '/authors.html', 'w')
786 self.printHeader(f)
788 f.write('<h1>Authors</h1>')
789 self.printNav(f)
791 # Authors :: List of authors
792 f.write(html_header(2, 'List of Authors'))
794 f.write('<table class="authors sortable" id="authors">')
795 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>')
796 for author in data.getAuthors(conf['max_authors']):
797 info = data.getAuthorInfo(author)
798 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']))
799 f.write('</table>')
801 allauthors = data.getAuthors()
802 if len(allauthors) > conf['max_authors']:
803 rest = allauthors[conf['max_authors']:]
804 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
806 # Authors :: Author of Month
807 f.write(html_header(2, 'Author of Month'))
808 f.write('<table class="sortable" id="aom">')
809 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'])
810 for yymm in reversed(sorted(data.author_of_month.keys())):
811 authordict = data.author_of_month[yymm]
812 authors = getkeyssortedbyvalues(authordict)
813 authors.reverse()
814 commits = data.author_of_month[yymm][authors[0]]
815 next = ', '.join(authors[1:conf['authors_top']+1])
816 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)))
818 f.write('</table>')
820 f.write(html_header(2, 'Author of Year'))
821 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'])
822 for yy in reversed(sorted(data.author_of_year.keys())):
823 authordict = data.author_of_year[yy]
824 authors = getkeyssortedbyvalues(authordict)
825 authors.reverse()
826 commits = data.author_of_year[yy][authors[0]]
827 next = ', '.join(authors[1:conf['authors_top']+1])
828 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)))
829 f.write('</table>')
831 # Domains
832 f.write(html_header(2, 'Commits by Domains'))
833 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
834 domains_by_commits.reverse() # most first
835 f.write('<div class="vtable"><table>')
836 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
837 fp = open(path + '/domains.dat', 'w')
838 n = 0
839 for domain in domains_by_commits:
840 if n == conf['max_domains']:
841 break
842 commits = 0
843 n += 1
844 info = data.getDomainInfo(domain)
845 fp.write('%s %d %d\n' % (domain, n , info['commits']))
846 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
847 f.write('</table></div>')
848 f.write('<img src="domains.png" alt="Commits by Domains" />')
849 fp.close()
851 f.write('</body></html>')
852 f.close()
855 # Files
856 f = open(path + '/files.html', 'w')
857 self.printHeader(f)
858 f.write('<h1>Files</h1>')
859 self.printNav(f)
861 f.write('<dl>\n')
862 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
863 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
864 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
865 f.write('</dl>\n')
867 # Files :: File count by date
868 f.write(html_header(2, 'File count by date'))
870 # use set to get rid of duplicate/unnecessary entries
871 files_by_date = set()
872 for stamp in sorted(data.files_by_stamp.keys()):
873 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
875 fg = open(path + '/files_by_date.dat', 'w')
876 for line in sorted(list(files_by_date)):
877 fg.write('%s\n' % line)
878 #for stamp in sorted(data.files_by_stamp.keys()):
879 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
880 fg.close()
882 f.write('<img src="files_by_date.png" alt="Files by Date" />')
884 #f.write('<h2>Average file size by date</h2>')
886 # Files :: Extensions
887 f.write(html_header(2, 'Extensions'))
888 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
889 for ext in sorted(data.extensions.keys()):
890 files = data.extensions[ext]['files']
891 lines = data.extensions[ext]['lines']
892 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))
893 f.write('</table>')
895 f.write('</body></html>')
896 f.close()
899 # Lines
900 f = open(path + '/lines.html', 'w')
901 self.printHeader(f)
902 f.write('<h1>Lines</h1>')
903 self.printNav(f)
905 f.write('<dl>\n')
906 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
907 f.write('</dl>\n')
909 f.write(html_header(2, 'Lines of Code'))
910 f.write('<img src="lines_of_code.png" />')
912 fg = open(path + '/lines_of_code.dat', 'w')
913 for stamp in sorted(data.changes_by_date.keys()):
914 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
915 fg.close()
917 f.write('</body></html>')
918 f.close()
921 # tags.html
922 f = open(path + '/tags.html', 'w')
923 self.printHeader(f)
924 f.write('<h1>Tags</h1>')
925 self.printNav(f)
927 f.write('<dl>')
928 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
929 if len(data.tags) > 0:
930 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
931 f.write('</dl>')
933 f.write('<table class="tags">')
934 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
935 # sort the tags by date desc
936 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
937 for tag in tags_sorted_by_date_desc:
938 authorinfo = []
939 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
940 for i in reversed(authors_by_commits):
941 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
942 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)))
943 f.write('</table>')
945 f.write('</body></html>')
946 f.close()
948 self.createGraphs(path)
950 def createGraphs(self, path):
951 print 'Generating graphs...'
953 # hour of day
954 f = open(path + '/hour_of_day.plot', 'w')
955 f.write(GNUPLOT_COMMON)
956 f.write(
958 set output 'hour_of_day.png'
959 unset key
960 set xrange [0.5:24.5]
961 set xtics 4
962 set grid y
963 set ylabel "Commits"
964 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
965 """)
966 f.close()
968 # day of week
969 f = open(path + '/day_of_week.plot', 'w')
970 f.write(GNUPLOT_COMMON)
971 f.write(
973 set output 'day_of_week.png'
974 unset key
975 set xrange [0.5:7.5]
976 set xtics 1
977 set grid y
978 set ylabel "Commits"
979 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
980 """)
981 f.close()
983 # Domains
984 f = open(path + '/domains.plot', 'w')
985 f.write(GNUPLOT_COMMON)
986 f.write(
988 set output 'domains.png'
989 unset key
990 unset xtics
991 set yrange [0:]
992 set grid y
993 set ylabel "Commits"
994 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
995 """)
996 f.close()
998 # Month of Year
999 f = open(path + '/month_of_year.plot', 'w')
1000 f.write(GNUPLOT_COMMON)
1001 f.write(
1003 set output 'month_of_year.png'
1004 unset key
1005 set xrange [0.5:12.5]
1006 set xtics 1
1007 set grid y
1008 set ylabel "Commits"
1009 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1010 """)
1011 f.close()
1013 # commits_by_year_month
1014 f = open(path + '/commits_by_year_month.plot', 'w')
1015 f.write(GNUPLOT_COMMON)
1016 f.write(
1018 set output 'commits_by_year_month.png'
1019 unset key
1020 set xdata time
1021 set timefmt "%Y-%m"
1022 set format x "%Y-%m"
1023 set xtics rotate by 90 15768000
1024 set bmargin 5
1025 set grid y
1026 set ylabel "Commits"
1027 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1028 """)
1029 f.close()
1031 # commits_by_year
1032 f = open(path + '/commits_by_year.plot', 'w')
1033 f.write(GNUPLOT_COMMON)
1034 f.write(
1036 set output 'commits_by_year.png'
1037 unset key
1038 set xtics 1 rotate by 90
1039 set grid y
1040 set ylabel "Commits"
1041 set yrange [0:]
1042 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1043 """)
1044 f.close()
1046 # Files by date
1047 f = open(path + '/files_by_date.plot', 'w')
1048 f.write(GNUPLOT_COMMON)
1049 f.write(
1051 set output 'files_by_date.png'
1052 unset key
1053 set xdata time
1054 set timefmt "%Y-%m-%d"
1055 set format x "%Y-%m-%d"
1056 set grid y
1057 set ylabel "Files"
1058 set xtics rotate by 90
1059 set ytics autofreq
1060 set bmargin 6
1061 plot 'files_by_date.dat' using 1:2 w steps
1062 """)
1063 f.close()
1065 # Lines of Code
1066 f = open(path + '/lines_of_code.plot', 'w')
1067 f.write(GNUPLOT_COMMON)
1068 f.write(
1070 set output 'lines_of_code.png'
1071 unset key
1072 set xdata time
1073 set timefmt "%s"
1074 set format x "%Y-%m-%d"
1075 set grid y
1076 set ylabel "Lines"
1077 set xtics rotate by 90
1078 set bmargin 6
1079 plot 'lines_of_code.dat' using 1:2 w lines
1080 """)
1081 f.close()
1083 os.chdir(path)
1084 files = glob.glob(path + '/*.plot')
1085 for f in files:
1086 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1087 if len(out) > 0:
1088 print out
1090 def printHeader(self, f, title = ''):
1091 f.write(
1092 """<?xml version="1.0" encoding="UTF-8"?>
1093 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1094 <html xmlns="http://www.w3.org/1999/xhtml">
1095 <head>
1096 <title>GitStats - %s</title>
1097 <link rel="stylesheet" href="%s" type="text/css" />
1098 <meta name="generator" content="GitStats %s" />
1099 <script type="text/javascript" src="sortable.js"></script>
1100 </head>
1101 <body>
1102 """ % (self.title, conf['style'], getversion()))
1104 def printNav(self, f):
1105 f.write("""
1106 <div class="nav">
1107 <ul>
1108 <li><a href="index.html">General</a></li>
1109 <li><a href="activity.html">Activity</a></li>
1110 <li><a href="authors.html">Authors</a></li>
1111 <li><a href="files.html">Files</a></li>
1112 <li><a href="lines.html">Lines</a></li>
1113 <li><a href="tags.html">Tags</a></li>
1114 </ul>
1115 </div>
1116 """)
1119 class GitStats:
1120 def run(self, args_orig):
1121 optlist, args = getopt.getopt(args_orig, 'c:')
1122 for o,v in optlist:
1123 if o == '-c':
1124 key, value = v.split('=', 1)
1125 if key not in conf:
1126 raise KeyError('no such key "%s" in config' % key)
1127 if isinstance(conf[key], int):
1128 conf[key] = int(value)
1129 else:
1130 conf[key] = value
1132 if len(args) < 2:
1133 print """
1134 Usage: gitstats [options] <gitpath> <outputpath>
1136 Options:
1137 -c key=value Override configuration value
1139 Default config values:
1141 """ % conf
1142 sys.exit(0)
1144 gitpath = args[0]
1145 outputpath = os.path.abspath(args[1])
1146 rundir = os.getcwd()
1148 try:
1149 os.makedirs(outputpath)
1150 except OSError:
1151 pass
1152 if not os.path.isdir(outputpath):
1153 print 'FATAL: Output path is not a directory or does not exist'
1154 sys.exit(1)
1156 print 'Git path: %s' % gitpath
1157 print 'Output path: %s' % outputpath
1159 os.chdir(gitpath)
1161 cachefile = os.path.join(outputpath, 'gitstats.cache')
1163 print 'Collecting data...'
1164 data = GitDataCollector()
1165 data.loadCache(cachefile)
1166 data.collect(gitpath)
1167 print 'Refining data...'
1168 data.saveCache(cachefile)
1169 data.refine()
1171 os.chdir(rundir)
1173 print 'Generating report...'
1174 report = HTMLReportCreator()
1175 report.create(data, outputpath)
1177 time_end = time.time()
1178 exectime_internal = time_end - time_start
1179 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1181 if __name__=='__main__':
1182 g = GitStats()
1183 g.run(sys.argv[1:])