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