todo: x-label bug & show raw data.
[gitstats.git] / gitstats
blob4d39923e4c04ec50bd4f25f52a77c50ff6f1cfb3
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 def getoutput(cmd, quiet = False):
16 if not quiet:
17 start = time.time()
18 print '>> %s' % cmd,
19 sys.stdout.flush()
20 output = commands.getoutput(cmd)
21 if not quiet:
22 end = time.time()
23 print '\r[%.5f] >> %s' % (end - start, cmd)
24 return output
26 def getkeyssortedbyvalues(dict):
27 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
29 # TODO getdictkeyssortedbyvaluekey(dict, key) - eg. dict['author'] = { 'commits' : 512 } - ...key(dict, 'commits')
31 class DataCollector:
32 """Manages data collection from a revision control repository."""
33 def __init__(self):
34 self.stamp_created = time.time()
35 pass
38 # This should be the main function to extract data from the repository.
39 def collect(self, dir):
40 self.dir = dir
43 # : get a dictionary of author
44 def getAuthorInfo(self, author):
45 return None
47 def getActivityByDayOfWeek(self):
48 return {}
50 def getActivityByHourOfDay(self):
51 return {}
54 # Get a list of authors
55 def getAuthors(self):
56 return []
58 def getFirstCommitDate(self):
59 return datetime.datetime.now()
61 def getLastCommitDate(self):
62 return datetime.datetime.now()
64 def getStampCreated(self):
65 return self.stamp_created
67 def getTags(self):
68 return []
70 def getTotalAuthors(self):
71 return -1
73 def getTotalCommits(self):
74 return -1
76 def getTotalFiles(self):
77 return -1
79 def getTotalLOC(self):
80 return -1
82 class GitDataCollector(DataCollector):
83 def collect(self, dir):
84 DataCollector.collect(self, dir)
86 self.total_authors = int(getoutput('git-log |git-shortlog -s |wc -l'))
87 self.total_commits = int(getoutput('git-rev-list HEAD |wc -l'))
88 self.total_files = int(getoutput('git-ls-files |wc -l'))
89 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
91 self.activity_by_hour_of_day = {} # hour -> commits
92 self.activity_by_day_of_week = {} # day -> commits
93 self.activity_by_month_of_year = {} # month [1-12] -> commits
94 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
96 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
98 # author of the month
99 self.author_of_month = {} # month -> author -> commits
100 self.author_of_year = {} # year -> author -> commits
101 self.commits_by_month = {} # month -> commits
102 self.commits_by_year = {} # year -> commits
103 self.first_commit_stamp = 0
104 self.last_commit_stamp = 0
106 # tags
107 self.tags = {}
108 lines = getoutput('git-show-ref --tags').split('\n')
109 for line in lines:
110 if len(line) == 0:
111 continue
112 (hash, tag) = line.split(' ')
113 tag = tag.replace('refs/tags/', '')
114 output = getoutput('git-log "%s" --pretty=format:"%%at %%an" -n 1' % hash)
115 if len(output) > 0:
116 parts = output.split(' ')
117 stamp = 0
118 try:
119 stamp = int(parts[0])
120 except ValueError:
121 stamp = 0
122 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
123 pass
125 # Collect revision statistics
126 # Outputs "<stamp> <author>"
127 lines = getoutput('git-rev-list --pretty=format:"%at %an" HEAD |grep -v ^commit').split('\n')
128 for line in lines:
129 # linux-2.6 says "<unknown>" for one line O_o
130 parts = line.split(' ')
131 author = ''
132 try:
133 stamp = int(parts[0])
134 except ValueError:
135 stamp = 0
136 if len(parts) > 1:
137 author = ' '.join(parts[1:])
138 date = datetime.datetime.fromtimestamp(float(stamp))
140 # First and last commit stamp
141 if self.last_commit_stamp == 0:
142 self.last_commit_stamp = stamp
143 self.first_commit_stamp = stamp
145 # activity
146 # hour
147 hour = date.hour
148 if hour in self.activity_by_hour_of_day:
149 self.activity_by_hour_of_day[hour] += 1
150 else:
151 self.activity_by_hour_of_day[hour] = 1
153 # day of week
154 day = date.weekday()
155 if day in self.activity_by_day_of_week:
156 self.activity_by_day_of_week[day] += 1
157 else:
158 self.activity_by_day_of_week[day] = 1
160 # hour of week
161 if day not in self.activity_by_hour_of_week:
162 self.activity_by_hour_of_week[day] = {}
163 if hour not in self.activity_by_hour_of_week[day]:
164 self.activity_by_hour_of_week[day][hour] = 1
165 else:
166 self.activity_by_hour_of_week[day][hour] += 1
168 # month of year
169 month = date.month
170 if month in self.activity_by_month_of_year:
171 self.activity_by_month_of_year[month] += 1
172 else:
173 self.activity_by_month_of_year[month] = 1
175 # author stats
176 if author not in self.authors:
177 self.authors[author] = {}
178 # TODO commits
179 if 'last_commit_stamp' not in self.authors[author]:
180 self.authors[author]['last_commit_stamp'] = stamp
181 self.authors[author]['first_commit_stamp'] = stamp
182 if 'commits' in self.authors[author]:
183 self.authors[author]['commits'] += 1
184 else:
185 self.authors[author]['commits'] = 1
187 # author of the month/year
188 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
189 if yymm in self.author_of_month:
190 if author in self.author_of_month[yymm]:
191 self.author_of_month[yymm][author] += 1
192 else:
193 self.author_of_month[yymm][author] = 1
194 else:
195 self.author_of_month[yymm] = {}
196 self.author_of_month[yymm][author] = 1
197 if yymm in self.commits_by_month:
198 self.commits_by_month[yymm] += 1
199 else:
200 self.commits_by_month[yymm] = 1
202 yy = datetime.datetime.fromtimestamp(stamp).year
203 if yy in self.author_of_year:
204 if author in self.author_of_year[yy]:
205 self.author_of_year[yy][author] += 1
206 else:
207 self.author_of_year[yy][author] = 1
208 else:
209 self.author_of_year[yy] = {}
210 self.author_of_year[yy][author] = 1
211 if yy in self.commits_by_year:
212 self.commits_by_year[yy] += 1
213 else:
214 self.commits_by_year[yy] = 1
216 # TODO Optimize this, it's the worst bottleneck
217 # outputs "<stamp> <files>" for each revision
218 self.files_by_stamp = {} # stamp -> files
219 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')
220 for line in lines:
221 parts = line.split(' ')
222 if len(parts) != 2:
223 continue
224 (stamp, files) = parts[0:2]
225 try:
226 self.files_by_stamp[int(stamp)] = int(files)
227 except ValueError:
228 print 'Warning: failed to parse line "%s"' % line
230 # extensions
231 self.extensions = {} # extension -> files, lines
232 lines = getoutput('git-ls-files').split('\n')
233 for line in lines:
234 base = os.path.basename(line)
235 if base.find('.') == -1:
236 ext = ''
237 else:
238 ext = base[(base.rfind('.') + 1):]
240 if ext not in self.extensions:
241 self.extensions[ext] = {'files': 0, 'lines': 0}
243 self.extensions[ext]['files'] += 1
244 try:
245 # FIXME filenames with spaces or special characters are broken
246 self.extensions[ext]['lines'] += int(getoutput('wc -l < %s' % line, quiet = True))
247 except:
248 print 'Warning: Could not count lines for file "%s"' % line
250 # line statistics
251 # outputs:
252 # N files changed, N insertions (+), N deletions(-)
253 # <stamp> <author>
254 self.changes_by_date = {} # stamp -> { files, ins, del }
255 lines = getoutput('git-log --shortstat --pretty=format:"%at %an" |tac').split('\n')
256 files = 0; inserted = 0; deleted = 0; total_lines = 0
257 for line in lines:
258 if len(line) == 0:
259 continue
261 # <stamp> <author>
262 if line.find(',') == -1:
263 pos = line.find(' ')
264 (stamp, author) = (int(line[:pos]), line[pos+1:])
265 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
266 else:
267 numbers = re.findall('\d+', line)
268 if len(numbers) == 3:
269 (files, inserted, deleted) = map(lambda el : int(el), numbers)
270 total_lines += inserted
271 total_lines -= deleted
272 else:
273 print 'Warning: failed to handle line "%s"' % line
274 (files, inserted, deleted) = (0, 0, 0)
275 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
276 self.total_lines = total_lines
278 def getActivityByDayOfWeek(self):
279 return self.activity_by_day_of_week
281 def getActivityByHourOfDay(self):
282 return self.activity_by_hour_of_day
284 def getAuthorInfo(self, author):
285 a = self.authors[author]
287 commits = a['commits']
288 commits_frac = (100 * float(commits)) / self.getTotalCommits()
289 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
290 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
291 delta = date_last - date_first
293 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 }
294 return res
296 def getAuthors(self):
297 return self.authors.keys()
299 def getFirstCommitDate(self):
300 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
302 def getLastCommitDate(self):
303 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
305 def getTags(self):
306 lines = getoutput('git-show-ref --tags |cut -d/ -f3')
307 return lines.split('\n')
309 def getTagDate(self, tag):
310 return self.revToDate('tags/' + tag)
312 def getTotalAuthors(self):
313 return self.total_authors
315 def getTotalCommits(self):
316 return self.total_commits
318 def getTotalFiles(self):
319 return self.total_files
321 def getTotalLOC(self):
322 return self.total_lines
324 def revToDate(self, rev):
325 stamp = int(getoutput('git-log --pretty=format:%%at "%s" -n 1' % rev))
326 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
328 class ReportCreator:
329 """Creates the actual report based on given data."""
330 def __init__(self):
331 pass
333 def create(self, data, path):
334 self.data = data
335 self.path = path
337 def html_linkify(text):
338 return text.lower().replace(' ', '_')
340 def html_header(level, text):
341 name = html_linkify(text)
342 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
344 class HTMLReportCreator(ReportCreator):
345 def create(self, data, path):
346 ReportCreator.create(self, data, path)
348 # TODO copy the CSS if it does not exist
349 if not os.path.exists(path + '/gitstats.css'):
350 shutil.copyfile('gitstats.css', path + '/gitstats.css')
351 pass
353 f = open(path + "/index.html", 'w')
354 format = '%Y-%m-%d %H:%m:%S'
355 self.printHeader(f)
357 f.write('<h1>GitStats</h1>')
359 self.printNav(f)
361 f.write('<dl>');
362 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
363 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
364 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
365 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
366 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
367 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
368 f.write('</dl>');
370 f.write('</body>\n</html>');
371 f.close()
374 # Activity
375 f = open(path + '/activity.html', 'w')
376 self.printHeader(f)
377 f.write('<h1>Activity</h1>')
378 self.printNav(f)
380 #f.write('<h2>Last 30 days</h2>')
382 #f.write('<h2>Last 12 months</h2>')
384 # Hour of Day
385 f.write(html_header(2, 'Hour of Day'))
386 hour_of_day = data.getActivityByHourOfDay()
387 f.write('<table><tr><th>Hour</th>')
388 for i in range(1, 25):
389 f.write('<th>%d</th>' % i)
390 f.write('</tr>\n<tr><th>Commits</th>')
391 fp = open(path + '/hour_of_day.dat', 'w')
392 for i in range(0, 24):
393 if i in hour_of_day:
394 f.write('<td>%d</td>' % hour_of_day[i])
395 fp.write('%d %d\n' % (i, hour_of_day[i]))
396 else:
397 f.write('<td>0</td>')
398 fp.write('%d 0\n' % i)
399 fp.close()
400 f.write('</tr>\n<tr><th>%</th>')
401 totalcommits = data.getTotalCommits()
402 for i in range(0, 24):
403 if i in hour_of_day:
404 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
405 else:
406 f.write('<td>0.00</td>')
407 f.write('</tr></table>')
408 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
409 fg = open(path + '/hour_of_day.dat', 'w')
410 for i in range(0, 24):
411 if i in hour_of_day:
412 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
413 else:
414 fg.write('%d 0\n' % (i + 1))
415 fg.close()
417 # Day of Week
418 f.write(html_header(2, 'Day of Week'))
419 day_of_week = data.getActivityByDayOfWeek()
420 f.write('<div class="vtable"><table>')
421 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
422 fp = open(path + '/day_of_week.dat', 'w')
423 for d in range(0, 7):
424 commits = 0
425 if d in day_of_week:
426 commits = day_of_week[d]
427 fp.write('%d %d\n' % (d + 1, commits))
428 f.write('<tr>')
429 f.write('<th>%d</th>' % (d + 1))
430 if d in day_of_week:
431 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
432 else:
433 f.write('<td>0</td>')
434 f.write('</tr>')
435 f.write('</table></div>')
436 f.write('<img src="day_of_week.png" alt="Day of Week" />')
437 fp.close()
439 # Hour of Week
440 f.write(html_header(2, 'Hour of Week'))
441 f.write('<table>')
443 f.write('<tr><th>Weekday</th>')
444 for hour in range(0, 24):
445 f.write('<th>%d</th>' % (hour + 1))
446 f.write('</tr>')
448 for weekday in range(0, 7):
449 f.write('<tr><th>%d</th>' % (weekday + 1))
450 for hour in range(0, 24):
451 try:
452 commits = data.activity_by_hour_of_week[weekday][hour]
453 except KeyError:
454 commits = 0
455 if commits != 0:
456 f.write('<td>%d</td>' % commits)
457 else:
458 f.write('<td></td>')
459 f.write('</tr>')
461 f.write('</table>')
463 # Month of Year
464 f.write(html_header(2, 'Month of Year'))
465 f.write('<div class="vtable"><table>')
466 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
467 fp = open (path + '/month_of_year.dat', 'w')
468 for mm in range(1, 13):
469 commits = 0
470 if mm in data.activity_by_month_of_year:
471 commits = data.activity_by_month_of_year[mm]
472 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
473 fp.write('%d %d\n' % (mm, commits))
474 fp.close()
475 f.write('</table></div>')
476 f.write('<img src="month_of_year.png" alt="Month of Year" />')
478 # Commits by year/month
479 f.write(html_header(2, 'Commits by year/month'))
480 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
481 for yymm in reversed(sorted(data.commits_by_month.keys())):
482 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
483 f.write('</table></div>')
484 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
485 fg = open(path + '/commits_by_year_month.dat', 'w')
486 for yymm in sorted(data.commits_by_month.keys()):
487 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
488 fg.close()
490 # Commits by year
491 f.write(html_header(2, 'Commits by Year'))
492 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
493 for yy in reversed(sorted(data.commits_by_year.keys())):
494 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()))
495 f.write('</table></div>')
496 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
497 fg = open(path + '/commits_by_year.dat', 'w')
498 for yy in sorted(data.commits_by_year.keys()):
499 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
500 fg.close()
502 f.write('</body></html>')
503 f.close()
506 # Authors
507 f = open(path + '/authors.html', 'w')
508 self.printHeader(f)
510 f.write('<h1>Authors</h1>')
511 self.printNav(f)
513 # Authors :: List of authors
514 f.write(html_header(2, 'List of Authors'))
516 f.write('<table class="authors">')
517 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th>Age</th></tr>')
518 for author in sorted(data.getAuthors()):
519 info = data.getAuthorInfo(author)
520 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']))
521 f.write('</table>')
523 # Authors :: Author of Month
524 f.write(html_header(2, 'Author of Month'))
525 f.write('<table>')
526 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th></tr>')
527 for yymm in reversed(sorted(data.author_of_month.keys())):
528 authordict = data.author_of_month[yymm]
529 authors = getkeyssortedbyvalues(authordict)
530 authors.reverse()
531 commits = data.author_of_month[yymm][authors[0]]
532 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]))
534 f.write('</table>')
536 f.write(html_header(2, 'Author of Year'))
537 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th></tr>')
538 for yy in reversed(sorted(data.author_of_year.keys())):
539 authordict = data.author_of_year[yy]
540 authors = getkeyssortedbyvalues(authordict)
541 authors.reverse()
542 commits = data.author_of_year[yy][authors[0]]
543 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]))
544 f.write('</table>')
546 f.write('</body></html>')
547 f.close()
550 # Files
551 f = open(path + '/files.html', 'w')
552 self.printHeader(f)
553 f.write('<h1>Files</h1>')
554 self.printNav(f)
556 f.write('<dl>\n')
557 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
558 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
559 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
560 f.write('</dl>\n')
562 # Files :: File count by date
563 f.write(html_header(2, 'File count by date'))
565 fg = open(path + '/files_by_date.dat', 'w')
566 for stamp in sorted(data.files_by_stamp.keys()):
567 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
568 fg.close()
570 f.write('<img src="files_by_date.png" alt="Files by Date" />')
572 #f.write('<h2>Average file size by date</h2>')
574 # Files :: Extensions
575 f.write(html_header(2, 'Extensions'))
576 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
577 for ext in sorted(data.extensions.keys()):
578 files = data.extensions[ext]['files']
579 lines = data.extensions[ext]['lines']
580 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))
581 f.write('</table>')
583 f.write('</body></html>')
584 f.close()
587 # Lines
588 f = open(path + '/lines.html', 'w')
589 self.printHeader(f)
590 f.write('<h1>Lines</h1>')
591 self.printNav(f)
593 f.write('<dl>\n')
594 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
595 f.write('</dl>\n')
597 f.write(html_header(2, 'Lines of Code'))
598 f.write('<img src="lines_of_code.png" />')
600 fg = open(path + '/lines_of_code.dat', 'w')
601 for stamp in sorted(data.changes_by_date.keys()):
602 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
603 fg.close()
605 f.write('</body></html>')
606 f.close()
609 # tags.html
610 f = open(path + '/tags.html', 'w')
611 self.printHeader(f)
612 f.write('<h1>Tags</h1>')
613 self.printNav(f)
615 f.write('<dl>')
616 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
617 if len(data.tags) > 0:
618 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
619 f.write('</dl>')
621 f.write('<table>')
622 f.write('<tr><th>Name</th><th>Date</th></tr>')
623 # sort the tags by date desc
624 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
625 for tag in tags_sorted_by_date_desc:
626 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
627 f.write('</table>')
629 f.write('</body></html>')
630 f.close()
632 self.createGraphs(path)
633 pass
635 def createGraphs(self, path):
636 print 'Generating graphs...'
638 # hour of day
639 f = open(path + '/hour_of_day.plot', 'w')
640 f.write(GNUPLOT_COMMON)
641 f.write(
643 set output 'hour_of_day.png'
644 unset key
645 set xrange [0.5:24.5]
646 set xtics 4
647 set ylabel "Commits"
648 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
649 """)
650 f.close()
652 # day of week
653 f = open(path + '/day_of_week.plot', 'w')
654 f.write(GNUPLOT_COMMON)
655 f.write(
657 set output 'day_of_week.png'
658 unset key
659 set xrange [0.5:7.5]
660 set xtics 1
661 set ylabel "Commits"
662 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
663 """)
664 f.close()
666 # Month of Year
667 f = open(path + '/month_of_year.plot', 'w')
668 f.write(GNUPLOT_COMMON)
669 f.write(
671 set output 'month_of_year.png'
672 unset key
673 set xrange [0.5:12.5]
674 set xtics 1
675 set ylabel "Commits"
676 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
677 """)
678 f.close()
680 # commits_by_year_month
681 f = open(path + '/commits_by_year_month.plot', 'w')
682 f.write(GNUPLOT_COMMON)
683 f.write(
685 set output 'commits_by_year_month.png'
686 unset key
687 set xdata time
688 set timefmt "%Y-%m"
689 set format x "%Y-%m"
690 set xtics rotate by 90 15768000
691 set ylabel "Commits"
692 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
693 """)
694 f.close()
696 # commits_by_year
697 f = open(path + '/commits_by_year.plot', 'w')
698 f.write(GNUPLOT_COMMON)
699 f.write(
701 set output 'commits_by_year.png'
702 unset key
703 set xtics 1
704 set ylabel "Commits"
705 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
706 """)
707 f.close()
709 # Files by date
710 f = open(path + '/files_by_date.plot', 'w')
711 f.write(GNUPLOT_COMMON)
712 f.write(
714 set output 'files_by_date.png'
715 unset key
716 set xdata time
717 set timefmt "%Y-%m-%d"
718 set format x "%Y-%m-%d"
719 set ylabel "Files"
720 set xtics rotate by 90
721 plot 'files_by_date.dat' using 1:2 smooth csplines
722 """)
723 f.close()
725 # Lines of Code
726 f = open(path + '/lines_of_code.plot', 'w')
727 f.write(GNUPLOT_COMMON)
728 f.write(
730 set output 'lines_of_code.png'
731 unset key
732 set xdata time
733 set timefmt "%s"
734 set format x "%Y-%m-%d"
735 set ylabel "Lines"
736 set xtics rotate by 90
737 plot 'lines_of_code.dat' using 1:2 w lines
738 """)
739 f.close()
741 os.chdir(path)
742 files = glob.glob(path + '/*.plot')
743 for f in files:
744 out = getoutput('gnuplot %s' % f)
745 if len(out) > 0:
746 print out
748 def printHeader(self, f):
749 f.write(
750 """<?xml version="1.0" encoding="UTF-8"?>
751 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
752 <html xmlns="http://www.w3.org/1999/xhtml">
753 <head>
754 <title>GitStats</title>
755 <link rel="stylesheet" href="gitstats.css" type="text/css" />
756 <meta name="generator" content="GitStats" />
757 </head>
758 <body>
759 """)
761 def printNav(self, f):
762 f.write("""
763 <div class="nav">
764 <ul>
765 <li><a href="index.html">General</a></li>
766 <li><a href="activity.html">Activity</a></li>
767 <li><a href="authors.html">Authors</a></li>
768 <li><a href="files.html">Files</a></li>
769 <li><a href="lines.html">Lines</a></li>
770 <li><a href="tags.html">Tags</a></li>
771 </ul>
772 </div>
773 """)
776 usage = """
777 Usage: gitstats [options] <gitpath> <outputpath>
779 Options:
782 if len(sys.argv) < 3:
783 print usage
784 sys.exit(0)
786 gitpath = sys.argv[1]
787 outputpath = os.path.abspath(sys.argv[2])
788 rundir = os.getcwd()
790 try:
791 os.makedirs(outputpath)
792 except OSError:
793 pass
794 if not os.path.isdir(outputpath):
795 print 'FATAL: Output path is not a directory or does not exist'
796 sys.exit(1)
798 print 'Git path: %s' % gitpath
799 print 'Output path: %s' % outputpath
801 os.chdir(gitpath)
803 print 'Collecting data...'
804 data = GitDataCollector()
805 data.collect(gitpath)
807 os.chdir(rundir)
809 print 'Generating report...'
810 report = HTMLReportCreator()
811 report.create(data, outputpath)