Cleanup.
[gitstats.git] / gitstats
blob2a7db38a57bf788b0cf113aa17aa3503265d7ab8
1 #!/usr/bin/env python
2 # Copyright (c) 2007 Heikki Hokkanen <hoxu@users.sf.net>
3 # GPLv2
4 import commands
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 def getoutput(cmd, quiet = False):
20 global exectime_external
21 start = time.time()
22 if not quiet:
23 print '>> %s' % cmd,
24 sys.stdout.flush()
25 output = commands.getoutput(cmd)
26 end = time.time()
27 if not quiet:
28 print '\r[%.5f] >> %s' % (end - start, cmd)
29 exectime_external += (end - start)
30 return output
32 def getkeyssortedbyvalues(dict):
33 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
35 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
36 def getkeyssortedbyvaluekey(d, key):
37 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
39 class DataCollector:
40 """Manages data collection from a revision control repository."""
41 def __init__(self):
42 self.stamp_created = time.time()
45 # This should be the main function to extract data from the repository.
46 def collect(self, dir):
47 self.dir = dir
48 self.projectname = os.path.basename(os.path.abspath(dir))
51 # Produce any additional statistics from the extracted data.
52 def refine(self):
53 pass
56 # : get a dictionary of author
57 def getAuthorInfo(self, author):
58 return None
60 def getActivityByDayOfWeek(self):
61 return {}
63 def getActivityByHourOfDay(self):
64 return {}
67 # Get a list of authors
68 def getAuthors(self):
69 return []
71 def getFirstCommitDate(self):
72 return datetime.datetime.now()
74 def getLastCommitDate(self):
75 return datetime.datetime.now()
77 def getStampCreated(self):
78 return self.stamp_created
80 def getTags(self):
81 return []
83 def getTotalAuthors(self):
84 return -1
86 def getTotalCommits(self):
87 return -1
89 def getTotalFiles(self):
90 return -1
92 def getTotalLOC(self):
93 return -1
95 class GitDataCollector(DataCollector):
96 def collect(self, dir):
97 DataCollector.collect(self, dir)
99 self.total_authors = int(getoutput('git-log |git-shortlog -s |wc -l'))
100 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
102 self.activity_by_hour_of_day = {} # hour -> commits
103 self.activity_by_day_of_week = {} # day -> commits
104 self.activity_by_month_of_year = {} # month [1-12] -> commits
105 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
107 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
109 # author of the month
110 self.author_of_month = {} # month -> author -> commits
111 self.author_of_year = {} # year -> author -> commits
112 self.commits_by_month = {} # month -> commits
113 self.commits_by_year = {} # year -> commits
114 self.first_commit_stamp = 0
115 self.last_commit_stamp = 0
117 # tags
118 self.tags = {}
119 lines = getoutput('git-show-ref --tags').split('\n')
120 for line in lines:
121 if len(line) == 0:
122 continue
123 (hash, tag) = line.split(' ')
124 tag = tag.replace('refs/tags/', '')
125 output = getoutput('git-log "%s" --pretty=format:"%%at %%an" -n 1' % hash)
126 if len(output) > 0:
127 parts = output.split(' ')
128 stamp = 0
129 try:
130 stamp = int(parts[0])
131 except ValueError:
132 stamp = 0
133 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
135 # Collect revision statistics
136 # Outputs "<stamp> <author>"
137 lines = getoutput('git-rev-list --pretty=format:"%at %an" HEAD |grep -v ^commit').split('\n')
138 for line in lines:
139 # linux-2.6 says "<unknown>" for one line O_o
140 parts = line.split(' ')
141 author = ''
142 try:
143 stamp = int(parts[0])
144 except ValueError:
145 stamp = 0
146 if len(parts) > 1:
147 author = ' '.join(parts[1:])
148 date = datetime.datetime.fromtimestamp(float(stamp))
150 # First and last commit stamp
151 if self.last_commit_stamp == 0:
152 self.last_commit_stamp = stamp
153 self.first_commit_stamp = stamp
155 # activity
156 # hour
157 hour = date.hour
158 if hour in self.activity_by_hour_of_day:
159 self.activity_by_hour_of_day[hour] += 1
160 else:
161 self.activity_by_hour_of_day[hour] = 1
163 # day of week
164 day = date.weekday()
165 if day in self.activity_by_day_of_week:
166 self.activity_by_day_of_week[day] += 1
167 else:
168 self.activity_by_day_of_week[day] = 1
170 # hour of week
171 if day not in self.activity_by_hour_of_week:
172 self.activity_by_hour_of_week[day] = {}
173 if hour not in self.activity_by_hour_of_week[day]:
174 self.activity_by_hour_of_week[day][hour] = 1
175 else:
176 self.activity_by_hour_of_week[day][hour] += 1
178 # month of year
179 month = date.month
180 if month in self.activity_by_month_of_year:
181 self.activity_by_month_of_year[month] += 1
182 else:
183 self.activity_by_month_of_year[month] = 1
185 # author stats
186 if author not in self.authors:
187 self.authors[author] = {}
188 # commits
189 if 'last_commit_stamp' not in self.authors[author]:
190 self.authors[author]['last_commit_stamp'] = stamp
191 self.authors[author]['first_commit_stamp'] = stamp
192 if 'commits' in self.authors[author]:
193 self.authors[author]['commits'] += 1
194 else:
195 self.authors[author]['commits'] = 1
197 # author of the month/year
198 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
199 if yymm in self.author_of_month:
200 if author in self.author_of_month[yymm]:
201 self.author_of_month[yymm][author] += 1
202 else:
203 self.author_of_month[yymm][author] = 1
204 else:
205 self.author_of_month[yymm] = {}
206 self.author_of_month[yymm][author] = 1
207 if yymm in self.commits_by_month:
208 self.commits_by_month[yymm] += 1
209 else:
210 self.commits_by_month[yymm] = 1
212 yy = datetime.datetime.fromtimestamp(stamp).year
213 if yy in self.author_of_year:
214 if author in self.author_of_year[yy]:
215 self.author_of_year[yy][author] += 1
216 else:
217 self.author_of_year[yy][author] = 1
218 else:
219 self.author_of_year[yy] = {}
220 self.author_of_year[yy][author] = 1
221 if yy in self.commits_by_year:
222 self.commits_by_year[yy] += 1
223 else:
224 self.commits_by_year[yy] = 1
226 # TODO Optimize this, it's the worst bottleneck
227 # outputs "<stamp> <files>" for each revision
228 self.files_by_stamp = {} # stamp -> files
229 lines = getoutput('git-rev-list --pretty=format:"%at %T" HEAD |grep -v ^commit |while read line; do set $line; echo "$1 $(git-ls-tree -r --name-only "$2" |wc -l)"; done').split('\n')
230 self.total_commits = len(lines)
231 for line in lines:
232 parts = line.split(' ')
233 if len(parts) != 2:
234 continue
235 (stamp, files) = parts[0:2]
236 try:
237 self.files_by_stamp[int(stamp)] = int(files)
238 except ValueError:
239 print 'Warning: failed to parse line "%s"' % line
241 # extensions
242 self.extensions = {} # extension -> files, lines
243 lines = getoutput('git-ls-files').split('\n')
244 self.total_files = len(lines)
245 for line in lines:
246 base = os.path.basename(line)
247 if base.find('.') == -1:
248 ext = ''
249 else:
250 ext = base[(base.rfind('.') + 1):]
252 if ext not in self.extensions:
253 self.extensions[ext] = {'files': 0, 'lines': 0}
255 self.extensions[ext]['files'] += 1
256 try:
257 # Escaping could probably be improved here
258 self.extensions[ext]['lines'] += int(getoutput('wc -l < %s' % re.sub(r'(\W)', r'\\\1', line), quiet = True))
259 except:
260 print 'Warning: Could not count lines for file "%s"' % line
262 # line statistics
263 # outputs:
264 # N files changed, N insertions (+), N deletions(-)
265 # <stamp> <author>
266 self.changes_by_date = {} # stamp -> { files, ins, del }
267 lines = getoutput('git-log --shortstat --pretty=format:"%at %an"').split('\n')
268 lines.reverse()
269 files = 0; inserted = 0; deleted = 0; total_lines = 0
270 for line in lines:
271 if len(line) == 0:
272 continue
274 # <stamp> <author>
275 if line.find('files changed,') == -1:
276 pos = line.find(' ')
277 if pos != -1:
278 try:
279 (stamp, author) = (int(line[:pos]), line[pos+1:])
280 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
281 except ValueError:
282 print 'Warning: unexpected line "%s"' % line
283 else:
284 print 'Warning: unexpected line "%s"' % line
285 else:
286 numbers = re.findall('\d+', line)
287 if len(numbers) == 3:
288 (files, inserted, deleted) = map(lambda el : int(el), numbers)
289 total_lines += inserted
290 total_lines -= deleted
291 else:
292 print 'Warning: failed to handle line "%s"' % line
293 (files, inserted, deleted) = (0, 0, 0)
294 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
295 self.total_lines = total_lines
297 def refine(self):
298 # authors
299 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
300 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
301 authors_by_commits.reverse() # most first
302 for i, name in enumerate(authors_by_commits):
303 self.authors[name]['place_by_commits'] = i + 1
305 for name in self.authors.keys():
306 a = self.authors[name]
307 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
308 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
309 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
310 delta = date_last - date_first
311 a['date_first'] = date_first.strftime('%Y-%m-%d')
312 a['date_last'] = date_last.strftime('%Y-%m-%d')
313 a['timedelta'] = delta
315 def getActivityByDayOfWeek(self):
316 return self.activity_by_day_of_week
318 def getActivityByHourOfDay(self):
319 return self.activity_by_hour_of_day
321 def getAuthorInfo(self, author):
322 return self.authors[author]
324 def getAuthors(self):
325 return self.authors.keys()
327 def getFirstCommitDate(self):
328 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
330 def getLastCommitDate(self):
331 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
333 def getTags(self):
334 lines = getoutput('git-show-ref --tags |cut -d/ -f3')
335 return lines.split('\n')
337 def getTagDate(self, tag):
338 return self.revToDate('tags/' + tag)
340 def getTotalAuthors(self):
341 return self.total_authors
343 def getTotalCommits(self):
344 return self.total_commits
346 def getTotalFiles(self):
347 return self.total_files
349 def getTotalLOC(self):
350 return self.total_lines
352 def revToDate(self, rev):
353 stamp = int(getoutput('git-log --pretty=format:%%at "%s" -n 1' % rev))
354 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
356 class ReportCreator:
357 """Creates the actual report based on given data."""
358 def __init__(self):
359 pass
361 def create(self, data, path):
362 self.data = data
363 self.path = path
365 def html_linkify(text):
366 return text.lower().replace(' ', '_')
368 def html_header(level, text):
369 name = html_linkify(text)
370 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
372 class HTMLReportCreator(ReportCreator):
373 def create(self, data, path):
374 ReportCreator.create(self, data, path)
375 self.title = data.projectname
377 # copy the CSS if it does not exist
378 if not os.path.exists(path + '/gitstats.css'):
379 shutil.copyfile('gitstats.css', path + '/gitstats.css')
381 f = open(path + "/index.html", 'w')
382 format = '%Y-%m-%d %H:%m:%S'
383 self.printHeader(f)
385 f.write('<h1>GitStats - %s</h1>' % data.projectname)
387 self.printNav(f)
389 f.write('<dl>');
390 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
391 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
392 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
393 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
394 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
395 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
396 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
397 f.write('</dl>');
399 f.write('</body>\n</html>');
400 f.close()
403 # Activity
404 f = open(path + '/activity.html', 'w')
405 self.printHeader(f)
406 f.write('<h1>Activity</h1>')
407 self.printNav(f)
409 #f.write('<h2>Last 30 days</h2>')
411 #f.write('<h2>Last 12 months</h2>')
413 # Hour of Day
414 f.write(html_header(2, 'Hour of Day'))
415 hour_of_day = data.getActivityByHourOfDay()
416 f.write('<table><tr><th>Hour</th>')
417 for i in range(1, 25):
418 f.write('<th>%d</th>' % i)
419 f.write('</tr>\n<tr><th>Commits</th>')
420 fp = open(path + '/hour_of_day.dat', 'w')
421 for i in range(0, 24):
422 if i in hour_of_day:
423 f.write('<td>%d</td>' % hour_of_day[i])
424 fp.write('%d %d\n' % (i, hour_of_day[i]))
425 else:
426 f.write('<td>0</td>')
427 fp.write('%d 0\n' % i)
428 fp.close()
429 f.write('</tr>\n<tr><th>%</th>')
430 totalcommits = data.getTotalCommits()
431 for i in range(0, 24):
432 if i in hour_of_day:
433 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
434 else:
435 f.write('<td>0.00</td>')
436 f.write('</tr></table>')
437 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
438 fg = open(path + '/hour_of_day.dat', 'w')
439 for i in range(0, 24):
440 if i in hour_of_day:
441 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
442 else:
443 fg.write('%d 0\n' % (i + 1))
444 fg.close()
446 # Day of Week
447 f.write(html_header(2, 'Day of Week'))
448 day_of_week = data.getActivityByDayOfWeek()
449 f.write('<div class="vtable"><table>')
450 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
451 fp = open(path + '/day_of_week.dat', 'w')
452 for d in range(0, 7):
453 commits = 0
454 if d in day_of_week:
455 commits = day_of_week[d]
456 fp.write('%d %d\n' % (d + 1, commits))
457 f.write('<tr>')
458 f.write('<th>%d</th>' % (d + 1))
459 if d in day_of_week:
460 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
461 else:
462 f.write('<td>0</td>')
463 f.write('</tr>')
464 f.write('</table></div>')
465 f.write('<img src="day_of_week.png" alt="Day of Week" />')
466 fp.close()
468 # Hour of Week
469 f.write(html_header(2, 'Hour of Week'))
470 f.write('<table>')
472 f.write('<tr><th>Weekday</th>')
473 for hour in range(0, 24):
474 f.write('<th>%d</th>' % (hour + 1))
475 f.write('</tr>')
477 for weekday in range(0, 7):
478 f.write('<tr><th>%d</th>' % (weekday + 1))
479 for hour in range(0, 24):
480 try:
481 commits = data.activity_by_hour_of_week[weekday][hour]
482 except KeyError:
483 commits = 0
484 if commits != 0:
485 f.write('<td>%d</td>' % commits)
486 else:
487 f.write('<td></td>')
488 f.write('</tr>')
490 f.write('</table>')
492 # Month of Year
493 f.write(html_header(2, 'Month of Year'))
494 f.write('<div class="vtable"><table>')
495 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
496 fp = open (path + '/month_of_year.dat', 'w')
497 for mm in range(1, 13):
498 commits = 0
499 if mm in data.activity_by_month_of_year:
500 commits = data.activity_by_month_of_year[mm]
501 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
502 fp.write('%d %d\n' % (mm, commits))
503 fp.close()
504 f.write('</table></div>')
505 f.write('<img src="month_of_year.png" alt="Month of Year" />')
507 # Commits by year/month
508 f.write(html_header(2, 'Commits by year/month'))
509 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
510 for yymm in reversed(sorted(data.commits_by_month.keys())):
511 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
512 f.write('</table></div>')
513 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
514 fg = open(path + '/commits_by_year_month.dat', 'w')
515 for yymm in sorted(data.commits_by_month.keys()):
516 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
517 fg.close()
519 # Commits by year
520 f.write(html_header(2, 'Commits by Year'))
521 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
522 for yy in reversed(sorted(data.commits_by_year.keys())):
523 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()))
524 f.write('</table></div>')
525 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
526 fg = open(path + '/commits_by_year.dat', 'w')
527 for yy in sorted(data.commits_by_year.keys()):
528 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
529 fg.close()
531 f.write('</body></html>')
532 f.close()
535 # Authors
536 f = open(path + '/authors.html', 'w')
537 self.printHeader(f)
539 f.write('<h1>Authors</h1>')
540 self.printNav(f)
542 # Authors :: List of authors
543 f.write(html_header(2, 'List of Authors'))
545 f.write('<table class="authors">')
546 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>')
547 for author in sorted(data.getAuthors()):
548 info = data.getAuthorInfo(author)
549 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']))
550 f.write('</table>')
552 # Authors :: Author of Month
553 f.write(html_header(2, 'Author of Month'))
554 f.write('<table>')
555 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
556 for yymm in reversed(sorted(data.author_of_month.keys())):
557 authordict = data.author_of_month[yymm]
558 authors = getkeyssortedbyvalues(authordict)
559 authors.reverse()
560 commits = data.author_of_month[yymm][authors[0]]
561 next = ', '.join(authors[1:5])
562 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))
564 f.write('</table>')
566 f.write(html_header(2, 'Author of Year'))
567 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
568 for yy in reversed(sorted(data.author_of_year.keys())):
569 authordict = data.author_of_year[yy]
570 authors = getkeyssortedbyvalues(authordict)
571 authors.reverse()
572 commits = data.author_of_year[yy][authors[0]]
573 next = ', '.join(authors[1:5])
574 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))
575 f.write('</table>')
577 f.write('</body></html>')
578 f.close()
581 # Files
582 f = open(path + '/files.html', 'w')
583 self.printHeader(f)
584 f.write('<h1>Files</h1>')
585 self.printNav(f)
587 f.write('<dl>\n')
588 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
589 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
590 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
591 f.write('</dl>\n')
593 # Files :: File count by date
594 f.write(html_header(2, 'File count by date'))
596 fg = open(path + '/files_by_date.dat', 'w')
597 for stamp in sorted(data.files_by_stamp.keys()):
598 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
599 fg.close()
601 f.write('<img src="files_by_date.png" alt="Files by Date" />')
603 #f.write('<h2>Average file size by date</h2>')
605 # Files :: Extensions
606 f.write(html_header(2, 'Extensions'))
607 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
608 for ext in sorted(data.extensions.keys()):
609 files = data.extensions[ext]['files']
610 lines = data.extensions[ext]['lines']
611 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))
612 f.write('</table>')
614 f.write('</body></html>')
615 f.close()
618 # Lines
619 f = open(path + '/lines.html', 'w')
620 self.printHeader(f)
621 f.write('<h1>Lines</h1>')
622 self.printNav(f)
624 f.write('<dl>\n')
625 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
626 f.write('</dl>\n')
628 f.write(html_header(2, 'Lines of Code'))
629 f.write('<img src="lines_of_code.png" />')
631 fg = open(path + '/lines_of_code.dat', 'w')
632 for stamp in sorted(data.changes_by_date.keys()):
633 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
634 fg.close()
636 f.write('</body></html>')
637 f.close()
640 # tags.html
641 f = open(path + '/tags.html', 'w')
642 self.printHeader(f)
643 f.write('<h1>Tags</h1>')
644 self.printNav(f)
646 f.write('<dl>')
647 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
648 if len(data.tags) > 0:
649 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
650 f.write('</dl>')
652 f.write('<table>')
653 f.write('<tr><th>Name</th><th>Date</th></tr>')
654 # sort the tags by date desc
655 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
656 for tag in tags_sorted_by_date_desc:
657 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
658 f.write('</table>')
660 f.write('</body></html>')
661 f.close()
663 self.createGraphs(path)
665 def createGraphs(self, path):
666 print 'Generating graphs...'
668 # hour of day
669 f = open(path + '/hour_of_day.plot', 'w')
670 f.write(GNUPLOT_COMMON)
671 f.write(
673 set output 'hour_of_day.png'
674 unset key
675 set xrange [0.5:24.5]
676 set xtics 4
677 set ylabel "Commits"
678 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
679 """)
680 f.close()
682 # day of week
683 f = open(path + '/day_of_week.plot', 'w')
684 f.write(GNUPLOT_COMMON)
685 f.write(
687 set output 'day_of_week.png'
688 unset key
689 set xrange [0.5:7.5]
690 set xtics 1
691 set ylabel "Commits"
692 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
693 """)
694 f.close()
696 # Month of Year
697 f = open(path + '/month_of_year.plot', 'w')
698 f.write(GNUPLOT_COMMON)
699 f.write(
701 set output 'month_of_year.png'
702 unset key
703 set xrange [0.5:12.5]
704 set xtics 1
705 set ylabel "Commits"
706 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
707 """)
708 f.close()
710 # commits_by_year_month
711 f = open(path + '/commits_by_year_month.plot', 'w')
712 f.write(GNUPLOT_COMMON)
713 f.write(
715 set output 'commits_by_year_month.png'
716 unset key
717 set xdata time
718 set timefmt "%Y-%m"
719 set format x "%Y-%m"
720 set xtics rotate by 90 15768000
721 set bmargin 5
722 set ylabel "Commits"
723 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
724 """)
725 f.close()
727 # commits_by_year
728 f = open(path + '/commits_by_year.plot', 'w')
729 f.write(GNUPLOT_COMMON)
730 f.write(
732 set output 'commits_by_year.png'
733 unset key
734 set xtics 1
735 set ylabel "Commits"
736 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
737 """)
738 f.close()
740 # Files by date
741 f = open(path + '/files_by_date.plot', 'w')
742 f.write(GNUPLOT_COMMON)
743 f.write(
745 set output 'files_by_date.png'
746 unset key
747 set xdata time
748 set timefmt "%Y-%m-%d"
749 set format x "%Y-%m-%d"
750 set ylabel "Files"
751 set xtics rotate by 90
752 set bmargin 6
753 plot 'files_by_date.dat' using 1:2 smooth csplines
754 """)
755 f.close()
757 # Lines of Code
758 f = open(path + '/lines_of_code.plot', 'w')
759 f.write(GNUPLOT_COMMON)
760 f.write(
762 set output 'lines_of_code.png'
763 unset key
764 set xdata time
765 set timefmt "%s"
766 set format x "%Y-%m-%d"
767 set ylabel "Lines"
768 set xtics rotate by 90
769 set bmargin 6
770 plot 'lines_of_code.dat' using 1:2 w lines
771 """)
772 f.close()
774 os.chdir(path)
775 files = glob.glob(path + '/*.plot')
776 for f in files:
777 out = getoutput('gnuplot %s' % f)
778 if len(out) > 0:
779 print out
781 def printHeader(self, f, title = ''):
782 f.write(
783 """<?xml version="1.0" encoding="UTF-8"?>
784 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
785 <html xmlns="http://www.w3.org/1999/xhtml">
786 <head>
787 <title>GitStats - %s</title>
788 <link rel="stylesheet" href="gitstats.css" type="text/css" />
789 <meta name="generator" content="GitStats" />
790 </head>
791 <body>
792 """ % self.title)
794 def printNav(self, f):
795 f.write("""
796 <div class="nav">
797 <ul>
798 <li><a href="index.html">General</a></li>
799 <li><a href="activity.html">Activity</a></li>
800 <li><a href="authors.html">Authors</a></li>
801 <li><a href="files.html">Files</a></li>
802 <li><a href="lines.html">Lines</a></li>
803 <li><a href="tags.html">Tags</a></li>
804 </ul>
805 </div>
806 """)
809 usage = """
810 Usage: gitstats [options] <gitpath> <outputpath>
812 Options:
815 if len(sys.argv) < 3:
816 print usage
817 sys.exit(0)
819 gitpath = sys.argv[1]
820 outputpath = os.path.abspath(sys.argv[2])
821 rundir = os.getcwd()
823 try:
824 os.makedirs(outputpath)
825 except OSError:
826 pass
827 if not os.path.isdir(outputpath):
828 print 'FATAL: Output path is not a directory or does not exist'
829 sys.exit(1)
831 print 'Git path: %s' % gitpath
832 print 'Output path: %s' % outputpath
834 os.chdir(gitpath)
836 print 'Collecting data...'
837 data = GitDataCollector()
838 data.collect(gitpath)
839 print 'Refining data...'
840 data.refine()
842 os.chdir(rundir)
844 print 'Generating report...'
845 report = HTMLReportCreator()
846 report.create(data, outputpath)
848 time_end = time.time()
849 exectime_internal = time_end - time_start
850 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)