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