todo: ideas on tags.
[gitstats.git] / gitstats
blob9830b575e006d99f3b57cafb152523df08846223
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 re
9 import shutil
10 import subprocess
11 import sys
12 import time
13 import zlib
15 GNUPLOT_COMMON = 'set terminal png transparent\nset size 0.5,0.5\n'
16 MAX_EXT_LENGTH = 10 # maximum file extension length
18 exectime_internal = 0.0
19 exectime_external = 0.0
20 time_start = time.time()
22 # By default, gnuplot is searched from path, but can be overridden with the
23 # environment variable "GNUPLOT"
24 gnuplot_cmd = 'gnuplot'
25 if 'GNUPLOT' in os.environ:
26 gnuplot_cmd = os.environ['GNUPLOT']
28 def getpipeoutput(cmds, quiet = False):
29 global exectime_external
30 start = time.time()
31 if not quiet:
32 print '>> ' + ' | '.join(cmds),
33 sys.stdout.flush()
34 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
35 p = p0
36 for x in cmds[1:]:
37 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
38 p0 = p
39 output = p.communicate()[0]
40 end = time.time()
41 if not quiet:
42 print '\r[%.5f] >> %s' % (end - start, ' | '.join(cmds))
43 exectime_external += (end - start)
44 return output.rstrip('\n')
46 def getkeyssortedbyvalues(dict):
47 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
49 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
50 def getkeyssortedbyvaluekey(d, key):
51 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
53 VERSION = 0
54 def getversion():
55 global VERSION
56 if VERSION == 0:
57 VERSION = getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
58 return VERSION
60 class DataCollector:
61 """Manages data collection from a revision control repository."""
62 def __init__(self):
63 self.stamp_created = time.time()
64 self.cache = {}
67 # This should be the main function to extract data from the repository.
68 def collect(self, dir):
69 self.dir = dir
70 self.projectname = os.path.basename(os.path.abspath(dir))
73 # Load cacheable data
74 def loadCache(self, cachefile):
75 if not os.path.exists(cachefile):
76 return
77 print 'Loading cache...'
78 f = open(cachefile)
79 try:
80 self.cache = pickle.loads(zlib.decompress(f.read()))
81 except:
82 # temporary hack to upgrade non-compressed caches
83 f.seek(0)
84 self.cache = pickle.load(f)
85 f.close()
88 # Produce any additional statistics from the extracted data.
89 def refine(self):
90 pass
93 # : get a dictionary of author
94 def getAuthorInfo(self, author):
95 return None
97 def getActivityByDayOfWeek(self):
98 return {}
100 def getActivityByHourOfDay(self):
101 return {}
104 # Get a list of authors
105 def getAuthors(self):
106 return []
108 def getFirstCommitDate(self):
109 return datetime.datetime.now()
111 def getLastCommitDate(self):
112 return datetime.datetime.now()
114 def getStampCreated(self):
115 return self.stamp_created
117 def getTags(self):
118 return []
120 def getTotalAuthors(self):
121 return -1
123 def getTotalCommits(self):
124 return -1
126 def getTotalFiles(self):
127 return -1
129 def getTotalLOC(self):
130 return -1
133 # Save cacheable data
134 def saveCache(self, filename):
135 print 'Saving cache...'
136 f = open(cachefile, 'w')
137 #pickle.dump(self.cache, f)
138 data = zlib.compress(pickle.dumps(self.cache))
139 f.write(data)
140 f.close()
142 class GitDataCollector(DataCollector):
143 def collect(self, dir):
144 DataCollector.collect(self, dir)
146 try:
147 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
148 except:
149 self.total_authors = 0
150 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
152 self.activity_by_hour_of_day = {} # hour -> commits
153 self.activity_by_day_of_week = {} # day -> commits
154 self.activity_by_month_of_year = {} # month [1-12] -> commits
155 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
156 self.activity_by_hour_of_day_busiest = 0
157 self.activity_by_hour_of_week_busiest = 0
159 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
161 # author of the month
162 self.author_of_month = {} # month -> author -> commits
163 self.author_of_year = {} # year -> author -> commits
164 self.commits_by_month = {} # month -> commits
165 self.commits_by_year = {} # year -> commits
166 self.first_commit_stamp = 0
167 self.last_commit_stamp = 0
169 # tags
170 self.tags = {}
171 lines = getpipeoutput(['git show-ref --tags']).split('\n')
172 for line in lines:
173 if len(line) == 0:
174 continue
175 (hash, tag) = line.split(' ')
177 tag = tag.replace('refs/tags/', '')
178 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
179 if len(output) > 0:
180 parts = output.split(' ')
181 stamp = 0
182 try:
183 stamp = int(parts[0])
184 except ValueError:
185 stamp = 0
186 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
188 # Collect revision statistics
189 # Outputs "<stamp> <author>"
190 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
191 for line in lines:
192 # linux-2.6 says "<unknown>" for one line O_o
193 parts = line.split(' ')
194 author = ''
195 try:
196 stamp = int(parts[0])
197 except ValueError:
198 stamp = 0
199 if len(parts) > 1:
200 author = ' '.join(parts[1:])
201 date = datetime.datetime.fromtimestamp(float(stamp))
203 # First and last commit stamp
204 if self.last_commit_stamp == 0:
205 self.last_commit_stamp = stamp
206 self.first_commit_stamp = stamp
208 # activity
209 # hour
210 hour = date.hour
211 if hour in self.activity_by_hour_of_day:
212 self.activity_by_hour_of_day[hour] += 1
213 else:
214 self.activity_by_hour_of_day[hour] = 1
215 # most active hour?
216 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
217 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
219 # day of week
220 day = date.weekday()
221 if day in self.activity_by_day_of_week:
222 self.activity_by_day_of_week[day] += 1
223 else:
224 self.activity_by_day_of_week[day] = 1
226 # hour of week
227 if day not in self.activity_by_hour_of_week:
228 self.activity_by_hour_of_week[day] = {}
229 if hour not in self.activity_by_hour_of_week[day]:
230 self.activity_by_hour_of_week[day][hour] = 1
231 else:
232 self.activity_by_hour_of_week[day][hour] += 1
233 # most active hour?
234 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
235 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
237 # month of year
238 month = date.month
239 if month in self.activity_by_month_of_year:
240 self.activity_by_month_of_year[month] += 1
241 else:
242 self.activity_by_month_of_year[month] = 1
244 # author stats
245 if author not in self.authors:
246 self.authors[author] = {}
247 # commits
248 if 'last_commit_stamp' not in self.authors[author]:
249 self.authors[author]['last_commit_stamp'] = stamp
250 self.authors[author]['first_commit_stamp'] = stamp
251 if 'commits' in self.authors[author]:
252 self.authors[author]['commits'] += 1
253 else:
254 self.authors[author]['commits'] = 1
256 # author of the month/year
257 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
258 if yymm in self.author_of_month:
259 if author in self.author_of_month[yymm]:
260 self.author_of_month[yymm][author] += 1
261 else:
262 self.author_of_month[yymm][author] = 1
263 else:
264 self.author_of_month[yymm] = {}
265 self.author_of_month[yymm][author] = 1
266 if yymm in self.commits_by_month:
267 self.commits_by_month[yymm] += 1
268 else:
269 self.commits_by_month[yymm] = 1
271 yy = datetime.datetime.fromtimestamp(stamp).year
272 if yy in self.author_of_year:
273 if author in self.author_of_year[yy]:
274 self.author_of_year[yy][author] += 1
275 else:
276 self.author_of_year[yy][author] = 1
277 else:
278 self.author_of_year[yy] = {}
279 self.author_of_year[yy][author] = 1
280 if yy in self.commits_by_year:
281 self.commits_by_year[yy] += 1
282 else:
283 self.commits_by_year[yy] = 1
285 # TODO Optimize this, it's the worst bottleneck
286 # outputs "<stamp> <files>" for each revision
287 self.files_by_stamp = {} # stamp -> files
288 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
289 lines = []
290 for revline in revlines:
291 time, rev = revline.split(' ')
292 #linecount = int(getpipeoutput(['git-ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
293 linecount = self.getFilesInCommit(rev)
294 lines.append('%d %d' % (int(time), linecount))
296 self.total_commits = len(lines)
297 for line in lines:
298 parts = line.split(' ')
299 if len(parts) != 2:
300 continue
301 (stamp, files) = parts[0:2]
302 try:
303 self.files_by_stamp[int(stamp)] = int(files)
304 except ValueError:
305 print 'Warning: failed to parse line "%s"' % line
307 # extensions
308 self.extensions = {} # extension -> files, lines
309 lines = getpipeoutput(['git ls-files']).split('\n')
310 self.total_files = len(lines)
311 for line in lines:
312 base = os.path.basename(line)
313 # Ignore extensionless (including .hidden files)
314 if base.find('.') == -1 or base.rfind('.') == 0:
315 ext = ''
316 else:
317 ext = base[(base.rfind('.') + 1):]
318 if len(ext) > MAX_EXT_LENGTH:
319 ext = ''
321 if ext not in self.extensions:
322 self.extensions[ext] = {'files': 0, 'lines': 0}
324 self.extensions[ext]['files'] += 1
325 try:
326 # Escaping could probably be improved here
327 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
328 except:
329 print 'Warning: Could not count lines for file "%s"' % line
331 # line statistics
332 # outputs:
333 # N files changed, N insertions (+), N deletions(-)
334 # <stamp> <author>
335 self.changes_by_date = {} # stamp -> { files, ins, del }
336 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
337 lines.reverse()
338 files = 0; inserted = 0; deleted = 0; total_lines = 0
339 for line in lines:
340 if len(line) == 0:
341 continue
343 # <stamp> <author>
344 if line.find('files changed,') == -1:
345 pos = line.find(' ')
346 if pos != -1:
347 try:
348 (stamp, author) = (int(line[:pos]), line[pos+1:])
349 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
350 except ValueError:
351 print 'Warning: unexpected line "%s"' % line
352 else:
353 print 'Warning: unexpected line "%s"' % line
354 else:
355 numbers = re.findall('\d+', line)
356 if len(numbers) == 3:
357 (files, inserted, deleted) = map(lambda el : int(el), numbers)
358 total_lines += inserted
359 total_lines -= deleted
360 else:
361 print 'Warning: failed to handle line "%s"' % line
362 (files, inserted, deleted) = (0, 0, 0)
363 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
364 self.total_lines = total_lines
366 def refine(self):
367 # authors
368 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
369 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
370 authors_by_commits.reverse() # most first
371 for i, name in enumerate(authors_by_commits):
372 self.authors[name]['place_by_commits'] = i + 1
374 for name in self.authors.keys():
375 a = self.authors[name]
376 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
377 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
378 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
379 delta = date_last - date_first
380 a['date_first'] = date_first.strftime('%Y-%m-%d')
381 a['date_last'] = date_last.strftime('%Y-%m-%d')
382 a['timedelta'] = delta
384 def getActivityByDayOfWeek(self):
385 return self.activity_by_day_of_week
387 def getActivityByHourOfDay(self):
388 return self.activity_by_hour_of_day
390 def getAuthorInfo(self, author):
391 return self.authors[author]
393 def getAuthors(self):
394 return self.authors.keys()
396 def getCommitDeltaDays(self):
397 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
399 def getFilesInCommit(self, rev):
400 try:
401 res = self.cache['files_in_tree'][rev]
402 except:
403 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
404 if 'files_in_tree' not in self.cache:
405 self.cache['files_in_tree'] = {}
406 self.cache['files_in_tree'][rev] = res
408 return res
410 def getFirstCommitDate(self):
411 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
413 def getLastCommitDate(self):
414 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
416 def getTags(self):
417 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
418 return lines.split('\n')
420 def getTagDate(self, tag):
421 return self.revToDate('tags/' + tag)
423 def getTotalAuthors(self):
424 return self.total_authors
426 def getTotalCommits(self):
427 return self.total_commits
429 def getTotalFiles(self):
430 return self.total_files
432 def getTotalLOC(self):
433 return self.total_lines
435 def revToDate(self, rev):
436 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
437 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
439 class ReportCreator:
440 """Creates the actual report based on given data."""
441 def __init__(self):
442 pass
444 def create(self, data, path):
445 self.data = data
446 self.path = path
448 def html_linkify(text):
449 return text.lower().replace(' ', '_')
451 def html_header(level, text):
452 name = html_linkify(text)
453 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
455 class HTMLReportCreator(ReportCreator):
456 def create(self, data, path):
457 ReportCreator.create(self, data, path)
458 self.title = data.projectname
460 # copy static files if they do not exist
461 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
462 basedir = os.path.dirname(os.path.abspath(__file__))
463 shutil.copyfile(basedir + '/' + file, path + '/' + file)
465 f = open(path + "/index.html", 'w')
466 format = '%Y-%m-%d %H:%M:%S'
467 self.printHeader(f)
469 f.write('<h1>GitStats - %s</h1>' % data.projectname)
471 self.printNav(f)
473 f.write('<dl>')
474 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
475 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
476 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
477 f.write('<dt>Report Period</dt><dd>%s to %s (%d days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays()))
478 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
479 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
480 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
481 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
482 f.write('</dl>')
484 f.write('</body>\n</html>')
485 f.close()
488 # Activity
489 f = open(path + '/activity.html', 'w')
490 self.printHeader(f)
491 f.write('<h1>Activity</h1>')
492 self.printNav(f)
494 #f.write('<h2>Last 30 days</h2>')
496 #f.write('<h2>Last 12 months</h2>')
498 # Hour of Day
499 f.write(html_header(2, 'Hour of Day'))
500 hour_of_day = data.getActivityByHourOfDay()
501 f.write('<table><tr><th>Hour</th>')
502 for i in range(0, 24):
503 f.write('<th>%d</th>' % i)
504 f.write('</tr>\n<tr><th>Commits</th>')
505 fp = open(path + '/hour_of_day.dat', 'w')
506 for i in range(0, 24):
507 if i in hour_of_day:
508 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
509 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
510 fp.write('%d %d\n' % (i, hour_of_day[i]))
511 else:
512 f.write('<td>0</td>')
513 fp.write('%d 0\n' % i)
514 fp.close()
515 f.write('</tr>\n<tr><th>%</th>')
516 totalcommits = data.getTotalCommits()
517 for i in range(0, 24):
518 if i in hour_of_day:
519 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
520 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
521 else:
522 f.write('<td>0.00</td>')
523 f.write('</tr></table>')
524 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
525 fg = open(path + '/hour_of_day.dat', 'w')
526 for i in range(0, 24):
527 if i in hour_of_day:
528 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
529 else:
530 fg.write('%d 0\n' % (i + 1))
531 fg.close()
533 # Day of Week
534 f.write(html_header(2, 'Day of Week'))
535 day_of_week = data.getActivityByDayOfWeek()
536 f.write('<div class="vtable"><table>')
537 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
538 fp = open(path + '/day_of_week.dat', 'w')
539 for d in range(0, 7):
540 commits = 0
541 if d in day_of_week:
542 commits = day_of_week[d]
543 fp.write('%d %d\n' % (d + 1, commits))
544 f.write('<tr>')
545 f.write('<th>%d</th>' % (d + 1))
546 if d in day_of_week:
547 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
548 else:
549 f.write('<td>0</td>')
550 f.write('</tr>')
551 f.write('</table></div>')
552 f.write('<img src="day_of_week.png" alt="Day of Week" />')
553 fp.close()
555 # Hour of Week
556 f.write(html_header(2, 'Hour of Week'))
557 f.write('<table>')
559 f.write('<tr><th>Weekday</th>')
560 for hour in range(0, 24):
561 f.write('<th>%d</th>' % (hour))
562 f.write('</tr>')
564 for weekday in range(0, 7):
565 f.write('<tr><th>%d</th>' % (weekday + 1))
566 for hour in range(0, 24):
567 try:
568 commits = data.activity_by_hour_of_week[weekday][hour]
569 except KeyError:
570 commits = 0
571 if commits != 0:
572 f.write('<td')
573 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
574 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
575 f.write('>%d</td>' % commits)
576 else:
577 f.write('<td></td>')
578 f.write('</tr>')
580 f.write('</table>')
582 # Month of Year
583 f.write(html_header(2, 'Month of Year'))
584 f.write('<div class="vtable"><table>')
585 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
586 fp = open (path + '/month_of_year.dat', 'w')
587 for mm in range(1, 13):
588 commits = 0
589 if mm in data.activity_by_month_of_year:
590 commits = data.activity_by_month_of_year[mm]
591 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
592 fp.write('%d %d\n' % (mm, commits))
593 fp.close()
594 f.write('</table></div>')
595 f.write('<img src="month_of_year.png" alt="Month of Year" />')
597 # Commits by year/month
598 f.write(html_header(2, 'Commits by year/month'))
599 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
600 for yymm in reversed(sorted(data.commits_by_month.keys())):
601 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
602 f.write('</table></div>')
603 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
604 fg = open(path + '/commits_by_year_month.dat', 'w')
605 for yymm in sorted(data.commits_by_month.keys()):
606 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
607 fg.close()
609 # Commits by year
610 f.write(html_header(2, 'Commits by Year'))
611 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
612 for yy in reversed(sorted(data.commits_by_year.keys())):
613 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()))
614 f.write('</table></div>')
615 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
616 fg = open(path + '/commits_by_year.dat', 'w')
617 for yy in sorted(data.commits_by_year.keys()):
618 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
619 fg.close()
621 f.write('</body></html>')
622 f.close()
625 # Authors
626 f = open(path + '/authors.html', 'w')
627 self.printHeader(f)
629 f.write('<h1>Authors</h1>')
630 self.printNav(f)
632 # Authors :: List of authors
633 f.write(html_header(2, 'List of Authors'))
635 f.write('<table class="authors sortable" id="authors">')
636 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th class="unsortable">Age</th><th># by commits</th></tr>')
637 for author in sorted(data.getAuthors()):
638 info = data.getAuthorInfo(author)
639 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td></tr>' % (author, info['commits'], info['commits_frac'], info['date_first'], info['date_last'], info['timedelta'], info['place_by_commits']))
640 f.write('</table>')
642 # Authors :: Author of Month
643 f.write(html_header(2, 'Author of Month'))
644 f.write('<table class="sortable" id="aom">')
645 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
646 for yymm in reversed(sorted(data.author_of_month.keys())):
647 authordict = data.author_of_month[yymm]
648 authors = getkeyssortedbyvalues(authordict)
649 authors.reverse()
650 commits = data.author_of_month[yymm][authors[0]]
651 next = ', '.join(authors[1:5])
652 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yymm, authors[0], commits, (100 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm], next))
654 f.write('</table>')
656 f.write(html_header(2, 'Author of Year'))
657 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>')
658 for yy in reversed(sorted(data.author_of_year.keys())):
659 authordict = data.author_of_year[yy]
660 authors = getkeyssortedbyvalues(authordict)
661 authors.reverse()
662 commits = data.author_of_year[yy][authors[0]]
663 next = ', '.join(authors[1:5])
664 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yy, authors[0], commits, (100 * commits) / data.commits_by_year[yy], data.commits_by_year[yy], next))
665 f.write('</table>')
667 f.write('</body></html>')
668 f.close()
671 # Files
672 f = open(path + '/files.html', 'w')
673 self.printHeader(f)
674 f.write('<h1>Files</h1>')
675 self.printNav(f)
677 f.write('<dl>\n')
678 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
679 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
680 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
681 f.write('</dl>\n')
683 # Files :: File count by date
684 f.write(html_header(2, 'File count by date'))
686 fg = open(path + '/files_by_date.dat', 'w')
687 for stamp in sorted(data.files_by_stamp.keys()):
688 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
689 fg.close()
691 f.write('<img src="files_by_date.png" alt="Files by Date" />')
693 #f.write('<h2>Average file size by date</h2>')
695 # Files :: Extensions
696 f.write(html_header(2, 'Extensions'))
697 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
698 for ext in sorted(data.extensions.keys()):
699 files = data.extensions[ext]['files']
700 lines = data.extensions[ext]['lines']
701 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))
702 f.write('</table>')
704 f.write('</body></html>')
705 f.close()
708 # Lines
709 f = open(path + '/lines.html', 'w')
710 self.printHeader(f)
711 f.write('<h1>Lines</h1>')
712 self.printNav(f)
714 f.write('<dl>\n')
715 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
716 f.write('</dl>\n')
718 f.write(html_header(2, 'Lines of Code'))
719 f.write('<img src="lines_of_code.png" />')
721 fg = open(path + '/lines_of_code.dat', 'w')
722 for stamp in sorted(data.changes_by_date.keys()):
723 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
724 fg.close()
726 f.write('</body></html>')
727 f.close()
730 # tags.html
731 f = open(path + '/tags.html', 'w')
732 self.printHeader(f)
733 f.write('<h1>Tags</h1>')
734 self.printNav(f)
736 f.write('<dl>')
737 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
738 if len(data.tags) > 0:
739 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
740 f.write('</dl>')
742 f.write('<table>')
743 f.write('<tr><th>Name</th><th>Date</th></tr>')
744 # sort the tags by date desc
745 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
746 for tag in tags_sorted_by_date_desc:
747 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
748 f.write('</table>')
750 f.write('</body></html>')
751 f.close()
753 self.createGraphs(path)
755 def createGraphs(self, path):
756 print 'Generating graphs...'
758 # hour of day
759 f = open(path + '/hour_of_day.plot', 'w')
760 f.write(GNUPLOT_COMMON)
761 f.write(
763 set output 'hour_of_day.png'
764 unset key
765 set xrange [0.5:24.5]
766 set xtics 4
767 set ylabel "Commits"
768 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
769 """)
770 f.close()
772 # day of week
773 f = open(path + '/day_of_week.plot', 'w')
774 f.write(GNUPLOT_COMMON)
775 f.write(
777 set output 'day_of_week.png'
778 unset key
779 set xrange [0.5:7.5]
780 set xtics 1
781 set ylabel "Commits"
782 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
783 """)
784 f.close()
786 # Month of Year
787 f = open(path + '/month_of_year.plot', 'w')
788 f.write(GNUPLOT_COMMON)
789 f.write(
791 set output 'month_of_year.png'
792 unset key
793 set xrange [0.5:12.5]
794 set xtics 1
795 set ylabel "Commits"
796 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
797 """)
798 f.close()
800 # commits_by_year_month
801 f = open(path + '/commits_by_year_month.plot', 'w')
802 f.write(GNUPLOT_COMMON)
803 f.write(
805 set output 'commits_by_year_month.png'
806 unset key
807 set xdata time
808 set timefmt "%Y-%m"
809 set format x "%Y-%m"
810 set xtics rotate by 90 15768000
811 set bmargin 5
812 set ylabel "Commits"
813 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
814 """)
815 f.close()
817 # commits_by_year
818 f = open(path + '/commits_by_year.plot', 'w')
819 f.write(GNUPLOT_COMMON)
820 f.write(
822 set output 'commits_by_year.png'
823 unset key
824 set xtics 1
825 set ylabel "Commits"
826 set yrange [0:]
827 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
828 """)
829 f.close()
831 # Files by date
832 f = open(path + '/files_by_date.plot', 'w')
833 f.write(GNUPLOT_COMMON)
834 f.write(
836 set output 'files_by_date.png'
837 unset key
838 set xdata time
839 set timefmt "%Y-%m-%d"
840 set format x "%Y-%m-%d"
841 set ylabel "Files"
842 set xtics rotate by 90
843 set bmargin 6
844 plot 'files_by_date.dat' using 1:2 w histeps
845 """)
846 f.close()
848 # Lines of Code
849 f = open(path + '/lines_of_code.plot', 'w')
850 f.write(GNUPLOT_COMMON)
851 f.write(
853 set output 'lines_of_code.png'
854 unset key
855 set xdata time
856 set timefmt "%s"
857 set format x "%Y-%m-%d"
858 set ylabel "Lines"
859 set xtics rotate by 90
860 set bmargin 6
861 plot 'lines_of_code.dat' using 1:2 w lines
862 """)
863 f.close()
865 os.chdir(path)
866 files = glob.glob(path + '/*.plot')
867 for f in files:
868 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
869 if len(out) > 0:
870 print out
872 def printHeader(self, f, title = ''):
873 f.write(
874 """<?xml version="1.0" encoding="UTF-8"?>
875 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
876 <html xmlns="http://www.w3.org/1999/xhtml">
877 <head>
878 <title>GitStats - %s</title>
879 <link rel="stylesheet" href="gitstats.css" type="text/css" />
880 <meta name="generator" content="GitStats %s" />
881 <script type="text/javascript" src="sortable.js"></script>
882 </head>
883 <body>
884 """ % (self.title, getversion()))
886 def printNav(self, f):
887 f.write("""
888 <div class="nav">
889 <ul>
890 <li><a href="index.html">General</a></li>
891 <li><a href="activity.html">Activity</a></li>
892 <li><a href="authors.html">Authors</a></li>
893 <li><a href="files.html">Files</a></li>
894 <li><a href="lines.html">Lines</a></li>
895 <li><a href="tags.html">Tags</a></li>
896 </ul>
897 </div>
898 """)
901 usage = """
902 Usage: gitstats [options] <gitpath> <outputpath>
904 Options:
907 if len(sys.argv) < 3:
908 print usage
909 sys.exit(0)
911 gitpath = sys.argv[1]
912 outputpath = os.path.abspath(sys.argv[2])
913 rundir = os.getcwd()
915 try:
916 os.makedirs(outputpath)
917 except OSError:
918 pass
919 if not os.path.isdir(outputpath):
920 print 'FATAL: Output path is not a directory or does not exist'
921 sys.exit(1)
923 print 'Git path: %s' % gitpath
924 print 'Output path: %s' % outputpath
926 os.chdir(gitpath)
928 cachefile = os.path.join(outputpath, 'gitstats.cache')
930 print 'Collecting data...'
931 data = GitDataCollector()
932 data.loadCache(cachefile)
933 data.collect(gitpath)
934 print 'Refining data...'
935 data.saveCache(cachefile)
936 data.refine()
938 os.chdir(rundir)
940 print 'Generating report...'
941 report = HTMLReportCreator()
942 report.create(data, outputpath)
944 time_end = time.time()
945 exectime_internal = time_end - time_start
946 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)