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