Revert to earlier behaviour when showing commands.
[gitstats.git] / gitstats
blobff10e7679fb6c39041aba26bedfae04dceaf6341
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2008 Heikki Hokkanen <hoxu@users.sf.net>
3 # GPLv2
4 import subprocess
5 import datetime
6 import glob
7 import os
8 import re
9 import shutil
10 import sys
11 import time
13 GNUPLOT_COMMON = 'set terminal png transparent\nset size 0.5,0.5\n'
15 exectime_internal = 0.0
16 exectime_external = 0.0
17 time_start = time.time()
19 # By default, gnuplot is searched from path, but can be overridden with the
20 # environment variable "GNUPLOT"
21 gnuplot_cmd = 'gnuplot'
22 if 'GNUPLOT' in os.environ:
23 gnuplot_cmd = os.environ['GNUPLOT']
25 def getpipeoutput(cmds, quiet = False):
26 global exectime_external
27 start = time.time()
28 if not quiet:
29 print '>> ' + ' | '.join(cmds),
30 sys.stdout.flush()
31 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
32 p = p0
33 for x in cmds[1:]:
34 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
35 p0 = p
36 output = p.communicate()[0]
37 end = time.time()
38 if not quiet:
39 print '\r[%.5f] >> %s' % (end - start, ' | '.join(cmds))
40 exectime_external += (end - start)
41 return output.rstrip('\n')
43 def getkeyssortedbyvalues(dict):
44 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
46 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
47 def getkeyssortedbyvaluekey(d, key):
48 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
50 class DataCollector:
51 """Manages data collection from a revision control repository."""
52 def __init__(self):
53 self.stamp_created = time.time()
54 pass
57 # This should be the main function to extract data from the repository.
58 def collect(self, dir):
59 self.dir = dir
60 self.projectname = os.path.basename(os.path.abspath(dir))
63 # Produce any additional statistics from the extracted data.
64 def refine(self):
65 pass
68 # : get a dictionary of author
69 def getAuthorInfo(self, author):
70 return None
72 def getActivityByDayOfWeek(self):
73 return {}
75 def getActivityByHourOfDay(self):
76 return {}
79 # Get a list of authors
80 def getAuthors(self):
81 return []
83 def getFirstCommitDate(self):
84 return datetime.datetime.now()
86 def getLastCommitDate(self):
87 return datetime.datetime.now()
89 def getStampCreated(self):
90 return self.stamp_created
92 def getTags(self):
93 return []
95 def getTotalAuthors(self):
96 return -1
98 def getTotalCommits(self):
99 return -1
101 def getTotalFiles(self):
102 return -1
104 def getTotalLOC(self):
105 return -1
107 class GitDataCollector(DataCollector):
108 def collect(self, dir):
109 DataCollector.collect(self, dir)
111 try:
112 self.total_authors = int(getpipeoutput(('git-log', 'git-shortlog -s', 'wc -l')))
113 except:
114 self.total_authors = 0
115 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
117 self.activity_by_hour_of_day = {} # hour -> commits
118 self.activity_by_day_of_week = {} # day -> commits
119 self.activity_by_month_of_year = {} # month [1-12] -> commits
120 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
122 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
124 # author of the month
125 self.author_of_month = {} # month -> author -> commits
126 self.author_of_year = {} # year -> author -> commits
127 self.commits_by_month = {} # month -> commits
128 self.commits_by_year = {} # year -> commits
129 self.first_commit_stamp = 0
130 self.last_commit_stamp = 0
132 # tags
133 self.tags = {}
134 lines = getpipeoutput((('git-show-ref --tags'),)).split('\n')
135 for line in lines:
136 if len(line) == 0:
137 continue
138 print "line = ", line
139 splitted_str = line.split(' ')
140 print "splitted_str = ", splitted_str
141 (hash, tag) = splitted_str
143 tag = tag.replace('refs/tags/', '')
144 output = getpipeoutput((('git-log "%s" --pretty=format:"%%at %%an" -n 1' % hash),))
145 if len(output) > 0:
146 parts = output.split(' ')
147 stamp = 0
148 try:
149 stamp = int(parts[0])
150 except ValueError:
151 stamp = 0
152 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
153 pass
155 # Collect revision statistics
156 # Outputs "<stamp> <author>"
157 lines = getpipeoutput(('git-rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit')).split('\n')
158 for line in lines:
159 # linux-2.6 says "<unknown>" for one line O_o
160 parts = line.split(' ')
161 author = ''
162 try:
163 stamp = int(parts[0])
164 except ValueError:
165 print "lines = ", lines
166 print "line = ", line
167 raise
168 stamp = 0
169 if len(parts) > 1:
170 author = ' '.join(parts[1:])
171 date = datetime.datetime.fromtimestamp(float(stamp))
173 # First and last commit stamp
174 if self.last_commit_stamp == 0:
175 self.last_commit_stamp = stamp
176 self.first_commit_stamp = stamp
178 # activity
179 # hour
180 hour = date.hour
181 if hour in self.activity_by_hour_of_day:
182 self.activity_by_hour_of_day[hour] += 1
183 else:
184 self.activity_by_hour_of_day[hour] = 1
186 # day of week
187 day = date.weekday()
188 if day in self.activity_by_day_of_week:
189 self.activity_by_day_of_week[day] += 1
190 else:
191 self.activity_by_day_of_week[day] = 1
193 # hour of week
194 if day not in self.activity_by_hour_of_week:
195 self.activity_by_hour_of_week[day] = {}
196 if hour not in self.activity_by_hour_of_week[day]:
197 self.activity_by_hour_of_week[day][hour] = 1
198 else:
199 self.activity_by_hour_of_week[day][hour] += 1
201 # month of year
202 month = date.month
203 if month in self.activity_by_month_of_year:
204 self.activity_by_month_of_year[month] += 1
205 else:
206 self.activity_by_month_of_year[month] = 1
208 # author stats
209 if author not in self.authors:
210 self.authors[author] = {}
211 # TODO commits
212 if 'last_commit_stamp' not in self.authors[author]:
213 self.authors[author]['last_commit_stamp'] = stamp
214 self.authors[author]['first_commit_stamp'] = stamp
215 if 'commits' in self.authors[author]:
216 self.authors[author]['commits'] += 1
217 else:
218 self.authors[author]['commits'] = 1
220 # author of the month/year
221 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
222 if yymm in self.author_of_month:
223 if author in self.author_of_month[yymm]:
224 self.author_of_month[yymm][author] += 1
225 else:
226 self.author_of_month[yymm][author] = 1
227 else:
228 self.author_of_month[yymm] = {}
229 self.author_of_month[yymm][author] = 1
230 if yymm in self.commits_by_month:
231 self.commits_by_month[yymm] += 1
232 else:
233 self.commits_by_month[yymm] = 1
235 yy = datetime.datetime.fromtimestamp(stamp).year
236 if yy in self.author_of_year:
237 if author in self.author_of_year[yy]:
238 self.author_of_year[yy][author] += 1
239 else:
240 self.author_of_year[yy][author] = 1
241 else:
242 self.author_of_year[yy] = {}
243 self.author_of_year[yy][author] = 1
244 if yy in self.commits_by_year:
245 self.commits_by_year[yy] += 1
246 else:
247 self.commits_by_year[yy] = 1
249 # TODO Optimize this, it's the worst bottleneck
250 # outputs "<stamp> <files>" for each revision
251 self.files_by_stamp = {} # stamp -> files
252 lines = getpipeoutput(('git-rev-list --pretty=format:"%at %H" HEAD',
253 'grep -v ^commit')).strip().split('\n')
254 #'sh while read line; do set $line; echo "$1 $(git-ls-tree -r "$2" |wc -l)"; done')).split('\n')
255 tmp = [None] * len(lines)
256 for idx in xrange(len(lines)):
257 (a, b) = lines[idx].split(" ")
258 tmp[idx] = a + getpipeoutput(('git-ls-tree -r ' + b, 'wc -l')).strip('\n')
259 lines = tmp
261 self.total_commits = len(lines)
262 for line in lines:
263 parts = line.split(' ')
264 if len(parts) != 2:
265 continue
266 (stamp, files) = parts[0:2]
267 try:
268 self.files_by_stamp[int(stamp)] = int(files)
269 except ValueError:
270 print 'Warning: failed to parse line "%s"' % line
272 # extensions
273 self.extensions = {} # extension -> files, lines
274 lines = getpipeoutput(('git-ls-files',)).split('\n')
275 self.total_files = len(lines)
276 for line in lines:
277 base = os.path.basename(line)
278 if base.find('.') == -1:
279 ext = ''
280 else:
281 ext = base[(base.rfind('.') + 1):]
283 if ext not in self.extensions:
284 self.extensions[ext] = {'files': 0, 'lines': 0}
286 self.extensions[ext]['files'] += 1
287 try:
288 # Escaping could probably be improved here
289 self.extensions[ext]['lines'] += int(getpipeoutput(('wc -l "%s"' % line,)).split()[0])
290 except:
291 print 'Warning: Could not count lines for file "%s"' % line
293 # line statistics
294 # outputs:
295 # N files changed, N insertions (+), N deletions(-)
296 # <stamp> <author>
297 self.changes_by_date = {} # stamp -> { files, ins, del }
298 lines = getpipeoutput(('git-log --shortstat --pretty=format:"%at %an"',)).split('\n')
299 lines.reverse()
300 files = 0; inserted = 0; deleted = 0; total_lines = 0
301 for line in lines:
302 if len(line) == 0:
303 continue
305 # <stamp> <author>
306 if line.find('files changed,') == -1:
307 pos = line.find(' ')
308 if pos != -1:
309 (stamp, author) = (int(line[:pos]), line[pos+1:])
310 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
311 else:
312 print 'Warning: unexpected line "%s"' % line
313 else:
314 numbers = re.findall('\d+', line)
315 if len(numbers) == 3:
316 (files, inserted, deleted) = map(lambda el : int(el), numbers)
317 total_lines += inserted
318 total_lines -= deleted
319 else:
320 print 'Warning: failed to handle line "%s"' % line
321 (files, inserted, deleted) = (0, 0, 0)
322 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
323 self.total_lines = total_lines
325 def refine(self):
326 # authors
327 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
328 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
329 authors_by_commits.reverse() # most first
330 for i, name in enumerate(authors_by_commits):
331 self.authors[name]['place_by_commits'] = i + 1
333 for name in self.authors.keys():
334 a = self.authors[name]
335 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
336 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
337 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
338 delta = date_last - date_first
339 a['date_first'] = date_first.strftime('%Y-%m-%d')
340 a['date_last'] = date_last.strftime('%Y-%m-%d')
341 a['timedelta'] = delta
343 def getActivityByDayOfWeek(self):
344 return self.activity_by_day_of_week
346 def getActivityByHourOfDay(self):
347 return self.activity_by_hour_of_day
349 def getAuthorInfo(self, author):
350 return self.authors[author]
352 def getAuthors(self):
353 return self.authors.keys()
355 def getFirstCommitDate(self):
356 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
358 def getLastCommitDate(self):
359 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
361 def getTags(self):
362 lines = getpipeoutput(('git-show-ref --tags',
363 'cut -d/ -f3'))
364 return lines.split('\n')
366 def getTagDate(self, tag):
367 return self.revToDate('tags/' + tag)
369 def getTotalAuthors(self):
370 return self.total_authors
372 def getTotalCommits(self):
373 return self.total_commits
375 def getTotalFiles(self):
376 return self.total_files
378 def getTotalLOC(self):
379 return self.total_lines
381 def revToDate(self, rev):
382 stamp = int(getpipeoutput(('git-log --pretty=format:%%at "%s" -n 1' % rev,)))
383 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
385 class ReportCreator:
386 """Creates the actual report based on given data."""
387 def __init__(self):
388 pass
390 def create(self, data, path):
391 self.data = data
392 self.path = path
394 def html_linkify(text):
395 return text.lower().replace(' ', '_')
397 def html_header(level, text):
398 name = html_linkify(text)
399 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
401 class HTMLReportCreator(ReportCreator):
402 def create(self, data, path):
403 ReportCreator.create(self, data, path)
404 self.title = data.projectname
406 # TODO copy the CSS if it does not exist
407 if not os.path.exists(path + '/gitstats.css'):
408 basedir = os.path.dirname(os.path.abspath(__file__))
409 shutil.copyfile(basedir + '/gitstats.css', path + '/gitstats.css')
410 pass
412 f = open(path + "/index.html", 'w')
413 format = '%Y-%m-%d %H:%m:%S'
414 self.printHeader(f)
416 f.write('<h1>GitStats - %s</h1>' % data.projectname)
418 self.printNav(f)
420 f.write('<dl>');
421 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
422 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
423 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
424 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
425 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
426 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
427 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
428 f.write('</dl>');
430 f.write('</body>\n</html>');
431 f.close()
434 # Activity
435 f = open(path + '/activity.html', 'w')
436 self.printHeader(f)
437 f.write('<h1>Activity</h1>')
438 self.printNav(f)
440 #f.write('<h2>Last 30 days</h2>')
442 #f.write('<h2>Last 12 months</h2>')
444 # Hour of Day
445 f.write(html_header(2, 'Hour of Day'))
446 hour_of_day = data.getActivityByHourOfDay()
447 f.write('<table><tr><th>Hour</th>')
448 for i in range(1, 25):
449 f.write('<th>%d</th>' % i)
450 f.write('</tr>\n<tr><th>Commits</th>')
451 fp = open(path + '/hour_of_day.dat', 'w')
452 for i in range(0, 24):
453 if i in hour_of_day:
454 f.write('<td>%d</td>' % hour_of_day[i])
455 fp.write('%d %d\n' % (i, hour_of_day[i]))
456 else:
457 f.write('<td>0</td>')
458 fp.write('%d 0\n' % i)
459 fp.close()
460 f.write('</tr>\n<tr><th>%</th>')
461 totalcommits = data.getTotalCommits()
462 for i in range(0, 24):
463 if i in hour_of_day:
464 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
465 else:
466 f.write('<td>0.00</td>')
467 f.write('</tr></table>')
468 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
469 fg = open(path + '/hour_of_day.dat', 'w')
470 for i in range(0, 24):
471 if i in hour_of_day:
472 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
473 else:
474 fg.write('%d 0\n' % (i + 1))
475 fg.close()
477 # Day of Week
478 f.write(html_header(2, 'Day of Week'))
479 day_of_week = data.getActivityByDayOfWeek()
480 f.write('<div class="vtable"><table>')
481 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
482 fp = open(path + '/day_of_week.dat', 'w')
483 for d in range(0, 7):
484 commits = 0
485 if d in day_of_week:
486 commits = day_of_week[d]
487 fp.write('%d %d\n' % (d + 1, commits))
488 f.write('<tr>')
489 f.write('<th>%d</th>' % (d + 1))
490 if d in day_of_week:
491 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
492 else:
493 f.write('<td>0</td>')
494 f.write('</tr>')
495 f.write('</table></div>')
496 f.write('<img src="day_of_week.png" alt="Day of Week" />')
497 fp.close()
499 # Hour of Week
500 f.write(html_header(2, 'Hour of Week'))
501 f.write('<table>')
503 f.write('<tr><th>Weekday</th>')
504 for hour in range(0, 24):
505 f.write('<th>%d</th>' % (hour + 1))
506 f.write('</tr>')
508 for weekday in range(0, 7):
509 f.write('<tr><th>%d</th>' % (weekday + 1))
510 for hour in range(0, 24):
511 try:
512 commits = data.activity_by_hour_of_week[weekday][hour]
513 except KeyError:
514 commits = 0
515 if commits != 0:
516 f.write('<td>%d</td>' % commits)
517 else:
518 f.write('<td></td>')
519 f.write('</tr>')
521 f.write('</table>')
523 # Month of Year
524 f.write(html_header(2, 'Month of Year'))
525 f.write('<div class="vtable"><table>')
526 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
527 fp = open (path + '/month_of_year.dat', 'w')
528 for mm in range(1, 13):
529 commits = 0
530 if mm in data.activity_by_month_of_year:
531 commits = data.activity_by_month_of_year[mm]
532 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
533 fp.write('%d %d\n' % (mm, commits))
534 fp.close()
535 f.write('</table></div>')
536 f.write('<img src="month_of_year.png" alt="Month of Year" />')
538 # Commits by year/month
539 f.write(html_header(2, 'Commits by year/month'))
540 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
541 for yymm in reversed(sorted(data.commits_by_month.keys())):
542 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
543 f.write('</table></div>')
544 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
545 fg = open(path + '/commits_by_year_month.dat', 'w')
546 for yymm in sorted(data.commits_by_month.keys()):
547 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
548 fg.close()
550 # Commits by year
551 f.write(html_header(2, 'Commits by Year'))
552 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
553 for yy in reversed(sorted(data.commits_by_year.keys())):
554 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()))
555 f.write('</table></div>')
556 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
557 fg = open(path + '/commits_by_year.dat', 'w')
558 for yy in sorted(data.commits_by_year.keys()):
559 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
560 fg.close()
562 f.write('</body></html>')
563 f.close()
566 # Authors
567 f = open(path + '/authors.html', 'w')
568 self.printHeader(f)
570 f.write('<h1>Authors</h1>')
571 self.printNav(f)
573 # Authors :: List of authors
574 f.write(html_header(2, 'List of Authors'))
576 f.write('<table class="authors">')
577 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th>Age</th><th># by commits</th></tr>')
578 for author in sorted(data.getAuthors()):
579 info = data.getAuthorInfo(author)
580 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']))
581 f.write('</table>')
583 # Authors :: Author of Month
584 f.write(html_header(2, 'Author of Month'))
585 f.write('<table>')
586 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
587 for yymm in reversed(sorted(data.author_of_month.keys())):
588 authordict = data.author_of_month[yymm]
589 authors = getkeyssortedbyvalues(authordict)
590 authors.reverse()
591 commits = data.author_of_month[yymm][authors[0]]
592 next = ', '.join(authors[1:5])
593 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))
595 f.write('</table>')
597 f.write(html_header(2, 'Author of Year'))
598 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
599 for yy in reversed(sorted(data.author_of_year.keys())):
600 authordict = data.author_of_year[yy]
601 authors = getkeyssortedbyvalues(authordict)
602 authors.reverse()
603 commits = data.author_of_year[yy][authors[0]]
604 next = ', '.join(authors[1:5])
605 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))
606 f.write('</table>')
608 f.write('</body></html>')
609 f.close()
612 # Files
613 f = open(path + '/files.html', 'w')
614 self.printHeader(f)
615 f.write('<h1>Files</h1>')
616 self.printNav(f)
618 f.write('<dl>\n')
619 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
620 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
621 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
622 f.write('</dl>\n')
624 # Files :: File count by date
625 f.write(html_header(2, 'File count by date'))
627 fg = open(path + '/files_by_date.dat', 'w')
628 for stamp in sorted(data.files_by_stamp.keys()):
629 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
630 fg.close()
632 f.write('<img src="files_by_date.png" alt="Files by Date" />')
634 #f.write('<h2>Average file size by date</h2>')
636 # Files :: Extensions
637 f.write(html_header(2, 'Extensions'))
638 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
639 for ext in sorted(data.extensions.keys()):
640 files = data.extensions[ext]['files']
641 lines = data.extensions[ext]['lines']
642 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))
643 f.write('</table>')
645 f.write('</body></html>')
646 f.close()
649 # Lines
650 f = open(path + '/lines.html', 'w')
651 self.printHeader(f)
652 f.write('<h1>Lines</h1>')
653 self.printNav(f)
655 f.write('<dl>\n')
656 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
657 f.write('</dl>\n')
659 f.write(html_header(2, 'Lines of Code'))
660 f.write('<img src="lines_of_code.png" />')
662 fg = open(path + '/lines_of_code.dat', 'w')
663 for stamp in sorted(data.changes_by_date.keys()):
664 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
665 fg.close()
667 f.write('</body></html>')
668 f.close()
671 # tags.html
672 f = open(path + '/tags.html', 'w')
673 self.printHeader(f)
674 f.write('<h1>Tags</h1>')
675 self.printNav(f)
677 f.write('<dl>')
678 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
679 if len(data.tags) > 0:
680 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
681 f.write('</dl>')
683 f.write('<table>')
684 f.write('<tr><th>Name</th><th>Date</th></tr>')
685 # sort the tags by date desc
686 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
687 for tag in tags_sorted_by_date_desc:
688 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
689 f.write('</table>')
691 f.write('</body></html>')
692 f.close()
694 self.createGraphs(path)
695 pass
697 def createGraphs(self, path):
698 print 'Generating graphs...'
700 # hour of day
701 f = open(path + '/hour_of_day.plot', 'w')
702 f.write(GNUPLOT_COMMON)
703 f.write(
705 set output 'hour_of_day.png'
706 unset key
707 set xrange [0.5:24.5]
708 set xtics 4
709 set ylabel "Commits"
710 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
711 """)
712 f.close()
714 # day of week
715 f = open(path + '/day_of_week.plot', 'w')
716 f.write(GNUPLOT_COMMON)
717 f.write(
719 set output 'day_of_week.png'
720 unset key
721 set xrange [0.5:7.5]
722 set xtics 1
723 set ylabel "Commits"
724 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
725 """)
726 f.close()
728 # Month of Year
729 f = open(path + '/month_of_year.plot', 'w')
730 f.write(GNUPLOT_COMMON)
731 f.write(
733 set output 'month_of_year.png'
734 unset key
735 set xrange [0.5:12.5]
736 set xtics 1
737 set ylabel "Commits"
738 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
739 """)
740 f.close()
742 # commits_by_year_month
743 f = open(path + '/commits_by_year_month.plot', 'w')
744 f.write(GNUPLOT_COMMON)
745 f.write(
747 set output 'commits_by_year_month.png'
748 unset key
749 set xdata time
750 set timefmt "%Y-%m"
751 set format x "%Y-%m"
752 set xtics rotate by 90 15768000
753 set bmargin 5
754 set ylabel "Commits"
755 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
756 """)
757 f.close()
759 # commits_by_year
760 f = open(path + '/commits_by_year.plot', 'w')
761 f.write(GNUPLOT_COMMON)
762 f.write(
764 set output 'commits_by_year.png'
765 unset key
766 set xtics 1
767 set ylabel "Commits"
768 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
769 """)
770 f.close()
772 # Files by date
773 f = open(path + '/files_by_date.plot', 'w')
774 f.write(GNUPLOT_COMMON)
775 f.write(
777 set output 'files_by_date.png'
778 unset key
779 set xdata time
780 set timefmt "%Y-%m-%d"
781 set format x "%Y-%m-%d"
782 set ylabel "Files"
783 set xtics rotate by 90
784 set bmargin 6
785 plot 'files_by_date.dat' using 1:2 smooth csplines
786 """)
787 f.close()
789 # Lines of Code
790 f = open(path + '/lines_of_code.plot', 'w')
791 f.write(GNUPLOT_COMMON)
792 f.write(
794 set output 'lines_of_code.png'
795 unset key
796 set xdata time
797 set timefmt "%s"
798 set format x "%Y-%m-%d"
799 set ylabel "Lines"
800 set xtics rotate by 90
801 set bmargin 6
802 plot 'lines_of_code.dat' using 1:2 w lines
803 """)
804 f.close()
806 os.chdir(path)
807 files = glob.glob(path + '/*.plot')
808 for f in files:
809 out = getpipeoutput((gnuplot_cmd + ' "%s"' % f,))
810 if len(out) > 0:
811 print out
813 def printHeader(self, f, title = ''):
814 f.write(
815 """<?xml version="1.0" encoding="UTF-8"?>
816 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
817 <html xmlns="http://www.w3.org/1999/xhtml">
818 <head>
819 <title>GitStats - %s</title>
820 <link rel="stylesheet" href="gitstats.css" type="text/css" />
821 <meta name="generator" content="GitStats" />
822 </head>
823 <body>
824 """ % self.title)
826 def printNav(self, f):
827 f.write("""
828 <div class="nav">
829 <ul>
830 <li><a href="index.html">General</a></li>
831 <li><a href="activity.html">Activity</a></li>
832 <li><a href="authors.html">Authors</a></li>
833 <li><a href="files.html">Files</a></li>
834 <li><a href="lines.html">Lines</a></li>
835 <li><a href="tags.html">Tags</a></li>
836 </ul>
837 </div>
838 """)
841 usage = """
842 Usage: gitstats [options] <gitpath> <outputpath>
844 Options:
847 if len(sys.argv) < 3:
848 print usage
849 sys.exit(0)
851 gitpath = sys.argv[1]
852 outputpath = os.path.abspath(sys.argv[2])
853 rundir = os.getcwd()
855 try:
856 os.makedirs(outputpath)
857 except OSError:
858 pass
859 if not os.path.isdir(outputpath):
860 print 'FATAL: Output path is not a directory or does not exist'
861 sys.exit(1)
863 print 'Git path: %s' % gitpath
864 print 'Output path: %s' % outputpath
866 os.chdir(gitpath)
868 print 'Collecting data...'
869 data = GitDataCollector()
870 data.collect(gitpath)
871 print 'Refining data...'
872 data.refine()
874 os.chdir(rundir)
876 print 'Generating report...'
877 report = HTMLReportCreator()
878 report.create(data, outputpath)
880 time_end = time.time()
881 exectime_internal = time_end - time_start
882 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)