Merge branch 'work' into windows
[gitstats.git] / gitstats
blobe79f9cd579e5d6018e09669039fd53a2ceac084f
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()
56 # This should be the main function to extract data from the repository.
57 def collect(self, dir):
58 self.dir = dir
59 self.projectname = os.path.basename(os.path.abspath(dir))
62 # Produce any additional statistics from the extracted data.
63 def refine(self):
64 pass
67 # : get a dictionary of author
68 def getAuthorInfo(self, author):
69 return None
71 def getActivityByDayOfWeek(self):
72 return {}
74 def getActivityByHourOfDay(self):
75 return {}
78 # Get a list of authors
79 def getAuthors(self):
80 return []
82 def getFirstCommitDate(self):
83 return datetime.datetime.now()
85 def getLastCommitDate(self):
86 return datetime.datetime.now()
88 def getStampCreated(self):
89 return self.stamp_created
91 def getTags(self):
92 return []
94 def getTotalAuthors(self):
95 return -1
97 def getTotalCommits(self):
98 return -1
100 def getTotalFiles(self):
101 return -1
103 def getTotalLOC(self):
104 return -1
106 class GitDataCollector(DataCollector):
107 def collect(self, dir):
108 DataCollector.collect(self, dir)
110 try:
111 self.total_authors = int(getpipeoutput(['git-log', 'git-shortlog -s', 'wc -l']))
112 except:
113 self.total_authors = 0
114 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
116 self.activity_by_hour_of_day = {} # hour -> commits
117 self.activity_by_day_of_week = {} # day -> commits
118 self.activity_by_month_of_year = {} # month [1-12] -> commits
119 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
121 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
123 # author of the month
124 self.author_of_month = {} # month -> author -> commits
125 self.author_of_year = {} # year -> author -> commits
126 self.commits_by_month = {} # month -> commits
127 self.commits_by_year = {} # year -> commits
128 self.first_commit_stamp = 0
129 self.last_commit_stamp = 0
131 # tags
132 self.tags = {}
133 lines = getpipeoutput(['git-show-ref --tags']).split('\n')
134 for line in lines:
135 if len(line) == 0:
136 continue
137 print "line = ", line
138 splitted_str = line.split(' ')
139 print "splitted_str = ", splitted_str
140 (hash, tag) = splitted_str
142 tag = tag.replace('refs/tags/', '')
143 output = getpipeoutput(['git-log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
144 if len(output) > 0:
145 parts = output.split(' ')
146 stamp = 0
147 try:
148 stamp = int(parts[0])
149 except ValueError:
150 stamp = 0
151 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
153 # Collect revision statistics
154 # Outputs "<stamp> <author>"
155 lines = getpipeoutput(['git-rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
156 for line in lines:
157 # linux-2.6 says "<unknown>" for one line O_o
158 parts = line.split(' ')
159 author = ''
160 try:
161 stamp = int(parts[0])
162 except ValueError:
163 print "lines = ", lines
164 print "line = ", line
165 raise
166 stamp = 0
167 if len(parts) > 1:
168 author = ' '.join(parts[1:])
169 date = datetime.datetime.fromtimestamp(float(stamp))
171 # First and last commit stamp
172 if self.last_commit_stamp == 0:
173 self.last_commit_stamp = stamp
174 self.first_commit_stamp = stamp
176 # activity
177 # hour
178 hour = date.hour
179 if hour in self.activity_by_hour_of_day:
180 self.activity_by_hour_of_day[hour] += 1
181 else:
182 self.activity_by_hour_of_day[hour] = 1
184 # day of week
185 day = date.weekday()
186 if day in self.activity_by_day_of_week:
187 self.activity_by_day_of_week[day] += 1
188 else:
189 self.activity_by_day_of_week[day] = 1
191 # hour of week
192 if day not in self.activity_by_hour_of_week:
193 self.activity_by_hour_of_week[day] = {}
194 if hour not in self.activity_by_hour_of_week[day]:
195 self.activity_by_hour_of_week[day][hour] = 1
196 else:
197 self.activity_by_hour_of_week[day][hour] += 1
199 # month of year
200 month = date.month
201 if month in self.activity_by_month_of_year:
202 self.activity_by_month_of_year[month] += 1
203 else:
204 self.activity_by_month_of_year[month] = 1
206 # author stats
207 if author not in self.authors:
208 self.authors[author] = {}
209 # commits
210 if 'last_commit_stamp' not in self.authors[author]:
211 self.authors[author]['last_commit_stamp'] = stamp
212 self.authors[author]['first_commit_stamp'] = stamp
213 if 'commits' in self.authors[author]:
214 self.authors[author]['commits'] += 1
215 else:
216 self.authors[author]['commits'] = 1
218 # author of the month/year
219 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
220 if yymm in self.author_of_month:
221 if author in self.author_of_month[yymm]:
222 self.author_of_month[yymm][author] += 1
223 else:
224 self.author_of_month[yymm][author] = 1
225 else:
226 self.author_of_month[yymm] = {}
227 self.author_of_month[yymm][author] = 1
228 if yymm in self.commits_by_month:
229 self.commits_by_month[yymm] += 1
230 else:
231 self.commits_by_month[yymm] = 1
233 yy = datetime.datetime.fromtimestamp(stamp).year
234 if yy in self.author_of_year:
235 if author in self.author_of_year[yy]:
236 self.author_of_year[yy][author] += 1
237 else:
238 self.author_of_year[yy][author] = 1
239 else:
240 self.author_of_year[yy] = {}
241 self.author_of_year[yy][author] = 1
242 if yy in self.commits_by_year:
243 self.commits_by_year[yy] += 1
244 else:
245 self.commits_by_year[yy] = 1
247 # TODO Optimize this, it's the worst bottleneck
248 # outputs "<stamp> <files>" for each revision
249 self.files_by_stamp = {} # stamp -> files
250 revlines = getpipeoutput(['git-rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
251 lines = []
252 for revline in revlines:
253 time, rev = revline.split(' ')
254 linecount = int(getpipeoutput(['git-ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
255 lines.append('%d %d' % (int(time), linecount))
257 self.total_commits = len(lines)
258 for line in lines:
259 parts = line.split(' ')
260 if len(parts) != 2:
261 continue
262 (stamp, files) = parts[0:2]
263 try:
264 self.files_by_stamp[int(stamp)] = int(files)
265 except ValueError:
266 print 'Warning: failed to parse line "%s"' % line
268 # extensions
269 self.extensions = {} # extension -> files, lines
270 lines = getpipeoutput(['git-ls-files']).split('\n')
271 self.total_files = len(lines)
272 for line in lines:
273 base = os.path.basename(line)
274 if base.find('.') == -1:
275 ext = ''
276 else:
277 ext = base[(base.rfind('.') + 1):]
279 if ext not in self.extensions:
280 self.extensions[ext] = {'files': 0, 'lines': 0}
282 self.extensions[ext]['files'] += 1
283 try:
284 # Escaping could probably be improved here
285 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
286 except:
287 print 'Warning: Could not count lines for file "%s"' % line
289 # line statistics
290 # outputs:
291 # N files changed, N insertions (+), N deletions(-)
292 # <stamp> <author>
293 self.changes_by_date = {} # stamp -> { files, ins, del }
294 lines = getpipeoutput(['git-log --shortstat --pretty=format:"%at %an"']).split('\n')
295 lines.reverse()
296 files = 0; inserted = 0; deleted = 0; total_lines = 0
297 for line in lines:
298 if len(line) == 0:
299 continue
301 # <stamp> <author>
302 if line.find('files changed,') == -1:
303 pos = line.find(' ')
304 if pos != -1:
305 try:
306 (stamp, author) = (int(line[:pos]), line[pos+1:])
307 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
308 except ValueError:
309 print 'Warning: unexpected line "%s"' % line
310 else:
311 print 'Warning: unexpected line "%s"' % line
312 else:
313 numbers = re.findall('\d+', line)
314 if len(numbers) == 3:
315 (files, inserted, deleted) = map(lambda el : int(el), numbers)
316 total_lines += inserted
317 total_lines -= deleted
318 else:
319 print 'Warning: failed to handle line "%s"' % line
320 (files, inserted, deleted) = (0, 0, 0)
321 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
322 self.total_lines = total_lines
324 def refine(self):
325 # authors
326 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
327 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
328 authors_by_commits.reverse() # most first
329 for i, name in enumerate(authors_by_commits):
330 self.authors[name]['place_by_commits'] = i + 1
332 for name in self.authors.keys():
333 a = self.authors[name]
334 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
335 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
336 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
337 delta = date_last - date_first
338 a['date_first'] = date_first.strftime('%Y-%m-%d')
339 a['date_last'] = date_last.strftime('%Y-%m-%d')
340 a['timedelta'] = delta
342 def getActivityByDayOfWeek(self):
343 return self.activity_by_day_of_week
345 def getActivityByHourOfDay(self):
346 return self.activity_by_hour_of_day
348 def getAuthorInfo(self, author):
349 return self.authors[author]
351 def getAuthors(self):
352 return self.authors.keys()
354 def getFirstCommitDate(self):
355 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
357 def getLastCommitDate(self):
358 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
360 def getTags(self):
361 lines = getpipeoutput(['git-show-ref --tags', 'cut -d/ -f3'])
362 return lines.split('\n')
364 def getTagDate(self, tag):
365 return self.revToDate('tags/' + tag)
367 def getTotalAuthors(self):
368 return self.total_authors
370 def getTotalCommits(self):
371 return self.total_commits
373 def getTotalFiles(self):
374 return self.total_files
376 def getTotalLOC(self):
377 return self.total_lines
379 def revToDate(self, rev):
380 stamp = int(getpipeoutput(['git-log --pretty=format:%%at "%s" -n 1' % rev]))
381 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
383 class ReportCreator:
384 """Creates the actual report based on given data."""
385 def __init__(self):
386 pass
388 def create(self, data, path):
389 self.data = data
390 self.path = path
392 def html_linkify(text):
393 return text.lower().replace(' ', '_')
395 def html_header(level, text):
396 name = html_linkify(text)
397 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
399 class HTMLReportCreator(ReportCreator):
400 def create(self, data, path):
401 ReportCreator.create(self, data, path)
402 self.title = data.projectname
404 # copy the CSS if it does not exist
405 if not os.path.exists(path + '/gitstats.css'):
406 basedir = os.path.dirname(os.path.abspath(__file__))
407 shutil.copyfile(basedir + '/gitstats.css', path + '/gitstats.css')
409 f = open(path + "/index.html", 'w')
410 format = '%Y-%m-%d %H:%m:%S'
411 self.printHeader(f)
413 f.write('<h1>GitStats - %s</h1>' % data.projectname)
415 self.printNav(f)
417 f.write('<dl>');
418 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
419 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
420 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
421 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
422 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
423 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
424 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
425 f.write('</dl>');
427 f.write('</body>\n</html>');
428 f.close()
431 # Activity
432 f = open(path + '/activity.html', 'w')
433 self.printHeader(f)
434 f.write('<h1>Activity</h1>')
435 self.printNav(f)
437 #f.write('<h2>Last 30 days</h2>')
439 #f.write('<h2>Last 12 months</h2>')
441 # Hour of Day
442 f.write(html_header(2, 'Hour of Day'))
443 hour_of_day = data.getActivityByHourOfDay()
444 f.write('<table><tr><th>Hour</th>')
445 for i in range(1, 25):
446 f.write('<th>%d</th>' % i)
447 f.write('</tr>\n<tr><th>Commits</th>')
448 fp = open(path + '/hour_of_day.dat', 'w')
449 for i in range(0, 24):
450 if i in hour_of_day:
451 f.write('<td>%d</td>' % hour_of_day[i])
452 fp.write('%d %d\n' % (i, hour_of_day[i]))
453 else:
454 f.write('<td>0</td>')
455 fp.write('%d 0\n' % i)
456 fp.close()
457 f.write('</tr>\n<tr><th>%</th>')
458 totalcommits = data.getTotalCommits()
459 for i in range(0, 24):
460 if i in hour_of_day:
461 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
462 else:
463 f.write('<td>0.00</td>')
464 f.write('</tr></table>')
465 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
466 fg = open(path + '/hour_of_day.dat', 'w')
467 for i in range(0, 24):
468 if i in hour_of_day:
469 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
470 else:
471 fg.write('%d 0\n' % (i + 1))
472 fg.close()
474 # Day of Week
475 f.write(html_header(2, 'Day of Week'))
476 day_of_week = data.getActivityByDayOfWeek()
477 f.write('<div class="vtable"><table>')
478 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
479 fp = open(path + '/day_of_week.dat', 'w')
480 for d in range(0, 7):
481 commits = 0
482 if d in day_of_week:
483 commits = day_of_week[d]
484 fp.write('%d %d\n' % (d + 1, commits))
485 f.write('<tr>')
486 f.write('<th>%d</th>' % (d + 1))
487 if d in day_of_week:
488 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
489 else:
490 f.write('<td>0</td>')
491 f.write('</tr>')
492 f.write('</table></div>')
493 f.write('<img src="day_of_week.png" alt="Day of Week" />')
494 fp.close()
496 # Hour of Week
497 f.write(html_header(2, 'Hour of Week'))
498 f.write('<table>')
500 f.write('<tr><th>Weekday</th>')
501 for hour in range(0, 24):
502 f.write('<th>%d</th>' % (hour + 1))
503 f.write('</tr>')
505 for weekday in range(0, 7):
506 f.write('<tr><th>%d</th>' % (weekday + 1))
507 for hour in range(0, 24):
508 try:
509 commits = data.activity_by_hour_of_week[weekday][hour]
510 except KeyError:
511 commits = 0
512 if commits != 0:
513 f.write('<td>%d</td>' % commits)
514 else:
515 f.write('<td></td>')
516 f.write('</tr>')
518 f.write('</table>')
520 # Month of Year
521 f.write(html_header(2, 'Month of Year'))
522 f.write('<div class="vtable"><table>')
523 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
524 fp = open (path + '/month_of_year.dat', 'w')
525 for mm in range(1, 13):
526 commits = 0
527 if mm in data.activity_by_month_of_year:
528 commits = data.activity_by_month_of_year[mm]
529 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
530 fp.write('%d %d\n' % (mm, commits))
531 fp.close()
532 f.write('</table></div>')
533 f.write('<img src="month_of_year.png" alt="Month of Year" />')
535 # Commits by year/month
536 f.write(html_header(2, 'Commits by year/month'))
537 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
538 for yymm in reversed(sorted(data.commits_by_month.keys())):
539 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
540 f.write('</table></div>')
541 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
542 fg = open(path + '/commits_by_year_month.dat', 'w')
543 for yymm in sorted(data.commits_by_month.keys()):
544 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
545 fg.close()
547 # Commits by year
548 f.write(html_header(2, 'Commits by Year'))
549 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
550 for yy in reversed(sorted(data.commits_by_year.keys())):
551 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()))
552 f.write('</table></div>')
553 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
554 fg = open(path + '/commits_by_year.dat', 'w')
555 for yy in sorted(data.commits_by_year.keys()):
556 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
557 fg.close()
559 f.write('</body></html>')
560 f.close()
563 # Authors
564 f = open(path + '/authors.html', 'w')
565 self.printHeader(f)
567 f.write('<h1>Authors</h1>')
568 self.printNav(f)
570 # Authors :: List of authors
571 f.write(html_header(2, 'List of Authors'))
573 f.write('<table class="authors">')
574 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>')
575 for author in sorted(data.getAuthors()):
576 info = data.getAuthorInfo(author)
577 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']))
578 f.write('</table>')
580 # Authors :: Author of Month
581 f.write(html_header(2, 'Author of Month'))
582 f.write('<table>')
583 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
584 for yymm in reversed(sorted(data.author_of_month.keys())):
585 authordict = data.author_of_month[yymm]
586 authors = getkeyssortedbyvalues(authordict)
587 authors.reverse()
588 commits = data.author_of_month[yymm][authors[0]]
589 next = ', '.join(authors[1:5])
590 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))
592 f.write('</table>')
594 f.write(html_header(2, 'Author of Year'))
595 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
596 for yy in reversed(sorted(data.author_of_year.keys())):
597 authordict = data.author_of_year[yy]
598 authors = getkeyssortedbyvalues(authordict)
599 authors.reverse()
600 commits = data.author_of_year[yy][authors[0]]
601 next = ', '.join(authors[1:5])
602 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))
603 f.write('</table>')
605 f.write('</body></html>')
606 f.close()
609 # Files
610 f = open(path + '/files.html', 'w')
611 self.printHeader(f)
612 f.write('<h1>Files</h1>')
613 self.printNav(f)
615 f.write('<dl>\n')
616 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
617 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
618 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
619 f.write('</dl>\n')
621 # Files :: File count by date
622 f.write(html_header(2, 'File count by date'))
624 fg = open(path + '/files_by_date.dat', 'w')
625 for stamp in sorted(data.files_by_stamp.keys()):
626 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
627 fg.close()
629 f.write('<img src="files_by_date.png" alt="Files by Date" />')
631 #f.write('<h2>Average file size by date</h2>')
633 # Files :: Extensions
634 f.write(html_header(2, 'Extensions'))
635 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
636 for ext in sorted(data.extensions.keys()):
637 files = data.extensions[ext]['files']
638 lines = data.extensions[ext]['lines']
639 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))
640 f.write('</table>')
642 f.write('</body></html>')
643 f.close()
646 # Lines
647 f = open(path + '/lines.html', 'w')
648 self.printHeader(f)
649 f.write('<h1>Lines</h1>')
650 self.printNav(f)
652 f.write('<dl>\n')
653 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
654 f.write('</dl>\n')
656 f.write(html_header(2, 'Lines of Code'))
657 f.write('<img src="lines_of_code.png" />')
659 fg = open(path + '/lines_of_code.dat', 'w')
660 for stamp in sorted(data.changes_by_date.keys()):
661 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
662 fg.close()
664 f.write('</body></html>')
665 f.close()
668 # tags.html
669 f = open(path + '/tags.html', 'w')
670 self.printHeader(f)
671 f.write('<h1>Tags</h1>')
672 self.printNav(f)
674 f.write('<dl>')
675 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
676 if len(data.tags) > 0:
677 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
678 f.write('</dl>')
680 f.write('<table>')
681 f.write('<tr><th>Name</th><th>Date</th></tr>')
682 # sort the tags by date desc
683 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
684 for tag in tags_sorted_by_date_desc:
685 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
686 f.write('</table>')
688 f.write('</body></html>')
689 f.close()
691 self.createGraphs(path)
693 def createGraphs(self, path):
694 print 'Generating graphs...'
696 # hour of day
697 f = open(path + '/hour_of_day.plot', 'w')
698 f.write(GNUPLOT_COMMON)
699 f.write(
701 set output 'hour_of_day.png'
702 unset key
703 set xrange [0.5:24.5]
704 set xtics 4
705 set ylabel "Commits"
706 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
707 """)
708 f.close()
710 # day of week
711 f = open(path + '/day_of_week.plot', 'w')
712 f.write(GNUPLOT_COMMON)
713 f.write(
715 set output 'day_of_week.png'
716 unset key
717 set xrange [0.5:7.5]
718 set xtics 1
719 set ylabel "Commits"
720 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
721 """)
722 f.close()
724 # Month of Year
725 f = open(path + '/month_of_year.plot', 'w')
726 f.write(GNUPLOT_COMMON)
727 f.write(
729 set output 'month_of_year.png'
730 unset key
731 set xrange [0.5:12.5]
732 set xtics 1
733 set ylabel "Commits"
734 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
735 """)
736 f.close()
738 # commits_by_year_month
739 f = open(path + '/commits_by_year_month.plot', 'w')
740 f.write(GNUPLOT_COMMON)
741 f.write(
743 set output 'commits_by_year_month.png'
744 unset key
745 set xdata time
746 set timefmt "%Y-%m"
747 set format x "%Y-%m"
748 set xtics rotate by 90 15768000
749 set bmargin 5
750 set ylabel "Commits"
751 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
752 """)
753 f.close()
755 # commits_by_year
756 f = open(path + '/commits_by_year.plot', 'w')
757 f.write(GNUPLOT_COMMON)
758 f.write(
760 set output 'commits_by_year.png'
761 unset key
762 set xtics 1
763 set ylabel "Commits"
764 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
765 """)
766 f.close()
768 # Files by date
769 f = open(path + '/files_by_date.plot', 'w')
770 f.write(GNUPLOT_COMMON)
771 f.write(
773 set output 'files_by_date.png'
774 unset key
775 set xdata time
776 set timefmt "%Y-%m-%d"
777 set format x "%Y-%m-%d"
778 set ylabel "Files"
779 set xtics rotate by 90
780 set bmargin 6
781 plot 'files_by_date.dat' using 1:2 smooth csplines
782 """)
783 f.close()
785 # Lines of Code
786 f = open(path + '/lines_of_code.plot', 'w')
787 f.write(GNUPLOT_COMMON)
788 f.write(
790 set output 'lines_of_code.png'
791 unset key
792 set xdata time
793 set timefmt "%s"
794 set format x "%Y-%m-%d"
795 set ylabel "Lines"
796 set xtics rotate by 90
797 set bmargin 6
798 plot 'lines_of_code.dat' using 1:2 w lines
799 """)
800 f.close()
802 os.chdir(path)
803 files = glob.glob(path + '/*.plot')
804 for f in files:
805 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
806 if len(out) > 0:
807 print out
809 def printHeader(self, f, title = ''):
810 f.write(
811 """<?xml version="1.0" encoding="UTF-8"?>
812 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
813 <html xmlns="http://www.w3.org/1999/xhtml">
814 <head>
815 <title>GitStats - %s</title>
816 <link rel="stylesheet" href="gitstats.css" type="text/css" />
817 <meta name="generator" content="GitStats" />
818 </head>
819 <body>
820 """ % self.title)
822 def printNav(self, f):
823 f.write("""
824 <div class="nav">
825 <ul>
826 <li><a href="index.html">General</a></li>
827 <li><a href="activity.html">Activity</a></li>
828 <li><a href="authors.html">Authors</a></li>
829 <li><a href="files.html">Files</a></li>
830 <li><a href="lines.html">Lines</a></li>
831 <li><a href="tags.html">Tags</a></li>
832 </ul>
833 </div>
834 """)
837 usage = """
838 Usage: gitstats [options] <gitpath> <outputpath>
840 Options:
843 if len(sys.argv) < 3:
844 print usage
845 sys.exit(0)
847 gitpath = sys.argv[1]
848 outputpath = os.path.abspath(sys.argv[2])
849 rundir = os.getcwd()
851 try:
852 os.makedirs(outputpath)
853 except OSError:
854 pass
855 if not os.path.isdir(outputpath):
856 print 'FATAL: Output path is not a directory or does not exist'
857 sys.exit(1)
859 print 'Git path: %s' % gitpath
860 print 'Output path: %s' % outputpath
862 os.chdir(gitpath)
864 print 'Collecting data...'
865 data = GitDataCollector()
866 data.collect(gitpath)
867 print 'Refining data...'
868 data.refine()
870 os.chdir(rundir)
872 print 'Generating report...'
873 report = HTMLReportCreator()
874 report.create(data, outputpath)
876 time_end = time.time()
877 exectime_internal = time_end - time_start
878 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)