authors: added "Next top 5" column to author of month/year.
[gitstats.git] / gitstats
blobe6077fcd561533572f3f07b97827241f98dd0e4c
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 # TODO getdictkeyssortedbyvaluekey(dict, key) - eg. dict['author'] = { 'commits' : 512 } - ...key(dict, 'commits')
37 class DataCollector:
38 """Manages data collection from a revision control repository."""
39 def __init__(self):
40 self.stamp_created = time.time()
41 pass
44 # This should be the main function to extract data from the repository.
45 def collect(self, dir):
46 self.dir = dir
47 self.projectname = os.path.basename(os.path.abspath(dir))
50 # : get a dictionary of author
51 def getAuthorInfo(self, author):
52 return None
54 def getActivityByDayOfWeek(self):
55 return {}
57 def getActivityByHourOfDay(self):
58 return {}
61 # Get a list of authors
62 def getAuthors(self):
63 return []
65 def getFirstCommitDate(self):
66 return datetime.datetime.now()
68 def getLastCommitDate(self):
69 return datetime.datetime.now()
71 def getStampCreated(self):
72 return self.stamp_created
74 def getTags(self):
75 return []
77 def getTotalAuthors(self):
78 return -1
80 def getTotalCommits(self):
81 return -1
83 def getTotalFiles(self):
84 return -1
86 def getTotalLOC(self):
87 return -1
89 class GitDataCollector(DataCollector):
90 def collect(self, dir):
91 DataCollector.collect(self, dir)
93 self.total_authors = int(getoutput('git-log |git-shortlog -s |wc -l'))
94 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
96 self.activity_by_hour_of_day = {} # hour -> commits
97 self.activity_by_day_of_week = {} # day -> commits
98 self.activity_by_month_of_year = {} # month [1-12] -> commits
99 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
101 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
103 # author of the month
104 self.author_of_month = {} # month -> author -> commits
105 self.author_of_year = {} # year -> author -> commits
106 self.commits_by_month = {} # month -> commits
107 self.commits_by_year = {} # year -> commits
108 self.first_commit_stamp = 0
109 self.last_commit_stamp = 0
111 # tags
112 self.tags = {}
113 lines = getoutput('git-show-ref --tags').split('\n')
114 for line in lines:
115 if len(line) == 0:
116 continue
117 (hash, tag) = line.split(' ')
118 tag = tag.replace('refs/tags/', '')
119 output = getoutput('git-log "%s" --pretty=format:"%%at %%an" -n 1' % hash)
120 if len(output) > 0:
121 parts = output.split(' ')
122 stamp = 0
123 try:
124 stamp = int(parts[0])
125 except ValueError:
126 stamp = 0
127 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
128 pass
130 # Collect revision statistics
131 # Outputs "<stamp> <author>"
132 lines = getoutput('git-rev-list --pretty=format:"%at %an" HEAD |grep -v ^commit').split('\n')
133 for line in lines:
134 # linux-2.6 says "<unknown>" for one line O_o
135 parts = line.split(' ')
136 author = ''
137 try:
138 stamp = int(parts[0])
139 except ValueError:
140 stamp = 0
141 if len(parts) > 1:
142 author = ' '.join(parts[1:])
143 date = datetime.datetime.fromtimestamp(float(stamp))
145 # First and last commit stamp
146 if self.last_commit_stamp == 0:
147 self.last_commit_stamp = stamp
148 self.first_commit_stamp = stamp
150 # activity
151 # hour
152 hour = date.hour
153 if hour in self.activity_by_hour_of_day:
154 self.activity_by_hour_of_day[hour] += 1
155 else:
156 self.activity_by_hour_of_day[hour] = 1
158 # day of week
159 day = date.weekday()
160 if day in self.activity_by_day_of_week:
161 self.activity_by_day_of_week[day] += 1
162 else:
163 self.activity_by_day_of_week[day] = 1
165 # hour of week
166 if day not in self.activity_by_hour_of_week:
167 self.activity_by_hour_of_week[day] = {}
168 if hour not in self.activity_by_hour_of_week[day]:
169 self.activity_by_hour_of_week[day][hour] = 1
170 else:
171 self.activity_by_hour_of_week[day][hour] += 1
173 # month of year
174 month = date.month
175 if month in self.activity_by_month_of_year:
176 self.activity_by_month_of_year[month] += 1
177 else:
178 self.activity_by_month_of_year[month] = 1
180 # author stats
181 if author not in self.authors:
182 self.authors[author] = {}
183 # TODO commits
184 if 'last_commit_stamp' not in self.authors[author]:
185 self.authors[author]['last_commit_stamp'] = stamp
186 self.authors[author]['first_commit_stamp'] = stamp
187 if 'commits' in self.authors[author]:
188 self.authors[author]['commits'] += 1
189 else:
190 self.authors[author]['commits'] = 1
192 # author of the month/year
193 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
194 if yymm in self.author_of_month:
195 if author in self.author_of_month[yymm]:
196 self.author_of_month[yymm][author] += 1
197 else:
198 self.author_of_month[yymm][author] = 1
199 else:
200 self.author_of_month[yymm] = {}
201 self.author_of_month[yymm][author] = 1
202 if yymm in self.commits_by_month:
203 self.commits_by_month[yymm] += 1
204 else:
205 self.commits_by_month[yymm] = 1
207 yy = datetime.datetime.fromtimestamp(stamp).year
208 if yy in self.author_of_year:
209 if author in self.author_of_year[yy]:
210 self.author_of_year[yy][author] += 1
211 else:
212 self.author_of_year[yy][author] = 1
213 else:
214 self.author_of_year[yy] = {}
215 self.author_of_year[yy][author] = 1
216 if yy in self.commits_by_year:
217 self.commits_by_year[yy] += 1
218 else:
219 self.commits_by_year[yy] = 1
221 # TODO Optimize this, it's the worst bottleneck
222 # outputs "<stamp> <files>" for each revision
223 self.files_by_stamp = {} # stamp -> files
224 lines = getoutput('git-rev-list --pretty=format:"%at %H" HEAD |grep -v ^commit |while read line; do set $line; echo "$1 $(git-ls-tree -r "$2" |wc -l)"; done').split('\n')
225 self.total_commits = len(lines)
226 for line in lines:
227 parts = line.split(' ')
228 if len(parts) != 2:
229 continue
230 (stamp, files) = parts[0:2]
231 try:
232 self.files_by_stamp[int(stamp)] = int(files)
233 except ValueError:
234 print 'Warning: failed to parse line "%s"' % line
236 # extensions
237 self.extensions = {} # extension -> files, lines
238 lines = getoutput('git-ls-files').split('\n')
239 self.total_files = len(lines)
240 for line in lines:
241 base = os.path.basename(line)
242 if base.find('.') == -1:
243 ext = ''
244 else:
245 ext = base[(base.rfind('.') + 1):]
247 if ext not in self.extensions:
248 self.extensions[ext] = {'files': 0, 'lines': 0}
250 self.extensions[ext]['files'] += 1
251 try:
252 # Escaping could probably be improved here
253 self.extensions[ext]['lines'] += int(getoutput('wc -l < %s' % re.sub(r'(\W)', r'\\\1', line), quiet = True))
254 except:
255 print 'Warning: Could not count lines for file "%s"' % line
257 # line statistics
258 # outputs:
259 # N files changed, N insertions (+), N deletions(-)
260 # <stamp> <author>
261 self.changes_by_date = {} # stamp -> { files, ins, del }
262 lines = getoutput('git-log --shortstat --pretty=format:"%at %an"').split('\n')
263 lines.reverse()
264 files = 0; inserted = 0; deleted = 0; total_lines = 0
265 for line in lines:
266 if len(line) == 0:
267 continue
269 # <stamp> <author>
270 if line.find('files changed,') == -1:
271 pos = line.find(' ')
272 if pos != -1:
273 (stamp, author) = (int(line[:pos]), line[pos+1:])
274 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
275 else:
276 print 'Warning: unexpected line "%s"' % line
277 else:
278 numbers = re.findall('\d+', line)
279 if len(numbers) == 3:
280 (files, inserted, deleted) = map(lambda el : int(el), numbers)
281 total_lines += inserted
282 total_lines -= deleted
283 else:
284 print 'Warning: failed to handle line "%s"' % line
285 (files, inserted, deleted) = (0, 0, 0)
286 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
287 self.total_lines = total_lines
289 def getActivityByDayOfWeek(self):
290 return self.activity_by_day_of_week
292 def getActivityByHourOfDay(self):
293 return self.activity_by_hour_of_day
295 def getAuthorInfo(self, author):
296 a = self.authors[author]
298 commits = a['commits']
299 commits_frac = (100 * float(commits)) / self.getTotalCommits()
300 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
301 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
302 delta = date_last - date_first
304 res = { 'commits': commits, 'commits_frac': commits_frac, 'date_first': date_first.strftime('%Y-%m-%d'), 'date_last': date_last.strftime('%Y-%m-%d'), 'timedelta' : delta }
305 return res
307 def getAuthors(self):
308 return self.authors.keys()
310 def getFirstCommitDate(self):
311 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
313 def getLastCommitDate(self):
314 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
316 def getTags(self):
317 lines = getoutput('git-show-ref --tags |cut -d/ -f3')
318 return lines.split('\n')
320 def getTagDate(self, tag):
321 return self.revToDate('tags/' + tag)
323 def getTotalAuthors(self):
324 return self.total_authors
326 def getTotalCommits(self):
327 return self.total_commits
329 def getTotalFiles(self):
330 return self.total_files
332 def getTotalLOC(self):
333 return self.total_lines
335 def revToDate(self, rev):
336 stamp = int(getoutput('git-log --pretty=format:%%at "%s" -n 1' % rev))
337 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
339 class ReportCreator:
340 """Creates the actual report based on given data."""
341 def __init__(self):
342 pass
344 def create(self, data, path):
345 self.data = data
346 self.path = path
348 def html_linkify(text):
349 return text.lower().replace(' ', '_')
351 def html_header(level, text):
352 name = html_linkify(text)
353 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
355 class HTMLReportCreator(ReportCreator):
356 def create(self, data, path):
357 ReportCreator.create(self, data, path)
358 self.title = data.projectname
360 # TODO copy the CSS if it does not exist
361 if not os.path.exists(path + '/gitstats.css'):
362 shutil.copyfile('gitstats.css', path + '/gitstats.css')
363 pass
365 f = open(path + "/index.html", 'w')
366 format = '%Y-%m-%d %H:%m:%S'
367 self.printHeader(f)
369 f.write('<h1>GitStats - %s</h1>' % data.projectname)
371 self.printNav(f)
373 f.write('<dl>');
374 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
375 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
376 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
377 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
378 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
379 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
380 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
381 f.write('</dl>');
383 f.write('</body>\n</html>');
384 f.close()
387 # Activity
388 f = open(path + '/activity.html', 'w')
389 self.printHeader(f)
390 f.write('<h1>Activity</h1>')
391 self.printNav(f)
393 #f.write('<h2>Last 30 days</h2>')
395 #f.write('<h2>Last 12 months</h2>')
397 # Hour of Day
398 f.write(html_header(2, 'Hour of Day'))
399 hour_of_day = data.getActivityByHourOfDay()
400 f.write('<table><tr><th>Hour</th>')
401 for i in range(1, 25):
402 f.write('<th>%d</th>' % i)
403 f.write('</tr>\n<tr><th>Commits</th>')
404 fp = open(path + '/hour_of_day.dat', 'w')
405 for i in range(0, 24):
406 if i in hour_of_day:
407 f.write('<td>%d</td>' % hour_of_day[i])
408 fp.write('%d %d\n' % (i, hour_of_day[i]))
409 else:
410 f.write('<td>0</td>')
411 fp.write('%d 0\n' % i)
412 fp.close()
413 f.write('</tr>\n<tr><th>%</th>')
414 totalcommits = data.getTotalCommits()
415 for i in range(0, 24):
416 if i in hour_of_day:
417 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
418 else:
419 f.write('<td>0.00</td>')
420 f.write('</tr></table>')
421 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
422 fg = open(path + '/hour_of_day.dat', 'w')
423 for i in range(0, 24):
424 if i in hour_of_day:
425 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
426 else:
427 fg.write('%d 0\n' % (i + 1))
428 fg.close()
430 # Day of Week
431 f.write(html_header(2, 'Day of Week'))
432 day_of_week = data.getActivityByDayOfWeek()
433 f.write('<div class="vtable"><table>')
434 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
435 fp = open(path + '/day_of_week.dat', 'w')
436 for d in range(0, 7):
437 commits = 0
438 if d in day_of_week:
439 commits = day_of_week[d]
440 fp.write('%d %d\n' % (d + 1, commits))
441 f.write('<tr>')
442 f.write('<th>%d</th>' % (d + 1))
443 if d in day_of_week:
444 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
445 else:
446 f.write('<td>0</td>')
447 f.write('</tr>')
448 f.write('</table></div>')
449 f.write('<img src="day_of_week.png" alt="Day of Week" />')
450 fp.close()
452 # Hour of Week
453 f.write(html_header(2, 'Hour of Week'))
454 f.write('<table>')
456 f.write('<tr><th>Weekday</th>')
457 for hour in range(0, 24):
458 f.write('<th>%d</th>' % (hour + 1))
459 f.write('</tr>')
461 for weekday in range(0, 7):
462 f.write('<tr><th>%d</th>' % (weekday + 1))
463 for hour in range(0, 24):
464 try:
465 commits = data.activity_by_hour_of_week[weekday][hour]
466 except KeyError:
467 commits = 0
468 if commits != 0:
469 f.write('<td>%d</td>' % commits)
470 else:
471 f.write('<td></td>')
472 f.write('</tr>')
474 f.write('</table>')
476 # Month of Year
477 f.write(html_header(2, 'Month of Year'))
478 f.write('<div class="vtable"><table>')
479 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
480 fp = open (path + '/month_of_year.dat', 'w')
481 for mm in range(1, 13):
482 commits = 0
483 if mm in data.activity_by_month_of_year:
484 commits = data.activity_by_month_of_year[mm]
485 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
486 fp.write('%d %d\n' % (mm, commits))
487 fp.close()
488 f.write('</table></div>')
489 f.write('<img src="month_of_year.png" alt="Month of Year" />')
491 # Commits by year/month
492 f.write(html_header(2, 'Commits by year/month'))
493 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
494 for yymm in reversed(sorted(data.commits_by_month.keys())):
495 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
496 f.write('</table></div>')
497 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
498 fg = open(path + '/commits_by_year_month.dat', 'w')
499 for yymm in sorted(data.commits_by_month.keys()):
500 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
501 fg.close()
503 # Commits by year
504 f.write(html_header(2, 'Commits by Year'))
505 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
506 for yy in reversed(sorted(data.commits_by_year.keys())):
507 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()))
508 f.write('</table></div>')
509 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
510 fg = open(path + '/commits_by_year.dat', 'w')
511 for yy in sorted(data.commits_by_year.keys()):
512 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
513 fg.close()
515 f.write('</body></html>')
516 f.close()
519 # Authors
520 f = open(path + '/authors.html', 'w')
521 self.printHeader(f)
523 f.write('<h1>Authors</h1>')
524 self.printNav(f)
526 # Authors :: List of authors
527 f.write(html_header(2, 'List of Authors'))
529 f.write('<table class="authors">')
530 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th>Age</th></tr>')
531 for author in sorted(data.getAuthors()):
532 info = data.getAuthorInfo(author)
533 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (author, info['commits'], info['commits_frac'], info['date_first'], info['date_last'], info['timedelta']))
534 f.write('</table>')
536 # Authors :: Author of Month
537 f.write(html_header(2, 'Author of Month'))
538 f.write('<table>')
539 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
540 for yymm in reversed(sorted(data.author_of_month.keys())):
541 authordict = data.author_of_month[yymm]
542 authors = getkeyssortedbyvalues(authordict)
543 authors.reverse()
544 commits = data.author_of_month[yymm][authors[0]]
545 next = ', '.join(authors[1:5])
546 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))
548 f.write('</table>')
550 f.write(html_header(2, 'Author of Year'))
551 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
552 for yy in reversed(sorted(data.author_of_year.keys())):
553 authordict = data.author_of_year[yy]
554 authors = getkeyssortedbyvalues(authordict)
555 authors.reverse()
556 commits = data.author_of_year[yy][authors[0]]
557 next = ', '.join(authors[1:5])
558 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))
559 f.write('</table>')
561 f.write('</body></html>')
562 f.close()
565 # Files
566 f = open(path + '/files.html', 'w')
567 self.printHeader(f)
568 f.write('<h1>Files</h1>')
569 self.printNav(f)
571 f.write('<dl>\n')
572 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
573 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
574 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
575 f.write('</dl>\n')
577 # Files :: File count by date
578 f.write(html_header(2, 'File count by date'))
580 fg = open(path + '/files_by_date.dat', 'w')
581 for stamp in sorted(data.files_by_stamp.keys()):
582 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
583 fg.close()
585 f.write('<img src="files_by_date.png" alt="Files by Date" />')
587 #f.write('<h2>Average file size by date</h2>')
589 # Files :: Extensions
590 f.write(html_header(2, 'Extensions'))
591 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
592 for ext in sorted(data.extensions.keys()):
593 files = data.extensions[ext]['files']
594 lines = data.extensions[ext]['lines']
595 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))
596 f.write('</table>')
598 f.write('</body></html>')
599 f.close()
602 # Lines
603 f = open(path + '/lines.html', 'w')
604 self.printHeader(f)
605 f.write('<h1>Lines</h1>')
606 self.printNav(f)
608 f.write('<dl>\n')
609 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
610 f.write('</dl>\n')
612 f.write(html_header(2, 'Lines of Code'))
613 f.write('<img src="lines_of_code.png" />')
615 fg = open(path + '/lines_of_code.dat', 'w')
616 for stamp in sorted(data.changes_by_date.keys()):
617 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
618 fg.close()
620 f.write('</body></html>')
621 f.close()
624 # tags.html
625 f = open(path + '/tags.html', 'w')
626 self.printHeader(f)
627 f.write('<h1>Tags</h1>')
628 self.printNav(f)
630 f.write('<dl>')
631 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
632 if len(data.tags) > 0:
633 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
634 f.write('</dl>')
636 f.write('<table>')
637 f.write('<tr><th>Name</th><th>Date</th></tr>')
638 # sort the tags by date desc
639 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
640 for tag in tags_sorted_by_date_desc:
641 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
642 f.write('</table>')
644 f.write('</body></html>')
645 f.close()
647 self.createGraphs(path)
648 pass
650 def createGraphs(self, path):
651 print 'Generating graphs...'
653 # hour of day
654 f = open(path + '/hour_of_day.plot', 'w')
655 f.write(GNUPLOT_COMMON)
656 f.write(
658 set output 'hour_of_day.png'
659 unset key
660 set xrange [0.5:24.5]
661 set xtics 4
662 set ylabel "Commits"
663 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
664 """)
665 f.close()
667 # day of week
668 f = open(path + '/day_of_week.plot', 'w')
669 f.write(GNUPLOT_COMMON)
670 f.write(
672 set output 'day_of_week.png'
673 unset key
674 set xrange [0.5:7.5]
675 set xtics 1
676 set ylabel "Commits"
677 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
678 """)
679 f.close()
681 # Month of Year
682 f = open(path + '/month_of_year.plot', 'w')
683 f.write(GNUPLOT_COMMON)
684 f.write(
686 set output 'month_of_year.png'
687 unset key
688 set xrange [0.5:12.5]
689 set xtics 1
690 set ylabel "Commits"
691 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
692 """)
693 f.close()
695 # commits_by_year_month
696 f = open(path + '/commits_by_year_month.plot', 'w')
697 f.write(GNUPLOT_COMMON)
698 f.write(
700 set output 'commits_by_year_month.png'
701 unset key
702 set xdata time
703 set timefmt "%Y-%m"
704 set format x "%Y-%m"
705 set xtics rotate by 90 15768000
706 set bmargin 5
707 set ylabel "Commits"
708 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
709 """)
710 f.close()
712 # commits_by_year
713 f = open(path + '/commits_by_year.plot', 'w')
714 f.write(GNUPLOT_COMMON)
715 f.write(
717 set output 'commits_by_year.png'
718 unset key
719 set xtics 1
720 set ylabel "Commits"
721 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
722 """)
723 f.close()
725 # Files by date
726 f = open(path + '/files_by_date.plot', 'w')
727 f.write(GNUPLOT_COMMON)
728 f.write(
730 set output 'files_by_date.png'
731 unset key
732 set xdata time
733 set timefmt "%Y-%m-%d"
734 set format x "%Y-%m-%d"
735 set ylabel "Files"
736 set xtics rotate by 90
737 set bmargin 6
738 plot 'files_by_date.dat' using 1:2 smooth csplines
739 """)
740 f.close()
742 # Lines of Code
743 f = open(path + '/lines_of_code.plot', 'w')
744 f.write(GNUPLOT_COMMON)
745 f.write(
747 set output 'lines_of_code.png'
748 unset key
749 set xdata time
750 set timefmt "%s"
751 set format x "%Y-%m-%d"
752 set ylabel "Lines"
753 set xtics rotate by 90
754 set bmargin 6
755 plot 'lines_of_code.dat' using 1:2 w lines
756 """)
757 f.close()
759 os.chdir(path)
760 files = glob.glob(path + '/*.plot')
761 for f in files:
762 out = getoutput('gnuplot %s' % f)
763 if len(out) > 0:
764 print out
766 def printHeader(self, f, title = ''):
767 f.write(
768 """<?xml version="1.0" encoding="UTF-8"?>
769 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
770 <html xmlns="http://www.w3.org/1999/xhtml">
771 <head>
772 <title>GitStats - %s</title>
773 <link rel="stylesheet" href="gitstats.css" type="text/css" />
774 <meta name="generator" content="GitStats" />
775 </head>
776 <body>
777 """ % self.title)
779 def printNav(self, f):
780 f.write("""
781 <div class="nav">
782 <ul>
783 <li><a href="index.html">General</a></li>
784 <li><a href="activity.html">Activity</a></li>
785 <li><a href="authors.html">Authors</a></li>
786 <li><a href="files.html">Files</a></li>
787 <li><a href="lines.html">Lines</a></li>
788 <li><a href="tags.html">Tags</a></li>
789 </ul>
790 </div>
791 """)
794 usage = """
795 Usage: gitstats [options] <gitpath> <outputpath>
797 Options:
800 if len(sys.argv) < 3:
801 print usage
802 sys.exit(0)
804 gitpath = sys.argv[1]
805 outputpath = os.path.abspath(sys.argv[2])
806 rundir = os.getcwd()
808 try:
809 os.makedirs(outputpath)
810 except OSError:
811 pass
812 if not os.path.isdir(outputpath):
813 print 'FATAL: Output path is not a directory or does not exist'
814 sys.exit(1)
816 print 'Git path: %s' % gitpath
817 print 'Output path: %s' % outputpath
819 os.chdir(gitpath)
821 print 'Collecting data...'
822 data = GitDataCollector()
823 data.collect(gitpath)
825 os.chdir(rundir)
827 print 'Generating report...'
828 report = HTMLReportCreator()
829 report.create(data, outputpath)
831 time_end = time.time()
832 exectime_internal = time_end - time_start
833 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)