Oops, fixed author parsing.
[gitstats.git] / gitstats
blob21809d4e2395078f1e5c02cf3e2962e6738512e2
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 {}
108 # Get a list of authors
109 def getAuthors(self):
110 return []
112 def getFirstCommitDate(self):
113 return datetime.datetime.now()
115 def getLastCommitDate(self):
116 return datetime.datetime.now()
118 def getStampCreated(self):
119 return self.stamp_created
121 def getTags(self):
122 return []
124 def getTotalAuthors(self):
125 return -1
127 def getTotalCommits(self):
128 return -1
130 def getTotalFiles(self):
131 return -1
133 def getTotalLOC(self):
134 return -1
137 # Save cacheable data
138 def saveCache(self, filename):
139 print 'Saving cache...'
140 f = open(cachefile, 'w')
141 #pickle.dump(self.cache, f)
142 data = zlib.compress(pickle.dumps(self.cache))
143 f.write(data)
144 f.close()
146 class GitDataCollector(DataCollector):
147 def collect(self, dir):
148 DataCollector.collect(self, dir)
150 try:
151 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
152 except:
153 self.total_authors = 0
154 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
156 self.activity_by_hour_of_day = {} # hour -> commits
157 self.activity_by_day_of_week = {} # day -> commits
158 self.activity_by_month_of_year = {} # month [1-12] -> commits
159 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
160 self.activity_by_hour_of_day_busiest = 0
161 self.activity_by_hour_of_week_busiest = 0
162 self.activity_by_year_week = {} # yy_wNN -> commits
163 self.activity_by_year_week_peak = 0
165 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days}
167 # author of the month
168 self.author_of_month = {} # month -> author -> commits
169 self.author_of_year = {} # year -> author -> commits
170 self.commits_by_month = {} # month -> commits
171 self.commits_by_year = {} # year -> commits
172 self.first_commit_stamp = 0
173 self.last_commit_stamp = 0
174 self.last_active_day = None
175 self.active_days = 0
177 # timezone
178 self.commits_by_timezone = {} # timezone -> commits
180 # tags
181 self.tags = {}
182 lines = getpipeoutput(['git show-ref --tags']).split('\n')
183 for line in lines:
184 if len(line) == 0:
185 continue
186 (hash, tag) = line.split(' ')
188 tag = tag.replace('refs/tags/', '')
189 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
190 if len(output) > 0:
191 parts = output.split(' ')
192 stamp = 0
193 try:
194 stamp = int(parts[0])
195 except ValueError:
196 stamp = 0
197 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
199 # collect info on tags, starting from latest
200 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
201 prev = None
202 for tag in reversed(tags_sorted_by_date_desc):
203 cmd = 'git shortlog -s "%s"' % tag
204 if prev != None:
205 cmd += ' "^%s"' % prev
206 output = getpipeoutput([cmd])
207 if len(output) == 0:
208 continue
209 prev = tag
210 for line in output.split('\n'):
211 parts = re.split('\s+', line, 2)
212 commits = int(parts[1])
213 author = parts[2]
214 self.tags[tag]['commits'] += commits
215 self.tags[tag]['authors'][author] = commits
217 # Collect revision statistics
218 # Outputs "<stamp> <author>"
219 lines = getpipeoutput(['git rev-list --pretty=format:"%at %ai %an" HEAD', 'grep -v ^commit']).split('\n')
220 for line in lines:
221 # linux-2.6 says "<unknown>" for one line O_o
222 parts = line.split(' ')
223 author = ''
224 try:
225 stamp = int(parts[0])
226 except ValueError:
227 stamp = 0
228 timezone = parts[3]
229 if len(parts) > 4:
230 author = ' '.join(parts[4:])
231 date = datetime.datetime.fromtimestamp(float(stamp))
233 # First and last commit stamp
234 if self.last_commit_stamp == 0:
235 self.last_commit_stamp = stamp
236 self.first_commit_stamp = stamp
238 # activity
239 # hour
240 hour = date.hour
241 if hour in self.activity_by_hour_of_day:
242 self.activity_by_hour_of_day[hour] += 1
243 else:
244 self.activity_by_hour_of_day[hour] = 1
245 # most active hour?
246 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
247 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
249 # day of week
250 day = date.weekday()
251 if day in self.activity_by_day_of_week:
252 self.activity_by_day_of_week[day] += 1
253 else:
254 self.activity_by_day_of_week[day] = 1
256 # hour of week
257 if day not in self.activity_by_hour_of_week:
258 self.activity_by_hour_of_week[day] = {}
259 if hour not in self.activity_by_hour_of_week[day]:
260 self.activity_by_hour_of_week[day][hour] = 1
261 else:
262 self.activity_by_hour_of_week[day][hour] += 1
263 # most active hour?
264 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
265 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
267 # month of year
268 month = date.month
269 if month in self.activity_by_month_of_year:
270 self.activity_by_month_of_year[month] += 1
271 else:
272 self.activity_by_month_of_year[month] = 1
274 # yearly/weekly activity
275 yyw = date.strftime('%Y-%W')
276 if yyw not in self.activity_by_year_week:
277 self.activity_by_year_week[yyw] = 1
278 else:
279 self.activity_by_year_week[yyw] += 1
280 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
281 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
283 # author stats
284 if author not in self.authors:
285 self.authors[author] = {}
286 # commits
287 if 'last_commit_stamp' not in self.authors[author]:
288 self.authors[author]['last_commit_stamp'] = stamp
289 self.authors[author]['first_commit_stamp'] = stamp
290 if 'commits' in self.authors[author]:
291 self.authors[author]['commits'] += 1
292 else:
293 self.authors[author]['commits'] = 1
295 # author of the month/year
296 yymm = date.strftime('%Y-%m')
297 if yymm in self.author_of_month:
298 if author in self.author_of_month[yymm]:
299 self.author_of_month[yymm][author] += 1
300 else:
301 self.author_of_month[yymm][author] = 1
302 else:
303 self.author_of_month[yymm] = {}
304 self.author_of_month[yymm][author] = 1
305 if yymm in self.commits_by_month:
306 self.commits_by_month[yymm] += 1
307 else:
308 self.commits_by_month[yymm] = 1
310 yy = date.year
311 if yy in self.author_of_year:
312 if author in self.author_of_year[yy]:
313 self.author_of_year[yy][author] += 1
314 else:
315 self.author_of_year[yy][author] = 1
316 else:
317 self.author_of_year[yy] = {}
318 self.author_of_year[yy][author] = 1
319 if yy in self.commits_by_year:
320 self.commits_by_year[yy] += 1
321 else:
322 self.commits_by_year[yy] = 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 += 1
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) > 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'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
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 for line in lines:
398 if len(line) == 0:
399 continue
401 # <stamp> <author>
402 if line.find('files changed,') == -1:
403 pos = line.find(' ')
404 if pos != -1:
405 try:
406 (stamp, author) = (int(line[:pos]), line[pos+1:])
407 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
408 except ValueError:
409 print 'Warning: unexpected line "%s"' % line
410 else:
411 print 'Warning: unexpected line "%s"' % line
412 else:
413 numbers = re.findall('\d+', line)
414 if len(numbers) == 3:
415 (files, inserted, deleted) = map(lambda el : int(el), numbers)
416 total_lines += inserted
417 total_lines -= deleted
418 else:
419 print 'Warning: failed to handle line "%s"' % line
420 (files, inserted, deleted) = (0, 0, 0)
421 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
422 self.total_lines = total_lines
424 def refine(self):
425 # authors
426 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
427 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
428 authors_by_commits.reverse() # most first
429 for i, name in enumerate(authors_by_commits):
430 self.authors[name]['place_by_commits'] = i + 1
432 for name in self.authors.keys():
433 a = self.authors[name]
434 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
435 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
436 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
437 delta = date_last - date_first
438 a['date_first'] = date_first.strftime('%Y-%m-%d')
439 a['date_last'] = date_last.strftime('%Y-%m-%d')
440 a['timedelta'] = delta
442 def getActiveDays(self):
443 return self.active_days
445 def getActivityByDayOfWeek(self):
446 return self.activity_by_day_of_week
448 def getActivityByHourOfDay(self):
449 return self.activity_by_hour_of_day
451 def getAuthorInfo(self, author):
452 return self.authors[author]
454 def getAuthors(self):
455 return self.authors.keys()
457 def getCommitDeltaDays(self):
458 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
460 def getFilesInCommit(self, rev):
461 try:
462 res = self.cache['files_in_tree'][rev]
463 except:
464 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
465 if 'files_in_tree' not in self.cache:
466 self.cache['files_in_tree'] = {}
467 self.cache['files_in_tree'][rev] = res
469 return res
471 def getFirstCommitDate(self):
472 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
474 def getLastCommitDate(self):
475 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
477 def getTags(self):
478 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
479 return lines.split('\n')
481 def getTagDate(self, tag):
482 return self.revToDate('tags/' + tag)
484 def getTotalAuthors(self):
485 return self.total_authors
487 def getTotalCommits(self):
488 return self.total_commits
490 def getTotalFiles(self):
491 return self.total_files
493 def getTotalLOC(self):
494 return self.total_lines
496 def revToDate(self, rev):
497 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
498 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
500 class ReportCreator:
501 """Creates the actual report based on given data."""
502 def __init__(self):
503 pass
505 def create(self, data, path):
506 self.data = data
507 self.path = path
509 def html_linkify(text):
510 return text.lower().replace(' ', '_')
512 def html_header(level, text):
513 name = html_linkify(text)
514 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
516 class HTMLReportCreator(ReportCreator):
517 def create(self, data, path):
518 ReportCreator.create(self, data, path)
519 self.title = data.projectname
521 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
522 binarypath = os.path.dirname(os.path.abspath(__file__))
523 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
524 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
525 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
526 for base in basedirs:
527 src = base + '/' + file
528 if os.path.exists(src):
529 shutil.copyfile(src, path + '/' + file)
530 break
531 else:
532 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
534 f = open(path + "/index.html", 'w')
535 format = '%Y-%m-%d %H:%M:%S'
536 self.printHeader(f)
538 f.write('<h1>GitStats - %s</h1>' % data.projectname)
540 self.printNav(f)
542 f.write('<dl>')
543 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
544 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
545 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
546 f.write('<dt>Report Period</dt><dd>%s to %s (%d days, %d active days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays(), data.getActiveDays()))
547 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
548 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
549 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
550 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
551 f.write('</dl>')
553 f.write('</body>\n</html>')
554 f.close()
557 # Activity
558 f = open(path + '/activity.html', 'w')
559 self.printHeader(f)
560 f.write('<h1>Activity</h1>')
561 self.printNav(f)
563 #f.write('<h2>Last 30 days</h2>')
565 #f.write('<h2>Last 12 months</h2>')
567 # Weekly activity
568 WEEKS = 32
569 f.write(html_header(2, 'Weekly activity'))
570 f.write('<p>Last %d weeks</p>' % WEEKS)
572 # generate weeks to show (previous N weeks from now)
573 now = datetime.datetime.now()
574 deltaweek = datetime.timedelta(7)
575 weeks = []
576 stampcur = now
577 for i in range(0, WEEKS):
578 weeks.insert(0, stampcur.strftime('%Y-%W'))
579 stampcur -= deltaweek
581 # top row: commits & bar
582 f.write('<table class="noborders"><tr>')
583 for i in range(0, WEEKS):
584 commits = 0
585 if weeks[i] in data.activity_by_year_week:
586 commits = data.activity_by_year_week[weeks[i]]
588 percentage = 0
589 if weeks[i] in data.activity_by_year_week:
590 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
591 height = max(1, int(200 * percentage))
592 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))
594 # bottom row: year/week
595 f.write('</tr><tr>')
596 for i in range(0, WEEKS):
597 f.write('<td>%s</td>' % (WEEKS - i))
598 f.write('</tr></table>')
600 # Hour of Day
601 f.write(html_header(2, 'Hour of Day'))
602 hour_of_day = data.getActivityByHourOfDay()
603 f.write('<table><tr><th>Hour</th>')
604 for i in range(0, 24):
605 f.write('<th>%d</th>' % i)
606 f.write('</tr>\n<tr><th>Commits</th>')
607 fp = open(path + '/hour_of_day.dat', 'w')
608 for i in range(0, 24):
609 if i in hour_of_day:
610 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
611 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
612 fp.write('%d %d\n' % (i, hour_of_day[i]))
613 else:
614 f.write('<td>0</td>')
615 fp.write('%d 0\n' % i)
616 fp.close()
617 f.write('</tr>\n<tr><th>%</th>')
618 totalcommits = data.getTotalCommits()
619 for i in range(0, 24):
620 if i in hour_of_day:
621 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
622 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
623 else:
624 f.write('<td>0.00</td>')
625 f.write('</tr></table>')
626 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
627 fg = open(path + '/hour_of_day.dat', 'w')
628 for i in range(0, 24):
629 if i in hour_of_day:
630 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
631 else:
632 fg.write('%d 0\n' % (i + 1))
633 fg.close()
635 # Day of Week
636 f.write(html_header(2, 'Day of Week'))
637 day_of_week = data.getActivityByDayOfWeek()
638 f.write('<div class="vtable"><table>')
639 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
640 fp = open(path + '/day_of_week.dat', 'w')
641 for d in range(0, 7):
642 commits = 0
643 if d in day_of_week:
644 commits = day_of_week[d]
645 fp.write('%d %d\n' % (d + 1, commits))
646 f.write('<tr>')
647 f.write('<th>%d</th>' % (d + 1))
648 if d in day_of_week:
649 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
650 else:
651 f.write('<td>0</td>')
652 f.write('</tr>')
653 f.write('</table></div>')
654 f.write('<img src="day_of_week.png" alt="Day of Week" />')
655 fp.close()
657 # Hour of Week
658 f.write(html_header(2, 'Hour of Week'))
659 f.write('<table>')
661 f.write('<tr><th>Weekday</th>')
662 for hour in range(0, 24):
663 f.write('<th>%d</th>' % (hour))
664 f.write('</tr>')
666 for weekday in range(0, 7):
667 f.write('<tr><th>%d</th>' % (weekday + 1))
668 for hour in range(0, 24):
669 try:
670 commits = data.activity_by_hour_of_week[weekday][hour]
671 except KeyError:
672 commits = 0
673 if commits != 0:
674 f.write('<td')
675 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
676 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
677 f.write('>%d</td>' % commits)
678 else:
679 f.write('<td></td>')
680 f.write('</tr>')
682 f.write('</table>')
684 # Month of Year
685 f.write(html_header(2, 'Month of Year'))
686 f.write('<div class="vtable"><table>')
687 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
688 fp = open (path + '/month_of_year.dat', 'w')
689 for mm in range(1, 13):
690 commits = 0
691 if mm in data.activity_by_month_of_year:
692 commits = data.activity_by_month_of_year[mm]
693 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
694 fp.write('%d %d\n' % (mm, commits))
695 fp.close()
696 f.write('</table></div>')
697 f.write('<img src="month_of_year.png" alt="Month of Year" />')
699 # Commits by year/month
700 f.write(html_header(2, 'Commits by year/month'))
701 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
702 for yymm in reversed(sorted(data.commits_by_month.keys())):
703 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
704 f.write('</table></div>')
705 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
706 fg = open(path + '/commits_by_year_month.dat', 'w')
707 for yymm in sorted(data.commits_by_month.keys()):
708 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
709 fg.close()
711 # Commits by year
712 f.write(html_header(2, 'Commits by Year'))
713 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
714 for yy in reversed(sorted(data.commits_by_year.keys())):
715 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()))
716 f.write('</table></div>')
717 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
718 fg = open(path + '/commits_by_year.dat', 'w')
719 for yy in sorted(data.commits_by_year.keys()):
720 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
721 fg.close()
723 # Commits by timezone
724 f.write(html_header(2, 'Commits by Timezone'))
725 f.write('<table><tr>')
726 f.write('<th>Timezone</th><th>Commits</th>')
727 max_commits_on_tz = max(data.commits_by_timezone.values())
728 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
729 commits = data.commits_by_timezone[i]
730 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
731 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
732 f.write('</tr></table>')
734 f.write('</body></html>')
735 f.close()
738 # Authors
739 f = open(path + '/authors.html', 'w')
740 self.printHeader(f)
742 f.write('<h1>Authors</h1>')
743 self.printNav(f)
745 # Authors :: List of authors
746 f.write(html_header(2, 'List of Authors'))
748 f.write('<table class="authors sortable" id="authors">')
749 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th class="unsortable">Age</th><th>Active days</th><th># by commits</th></tr>')
750 for author in sorted(data.getAuthors()):
751 info = data.getAuthorInfo(author)
752 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (author, info['commits'], info['commits_frac'], info['date_first'], info['date_last'], info['timedelta'], info['active_days'], info['place_by_commits']))
753 f.write('</table>')
755 # Authors :: Author of Month
756 f.write(html_header(2, 'Author of Month'))
757 f.write('<table class="sortable" id="aom">')
758 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
759 for yymm in reversed(sorted(data.author_of_month.keys())):
760 authordict = data.author_of_month[yymm]
761 authors = getkeyssortedbyvalues(authordict)
762 authors.reverse()
763 commits = data.author_of_month[yymm][authors[0]]
764 next = ', '.join(authors[1:5])
765 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))
767 f.write('</table>')
769 f.write(html_header(2, 'Author of Year'))
770 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>')
771 for yy in reversed(sorted(data.author_of_year.keys())):
772 authordict = data.author_of_year[yy]
773 authors = getkeyssortedbyvalues(authordict)
774 authors.reverse()
775 commits = data.author_of_year[yy][authors[0]]
776 next = ', '.join(authors[1:5])
777 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))
778 f.write('</table>')
780 f.write('</body></html>')
781 f.close()
784 # Files
785 f = open(path + '/files.html', 'w')
786 self.printHeader(f)
787 f.write('<h1>Files</h1>')
788 self.printNav(f)
790 f.write('<dl>\n')
791 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
792 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
793 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
794 f.write('</dl>\n')
796 # Files :: File count by date
797 f.write(html_header(2, 'File count by date'))
799 fg = open(path + '/files_by_date.dat', 'w')
800 for stamp in sorted(data.files_by_stamp.keys()):
801 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
802 fg.close()
804 f.write('<img src="files_by_date.png" alt="Files by Date" />')
806 #f.write('<h2>Average file size by date</h2>')
808 # Files :: Extensions
809 f.write(html_header(2, 'Extensions'))
810 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
811 for ext in sorted(data.extensions.keys()):
812 files = data.extensions[ext]['files']
813 lines = data.extensions[ext]['lines']
814 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))
815 f.write('</table>')
817 f.write('</body></html>')
818 f.close()
821 # Lines
822 f = open(path + '/lines.html', 'w')
823 self.printHeader(f)
824 f.write('<h1>Lines</h1>')
825 self.printNav(f)
827 f.write('<dl>\n')
828 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
829 f.write('</dl>\n')
831 f.write(html_header(2, 'Lines of Code'))
832 f.write('<img src="lines_of_code.png" />')
834 fg = open(path + '/lines_of_code.dat', 'w')
835 for stamp in sorted(data.changes_by_date.keys()):
836 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
837 fg.close()
839 f.write('</body></html>')
840 f.close()
843 # tags.html
844 f = open(path + '/tags.html', 'w')
845 self.printHeader(f)
846 f.write('<h1>Tags</h1>')
847 self.printNav(f)
849 f.write('<dl>')
850 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
851 if len(data.tags) > 0:
852 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
853 f.write('</dl>')
855 f.write('<table>')
856 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
857 # sort the tags by date desc
858 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
859 for tag in tags_sorted_by_date_desc:
860 authorinfo = []
861 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
862 for i in reversed(authors_by_commits):
863 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
864 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)))
865 f.write('</table>')
867 f.write('</body></html>')
868 f.close()
870 self.createGraphs(path)
872 def createGraphs(self, path):
873 print 'Generating graphs...'
875 # hour of day
876 f = open(path + '/hour_of_day.plot', 'w')
877 f.write(GNUPLOT_COMMON)
878 f.write(
880 set output 'hour_of_day.png'
881 unset key
882 set xrange [0.5:24.5]
883 set xtics 4
884 set ylabel "Commits"
885 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
886 """)
887 f.close()
889 # day of week
890 f = open(path + '/day_of_week.plot', 'w')
891 f.write(GNUPLOT_COMMON)
892 f.write(
894 set output 'day_of_week.png'
895 unset key
896 set xrange [0.5:7.5]
897 set xtics 1
898 set ylabel "Commits"
899 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
900 """)
901 f.close()
903 # Month of Year
904 f = open(path + '/month_of_year.plot', 'w')
905 f.write(GNUPLOT_COMMON)
906 f.write(
908 set output 'month_of_year.png'
909 unset key
910 set xrange [0.5:12.5]
911 set xtics 1
912 set ylabel "Commits"
913 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
914 """)
915 f.close()
917 # commits_by_year_month
918 f = open(path + '/commits_by_year_month.plot', 'w')
919 f.write(GNUPLOT_COMMON)
920 f.write(
922 set output 'commits_by_year_month.png'
923 unset key
924 set xdata time
925 set timefmt "%Y-%m"
926 set format x "%Y-%m"
927 set xtics rotate by 90 15768000
928 set bmargin 5
929 set ylabel "Commits"
930 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
931 """)
932 f.close()
934 # commits_by_year
935 f = open(path + '/commits_by_year.plot', 'w')
936 f.write(GNUPLOT_COMMON)
937 f.write(
939 set output 'commits_by_year.png'
940 unset key
941 set xtics 1
942 set ylabel "Commits"
943 set yrange [0:]
944 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
945 """)
946 f.close()
948 # Files by date
949 f = open(path + '/files_by_date.plot', 'w')
950 f.write(GNUPLOT_COMMON)
951 f.write(
953 set output 'files_by_date.png'
954 unset key
955 set xdata time
956 set timefmt "%Y-%m-%d"
957 set format x "%Y-%m-%d"
958 set ylabel "Files"
959 set xtics rotate by 90
960 set ytics 1
961 set bmargin 6
962 plot 'files_by_date.dat' using 1:2 w steps
963 """)
964 f.close()
966 # Lines of Code
967 f = open(path + '/lines_of_code.plot', 'w')
968 f.write(GNUPLOT_COMMON)
969 f.write(
971 set output 'lines_of_code.png'
972 unset key
973 set xdata time
974 set timefmt "%s"
975 set format x "%Y-%m-%d"
976 set ylabel "Lines"
977 set xtics rotate by 90
978 set bmargin 6
979 plot 'lines_of_code.dat' using 1:2 w lines
980 """)
981 f.close()
983 os.chdir(path)
984 files = glob.glob(path + '/*.plot')
985 for f in files:
986 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
987 if len(out) > 0:
988 print out
990 def printHeader(self, f, title = ''):
991 f.write(
992 """<?xml version="1.0" encoding="UTF-8"?>
993 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
994 <html xmlns="http://www.w3.org/1999/xhtml">
995 <head>
996 <title>GitStats - %s</title>
997 <link rel="stylesheet" href="gitstats.css" type="text/css" />
998 <meta name="generator" content="GitStats %s" />
999 <script type="text/javascript" src="sortable.js"></script>
1000 </head>
1001 <body>
1002 """ % (self.title, getversion()))
1004 def printNav(self, f):
1005 f.write("""
1006 <div class="nav">
1007 <ul>
1008 <li><a href="index.html">General</a></li>
1009 <li><a href="activity.html">Activity</a></li>
1010 <li><a href="authors.html">Authors</a></li>
1011 <li><a href="files.html">Files</a></li>
1012 <li><a href="lines.html">Lines</a></li>
1013 <li><a href="tags.html">Tags</a></li>
1014 </ul>
1015 </div>
1016 """)
1019 usage = """
1020 Usage: gitstats [options] <gitpath> <outputpath>
1022 Options:
1025 if len(sys.argv) < 3:
1026 print usage
1027 sys.exit(0)
1029 gitpath = sys.argv[1]
1030 outputpath = os.path.abspath(sys.argv[2])
1031 rundir = os.getcwd()
1033 try:
1034 os.makedirs(outputpath)
1035 except OSError:
1036 pass
1037 if not os.path.isdir(outputpath):
1038 print 'FATAL: Output path is not a directory or does not exist'
1039 sys.exit(1)
1041 print 'Git path: %s' % gitpath
1042 print 'Output path: %s' % outputpath
1044 os.chdir(gitpath)
1046 cachefile = os.path.join(outputpath, 'gitstats.cache')
1048 print 'Collecting data...'
1049 data = GitDataCollector()
1050 data.loadCache(cachefile)
1051 data.collect(gitpath)
1052 print 'Refining data...'
1053 data.saveCache(cachefile)
1054 data.refine()
1056 os.chdir(rundir)
1058 print 'Generating report...'
1059 report = HTMLReportCreator()
1060 report.create(data, outputpath)
1062 time_end = time.time()
1063 exectime_internal = time_end - time_start
1064 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)