doc/author.txt: subject should include "gitstats".
[gitstats.git] / gitstats
blob41b5d68aee6383322099ebb15ab43f605c6895f9
1 #!/usr/bin/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" |tac').split('\n')
263 files = 0; inserted = 0; deleted = 0; total_lines = 0
264 for line in lines:
265 if len(line) == 0:
266 continue
268 # <stamp> <author>
269 if line.find('files changed,') == -1:
270 pos = line.find(' ')
271 if pos != -1:
272 (stamp, author) = (int(line[:pos]), line[pos+1:])
273 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
274 else:
275 print 'Warning: unexpected line "%s"' % line
276 else:
277 numbers = re.findall('\d+', line)
278 if len(numbers) == 3:
279 (files, inserted, deleted) = map(lambda el : int(el), numbers)
280 total_lines += inserted
281 total_lines -= deleted
282 else:
283 print 'Warning: failed to handle line "%s"' % line
284 (files, inserted, deleted) = (0, 0, 0)
285 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
286 self.total_lines = total_lines
288 def getActivityByDayOfWeek(self):
289 return self.activity_by_day_of_week
291 def getActivityByHourOfDay(self):
292 return self.activity_by_hour_of_day
294 def getAuthorInfo(self, author):
295 a = self.authors[author]
297 commits = a['commits']
298 commits_frac = (100 * float(commits)) / self.getTotalCommits()
299 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
300 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
301 delta = date_last - date_first
303 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 }
304 return res
306 def getAuthors(self):
307 return self.authors.keys()
309 def getFirstCommitDate(self):
310 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
312 def getLastCommitDate(self):
313 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
315 def getTags(self):
316 lines = getoutput('git-show-ref --tags |cut -d/ -f3')
317 return lines.split('\n')
319 def getTagDate(self, tag):
320 return self.revToDate('tags/' + tag)
322 def getTotalAuthors(self):
323 return self.total_authors
325 def getTotalCommits(self):
326 return self.total_commits
328 def getTotalFiles(self):
329 return self.total_files
331 def getTotalLOC(self):
332 return self.total_lines
334 def revToDate(self, rev):
335 stamp = int(getoutput('git-log --pretty=format:%%at "%s" -n 1' % rev))
336 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
338 class ReportCreator:
339 """Creates the actual report based on given data."""
340 def __init__(self):
341 pass
343 def create(self, data, path):
344 self.data = data
345 self.path = path
347 def html_linkify(text):
348 return text.lower().replace(' ', '_')
350 def html_header(level, text):
351 name = html_linkify(text)
352 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
354 class HTMLReportCreator(ReportCreator):
355 def create(self, data, path):
356 ReportCreator.create(self, data, path)
357 self.title = data.projectname
359 # TODO copy the CSS if it does not exist
360 if not os.path.exists(path + '/gitstats.css'):
361 shutil.copyfile('gitstats.css', path + '/gitstats.css')
362 pass
364 f = open(path + "/index.html", 'w')
365 format = '%Y-%m-%d %H:%m:%S'
366 self.printHeader(f)
368 f.write('<h1>GitStats - %s</h1>' % data.projectname)
370 self.printNav(f)
372 f.write('<dl>');
373 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
374 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
375 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
376 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
377 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
378 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
379 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
380 f.write('</dl>');
382 f.write('</body>\n</html>');
383 f.close()
386 # Activity
387 f = open(path + '/activity.html', 'w')
388 self.printHeader(f)
389 f.write('<h1>Activity</h1>')
390 self.printNav(f)
392 #f.write('<h2>Last 30 days</h2>')
394 #f.write('<h2>Last 12 months</h2>')
396 # Hour of Day
397 f.write(html_header(2, 'Hour of Day'))
398 hour_of_day = data.getActivityByHourOfDay()
399 f.write('<table><tr><th>Hour</th>')
400 for i in range(1, 25):
401 f.write('<th>%d</th>' % i)
402 f.write('</tr>\n<tr><th>Commits</th>')
403 fp = open(path + '/hour_of_day.dat', 'w')
404 for i in range(0, 24):
405 if i in hour_of_day:
406 f.write('<td>%d</td>' % hour_of_day[i])
407 fp.write('%d %d\n' % (i, hour_of_day[i]))
408 else:
409 f.write('<td>0</td>')
410 fp.write('%d 0\n' % i)
411 fp.close()
412 f.write('</tr>\n<tr><th>%</th>')
413 totalcommits = data.getTotalCommits()
414 for i in range(0, 24):
415 if i in hour_of_day:
416 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
417 else:
418 f.write('<td>0.00</td>')
419 f.write('</tr></table>')
420 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
421 fg = open(path + '/hour_of_day.dat', 'w')
422 for i in range(0, 24):
423 if i in hour_of_day:
424 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
425 else:
426 fg.write('%d 0\n' % (i + 1))
427 fg.close()
429 # Day of Week
430 f.write(html_header(2, 'Day of Week'))
431 day_of_week = data.getActivityByDayOfWeek()
432 f.write('<div class="vtable"><table>')
433 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
434 fp = open(path + '/day_of_week.dat', 'w')
435 for d in range(0, 7):
436 commits = 0
437 if d in day_of_week:
438 commits = day_of_week[d]
439 fp.write('%d %d\n' % (d + 1, commits))
440 f.write('<tr>')
441 f.write('<th>%d</th>' % (d + 1))
442 if d in day_of_week:
443 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
444 else:
445 f.write('<td>0</td>')
446 f.write('</tr>')
447 f.write('</table></div>')
448 f.write('<img src="day_of_week.png" alt="Day of Week" />')
449 fp.close()
451 # Hour of Week
452 f.write(html_header(2, 'Hour of Week'))
453 f.write('<table>')
455 f.write('<tr><th>Weekday</th>')
456 for hour in range(0, 24):
457 f.write('<th>%d</th>' % (hour + 1))
458 f.write('</tr>')
460 for weekday in range(0, 7):
461 f.write('<tr><th>%d</th>' % (weekday + 1))
462 for hour in range(0, 24):
463 try:
464 commits = data.activity_by_hour_of_week[weekday][hour]
465 except KeyError:
466 commits = 0
467 if commits != 0:
468 f.write('<td>%d</td>' % commits)
469 else:
470 f.write('<td></td>')
471 f.write('</tr>')
473 f.write('</table>')
475 # Month of Year
476 f.write(html_header(2, 'Month of Year'))
477 f.write('<div class="vtable"><table>')
478 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
479 fp = open (path + '/month_of_year.dat', 'w')
480 for mm in range(1, 13):
481 commits = 0
482 if mm in data.activity_by_month_of_year:
483 commits = data.activity_by_month_of_year[mm]
484 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
485 fp.write('%d %d\n' % (mm, commits))
486 fp.close()
487 f.write('</table></div>')
488 f.write('<img src="month_of_year.png" alt="Month of Year" />')
490 # Commits by year/month
491 f.write(html_header(2, 'Commits by year/month'))
492 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
493 for yymm in reversed(sorted(data.commits_by_month.keys())):
494 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
495 f.write('</table></div>')
496 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
497 fg = open(path + '/commits_by_year_month.dat', 'w')
498 for yymm in sorted(data.commits_by_month.keys()):
499 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
500 fg.close()
502 # Commits by year
503 f.write(html_header(2, 'Commits by Year'))
504 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
505 for yy in reversed(sorted(data.commits_by_year.keys())):
506 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()))
507 f.write('</table></div>')
508 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
509 fg = open(path + '/commits_by_year.dat', 'w')
510 for yy in sorted(data.commits_by_year.keys()):
511 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
512 fg.close()
514 f.write('</body></html>')
515 f.close()
518 # Authors
519 f = open(path + '/authors.html', 'w')
520 self.printHeader(f)
522 f.write('<h1>Authors</h1>')
523 self.printNav(f)
525 # Authors :: List of authors
526 f.write(html_header(2, 'List of Authors'))
528 f.write('<table class="authors">')
529 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th>Age</th></tr>')
530 for author in sorted(data.getAuthors()):
531 info = data.getAuthorInfo(author)
532 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']))
533 f.write('</table>')
535 # Authors :: Author of Month
536 f.write(html_header(2, 'Author of Month'))
537 f.write('<table>')
538 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th></tr>')
539 for yymm in reversed(sorted(data.author_of_month.keys())):
540 authordict = data.author_of_month[yymm]
541 authors = getkeyssortedbyvalues(authordict)
542 authors.reverse()
543 commits = data.author_of_month[yymm][authors[0]]
544 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td></tr>' % (yymm, authors[0], commits, (100 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm]))
546 f.write('</table>')
548 f.write(html_header(2, 'Author of Year'))
549 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th></tr>')
550 for yy in reversed(sorted(data.author_of_year.keys())):
551 authordict = data.author_of_year[yy]
552 authors = getkeyssortedbyvalues(authordict)
553 authors.reverse()
554 commits = data.author_of_year[yy][authors[0]]
555 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td></tr>' % (yy, authors[0], commits, (100 * commits) / data.commits_by_year[yy], data.commits_by_year[yy]))
556 f.write('</table>')
558 f.write('</body></html>')
559 f.close()
562 # Files
563 f = open(path + '/files.html', 'w')
564 self.printHeader(f)
565 f.write('<h1>Files</h1>')
566 self.printNav(f)
568 f.write('<dl>\n')
569 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
570 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
571 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
572 f.write('</dl>\n')
574 # Files :: File count by date
575 f.write(html_header(2, 'File count by date'))
577 fg = open(path + '/files_by_date.dat', 'w')
578 for stamp in sorted(data.files_by_stamp.keys()):
579 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
580 fg.close()
582 f.write('<img src="files_by_date.png" alt="Files by Date" />')
584 #f.write('<h2>Average file size by date</h2>')
586 # Files :: Extensions
587 f.write(html_header(2, 'Extensions'))
588 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
589 for ext in sorted(data.extensions.keys()):
590 files = data.extensions[ext]['files']
591 lines = data.extensions[ext]['lines']
592 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))
593 f.write('</table>')
595 f.write('</body></html>')
596 f.close()
599 # Lines
600 f = open(path + '/lines.html', 'w')
601 self.printHeader(f)
602 f.write('<h1>Lines</h1>')
603 self.printNav(f)
605 f.write('<dl>\n')
606 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
607 f.write('</dl>\n')
609 f.write(html_header(2, 'Lines of Code'))
610 f.write('<img src="lines_of_code.png" />')
612 fg = open(path + '/lines_of_code.dat', 'w')
613 for stamp in sorted(data.changes_by_date.keys()):
614 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
615 fg.close()
617 f.write('</body></html>')
618 f.close()
621 # tags.html
622 f = open(path + '/tags.html', 'w')
623 self.printHeader(f)
624 f.write('<h1>Tags</h1>')
625 self.printNav(f)
627 f.write('<dl>')
628 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
629 if len(data.tags) > 0:
630 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
631 f.write('</dl>')
633 f.write('<table>')
634 f.write('<tr><th>Name</th><th>Date</th></tr>')
635 # sort the tags by date desc
636 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
637 for tag in tags_sorted_by_date_desc:
638 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
639 f.write('</table>')
641 f.write('</body></html>')
642 f.close()
644 self.createGraphs(path)
645 pass
647 def createGraphs(self, path):
648 print 'Generating graphs...'
650 # hour of day
651 f = open(path + '/hour_of_day.plot', 'w')
652 f.write(GNUPLOT_COMMON)
653 f.write(
655 set output 'hour_of_day.png'
656 unset key
657 set xrange [0.5:24.5]
658 set xtics 4
659 set ylabel "Commits"
660 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
661 """)
662 f.close()
664 # day of week
665 f = open(path + '/day_of_week.plot', 'w')
666 f.write(GNUPLOT_COMMON)
667 f.write(
669 set output 'day_of_week.png'
670 unset key
671 set xrange [0.5:7.5]
672 set xtics 1
673 set ylabel "Commits"
674 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
675 """)
676 f.close()
678 # Month of Year
679 f = open(path + '/month_of_year.plot', 'w')
680 f.write(GNUPLOT_COMMON)
681 f.write(
683 set output 'month_of_year.png'
684 unset key
685 set xrange [0.5:12.5]
686 set xtics 1
687 set ylabel "Commits"
688 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
689 """)
690 f.close()
692 # commits_by_year_month
693 f = open(path + '/commits_by_year_month.plot', 'w')
694 f.write(GNUPLOT_COMMON)
695 f.write(
697 set output 'commits_by_year_month.png'
698 unset key
699 set xdata time
700 set timefmt "%Y-%m"
701 set format x "%Y-%m"
702 set xtics rotate by 90 15768000
703 set bmargin 5
704 set ylabel "Commits"
705 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
706 """)
707 f.close()
709 # commits_by_year
710 f = open(path + '/commits_by_year.plot', 'w')
711 f.write(GNUPLOT_COMMON)
712 f.write(
714 set output 'commits_by_year.png'
715 unset key
716 set xtics 1
717 set ylabel "Commits"
718 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
719 """)
720 f.close()
722 # Files by date
723 f = open(path + '/files_by_date.plot', 'w')
724 f.write(GNUPLOT_COMMON)
725 f.write(
727 set output 'files_by_date.png'
728 unset key
729 set xdata time
730 set timefmt "%Y-%m-%d"
731 set format x "%Y-%m-%d"
732 set ylabel "Files"
733 set xtics rotate by 90
734 set bmargin 6
735 plot 'files_by_date.dat' using 1:2 smooth csplines
736 """)
737 f.close()
739 # Lines of Code
740 f = open(path + '/lines_of_code.plot', 'w')
741 f.write(GNUPLOT_COMMON)
742 f.write(
744 set output 'lines_of_code.png'
745 unset key
746 set xdata time
747 set timefmt "%s"
748 set format x "%Y-%m-%d"
749 set ylabel "Lines"
750 set xtics rotate by 90
751 set bmargin 6
752 plot 'lines_of_code.dat' using 1:2 w lines
753 """)
754 f.close()
756 os.chdir(path)
757 files = glob.glob(path + '/*.plot')
758 for f in files:
759 out = getoutput('gnuplot %s' % f)
760 if len(out) > 0:
761 print out
763 def printHeader(self, f, title = ''):
764 f.write(
765 """<?xml version="1.0" encoding="UTF-8"?>
766 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
767 <html xmlns="http://www.w3.org/1999/xhtml">
768 <head>
769 <title>GitStats - %s</title>
770 <link rel="stylesheet" href="gitstats.css" type="text/css" />
771 <meta name="generator" content="GitStats" />
772 </head>
773 <body>
774 """ % self.title)
776 def printNav(self, f):
777 f.write("""
778 <div class="nav">
779 <ul>
780 <li><a href="index.html">General</a></li>
781 <li><a href="activity.html">Activity</a></li>
782 <li><a href="authors.html">Authors</a></li>
783 <li><a href="files.html">Files</a></li>
784 <li><a href="lines.html">Lines</a></li>
785 <li><a href="tags.html">Tags</a></li>
786 </ul>
787 </div>
788 """)
791 usage = """
792 Usage: gitstats [options] <gitpath> <outputpath>
794 Options:
797 if len(sys.argv) < 3:
798 print usage
799 sys.exit(0)
801 gitpath = sys.argv[1]
802 outputpath = os.path.abspath(sys.argv[2])
803 rundir = os.getcwd()
805 try:
806 os.makedirs(outputpath)
807 except OSError:
808 pass
809 if not os.path.isdir(outputpath):
810 print 'FATAL: Output path is not a directory or does not exist'
811 sys.exit(1)
813 print 'Git path: %s' % gitpath
814 print 'Output path: %s' % outputpath
816 os.chdir(gitpath)
818 print 'Collecting data...'
819 data = GitDataCollector()
820 data.collect(gitpath)
822 os.chdir(rundir)
824 print 'Generating report...'
825 report = HTMLReportCreator()
826 report.create(data, outputpath)
828 time_end = time.time()
829 exectime_internal = time_end - time_start
830 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)