Files by date: set ytics autofreq.
[gitstats.git] / gitstats
blob6b580866641c8358ed10b59598483b7a503287f5
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, lines_added, lines_removed}
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 = set()
177 # lines
178 self.total_lines = 0
179 self.total_lines_added = 0
180 self.total_lines_removed = 0
182 # timezone
183 self.commits_by_timezone = {} # timezone -> commits
185 # tags
186 self.tags = {}
187 lines = getpipeoutput(['git show-ref --tags']).split('\n')
188 for line in lines:
189 if len(line) == 0:
190 continue
191 (hash, tag) = line.split(' ')
193 tag = tag.replace('refs/tags/', '')
194 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
195 if len(output) > 0:
196 parts = output.split(' ')
197 stamp = 0
198 try:
199 stamp = int(parts[0])
200 except ValueError:
201 stamp = 0
202 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
204 # collect info on tags, starting from latest
205 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
206 prev = None
207 for tag in reversed(tags_sorted_by_date_desc):
208 cmd = 'git shortlog -s "%s"' % tag
209 if prev != None:
210 cmd += ' "^%s"' % prev
211 output = getpipeoutput([cmd])
212 if len(output) == 0:
213 continue
214 prev = tag
215 for line in output.split('\n'):
216 parts = re.split('\s+', line, 2)
217 commits = int(parts[1])
218 author = parts[2]
219 self.tags[tag]['commits'] += commits
220 self.tags[tag]['authors'][author] = commits
222 # Collect revision statistics
223 # Outputs "<stamp> <author>"
224 lines = getpipeoutput(['git rev-list --pretty=format:"%at %ai %an" HEAD', 'grep -v ^commit']).split('\n')
225 for line in lines:
226 parts = line.split(' ')
227 author = ''
228 try:
229 stamp = int(parts[0])
230 except ValueError:
231 stamp = 0
232 timezone = parts[3]
233 if len(parts) > 4:
234 author = ' '.join(parts[4:])
235 date = datetime.datetime.fromtimestamp(float(stamp))
237 # First and last commit stamp
238 if self.last_commit_stamp == 0:
239 self.last_commit_stamp = stamp
240 self.first_commit_stamp = stamp
242 # activity
243 # hour
244 hour = date.hour
245 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
246 # most active hour?
247 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
248 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
250 # day of week
251 day = date.weekday()
252 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
254 # hour of week
255 if day not in self.activity_by_hour_of_week:
256 self.activity_by_hour_of_week[day] = {}
257 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
258 # most active hour?
259 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
260 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
262 # month of year
263 month = date.month
264 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
266 # yearly/weekly activity
267 yyw = date.strftime('%Y-%W')
268 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
269 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
270 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
272 # author stats
273 if author not in self.authors:
274 self.authors[author] = {}
275 # commits
276 if 'last_commit_stamp' not in self.authors[author]:
277 self.authors[author]['last_commit_stamp'] = stamp
278 self.authors[author]['first_commit_stamp'] = stamp
279 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
281 # author of the month/year
282 yymm = date.strftime('%Y-%m')
283 if yymm in self.author_of_month:
284 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
285 else:
286 self.author_of_month[yymm] = {}
287 self.author_of_month[yymm][author] = 1
288 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
290 yy = date.year
291 if yy in self.author_of_year:
292 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
293 else:
294 self.author_of_year[yy] = {}
295 self.author_of_year[yy][author] = 1
296 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
298 # authors: active days
299 yymmdd = date.strftime('%Y-%m-%d')
300 if 'last_active_day' not in self.authors[author]:
301 self.authors[author]['last_active_day'] = yymmdd
302 self.authors[author]['active_days'] = 1
303 elif yymmdd != self.authors[author]['last_active_day']:
304 self.authors[author]['last_active_day'] = yymmdd
305 self.authors[author]['active_days'] += 1
307 # project: active days
308 if yymmdd != self.last_active_day:
309 self.last_active_day = yymmdd
310 self.active_days.add(yymmdd)
312 # timezone
313 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
315 # TODO Optimize this, it's the worst bottleneck
316 # outputs "<stamp> <files>" for each revision
317 self.files_by_stamp = {} # stamp -> files
318 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
319 lines = []
320 for revline in revlines:
321 time, rev = revline.split(' ')
322 linecount = self.getFilesInCommit(rev)
323 lines.append('%d %d' % (int(time), linecount))
325 self.total_commits = len(lines)
326 for line in lines:
327 parts = line.split(' ')
328 if len(parts) != 2:
329 continue
330 (stamp, files) = parts[0:2]
331 try:
332 self.files_by_stamp[int(stamp)] = int(files)
333 except ValueError:
334 print 'Warning: failed to parse line "%s"' % line
336 # extensions
337 self.extensions = {} # extension -> files, lines
338 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
339 self.total_files = len(lines)
340 for line in lines:
341 if len(line) == 0:
342 continue
343 parts = re.split('\s+', line, 4)
344 sha1 = parts[2]
345 filename = parts[3]
347 if filename.find('.') == -1 or filename.rfind('.') == 0:
348 ext = ''
349 else:
350 ext = filename[(filename.rfind('.') + 1):]
351 if len(ext) > MAX_EXT_LENGTH:
352 ext = ''
354 if ext not in self.extensions:
355 self.extensions[ext] = {'files': 0, 'lines': 0}
357 self.extensions[ext]['files'] += 1
358 try:
359 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
360 except:
361 print 'Warning: Could not count lines for file "%s"' % line
363 # line statistics
364 # outputs:
365 # N files changed, N insertions (+), N deletions(-)
366 # <stamp> <author>
367 self.changes_by_date = {} # stamp -> { files, ins, del }
368 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
369 lines.reverse()
370 files = 0; inserted = 0; deleted = 0; total_lines = 0
371 author = None
372 for line in lines:
373 if len(line) == 0:
374 continue
376 # <stamp> <author>
377 if line.find('files changed,') == -1:
378 pos = line.find(' ')
379 if pos != -1:
380 try:
381 (stamp, author) = (int(line[:pos]), line[pos+1:])
382 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
383 if author not in self.authors:
384 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
385 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
386 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
387 except ValueError:
388 print 'Warning: unexpected line "%s"' % line
389 else:
390 print 'Warning: unexpected line "%s"' % line
391 else:
392 numbers = re.findall('\d+', line)
393 if len(numbers) == 3:
394 (files, inserted, deleted) = map(lambda el : int(el), numbers)
395 total_lines += inserted
396 total_lines -= deleted
397 self.total_lines_added += inserted
398 self.total_lines_removed += deleted
399 else:
400 print 'Warning: failed to handle line "%s"' % line
401 (files, inserted, deleted) = (0, 0, 0)
402 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
403 self.total_lines = total_lines
405 def refine(self):
406 # authors
407 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
408 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
409 authors_by_commits.reverse() # most first
410 for i, name in enumerate(authors_by_commits):
411 self.authors[name]['place_by_commits'] = i + 1
413 for name in self.authors.keys():
414 a = self.authors[name]
415 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
416 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
417 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
418 delta = date_last - date_first
419 a['date_first'] = date_first.strftime('%Y-%m-%d')
420 a['date_last'] = date_last.strftime('%Y-%m-%d')
421 a['timedelta'] = delta
423 def getActiveDays(self):
424 return self.active_days
426 def getActivityByDayOfWeek(self):
427 return self.activity_by_day_of_week
429 def getActivityByHourOfDay(self):
430 return self.activity_by_hour_of_day
432 def getAuthorInfo(self, author):
433 return self.authors[author]
435 def getAuthors(self):
436 return self.authors.keys()
438 def getCommitDeltaDays(self):
439 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
441 def getFilesInCommit(self, rev):
442 try:
443 res = self.cache['files_in_tree'][rev]
444 except:
445 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
446 if 'files_in_tree' not in self.cache:
447 self.cache['files_in_tree'] = {}
448 self.cache['files_in_tree'][rev] = res
450 return res
452 def getFirstCommitDate(self):
453 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
455 def getLastCommitDate(self):
456 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
458 def getTags(self):
459 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
460 return lines.split('\n')
462 def getTagDate(self, tag):
463 return self.revToDate('tags/' + tag)
465 def getTotalAuthors(self):
466 return self.total_authors
468 def getTotalCommits(self):
469 return self.total_commits
471 def getTotalFiles(self):
472 return self.total_files
474 def getTotalLOC(self):
475 return self.total_lines
477 def revToDate(self, rev):
478 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
479 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
481 class ReportCreator:
482 """Creates the actual report based on given data."""
483 def __init__(self):
484 pass
486 def create(self, data, path):
487 self.data = data
488 self.path = path
490 def html_linkify(text):
491 return text.lower().replace(' ', '_')
493 def html_header(level, text):
494 name = html_linkify(text)
495 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
497 class HTMLReportCreator(ReportCreator):
498 def create(self, data, path):
499 ReportCreator.create(self, data, path)
500 self.title = data.projectname
502 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
503 binarypath = os.path.dirname(os.path.abspath(__file__))
504 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
505 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
506 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
507 for base in basedirs:
508 src = base + '/' + file
509 if os.path.exists(src):
510 shutil.copyfile(src, path + '/' + file)
511 break
512 else:
513 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
515 f = open(path + "/index.html", 'w')
516 format = '%Y-%m-%d %H:%M:%S'
517 self.printHeader(f)
519 f.write('<h1>GitStats - %s</h1>' % data.projectname)
521 self.printNav(f)
523 f.write('<dl>')
524 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
525 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
526 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
527 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
528 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())))
529 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
530 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))
531 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()))
532 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
533 f.write('</dl>')
535 f.write('</body>\n</html>')
536 f.close()
539 # Activity
540 f = open(path + '/activity.html', 'w')
541 self.printHeader(f)
542 f.write('<h1>Activity</h1>')
543 self.printNav(f)
545 #f.write('<h2>Last 30 days</h2>')
547 #f.write('<h2>Last 12 months</h2>')
549 # Weekly activity
550 WEEKS = 32
551 f.write(html_header(2, 'Weekly activity'))
552 f.write('<p>Last %d weeks</p>' % WEEKS)
554 # generate weeks to show (previous N weeks from now)
555 now = datetime.datetime.now()
556 deltaweek = datetime.timedelta(7)
557 weeks = []
558 stampcur = now
559 for i in range(0, WEEKS):
560 weeks.insert(0, stampcur.strftime('%Y-%W'))
561 stampcur -= deltaweek
563 # top row: commits & bar
564 f.write('<table class="noborders"><tr>')
565 for i in range(0, WEEKS):
566 commits = 0
567 if weeks[i] in data.activity_by_year_week:
568 commits = data.activity_by_year_week[weeks[i]]
570 percentage = 0
571 if weeks[i] in data.activity_by_year_week:
572 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
573 height = max(1, int(200 * percentage))
574 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))
576 # bottom row: year/week
577 f.write('</tr><tr>')
578 for i in range(0, WEEKS):
579 f.write('<td>%s</td>' % (WEEKS - i))
580 f.write('</tr></table>')
582 # Hour of Day
583 f.write(html_header(2, 'Hour of Day'))
584 hour_of_day = data.getActivityByHourOfDay()
585 f.write('<table><tr><th>Hour</th>')
586 for i in range(0, 24):
587 f.write('<th>%d</th>' % i)
588 f.write('</tr>\n<tr><th>Commits</th>')
589 fp = open(path + '/hour_of_day.dat', 'w')
590 for i in range(0, 24):
591 if i in hour_of_day:
592 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
593 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
594 fp.write('%d %d\n' % (i, hour_of_day[i]))
595 else:
596 f.write('<td>0</td>')
597 fp.write('%d 0\n' % i)
598 fp.close()
599 f.write('</tr>\n<tr><th>%</th>')
600 totalcommits = data.getTotalCommits()
601 for i in range(0, 24):
602 if i in hour_of_day:
603 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
604 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
605 else:
606 f.write('<td>0.00</td>')
607 f.write('</tr></table>')
608 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
609 fg = open(path + '/hour_of_day.dat', 'w')
610 for i in range(0, 24):
611 if i in hour_of_day:
612 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
613 else:
614 fg.write('%d 0\n' % (i + 1))
615 fg.close()
617 # Day of Week
618 f.write(html_header(2, 'Day of Week'))
619 day_of_week = data.getActivityByDayOfWeek()
620 f.write('<div class="vtable"><table>')
621 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
622 fp = open(path + '/day_of_week.dat', 'w')
623 for d in range(0, 7):
624 commits = 0
625 if d in day_of_week:
626 commits = day_of_week[d]
627 fp.write('%d %d\n' % (d + 1, commits))
628 f.write('<tr>')
629 f.write('<th>%d</th>' % (d + 1))
630 if d in day_of_week:
631 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
632 else:
633 f.write('<td>0</td>')
634 f.write('</tr>')
635 f.write('</table></div>')
636 f.write('<img src="day_of_week.png" alt="Day of Week" />')
637 fp.close()
639 # Hour of Week
640 f.write(html_header(2, 'Hour of Week'))
641 f.write('<table>')
643 f.write('<tr><th>Weekday</th>')
644 for hour in range(0, 24):
645 f.write('<th>%d</th>' % (hour))
646 f.write('</tr>')
648 for weekday in range(0, 7):
649 f.write('<tr><th>%d</th>' % (weekday + 1))
650 for hour in range(0, 24):
651 try:
652 commits = data.activity_by_hour_of_week[weekday][hour]
653 except KeyError:
654 commits = 0
655 if commits != 0:
656 f.write('<td')
657 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
658 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
659 f.write('>%d</td>' % commits)
660 else:
661 f.write('<td></td>')
662 f.write('</tr>')
664 f.write('</table>')
666 # Month of Year
667 f.write(html_header(2, 'Month of Year'))
668 f.write('<div class="vtable"><table>')
669 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
670 fp = open (path + '/month_of_year.dat', 'w')
671 for mm in range(1, 13):
672 commits = 0
673 if mm in data.activity_by_month_of_year:
674 commits = data.activity_by_month_of_year[mm]
675 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
676 fp.write('%d %d\n' % (mm, commits))
677 fp.close()
678 f.write('</table></div>')
679 f.write('<img src="month_of_year.png" alt="Month of Year" />')
681 # Commits by year/month
682 f.write(html_header(2, 'Commits by year/month'))
683 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
684 for yymm in reversed(sorted(data.commits_by_month.keys())):
685 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
686 f.write('</table></div>')
687 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
688 fg = open(path + '/commits_by_year_month.dat', 'w')
689 for yymm in sorted(data.commits_by_month.keys()):
690 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
691 fg.close()
693 # Commits by year
694 f.write(html_header(2, 'Commits by Year'))
695 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
696 for yy in reversed(sorted(data.commits_by_year.keys())):
697 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()))
698 f.write('</table></div>')
699 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
700 fg = open(path + '/commits_by_year.dat', 'w')
701 for yy in sorted(data.commits_by_year.keys()):
702 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
703 fg.close()
705 # Commits by timezone
706 f.write(html_header(2, 'Commits by Timezone'))
707 f.write('<table><tr>')
708 f.write('<th>Timezone</th><th>Commits</th>')
709 max_commits_on_tz = max(data.commits_by_timezone.values())
710 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
711 commits = data.commits_by_timezone[i]
712 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
713 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
714 f.write('</tr></table>')
716 f.write('</body></html>')
717 f.close()
720 # Authors
721 f = open(path + '/authors.html', 'w')
722 self.printHeader(f)
724 f.write('<h1>Authors</h1>')
725 self.printNav(f)
727 # Authors :: List of authors
728 f.write(html_header(2, 'List of Authors'))
730 f.write('<table class="authors sortable" id="authors">')
731 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>')
732 for author in sorted(data.getAuthors()):
733 info = data.getAuthorInfo(author)
734 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['lines_added'], info['lines_removed'], info['commits_frac'], info['date_first'], info['date_last'], info['timedelta'], info['active_days'], info['place_by_commits']))
735 f.write('</table>')
737 # Authors :: Author of Month
738 f.write(html_header(2, 'Author of Month'))
739 f.write('<table class="sortable" id="aom">')
740 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
741 for yymm in reversed(sorted(data.author_of_month.keys())):
742 authordict = data.author_of_month[yymm]
743 authors = getkeyssortedbyvalues(authordict)
744 authors.reverse()
745 commits = data.author_of_month[yymm][authors[0]]
746 next = ', '.join(authors[1:5])
747 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))
749 f.write('</table>')
751 f.write(html_header(2, 'Author of Year'))
752 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>')
753 for yy in reversed(sorted(data.author_of_year.keys())):
754 authordict = data.author_of_year[yy]
755 authors = getkeyssortedbyvalues(authordict)
756 authors.reverse()
757 commits = data.author_of_year[yy][authors[0]]
758 next = ', '.join(authors[1:5])
759 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))
760 f.write('</table>')
762 f.write('</body></html>')
763 f.close()
766 # Files
767 f = open(path + '/files.html', 'w')
768 self.printHeader(f)
769 f.write('<h1>Files</h1>')
770 self.printNav(f)
772 f.write('<dl>\n')
773 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
774 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
775 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
776 f.write('</dl>\n')
778 # Files :: File count by date
779 f.write(html_header(2, 'File count by date'))
781 # use set to get rid of duplicate/unnecessary entries
782 files_by_date = set()
783 for stamp in sorted(data.files_by_stamp.keys()):
784 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
786 fg = open(path + '/files_by_date.dat', 'w')
787 for line in sorted(list(files_by_date)):
788 fg.write('%s\n' % line)
789 #for stamp in sorted(data.files_by_stamp.keys()):
790 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
791 fg.close()
793 f.write('<img src="files_by_date.png" alt="Files by Date" />')
795 #f.write('<h2>Average file size by date</h2>')
797 # Files :: Extensions
798 f.write(html_header(2, 'Extensions'))
799 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
800 for ext in sorted(data.extensions.keys()):
801 files = data.extensions[ext]['files']
802 lines = data.extensions[ext]['lines']
803 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))
804 f.write('</table>')
806 f.write('</body></html>')
807 f.close()
810 # Lines
811 f = open(path + '/lines.html', 'w')
812 self.printHeader(f)
813 f.write('<h1>Lines</h1>')
814 self.printNav(f)
816 f.write('<dl>\n')
817 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
818 f.write('</dl>\n')
820 f.write(html_header(2, 'Lines of Code'))
821 f.write('<img src="lines_of_code.png" />')
823 fg = open(path + '/lines_of_code.dat', 'w')
824 for stamp in sorted(data.changes_by_date.keys()):
825 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
826 fg.close()
828 f.write('</body></html>')
829 f.close()
832 # tags.html
833 f = open(path + '/tags.html', 'w')
834 self.printHeader(f)
835 f.write('<h1>Tags</h1>')
836 self.printNav(f)
838 f.write('<dl>')
839 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
840 if len(data.tags) > 0:
841 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
842 f.write('</dl>')
844 f.write('<table class="tags">')
845 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
846 # sort the tags by date desc
847 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
848 for tag in tags_sorted_by_date_desc:
849 authorinfo = []
850 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
851 for i in reversed(authors_by_commits):
852 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
853 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)))
854 f.write('</table>')
856 f.write('</body></html>')
857 f.close()
859 self.createGraphs(path)
861 def createGraphs(self, path):
862 print 'Generating graphs...'
864 # hour of day
865 f = open(path + '/hour_of_day.plot', 'w')
866 f.write(GNUPLOT_COMMON)
867 f.write(
869 set output 'hour_of_day.png'
870 unset key
871 set xrange [0.5:24.5]
872 set xtics 4
873 set ylabel "Commits"
874 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
875 """)
876 f.close()
878 # day of week
879 f = open(path + '/day_of_week.plot', 'w')
880 f.write(GNUPLOT_COMMON)
881 f.write(
883 set output 'day_of_week.png'
884 unset key
885 set xrange [0.5:7.5]
886 set xtics 1
887 set ylabel "Commits"
888 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
889 """)
890 f.close()
892 # Month of Year
893 f = open(path + '/month_of_year.plot', 'w')
894 f.write(GNUPLOT_COMMON)
895 f.write(
897 set output 'month_of_year.png'
898 unset key
899 set xrange [0.5:12.5]
900 set xtics 1
901 set ylabel "Commits"
902 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
903 """)
904 f.close()
906 # commits_by_year_month
907 f = open(path + '/commits_by_year_month.plot', 'w')
908 f.write(GNUPLOT_COMMON)
909 f.write(
911 set output 'commits_by_year_month.png'
912 unset key
913 set xdata time
914 set timefmt "%Y-%m"
915 set format x "%Y-%m"
916 set xtics rotate by 90 15768000
917 set bmargin 5
918 set ylabel "Commits"
919 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
920 """)
921 f.close()
923 # commits_by_year
924 f = open(path + '/commits_by_year.plot', 'w')
925 f.write(GNUPLOT_COMMON)
926 f.write(
928 set output 'commits_by_year.png'
929 unset key
930 set xtics 1
931 set ylabel "Commits"
932 set yrange [0:]
933 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
934 """)
935 f.close()
937 # Files by date
938 f = open(path + '/files_by_date.plot', 'w')
939 f.write(GNUPLOT_COMMON)
940 f.write(
942 set output 'files_by_date.png'
943 unset key
944 set xdata time
945 set timefmt "%Y-%m-%d"
946 set format x "%Y-%m-%d"
947 set ylabel "Files"
948 set xtics rotate by 90
949 set ytics autofreq
950 set bmargin 6
951 plot 'files_by_date.dat' using 1:2 w steps
952 """)
953 f.close()
955 # Lines of Code
956 f = open(path + '/lines_of_code.plot', 'w')
957 f.write(GNUPLOT_COMMON)
958 f.write(
960 set output 'lines_of_code.png'
961 unset key
962 set xdata time
963 set timefmt "%s"
964 set format x "%Y-%m-%d"
965 set ylabel "Lines"
966 set xtics rotate by 90
967 set bmargin 6
968 plot 'lines_of_code.dat' using 1:2 w lines
969 """)
970 f.close()
972 os.chdir(path)
973 files = glob.glob(path + '/*.plot')
974 for f in files:
975 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
976 if len(out) > 0:
977 print out
979 def printHeader(self, f, title = ''):
980 f.write(
981 """<?xml version="1.0" encoding="UTF-8"?>
982 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
983 <html xmlns="http://www.w3.org/1999/xhtml">
984 <head>
985 <title>GitStats - %s</title>
986 <link rel="stylesheet" href="gitstats.css" type="text/css" />
987 <meta name="generator" content="GitStats %s" />
988 <script type="text/javascript" src="sortable.js"></script>
989 </head>
990 <body>
991 """ % (self.title, getversion()))
993 def printNav(self, f):
994 f.write("""
995 <div class="nav">
996 <ul>
997 <li><a href="index.html">General</a></li>
998 <li><a href="activity.html">Activity</a></li>
999 <li><a href="authors.html">Authors</a></li>
1000 <li><a href="files.html">Files</a></li>
1001 <li><a href="lines.html">Lines</a></li>
1002 <li><a href="tags.html">Tags</a></li>
1003 </ul>
1004 </div>
1005 """)
1008 usage = """
1009 Usage: gitstats [options] <gitpath> <outputpath>
1011 Options:
1014 if len(sys.argv) < 3:
1015 print usage
1016 sys.exit(0)
1018 gitpath = sys.argv[1]
1019 outputpath = os.path.abspath(sys.argv[2])
1020 rundir = os.getcwd()
1022 try:
1023 os.makedirs(outputpath)
1024 except OSError:
1025 pass
1026 if not os.path.isdir(outputpath):
1027 print 'FATAL: Output path is not a directory or does not exist'
1028 sys.exit(1)
1030 print 'Git path: %s' % gitpath
1031 print 'Output path: %s' % outputpath
1033 os.chdir(gitpath)
1035 cachefile = os.path.join(outputpath, 'gitstats.cache')
1037 print 'Collecting data...'
1038 data = GitDataCollector()
1039 data.loadCache(cachefile)
1040 data.collect(gitpath)
1041 print 'Refining data...'
1042 data.saveCache(cachefile)
1043 data.refine()
1045 os.chdir(rundir)
1047 print 'Generating report...'
1048 report = HTMLReportCreator()
1049 report.create(data, outputpath)
1051 time_end = time.time()
1052 exectime_internal = time_end - time_start
1053 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)