CSS: tweaked style.
[gitstats.git] / gitstats
blob8f7b4a7c212cac2622c02b2fbfd86203cf60acc8
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 # tags
178 self.tags = {}
179 lines = getpipeoutput(['git show-ref --tags']).split('\n')
180 for line in lines:
181 if len(line) == 0:
182 continue
183 (hash, tag) = line.split(' ')
185 tag = tag.replace('refs/tags/', '')
186 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
187 if len(output) > 0:
188 parts = output.split(' ')
189 stamp = 0
190 try:
191 stamp = int(parts[0])
192 except ValueError:
193 stamp = 0
194 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
196 # collect info on tags, starting from latest
197 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
198 prev = None
199 for tag in reversed(tags_sorted_by_date_desc):
200 cmd = 'git shortlog -s "%s"' % tag
201 if prev != None:
202 cmd += ' "^%s"' % prev
203 output = getpipeoutput([cmd])
204 if len(output) == 0:
205 continue
206 prev = tag
207 for line in output.split('\n'):
208 parts = re.split('\s+', line, 2)
209 commits = int(parts[1])
210 author = parts[2]
211 self.tags[tag]['commits'] += commits
212 self.tags[tag]['authors'][author] = commits
214 # Collect revision statistics
215 # Outputs "<stamp> <author>"
216 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
217 for line in lines:
218 # linux-2.6 says "<unknown>" for one line O_o
219 parts = line.split(' ')
220 author = ''
221 try:
222 stamp = int(parts[0])
223 except ValueError:
224 stamp = 0
225 if len(parts) > 1:
226 author = ' '.join(parts[1:])
227 date = datetime.datetime.fromtimestamp(float(stamp))
229 # First and last commit stamp
230 if self.last_commit_stamp == 0:
231 self.last_commit_stamp = stamp
232 self.first_commit_stamp = stamp
234 # activity
235 # hour
236 hour = date.hour
237 if hour in self.activity_by_hour_of_day:
238 self.activity_by_hour_of_day[hour] += 1
239 else:
240 self.activity_by_hour_of_day[hour] = 1
241 # most active hour?
242 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
243 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
245 # day of week
246 day = date.weekday()
247 if day in self.activity_by_day_of_week:
248 self.activity_by_day_of_week[day] += 1
249 else:
250 self.activity_by_day_of_week[day] = 1
252 # hour of week
253 if day not in self.activity_by_hour_of_week:
254 self.activity_by_hour_of_week[day] = {}
255 if hour not in self.activity_by_hour_of_week[day]:
256 self.activity_by_hour_of_week[day][hour] = 1
257 else:
258 self.activity_by_hour_of_week[day][hour] += 1
259 # most active hour?
260 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
261 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
263 # month of year
264 month = date.month
265 if month in self.activity_by_month_of_year:
266 self.activity_by_month_of_year[month] += 1
267 else:
268 self.activity_by_month_of_year[month] = 1
270 # yearly/weekly activity
271 yyw = date.strftime('%Y-%W')
272 if yyw not in self.activity_by_year_week:
273 self.activity_by_year_week[yyw] = 1
274 else:
275 self.activity_by_year_week[yyw] += 1
276 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
277 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
279 # author stats
280 if author not in self.authors:
281 self.authors[author] = {}
282 # commits
283 if 'last_commit_stamp' not in self.authors[author]:
284 self.authors[author]['last_commit_stamp'] = stamp
285 self.authors[author]['first_commit_stamp'] = stamp
286 if 'commits' in self.authors[author]:
287 self.authors[author]['commits'] += 1
288 else:
289 self.authors[author]['commits'] = 1
291 # author of the month/year
292 yymm = date.strftime('%Y-%m')
293 if yymm in self.author_of_month:
294 if author in self.author_of_month[yymm]:
295 self.author_of_month[yymm][author] += 1
296 else:
297 self.author_of_month[yymm][author] = 1
298 else:
299 self.author_of_month[yymm] = {}
300 self.author_of_month[yymm][author] = 1
301 if yymm in self.commits_by_month:
302 self.commits_by_month[yymm] += 1
303 else:
304 self.commits_by_month[yymm] = 1
306 yy = date.year
307 if yy in self.author_of_year:
308 if author in self.author_of_year[yy]:
309 self.author_of_year[yy][author] += 1
310 else:
311 self.author_of_year[yy][author] = 1
312 else:
313 self.author_of_year[yy] = {}
314 self.author_of_year[yy][author] = 1
315 if yy in self.commits_by_year:
316 self.commits_by_year[yy] += 1
317 else:
318 self.commits_by_year[yy] = 1
320 # authors: active days
321 yymmdd = date.strftime('%Y-%m-%d')
322 if 'last_active_day' not in self.authors[author]:
323 self.authors[author]['last_active_day'] = yymmdd
324 self.authors[author]['active_days'] = 1
325 elif yymmdd != self.authors[author]['last_active_day']:
326 self.authors[author]['last_active_day'] = yymmdd
327 self.authors[author]['active_days'] += 1
329 # project: active days
330 if yymmdd != self.last_active_day:
331 self.last_active_day = yymmdd
332 self.active_days += 1
334 # TODO Optimize this, it's the worst bottleneck
335 # outputs "<stamp> <files>" for each revision
336 self.files_by_stamp = {} # stamp -> files
337 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
338 lines = []
339 for revline in revlines:
340 time, rev = revline.split(' ')
341 linecount = self.getFilesInCommit(rev)
342 lines.append('%d %d' % (int(time), linecount))
344 self.total_commits = len(lines)
345 for line in lines:
346 parts = line.split(' ')
347 if len(parts) != 2:
348 continue
349 (stamp, files) = parts[0:2]
350 try:
351 self.files_by_stamp[int(stamp)] = int(files)
352 except ValueError:
353 print 'Warning: failed to parse line "%s"' % line
355 # extensions
356 self.extensions = {} # extension -> files, lines
357 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
358 self.total_files = len(lines)
359 for line in lines:
360 if len(line) == 0:
361 continue
362 parts = re.split('\s+', line, 4)
363 sha1 = parts[2]
364 filename = parts[3]
366 if filename.find('.') == -1 or filename.rfind('.') == 0:
367 ext = ''
368 else:
369 ext = filename[(filename.rfind('.') + 1):]
370 if len(ext) > MAX_EXT_LENGTH:
371 ext = ''
373 if ext not in self.extensions:
374 self.extensions[ext] = {'files': 0, 'lines': 0}
376 self.extensions[ext]['files'] += 1
377 try:
378 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
379 except:
380 print 'Warning: Could not count lines for file "%s"' % line
382 # line statistics
383 # outputs:
384 # N files changed, N insertions (+), N deletions(-)
385 # <stamp> <author>
386 self.changes_by_date = {} # stamp -> { files, ins, del }
387 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
388 lines.reverse()
389 files = 0; inserted = 0; deleted = 0; total_lines = 0
390 for line in lines:
391 if len(line) == 0:
392 continue
394 # <stamp> <author>
395 if line.find('files changed,') == -1:
396 pos = line.find(' ')
397 if pos != -1:
398 try:
399 (stamp, author) = (int(line[:pos]), line[pos+1:])
400 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
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 else:
412 print 'Warning: failed to handle line "%s"' % line
413 (files, inserted, deleted) = (0, 0, 0)
414 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
415 self.total_lines = total_lines
417 def refine(self):
418 # authors
419 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
420 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
421 authors_by_commits.reverse() # most first
422 for i, name in enumerate(authors_by_commits):
423 self.authors[name]['place_by_commits'] = i + 1
425 for name in self.authors.keys():
426 a = self.authors[name]
427 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
428 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
429 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
430 delta = date_last - date_first
431 a['date_first'] = date_first.strftime('%Y-%m-%d')
432 a['date_last'] = date_last.strftime('%Y-%m-%d')
433 a['timedelta'] = delta
435 def getActiveDays(self):
436 return self.active_days
438 def getActivityByDayOfWeek(self):
439 return self.activity_by_day_of_week
441 def getActivityByHourOfDay(self):
442 return self.activity_by_hour_of_day
444 def getAuthorInfo(self, author):
445 return self.authors[author]
447 def getAuthors(self):
448 return self.authors.keys()
450 def getCommitDeltaDays(self):
451 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
453 def getFilesInCommit(self, rev):
454 try:
455 res = self.cache['files_in_tree'][rev]
456 except:
457 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
458 if 'files_in_tree' not in self.cache:
459 self.cache['files_in_tree'] = {}
460 self.cache['files_in_tree'][rev] = res
462 return res
464 def getFirstCommitDate(self):
465 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
467 def getLastCommitDate(self):
468 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
470 def getTags(self):
471 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
472 return lines.split('\n')
474 def getTagDate(self, tag):
475 return self.revToDate('tags/' + tag)
477 def getTotalAuthors(self):
478 return self.total_authors
480 def getTotalCommits(self):
481 return self.total_commits
483 def getTotalFiles(self):
484 return self.total_files
486 def getTotalLOC(self):
487 return self.total_lines
489 def revToDate(self, rev):
490 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
491 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
493 class ReportCreator:
494 """Creates the actual report based on given data."""
495 def __init__(self):
496 pass
498 def create(self, data, path):
499 self.data = data
500 self.path = path
502 def html_linkify(text):
503 return text.lower().replace(' ', '_')
505 def html_header(level, text):
506 name = html_linkify(text)
507 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
509 class HTMLReportCreator(ReportCreator):
510 def create(self, data, path):
511 ReportCreator.create(self, data, path)
512 self.title = data.projectname
514 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
515 binarypath = os.path.dirname(os.path.abspath(__file__))
516 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
517 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
518 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
519 for base in basedirs:
520 src = base + '/' + file
521 if os.path.exists(src):
522 shutil.copyfile(src, path + '/' + file)
523 break
524 else:
525 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
527 f = open(path + "/index.html", 'w')
528 format = '%Y-%m-%d %H:%M:%S'
529 self.printHeader(f)
531 f.write('<h1>GitStats - %s</h1>' % data.projectname)
533 self.printNav(f)
535 f.write('<dl>')
536 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
537 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
538 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
539 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()))
540 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
541 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
542 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
543 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
544 f.write('</dl>')
546 f.write('</body>\n</html>')
547 f.close()
550 # Activity
551 f = open(path + '/activity.html', 'w')
552 self.printHeader(f)
553 f.write('<h1>Activity</h1>')
554 self.printNav(f)
556 #f.write('<h2>Last 30 days</h2>')
558 #f.write('<h2>Last 12 months</h2>')
560 # Weekly activity
561 WEEKS = 32
562 f.write(html_header(2, 'Weekly activity'))
563 f.write('<p>Last %d weeks</p>' % WEEKS)
565 # generate weeks to show (previous N weeks from now)
566 now = datetime.datetime.now()
567 deltaweek = datetime.timedelta(7)
568 weeks = []
569 stampcur = now
570 for i in range(0, WEEKS):
571 weeks.insert(0, stampcur.strftime('%Y-%W'))
572 stampcur -= deltaweek
574 # top row: commits & bar
575 f.write('<table class="noborders"><tr>')
576 for i in range(0, WEEKS):
577 commits = 0
578 if weeks[i] in data.activity_by_year_week:
579 commits = data.activity_by_year_week[weeks[i]]
581 percentage = 0
582 if weeks[i] in data.activity_by_year_week:
583 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
584 height = max(1, int(200 * percentage))
585 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))
587 # bottom row: year/week
588 f.write('</tr><tr>')
589 for i in range(0, WEEKS):
590 f.write('<td>%s</td>' % (WEEKS - i))
591 f.write('</tr></table>')
593 # Hour of Day
594 f.write(html_header(2, 'Hour of Day'))
595 hour_of_day = data.getActivityByHourOfDay()
596 f.write('<table><tr><th>Hour</th>')
597 for i in range(0, 24):
598 f.write('<th>%d</th>' % i)
599 f.write('</tr>\n<tr><th>Commits</th>')
600 fp = open(path + '/hour_of_day.dat', 'w')
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)">%d</td>' % (r, hour_of_day[i]))
605 fp.write('%d %d\n' % (i, hour_of_day[i]))
606 else:
607 f.write('<td>0</td>')
608 fp.write('%d 0\n' % i)
609 fp.close()
610 f.write('</tr>\n<tr><th>%</th>')
611 totalcommits = data.getTotalCommits()
612 for i in range(0, 24):
613 if i in hour_of_day:
614 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
615 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
616 else:
617 f.write('<td>0.00</td>')
618 f.write('</tr></table>')
619 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
620 fg = open(path + '/hour_of_day.dat', 'w')
621 for i in range(0, 24):
622 if i in hour_of_day:
623 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
624 else:
625 fg.write('%d 0\n' % (i + 1))
626 fg.close()
628 # Day of Week
629 f.write(html_header(2, 'Day of Week'))
630 day_of_week = data.getActivityByDayOfWeek()
631 f.write('<div class="vtable"><table>')
632 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
633 fp = open(path + '/day_of_week.dat', 'w')
634 for d in range(0, 7):
635 commits = 0
636 if d in day_of_week:
637 commits = day_of_week[d]
638 fp.write('%d %d\n' % (d + 1, commits))
639 f.write('<tr>')
640 f.write('<th>%d</th>' % (d + 1))
641 if d in day_of_week:
642 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
643 else:
644 f.write('<td>0</td>')
645 f.write('</tr>')
646 f.write('</table></div>')
647 f.write('<img src="day_of_week.png" alt="Day of Week" />')
648 fp.close()
650 # Hour of Week
651 f.write(html_header(2, 'Hour of Week'))
652 f.write('<table>')
654 f.write('<tr><th>Weekday</th>')
655 for hour in range(0, 24):
656 f.write('<th>%d</th>' % (hour))
657 f.write('</tr>')
659 for weekday in range(0, 7):
660 f.write('<tr><th>%d</th>' % (weekday + 1))
661 for hour in range(0, 24):
662 try:
663 commits = data.activity_by_hour_of_week[weekday][hour]
664 except KeyError:
665 commits = 0
666 if commits != 0:
667 f.write('<td')
668 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
669 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
670 f.write('>%d</td>' % commits)
671 else:
672 f.write('<td></td>')
673 f.write('</tr>')
675 f.write('</table>')
677 # Month of Year
678 f.write(html_header(2, 'Month of Year'))
679 f.write('<div class="vtable"><table>')
680 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
681 fp = open (path + '/month_of_year.dat', 'w')
682 for mm in range(1, 13):
683 commits = 0
684 if mm in data.activity_by_month_of_year:
685 commits = data.activity_by_month_of_year[mm]
686 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
687 fp.write('%d %d\n' % (mm, commits))
688 fp.close()
689 f.write('</table></div>')
690 f.write('<img src="month_of_year.png" alt="Month of Year" />')
692 # Commits by year/month
693 f.write(html_header(2, 'Commits by year/month'))
694 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
695 for yymm in reversed(sorted(data.commits_by_month.keys())):
696 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
697 f.write('</table></div>')
698 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
699 fg = open(path + '/commits_by_year_month.dat', 'w')
700 for yymm in sorted(data.commits_by_month.keys()):
701 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
702 fg.close()
704 # Commits by year
705 f.write(html_header(2, 'Commits by Year'))
706 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
707 for yy in reversed(sorted(data.commits_by_year.keys())):
708 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()))
709 f.write('</table></div>')
710 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
711 fg = open(path + '/commits_by_year.dat', 'w')
712 for yy in sorted(data.commits_by_year.keys()):
713 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
714 fg.close()
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>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>%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']))
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 fg = open(path + '/files_by_date.dat', 'w')
782 for stamp in sorted(data.files_by_stamp.keys()):
783 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
784 fg.close()
786 f.write('<img src="files_by_date.png" alt="Files by Date" />')
788 #f.write('<h2>Average file size by date</h2>')
790 # Files :: Extensions
791 f.write(html_header(2, 'Extensions'))
792 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
793 for ext in sorted(data.extensions.keys()):
794 files = data.extensions[ext]['files']
795 lines = data.extensions[ext]['lines']
796 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))
797 f.write('</table>')
799 f.write('</body></html>')
800 f.close()
803 # Lines
804 f = open(path + '/lines.html', 'w')
805 self.printHeader(f)
806 f.write('<h1>Lines</h1>')
807 self.printNav(f)
809 f.write('<dl>\n')
810 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
811 f.write('</dl>\n')
813 f.write(html_header(2, 'Lines of Code'))
814 f.write('<img src="lines_of_code.png" />')
816 fg = open(path + '/lines_of_code.dat', 'w')
817 for stamp in sorted(data.changes_by_date.keys()):
818 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
819 fg.close()
821 f.write('</body></html>')
822 f.close()
825 # tags.html
826 f = open(path + '/tags.html', 'w')
827 self.printHeader(f)
828 f.write('<h1>Tags</h1>')
829 self.printNav(f)
831 f.write('<dl>')
832 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
833 if len(data.tags) > 0:
834 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
835 f.write('</dl>')
837 f.write('<table>')
838 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
839 # sort the tags by date desc
840 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
841 for tag in tags_sorted_by_date_desc:
842 authorinfo = []
843 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
844 for i in reversed(authors_by_commits):
845 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
846 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)))
847 f.write('</table>')
849 f.write('</body></html>')
850 f.close()
852 self.createGraphs(path)
854 def createGraphs(self, path):
855 print 'Generating graphs...'
857 # hour of day
858 f = open(path + '/hour_of_day.plot', 'w')
859 f.write(GNUPLOT_COMMON)
860 f.write(
862 set output 'hour_of_day.png'
863 unset key
864 set xrange [0.5:24.5]
865 set xtics 4
866 set ylabel "Commits"
867 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
868 """)
869 f.close()
871 # day of week
872 f = open(path + '/day_of_week.plot', 'w')
873 f.write(GNUPLOT_COMMON)
874 f.write(
876 set output 'day_of_week.png'
877 unset key
878 set xrange [0.5:7.5]
879 set xtics 1
880 set ylabel "Commits"
881 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
882 """)
883 f.close()
885 # Month of Year
886 f = open(path + '/month_of_year.plot', 'w')
887 f.write(GNUPLOT_COMMON)
888 f.write(
890 set output 'month_of_year.png'
891 unset key
892 set xrange [0.5:12.5]
893 set xtics 1
894 set ylabel "Commits"
895 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
896 """)
897 f.close()
899 # commits_by_year_month
900 f = open(path + '/commits_by_year_month.plot', 'w')
901 f.write(GNUPLOT_COMMON)
902 f.write(
904 set output 'commits_by_year_month.png'
905 unset key
906 set xdata time
907 set timefmt "%Y-%m"
908 set format x "%Y-%m"
909 set xtics rotate by 90 15768000
910 set bmargin 5
911 set ylabel "Commits"
912 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
913 """)
914 f.close()
916 # commits_by_year
917 f = open(path + '/commits_by_year.plot', 'w')
918 f.write(GNUPLOT_COMMON)
919 f.write(
921 set output 'commits_by_year.png'
922 unset key
923 set xtics 1
924 set ylabel "Commits"
925 set yrange [0:]
926 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
927 """)
928 f.close()
930 # Files by date
931 f = open(path + '/files_by_date.plot', 'w')
932 f.write(GNUPLOT_COMMON)
933 f.write(
935 set output 'files_by_date.png'
936 unset key
937 set xdata time
938 set timefmt "%Y-%m-%d"
939 set format x "%Y-%m-%d"
940 set ylabel "Files"
941 set xtics rotate by 90
942 set ytics 1
943 set bmargin 6
944 plot 'files_by_date.dat' using 1:2 w steps
945 """)
946 f.close()
948 # Lines of Code
949 f = open(path + '/lines_of_code.plot', 'w')
950 f.write(GNUPLOT_COMMON)
951 f.write(
953 set output 'lines_of_code.png'
954 unset key
955 set xdata time
956 set timefmt "%s"
957 set format x "%Y-%m-%d"
958 set ylabel "Lines"
959 set xtics rotate by 90
960 set bmargin 6
961 plot 'lines_of_code.dat' using 1:2 w lines
962 """)
963 f.close()
965 os.chdir(path)
966 files = glob.glob(path + '/*.plot')
967 for f in files:
968 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
969 if len(out) > 0:
970 print out
972 def printHeader(self, f, title = ''):
973 f.write(
974 """<?xml version="1.0" encoding="UTF-8"?>
975 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
976 <html xmlns="http://www.w3.org/1999/xhtml">
977 <head>
978 <title>GitStats - %s</title>
979 <link rel="stylesheet" href="gitstats.css" type="text/css" />
980 <meta name="generator" content="GitStats %s" />
981 <script type="text/javascript" src="sortable.js"></script>
982 </head>
983 <body>
984 """ % (self.title, getversion()))
986 def printNav(self, f):
987 f.write("""
988 <div class="nav">
989 <ul>
990 <li><a href="index.html">General</a></li>
991 <li><a href="activity.html">Activity</a></li>
992 <li><a href="authors.html">Authors</a></li>
993 <li><a href="files.html">Files</a></li>
994 <li><a href="lines.html">Lines</a></li>
995 <li><a href="tags.html">Tags</a></li>
996 </ul>
997 </div>
998 """)
1001 usage = """
1002 Usage: gitstats [options] <gitpath> <outputpath>
1004 Options:
1007 if len(sys.argv) < 3:
1008 print usage
1009 sys.exit(0)
1011 gitpath = sys.argv[1]
1012 outputpath = os.path.abspath(sys.argv[2])
1013 rundir = os.getcwd()
1015 try:
1016 os.makedirs(outputpath)
1017 except OSError:
1018 pass
1019 if not os.path.isdir(outputpath):
1020 print 'FATAL: Output path is not a directory or does not exist'
1021 sys.exit(1)
1023 print 'Git path: %s' % gitpath
1024 print 'Output path: %s' % outputpath
1026 os.chdir(gitpath)
1028 cachefile = os.path.join(outputpath, 'gitstats.cache')
1030 print 'Collecting data...'
1031 data = GitDataCollector()
1032 data.loadCache(cachefile)
1033 data.collect(gitpath)
1034 print 'Refining data...'
1035 data.saveCache(cachefile)
1036 data.refine()
1038 os.chdir(rundir)
1040 print 'Generating report...'
1041 report = HTMLReportCreator()
1042 report.create(data, outputpath)
1044 time_end = time.time()
1045 exectime_internal = time_end - time_start
1046 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)