Add a graph for commits per domain.
[gitstats.git] / gitstats
blob3822a8d6b8303f5832e7368e0e00f52652ec13cc
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2009 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
3 # GPLv2 / GPLv3
4 import datetime
5 import glob
6 import os
7 import pickle
8 import platform
9 import re
10 import shutil
11 import subprocess
12 import sys
13 import time
14 import zlib
16 GNUPLOT_COMMON = 'set terminal png transparent\nset size 0.5,0.5\n'
17 MAX_EXT_LENGTH = 10 # maximum file extension length
18 ON_LINUX = (platform.system() == 'Linux')
20 exectime_internal = 0.0
21 exectime_external = 0.0
22 time_start = time.time()
24 # By default, gnuplot is searched from path, but can be overridden with the
25 # environment variable "GNUPLOT"
26 gnuplot_cmd = 'gnuplot'
27 if 'GNUPLOT' in os.environ:
28 gnuplot_cmd = os.environ['GNUPLOT']
30 def getpipeoutput(cmds, quiet = False):
31 global exectime_external
32 start = time.time()
33 if not quiet and ON_LINUX and os.isatty(1):
34 print '>> ' + ' | '.join(cmds),
35 sys.stdout.flush()
36 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
37 p = p0
38 for x in cmds[1:]:
39 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
40 p0 = p
41 output = p.communicate()[0]
42 end = time.time()
43 if not quiet:
44 if ON_LINUX and os.isatty(1):
45 print '\r',
46 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
47 exectime_external += (end - start)
48 return output.rstrip('\n')
50 def getkeyssortedbyvalues(dict):
51 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
53 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
54 def getkeyssortedbyvaluekey(d, key):
55 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
57 VERSION = 0
58 def getversion():
59 global VERSION
60 if VERSION == 0:
61 VERSION = getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
62 return VERSION
64 class DataCollector:
65 """Manages data collection from a revision control repository."""
66 def __init__(self):
67 self.stamp_created = time.time()
68 self.cache = {}
71 # This should be the main function to extract data from the repository.
72 def collect(self, dir):
73 self.dir = dir
74 self.projectname = os.path.basename(os.path.abspath(dir))
77 # Load cacheable data
78 def loadCache(self, cachefile):
79 if not os.path.exists(cachefile):
80 return
81 print 'Loading cache...'
82 f = open(cachefile)
83 try:
84 self.cache = pickle.loads(zlib.decompress(f.read()))
85 except:
86 # temporary hack to upgrade non-compressed caches
87 f.seek(0)
88 self.cache = pickle.load(f)
89 f.close()
92 # Produce any additional statistics from the extracted data.
93 def refine(self):
94 pass
97 # : get a dictionary of author
98 def getAuthorInfo(self, author):
99 return None
101 def getActivityByDayOfWeek(self):
102 return {}
104 def getActivityByHourOfDay(self):
105 return {}
107 # : get a dictionary of domains
108 def getDomainInfo(self, domain):
109 return None
112 # Get a list of authors
113 def getAuthors(self):
114 return []
116 def getFirstCommitDate(self):
117 return datetime.datetime.now()
119 def getLastCommitDate(self):
120 return datetime.datetime.now()
122 def getStampCreated(self):
123 return self.stamp_created
125 def getTags(self):
126 return []
128 def getTotalAuthors(self):
129 return -1
131 def getTotalCommits(self):
132 return -1
134 def getTotalFiles(self):
135 return -1
137 def getTotalLOC(self):
138 return -1
141 # Save cacheable data
142 def saveCache(self, filename):
143 print 'Saving cache...'
144 f = open(cachefile, 'w')
145 #pickle.dump(self.cache, f)
146 data = zlib.compress(pickle.dumps(self.cache))
147 f.write(data)
148 f.close()
150 class GitDataCollector(DataCollector):
151 def collect(self, dir):
152 DataCollector.collect(self, dir)
154 try:
155 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
156 except:
157 self.total_authors = 0
158 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
160 self.activity_by_hour_of_day = {} # hour -> commits
161 self.activity_by_day_of_week = {} # day -> commits
162 self.activity_by_month_of_year = {} # month [1-12] -> commits
163 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
164 self.activity_by_hour_of_day_busiest = 0
165 self.activity_by_hour_of_week_busiest = 0
166 self.activity_by_year_week = {} # yy_wNN -> commits
167 self.activity_by_year_week_peak = 0
169 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
171 # domains
172 self.domains = {} # domain -> commits
174 # author of the month
175 self.author_of_month = {} # month -> author -> commits
176 self.author_of_year = {} # year -> author -> commits
177 self.commits_by_month = {} # month -> commits
178 self.commits_by_year = {} # year -> commits
179 self.first_commit_stamp = 0
180 self.last_commit_stamp = 0
181 self.last_active_day = None
182 self.active_days = set()
184 # lines
185 self.total_lines = 0
186 self.total_lines_added = 0
187 self.total_lines_removed = 0
189 # timezone
190 self.commits_by_timezone = {} # timezone -> commits
192 # tags
193 self.tags = {}
194 lines = getpipeoutput(['git show-ref --tags']).split('\n')
195 for line in lines:
196 if len(line) == 0:
197 continue
198 (hash, tag) = line.split(' ')
200 tag = tag.replace('refs/tags/', '')
201 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
202 if len(output) > 0:
203 parts = output.split(' ')
204 stamp = 0
205 try:
206 stamp = int(parts[0])
207 except ValueError:
208 stamp = 0
209 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
211 # collect info on tags, starting from latest
212 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
213 prev = None
214 for tag in reversed(tags_sorted_by_date_desc):
215 cmd = 'git shortlog -s "%s"' % tag
216 if prev != None:
217 cmd += ' "^%s"' % prev
218 output = getpipeoutput([cmd])
219 if len(output) == 0:
220 continue
221 prev = tag
222 for line in output.split('\n'):
223 parts = re.split('\s+', line, 2)
224 commits = int(parts[1])
225 author = parts[2]
226 self.tags[tag]['commits'] += commits
227 self.tags[tag]['authors'][author] = commits
229 # Collect revision statistics
230 # Outputs "<stamp> <author>"
231 lines = getpipeoutput(['git rev-list --pretty=format:"%at %ai %aE %an" HEAD', 'grep -v ^commit']).split('\n')
232 for line in lines:
233 parts = line.split(' ')
234 author = ''
235 try:
236 stamp = int(parts[0])
237 except ValueError:
238 stamp = 0
239 timezone = parts[3]
240 domain = parts[4].rsplit('@', 1)[1]
241 if len(parts) > 5:
242 author = ' '.join(parts[5:])
243 date = datetime.datetime.fromtimestamp(float(stamp))
245 # First and last commit stamp
246 if self.last_commit_stamp == 0:
247 self.last_commit_stamp = stamp
248 self.first_commit_stamp = stamp
250 # activity
251 # hour
252 hour = date.hour
253 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
254 # most active hour?
255 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
256 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
258 # day of week
259 day = date.weekday()
260 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
262 # domain stats
263 if domain not in self.domains:
264 self.domains[domain] = {}
265 # commits
266 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
268 # hour of week
269 if day not in self.activity_by_hour_of_week:
270 self.activity_by_hour_of_week[day] = {}
271 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
272 # most active hour?
273 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
274 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
276 # month of year
277 month = date.month
278 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
280 # yearly/weekly activity
281 yyw = date.strftime('%Y-%W')
282 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
283 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
284 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
286 # author stats
287 if author not in self.authors:
288 self.authors[author] = {}
289 # commits
290 if 'last_commit_stamp' not in self.authors[author]:
291 self.authors[author]['last_commit_stamp'] = stamp
292 self.authors[author]['first_commit_stamp'] = stamp
293 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
295 # author of the month/year
296 yymm = date.strftime('%Y-%m')
297 if yymm in self.author_of_month:
298 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
299 else:
300 self.author_of_month[yymm] = {}
301 self.author_of_month[yymm][author] = 1
302 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
304 yy = date.year
305 if yy in self.author_of_year:
306 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
307 else:
308 self.author_of_year[yy] = {}
309 self.author_of_year[yy][author] = 1
310 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
312 # authors: active days
313 yymmdd = date.strftime('%Y-%m-%d')
314 if 'last_active_day' not in self.authors[author]:
315 self.authors[author]['last_active_day'] = yymmdd
316 self.authors[author]['active_days'] = 1
317 elif yymmdd != self.authors[author]['last_active_day']:
318 self.authors[author]['last_active_day'] = yymmdd
319 self.authors[author]['active_days'] += 1
321 # project: active days
322 if yymmdd != self.last_active_day:
323 self.last_active_day = yymmdd
324 self.active_days.add(yymmdd)
326 # timezone
327 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
329 # TODO Optimize this, it's the worst bottleneck
330 # outputs "<stamp> <files>" for each revision
331 self.files_by_stamp = {} # stamp -> files
332 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
333 lines = []
334 for revline in revlines:
335 time, rev = revline.split(' ')
336 linecount = self.getFilesInCommit(rev)
337 lines.append('%d %d' % (int(time), linecount))
339 self.total_commits = len(lines)
340 for line in lines:
341 parts = line.split(' ')
342 if len(parts) != 2:
343 continue
344 (stamp, files) = parts[0:2]
345 try:
346 self.files_by_stamp[int(stamp)] = int(files)
347 except ValueError:
348 print 'Warning: failed to parse line "%s"' % line
350 # extensions
351 self.extensions = {} # extension -> files, lines
352 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
353 self.total_files = len(lines)
354 for line in lines:
355 if len(line) == 0:
356 continue
357 parts = re.split('\s+', line, 4)
358 sha1 = parts[2]
359 filename = parts[3]
361 if filename.find('.') == -1 or filename.rfind('.') == 0:
362 ext = ''
363 else:
364 ext = filename[(filename.rfind('.') + 1):]
365 if len(ext) > MAX_EXT_LENGTH:
366 ext = ''
368 if ext not in self.extensions:
369 self.extensions[ext] = {'files': 0, 'lines': 0}
371 self.extensions[ext]['files'] += 1
372 try:
373 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
374 except:
375 print 'Warning: Could not count lines for file "%s"' % line
377 # line statistics
378 # outputs:
379 # N files changed, N insertions (+), N deletions(-)
380 # <stamp> <author>
381 self.changes_by_date = {} # stamp -> { files, ins, del }
382 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
383 lines.reverse()
384 files = 0; inserted = 0; deleted = 0; total_lines = 0
385 author = None
386 for line in lines:
387 if len(line) == 0:
388 continue
390 # <stamp> <author>
391 if line.find('files changed,') == -1:
392 pos = line.find(' ')
393 if pos != -1:
394 try:
395 (stamp, author) = (int(line[:pos]), line[pos+1:])
396 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
397 if author not in self.authors:
398 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
399 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
400 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
401 except ValueError:
402 print 'Warning: unexpected line "%s"' % line
403 else:
404 print 'Warning: unexpected line "%s"' % line
405 else:
406 numbers = re.findall('\d+', line)
407 if len(numbers) == 3:
408 (files, inserted, deleted) = map(lambda el : int(el), numbers)
409 total_lines += inserted
410 total_lines -= deleted
411 self.total_lines_added += inserted
412 self.total_lines_removed += deleted
413 else:
414 print 'Warning: failed to handle line "%s"' % line
415 (files, inserted, deleted) = (0, 0, 0)
416 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
417 self.total_lines = total_lines
419 def refine(self):
420 # authors
421 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
422 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
423 authors_by_commits.reverse() # most first
424 for i, name in enumerate(authors_by_commits):
425 self.authors[name]['place_by_commits'] = i + 1
427 for name in self.authors.keys():
428 a = self.authors[name]
429 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
430 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
431 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
432 delta = date_last - date_first
433 a['date_first'] = date_first.strftime('%Y-%m-%d')
434 a['date_last'] = date_last.strftime('%Y-%m-%d')
435 a['timedelta'] = delta
437 def getActiveDays(self):
438 return self.active_days
440 def getActivityByDayOfWeek(self):
441 return self.activity_by_day_of_week
443 def getActivityByHourOfDay(self):
444 return self.activity_by_hour_of_day
446 def getAuthorInfo(self, author):
447 return self.authors[author]
449 def getAuthors(self):
450 return self.authors.keys()
452 def getCommitDeltaDays(self):
453 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
455 def getDomainInfo(self, domain):
456 return self.domains[domain]
458 def getDomains(self):
459 return self.domains.keys()
461 def getFilesInCommit(self, rev):
462 try:
463 res = self.cache['files_in_tree'][rev]
464 except:
465 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
466 if 'files_in_tree' not in self.cache:
467 self.cache['files_in_tree'] = {}
468 self.cache['files_in_tree'][rev] = res
470 return res
472 def getFirstCommitDate(self):
473 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
475 def getLastCommitDate(self):
476 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
478 def getTags(self):
479 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
480 return lines.split('\n')
482 def getTagDate(self, tag):
483 return self.revToDate('tags/' + tag)
485 def getTotalAuthors(self):
486 return self.total_authors
488 def getTotalCommits(self):
489 return self.total_commits
491 def getTotalFiles(self):
492 return self.total_files
494 def getTotalLOC(self):
495 return self.total_lines
497 def revToDate(self, rev):
498 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
499 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
501 class ReportCreator:
502 """Creates the actual report based on given data."""
503 def __init__(self):
504 pass
506 def create(self, data, path):
507 self.data = data
508 self.path = path
510 def html_linkify(text):
511 return text.lower().replace(' ', '_')
513 def html_header(level, text):
514 name = html_linkify(text)
515 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
517 class HTMLReportCreator(ReportCreator):
518 def create(self, data, path):
519 ReportCreator.create(self, data, path)
520 self.title = data.projectname
522 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
523 binarypath = os.path.dirname(os.path.abspath(__file__))
524 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
525 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
526 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
527 for base in basedirs:
528 src = base + '/' + file
529 if os.path.exists(src):
530 shutil.copyfile(src, path + '/' + file)
531 break
532 else:
533 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
535 f = open(path + "/index.html", 'w')
536 format = '%Y-%m-%d %H:%M:%S'
537 self.printHeader(f)
539 f.write('<h1>GitStats - %s</h1>' % data.projectname)
541 self.printNav(f)
543 f.write('<dl>')
544 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
545 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
546 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
547 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
548 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())))
549 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
550 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))
551 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()))
552 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
553 f.write('</dl>')
555 f.write('</body>\n</html>')
556 f.close()
559 # Activity
560 f = open(path + '/activity.html', 'w')
561 self.printHeader(f)
562 f.write('<h1>Activity</h1>')
563 self.printNav(f)
565 #f.write('<h2>Last 30 days</h2>')
567 #f.write('<h2>Last 12 months</h2>')
569 # Weekly activity
570 WEEKS = 32
571 f.write(html_header(2, 'Weekly activity'))
572 f.write('<p>Last %d weeks</p>' % WEEKS)
574 # generate weeks to show (previous N weeks from now)
575 now = datetime.datetime.now()
576 deltaweek = datetime.timedelta(7)
577 weeks = []
578 stampcur = now
579 for i in range(0, WEEKS):
580 weeks.insert(0, stampcur.strftime('%Y-%W'))
581 stampcur -= deltaweek
583 # top row: commits & bar
584 f.write('<table class="noborders"><tr>')
585 for i in range(0, WEEKS):
586 commits = 0
587 if weeks[i] in data.activity_by_year_week:
588 commits = data.activity_by_year_week[weeks[i]]
590 percentage = 0
591 if weeks[i] in data.activity_by_year_week:
592 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
593 height = max(1, int(200 * percentage))
594 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))
596 # bottom row: year/week
597 f.write('</tr><tr>')
598 for i in range(0, WEEKS):
599 f.write('<td>%s</td>' % (WEEKS - i))
600 f.write('</tr></table>')
602 # Hour of Day
603 f.write(html_header(2, 'Hour of Day'))
604 hour_of_day = data.getActivityByHourOfDay()
605 f.write('<table><tr><th>Hour</th>')
606 for i in range(0, 24):
607 f.write('<th>%d</th>' % i)
608 f.write('</tr>\n<tr><th>Commits</th>')
609 fp = open(path + '/hour_of_day.dat', 'w')
610 for i in range(0, 24):
611 if i in hour_of_day:
612 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
613 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
614 fp.write('%d %d\n' % (i, hour_of_day[i]))
615 else:
616 f.write('<td>0</td>')
617 fp.write('%d 0\n' % i)
618 fp.close()
619 f.write('</tr>\n<tr><th>%</th>')
620 totalcommits = data.getTotalCommits()
621 for i in range(0, 24):
622 if i in hour_of_day:
623 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
624 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
625 else:
626 f.write('<td>0.00</td>')
627 f.write('</tr></table>')
628 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
629 fg = open(path + '/hour_of_day.dat', 'w')
630 for i in range(0, 24):
631 if i in hour_of_day:
632 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
633 else:
634 fg.write('%d 0\n' % (i + 1))
635 fg.close()
637 # Day of Week
638 f.write(html_header(2, 'Day of Week'))
639 day_of_week = data.getActivityByDayOfWeek()
640 f.write('<div class="vtable"><table>')
641 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
642 fp = open(path + '/day_of_week.dat', 'w')
643 for d in range(0, 7):
644 commits = 0
645 if d in day_of_week:
646 commits = day_of_week[d]
647 fp.write('%d %d\n' % (d + 1, commits))
648 f.write('<tr>')
649 f.write('<th>%d</th>' % (d + 1))
650 if d in day_of_week:
651 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
652 else:
653 f.write('<td>0</td>')
654 f.write('</tr>')
655 f.write('</table></div>')
656 f.write('<img src="day_of_week.png" alt="Day of Week" />')
657 fp.close()
659 # Domains
660 f.write(html_header(2, 'Commits by Domains'))
661 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
662 domains_by_commits.reverse() # most first
663 f.write('<div class="vtable"><table>')
664 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
665 fp = open(path + '/domains.dat', 'w')
666 n = 0
667 max_domains = 10
668 for domain in domains_by_commits:
669 if n == max_domains:
670 break
671 commits = 0
672 n += 1
673 info = data.getDomainInfo(domain)
674 fp.write('%s %d %d\n' % (domain, n , info['commits']))
675 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
676 f.write('</table></div>')
677 f.write('<img src="domains.png" alt="Commits by Domains" />')
678 fp.close()
680 # Hour of Week
681 f.write(html_header(2, 'Hour of Week'))
682 f.write('<table>')
684 f.write('<tr><th>Weekday</th>')
685 for hour in range(0, 24):
686 f.write('<th>%d</th>' % (hour))
687 f.write('</tr>')
689 for weekday in range(0, 7):
690 f.write('<tr><th>%d</th>' % (weekday + 1))
691 for hour in range(0, 24):
692 try:
693 commits = data.activity_by_hour_of_week[weekday][hour]
694 except KeyError:
695 commits = 0
696 if commits != 0:
697 f.write('<td')
698 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
699 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
700 f.write('>%d</td>' % commits)
701 else:
702 f.write('<td></td>')
703 f.write('</tr>')
705 f.write('</table>')
707 # Month of Year
708 f.write(html_header(2, 'Month of Year'))
709 f.write('<div class="vtable"><table>')
710 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
711 fp = open (path + '/month_of_year.dat', 'w')
712 for mm in range(1, 13):
713 commits = 0
714 if mm in data.activity_by_month_of_year:
715 commits = data.activity_by_month_of_year[mm]
716 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
717 fp.write('%d %d\n' % (mm, commits))
718 fp.close()
719 f.write('</table></div>')
720 f.write('<img src="month_of_year.png" alt="Month of Year" />')
722 # Commits by year/month
723 f.write(html_header(2, 'Commits by year/month'))
724 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
725 for yymm in reversed(sorted(data.commits_by_month.keys())):
726 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
727 f.write('</table></div>')
728 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
729 fg = open(path + '/commits_by_year_month.dat', 'w')
730 for yymm in sorted(data.commits_by_month.keys()):
731 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
732 fg.close()
734 # Commits by year
735 f.write(html_header(2, 'Commits by Year'))
736 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
737 for yy in reversed(sorted(data.commits_by_year.keys())):
738 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()))
739 f.write('</table></div>')
740 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
741 fg = open(path + '/commits_by_year.dat', 'w')
742 for yy in sorted(data.commits_by_year.keys()):
743 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
744 fg.close()
746 # Commits by timezone
747 f.write(html_header(2, 'Commits by Timezone'))
748 f.write('<table><tr>')
749 f.write('<th>Timezone</th><th>Commits</th>')
750 max_commits_on_tz = max(data.commits_by_timezone.values())
751 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
752 commits = data.commits_by_timezone[i]
753 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
754 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
755 f.write('</tr></table>')
757 f.write('</body></html>')
758 f.close()
761 # Authors
762 f = open(path + '/authors.html', 'w')
763 self.printHeader(f)
765 f.write('<h1>Authors</h1>')
766 self.printNav(f)
768 # Authors :: List of authors
769 f.write(html_header(2, 'List of Authors'))
771 f.write('<table class="authors sortable" id="authors">')
772 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>')
773 for author in sorted(data.getAuthors()):
774 info = data.getAuthorInfo(author)
775 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']))
776 f.write('</table>')
778 # Authors :: Author of Month
779 f.write(html_header(2, 'Author of Month'))
780 f.write('<table class="sortable" id="aom">')
781 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
782 for yymm in reversed(sorted(data.author_of_month.keys())):
783 authordict = data.author_of_month[yymm]
784 authors = getkeyssortedbyvalues(authordict)
785 authors.reverse()
786 commits = data.author_of_month[yymm][authors[0]]
787 next = ', '.join(authors[1:5])
788 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yymm, authors[0], commits, (100.0 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm], next))
790 f.write('</table>')
792 f.write(html_header(2, 'Author of Year'))
793 f.write('<table class="sortable" id="aoy"><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
794 for yy in reversed(sorted(data.author_of_year.keys())):
795 authordict = data.author_of_year[yy]
796 authors = getkeyssortedbyvalues(authordict)
797 authors.reverse()
798 commits = data.author_of_year[yy][authors[0]]
799 next = ', '.join(authors[1:5])
800 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yy, authors[0], commits, (100.0 * commits) / data.commits_by_year[yy], data.commits_by_year[yy], next))
801 f.write('</table>')
803 f.write('</body></html>')
804 f.close()
807 # Files
808 f = open(path + '/files.html', 'w')
809 self.printHeader(f)
810 f.write('<h1>Files</h1>')
811 self.printNav(f)
813 f.write('<dl>\n')
814 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
815 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
816 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
817 f.write('</dl>\n')
819 # Files :: File count by date
820 f.write(html_header(2, 'File count by date'))
822 # use set to get rid of duplicate/unnecessary entries
823 files_by_date = set()
824 for stamp in sorted(data.files_by_stamp.keys()):
825 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
827 fg = open(path + '/files_by_date.dat', 'w')
828 for line in sorted(list(files_by_date)):
829 fg.write('%s\n' % line)
830 #for stamp in sorted(data.files_by_stamp.keys()):
831 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
832 fg.close()
834 f.write('<img src="files_by_date.png" alt="Files by Date" />')
836 #f.write('<h2>Average file size by date</h2>')
838 # Files :: Extensions
839 f.write(html_header(2, 'Extensions'))
840 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
841 for ext in sorted(data.extensions.keys()):
842 files = data.extensions[ext]['files']
843 lines = data.extensions[ext]['lines']
844 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))
845 f.write('</table>')
847 f.write('</body></html>')
848 f.close()
851 # Lines
852 f = open(path + '/lines.html', 'w')
853 self.printHeader(f)
854 f.write('<h1>Lines</h1>')
855 self.printNav(f)
857 f.write('<dl>\n')
858 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
859 f.write('</dl>\n')
861 f.write(html_header(2, 'Lines of Code'))
862 f.write('<img src="lines_of_code.png" />')
864 fg = open(path + '/lines_of_code.dat', 'w')
865 for stamp in sorted(data.changes_by_date.keys()):
866 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
867 fg.close()
869 f.write('</body></html>')
870 f.close()
873 # tags.html
874 f = open(path + '/tags.html', 'w')
875 self.printHeader(f)
876 f.write('<h1>Tags</h1>')
877 self.printNav(f)
879 f.write('<dl>')
880 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
881 if len(data.tags) > 0:
882 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
883 f.write('</dl>')
885 f.write('<table class="tags">')
886 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
887 # sort the tags by date desc
888 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
889 for tag in tags_sorted_by_date_desc:
890 authorinfo = []
891 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
892 for i in reversed(authors_by_commits):
893 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
894 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)))
895 f.write('</table>')
897 f.write('</body></html>')
898 f.close()
900 self.createGraphs(path)
902 def createGraphs(self, path):
903 print 'Generating graphs...'
905 # hour of day
906 f = open(path + '/hour_of_day.plot', 'w')
907 f.write(GNUPLOT_COMMON)
908 f.write(
910 set output 'hour_of_day.png'
911 unset key
912 set xrange [0.5:24.5]
913 set xtics 4
914 set ylabel "Commits"
915 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
916 """)
917 f.close()
919 # day of week
920 f = open(path + '/day_of_week.plot', 'w')
921 f.write(GNUPLOT_COMMON)
922 f.write(
924 set output 'day_of_week.png'
925 unset key
926 set xrange [0.5:7.5]
927 set xtics 1
928 set ylabel "Commits"
929 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
930 """)
931 f.close()
933 # Domains
934 f = open(path + '/domains.plot', 'w')
935 f.write(GNUPLOT_COMMON)
936 f.write(
938 set output 'domains.png'
939 unset key
940 unset xtics
941 set grid y
942 set ylabel "Commits"
943 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
944 """)
945 f.close()
947 # Month of Year
948 f = open(path + '/month_of_year.plot', 'w')
949 f.write(GNUPLOT_COMMON)
950 f.write(
952 set output 'month_of_year.png'
953 unset key
954 set xrange [0.5:12.5]
955 set xtics 1
956 set ylabel "Commits"
957 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
958 """)
959 f.close()
961 # commits_by_year_month
962 f = open(path + '/commits_by_year_month.plot', 'w')
963 f.write(GNUPLOT_COMMON)
964 f.write(
966 set output 'commits_by_year_month.png'
967 unset key
968 set xdata time
969 set timefmt "%Y-%m"
970 set format x "%Y-%m"
971 set xtics rotate by 90 15768000
972 set bmargin 5
973 set ylabel "Commits"
974 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
975 """)
976 f.close()
978 # commits_by_year
979 f = open(path + '/commits_by_year.plot', 'w')
980 f.write(GNUPLOT_COMMON)
981 f.write(
983 set output 'commits_by_year.png'
984 unset key
985 set xtics 1
986 set ylabel "Commits"
987 set yrange [0:]
988 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
989 """)
990 f.close()
992 # Files by date
993 f = open(path + '/files_by_date.plot', 'w')
994 f.write(GNUPLOT_COMMON)
995 f.write(
997 set output 'files_by_date.png'
998 unset key
999 set xdata time
1000 set timefmt "%Y-%m-%d"
1001 set format x "%Y-%m-%d"
1002 set ylabel "Files"
1003 set xtics rotate by 90
1004 set ytics autofreq
1005 set bmargin 6
1006 plot 'files_by_date.dat' using 1:2 w steps
1007 """)
1008 f.close()
1010 # Lines of Code
1011 f = open(path + '/lines_of_code.plot', 'w')
1012 f.write(GNUPLOT_COMMON)
1013 f.write(
1015 set output 'lines_of_code.png'
1016 unset key
1017 set xdata time
1018 set timefmt "%s"
1019 set format x "%Y-%m-%d"
1020 set ylabel "Lines"
1021 set xtics rotate by 90
1022 set bmargin 6
1023 plot 'lines_of_code.dat' using 1:2 w lines
1024 """)
1025 f.close()
1027 os.chdir(path)
1028 files = glob.glob(path + '/*.plot')
1029 for f in files:
1030 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1031 if len(out) > 0:
1032 print out
1034 def printHeader(self, f, title = ''):
1035 f.write(
1036 """<?xml version="1.0" encoding="UTF-8"?>
1037 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1038 <html xmlns="http://www.w3.org/1999/xhtml">
1039 <head>
1040 <title>GitStats - %s</title>
1041 <link rel="stylesheet" href="gitstats.css" type="text/css" />
1042 <meta name="generator" content="GitStats %s" />
1043 <script type="text/javascript" src="sortable.js"></script>
1044 </head>
1045 <body>
1046 """ % (self.title, getversion()))
1048 def printNav(self, f):
1049 f.write("""
1050 <div class="nav">
1051 <ul>
1052 <li><a href="index.html">General</a></li>
1053 <li><a href="activity.html">Activity</a></li>
1054 <li><a href="authors.html">Authors</a></li>
1055 <li><a href="files.html">Files</a></li>
1056 <li><a href="lines.html">Lines</a></li>
1057 <li><a href="tags.html">Tags</a></li>
1058 </ul>
1059 </div>
1060 """)
1063 usage = """
1064 Usage: gitstats [options] <gitpath> <outputpath>
1066 Options:
1069 if len(sys.argv) < 3:
1070 print usage
1071 sys.exit(0)
1073 gitpath = sys.argv[1]
1074 outputpath = os.path.abspath(sys.argv[2])
1075 rundir = os.getcwd()
1077 try:
1078 os.makedirs(outputpath)
1079 except OSError:
1080 pass
1081 if not os.path.isdir(outputpath):
1082 print 'FATAL: Output path is not a directory or does not exist'
1083 sys.exit(1)
1085 print 'Git path: %s' % gitpath
1086 print 'Output path: %s' % outputpath
1088 os.chdir(gitpath)
1090 cachefile = os.path.join(outputpath, 'gitstats.cache')
1092 print 'Collecting data...'
1093 data = GitDataCollector()
1094 data.loadCache(cachefile)
1095 data.collect(gitpath)
1096 print 'Refining data...'
1097 data.saveCache(cachefile)
1098 data.refine()
1100 os.chdir(rundir)
1102 print 'Generating report...'
1103 report = HTMLReportCreator()
1104 report.create(data, outputpath)
1106 time_end = time.time()
1107 exectime_internal = time_end - time_start
1108 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)