todo: total repository size.
[gitstats.git] / gitstats
blob770ff945d100044f2d9adce0c9a703b552ec89be
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 # "commit <hash>"
132 # "<stamp> <author>"
133 self.files_by_stamp = {} # stamp -> files
134 lines = getoutput('git-rev-list --pretty=format:"%at %an" HEAD').split('\n')
135 self.total_commits = len(lines) / 2
136 commit = '0'
137 for line in lines:
138 if line[0] == 'c':
139 commit = line[7:]
140 continue
142 # linux-2.6 says "<unknown>" for one line O_o
143 parts = line.split(' ')
144 author = ''
145 try:
146 stamp = int(parts[0])
147 except ValueError:
148 stamp = 0
149 if len(parts) > 1:
150 author = ' '.join(parts[1:])
151 date = datetime.datetime.fromtimestamp(float(stamp))
153 # First and last commit stamp
154 if self.last_commit_stamp == 0:
155 self.last_commit_stamp = stamp
156 self.first_commit_stamp = stamp
158 # activity
159 # hour
160 hour = date.hour
161 if hour in self.activity_by_hour_of_day:
162 self.activity_by_hour_of_day[hour] += 1
163 else:
164 self.activity_by_hour_of_day[hour] = 1
166 # day of week
167 day = date.weekday()
168 if day in self.activity_by_day_of_week:
169 self.activity_by_day_of_week[day] += 1
170 else:
171 self.activity_by_day_of_week[day] = 1
173 # hour of week
174 if day not in self.activity_by_hour_of_week:
175 self.activity_by_hour_of_week[day] = {}
176 if hour not in self.activity_by_hour_of_week[day]:
177 self.activity_by_hour_of_week[day][hour] = 1
178 else:
179 self.activity_by_hour_of_week[day][hour] += 1
181 # month of year
182 month = date.month
183 if month in self.activity_by_month_of_year:
184 self.activity_by_month_of_year[month] += 1
185 else:
186 self.activity_by_month_of_year[month] = 1
188 # author stats
189 if author not in self.authors:
190 self.authors[author] = {}
191 # TODO commits
192 if 'last_commit_stamp' not in self.authors[author]:
193 self.authors[author]['last_commit_stamp'] = stamp
194 self.authors[author]['first_commit_stamp'] = stamp
195 if 'commits' in self.authors[author]:
196 self.authors[author]['commits'] += 1
197 else:
198 self.authors[author]['commits'] = 1
200 # author of the month/year
201 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
202 if yymm in self.author_of_month:
203 if author in self.author_of_month[yymm]:
204 self.author_of_month[yymm][author] += 1
205 else:
206 self.author_of_month[yymm][author] = 1
207 else:
208 self.author_of_month[yymm] = {}
209 self.author_of_month[yymm][author] = 1
210 if yymm in self.commits_by_month:
211 self.commits_by_month[yymm] += 1
212 else:
213 self.commits_by_month[yymm] = 1
215 yy = datetime.datetime.fromtimestamp(stamp).year
216 if yy in self.author_of_year:
217 if author in self.author_of_year[yy]:
218 self.author_of_year[yy][author] += 1
219 else:
220 self.author_of_year[yy][author] = 1
221 else:
222 self.author_of_year[yy] = {}
223 self.author_of_year[yy][author] = 1
224 if yy in self.commits_by_year:
225 self.commits_by_year[yy] += 1
226 else:
227 self.commits_by_year[yy] = 1
229 # file statistics
230 # "<stamp> <files>"
231 try:
232 files = int(getoutput('git-ls-tree -r "%s" |wc -l' % commit, quiet = True))
233 except ValueError:
234 files = 0
235 print 'Warning: failed to collect file statistics for commit "%s"' % commit
236 self.files_by_stamp[stamp] = files
238 # extensions
239 self.extensions = {} # extension -> files, lines
240 lines = getoutput('git-ls-files').split('\n')
241 self.total_files = len(lines)
242 for line in lines:
243 base = os.path.basename(line)
244 if base.find('.') == -1:
245 ext = ''
246 else:
247 ext = base[(base.rfind('.') + 1):]
249 if ext not in self.extensions:
250 self.extensions[ext] = {'files': 0, 'lines': 0}
252 self.extensions[ext]['files'] += 1
253 try:
254 # Escaping could probably be improved here
255 self.extensions[ext]['lines'] += int(getoutput('wc -l < %s' % re.sub(r'(\W)', r'\\\1', line), quiet = True))
256 except:
257 print 'Warning: Could not count lines for file "%s"' % line
259 # line statistics
260 # outputs:
261 # N files changed, N insertions (+), N deletions(-)
262 # <stamp> <author>
263 self.changes_by_date = {} # stamp -> { files, ins, del }
264 lines = getoutput('git-log --shortstat --pretty=format:"%at %an" |tac').split('\n')
265 files = 0; inserted = 0; deleted = 0; total_lines = 0
266 for line in lines:
267 if len(line) == 0:
268 continue
270 # <stamp> <author>
271 if line.find('files changed,') == -1:
272 pos = line.find(' ')
273 if pos != -1:
274 (stamp, author) = (int(line[:pos]), line[pos+1:])
275 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
276 else:
277 print 'Warning: unexpected line "%s"' % line
278 else:
279 numbers = re.findall('\d+', line)
280 if len(numbers) == 3:
281 (files, inserted, deleted) = map(lambda el : int(el), numbers)
282 total_lines += inserted
283 total_lines -= deleted
284 else:
285 print 'Warning: failed to handle line "%s"' % line
286 (files, inserted, deleted) = (0, 0, 0)
287 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
288 self.total_lines = total_lines
290 def getActivityByDayOfWeek(self):
291 return self.activity_by_day_of_week
293 def getActivityByHourOfDay(self):
294 return self.activity_by_hour_of_day
296 def getAuthorInfo(self, author):
297 a = self.authors[author]
299 commits = a['commits']
300 commits_frac = (100 * float(commits)) / self.getTotalCommits()
301 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
302 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
303 delta = date_last - date_first
305 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 }
306 return res
308 def getAuthors(self):
309 return self.authors.keys()
311 def getFirstCommitDate(self):
312 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
314 def getLastCommitDate(self):
315 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
317 def getTags(self):
318 lines = getoutput('git-show-ref --tags |cut -d/ -f3')
319 return lines.split('\n')
321 def getTagDate(self, tag):
322 return self.revToDate('tags/' + tag)
324 def getTotalAuthors(self):
325 return self.total_authors
327 def getTotalCommits(self):
328 return self.total_commits
330 def getTotalFiles(self):
331 return self.total_files
333 def getTotalLOC(self):
334 return self.total_lines
336 def revToDate(self, rev):
337 stamp = int(getoutput('git-log --pretty=format:%%at "%s" -n 1' % rev))
338 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
340 class ReportCreator:
341 """Creates the actual report based on given data."""
342 def __init__(self):
343 pass
345 def create(self, data, path):
346 self.data = data
347 self.path = path
349 def html_linkify(text):
350 return text.lower().replace(' ', '_')
352 def html_header(level, text):
353 name = html_linkify(text)
354 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
356 class HTMLReportCreator(ReportCreator):
357 def create(self, data, path):
358 ReportCreator.create(self, data, path)
359 self.title = data.projectname
361 # TODO copy the CSS if it does not exist
362 if not os.path.exists(path + '/gitstats.css'):
363 shutil.copyfile('gitstats.css', path + '/gitstats.css')
364 pass
366 f = open(path + "/index.html", 'w')
367 format = '%Y-%m-%d %H:%m:%S'
368 self.printHeader(f)
370 f.write('<h1>GitStats - %s</h1>' % data.projectname)
372 self.printNav(f)
374 f.write('<dl>');
375 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
376 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
377 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
378 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
379 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
380 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
381 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
382 f.write('</dl>');
384 f.write('</body>\n</html>');
385 f.close()
388 # Activity
389 f = open(path + '/activity.html', 'w')
390 self.printHeader(f)
391 f.write('<h1>Activity</h1>')
392 self.printNav(f)
394 #f.write('<h2>Last 30 days</h2>')
396 #f.write('<h2>Last 12 months</h2>')
398 # Hour of Day
399 f.write(html_header(2, 'Hour of Day'))
400 hour_of_day = data.getActivityByHourOfDay()
401 f.write('<table><tr><th>Hour</th>')
402 for i in range(1, 25):
403 f.write('<th>%d</th>' % i)
404 f.write('</tr>\n<tr><th>Commits</th>')
405 fp = open(path + '/hour_of_day.dat', 'w')
406 for i in range(0, 24):
407 if i in hour_of_day:
408 f.write('<td>%d</td>' % hour_of_day[i])
409 fp.write('%d %d\n' % (i, hour_of_day[i]))
410 else:
411 f.write('<td>0</td>')
412 fp.write('%d 0\n' % i)
413 fp.close()
414 f.write('</tr>\n<tr><th>%</th>')
415 totalcommits = data.getTotalCommits()
416 for i in range(0, 24):
417 if i in hour_of_day:
418 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
419 else:
420 f.write('<td>0.00</td>')
421 f.write('</tr></table>')
422 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
423 fg = open(path + '/hour_of_day.dat', 'w')
424 for i in range(0, 24):
425 if i in hour_of_day:
426 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
427 else:
428 fg.write('%d 0\n' % (i + 1))
429 fg.close()
431 # Day of Week
432 f.write(html_header(2, 'Day of Week'))
433 day_of_week = data.getActivityByDayOfWeek()
434 f.write('<div class="vtable"><table>')
435 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
436 fp = open(path + '/day_of_week.dat', 'w')
437 for d in range(0, 7):
438 commits = 0
439 if d in day_of_week:
440 commits = day_of_week[d]
441 fp.write('%d %d\n' % (d + 1, commits))
442 f.write('<tr>')
443 f.write('<th>%d</th>' % (d + 1))
444 if d in day_of_week:
445 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
446 else:
447 f.write('<td>0</td>')
448 f.write('</tr>')
449 f.write('</table></div>')
450 f.write('<img src="day_of_week.png" alt="Day of Week" />')
451 fp.close()
453 # Hour of Week
454 f.write(html_header(2, 'Hour of Week'))
455 f.write('<table>')
457 f.write('<tr><th>Weekday</th>')
458 for hour in range(0, 24):
459 f.write('<th>%d</th>' % (hour + 1))
460 f.write('</tr>')
462 for weekday in range(0, 7):
463 f.write('<tr><th>%d</th>' % (weekday + 1))
464 for hour in range(0, 24):
465 try:
466 commits = data.activity_by_hour_of_week[weekday][hour]
467 except KeyError:
468 commits = 0
469 if commits != 0:
470 f.write('<td>%d</td>' % commits)
471 else:
472 f.write('<td></td>')
473 f.write('</tr>')
475 f.write('</table>')
477 # Month of Year
478 f.write(html_header(2, 'Month of Year'))
479 f.write('<div class="vtable"><table>')
480 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
481 fp = open (path + '/month_of_year.dat', 'w')
482 for mm in range(1, 13):
483 commits = 0
484 if mm in data.activity_by_month_of_year:
485 commits = data.activity_by_month_of_year[mm]
486 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
487 fp.write('%d %d\n' % (mm, commits))
488 fp.close()
489 f.write('</table></div>')
490 f.write('<img src="month_of_year.png" alt="Month of Year" />')
492 # Commits by year/month
493 f.write(html_header(2, 'Commits by year/month'))
494 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
495 for yymm in reversed(sorted(data.commits_by_month.keys())):
496 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
497 f.write('</table></div>')
498 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
499 fg = open(path + '/commits_by_year_month.dat', 'w')
500 for yymm in sorted(data.commits_by_month.keys()):
501 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
502 fg.close()
504 # Commits by year
505 f.write(html_header(2, 'Commits by Year'))
506 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
507 for yy in reversed(sorted(data.commits_by_year.keys())):
508 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()))
509 f.write('</table></div>')
510 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
511 fg = open(path + '/commits_by_year.dat', 'w')
512 for yy in sorted(data.commits_by_year.keys()):
513 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
514 fg.close()
516 f.write('</body></html>')
517 f.close()
520 # Authors
521 f = open(path + '/authors.html', 'w')
522 self.printHeader(f)
524 f.write('<h1>Authors</h1>')
525 self.printNav(f)
527 # Authors :: List of authors
528 f.write(html_header(2, 'List of Authors'))
530 f.write('<table class="authors">')
531 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th>Age</th></tr>')
532 for author in sorted(data.getAuthors()):
533 info = data.getAuthorInfo(author)
534 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']))
535 f.write('</table>')
537 # Authors :: Author of Month
538 f.write(html_header(2, 'Author of Month'))
539 f.write('<table>')
540 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th></tr>')
541 for yymm in reversed(sorted(data.author_of_month.keys())):
542 authordict = data.author_of_month[yymm]
543 authors = getkeyssortedbyvalues(authordict)
544 authors.reverse()
545 commits = data.author_of_month[yymm][authors[0]]
546 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]))
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></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 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]))
558 f.write('</table>')
560 f.write('</body></html>')
561 f.close()
564 # Files
565 f = open(path + '/files.html', 'w')
566 self.printHeader(f)
567 f.write('<h1>Files</h1>')
568 self.printNav(f)
570 f.write('<dl>\n')
571 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
572 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
573 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
574 f.write('</dl>\n')
576 # Files :: File count by date
577 f.write(html_header(2, 'File count by date'))
579 fg = open(path + '/files_by_date.dat', 'w')
580 for stamp in sorted(data.files_by_stamp.keys()):
581 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
582 fg.close()
584 f.write('<img src="files_by_date.png" alt="Files by Date" />')
586 #f.write('<h2>Average file size by date</h2>')
588 # Files :: Extensions
589 f.write(html_header(2, 'Extensions'))
590 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
591 for ext in sorted(data.extensions.keys()):
592 files = data.extensions[ext]['files']
593 lines = data.extensions[ext]['lines']
594 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))
595 f.write('</table>')
597 f.write('</body></html>')
598 f.close()
601 # Lines
602 f = open(path + '/lines.html', 'w')
603 self.printHeader(f)
604 f.write('<h1>Lines</h1>')
605 self.printNav(f)
607 f.write('<dl>\n')
608 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
609 f.write('</dl>\n')
611 f.write(html_header(2, 'Lines of Code'))
612 f.write('<img src="lines_of_code.png" />')
614 fg = open(path + '/lines_of_code.dat', 'w')
615 for stamp in sorted(data.changes_by_date.keys()):
616 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
617 fg.close()
619 f.write('</body></html>')
620 f.close()
623 # tags.html
624 f = open(path + '/tags.html', 'w')
625 self.printHeader(f)
626 f.write('<h1>Tags</h1>')
627 self.printNav(f)
629 f.write('<dl>')
630 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
631 if len(data.tags) > 0:
632 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
633 f.write('</dl>')
635 f.write('<table>')
636 f.write('<tr><th>Name</th><th>Date</th></tr>')
637 # sort the tags by date desc
638 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
639 for tag in tags_sorted_by_date_desc:
640 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
641 f.write('</table>')
643 f.write('</body></html>')
644 f.close()
646 self.createGraphs(path)
647 pass
649 def createGraphs(self, path):
650 print 'Generating graphs...'
652 # hour of day
653 f = open(path + '/hour_of_day.plot', 'w')
654 f.write(GNUPLOT_COMMON)
655 f.write(
657 set output 'hour_of_day.png'
658 unset key
659 set xrange [0.5:24.5]
660 set xtics 4
661 set ylabel "Commits"
662 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
663 """)
664 f.close()
666 # day of week
667 f = open(path + '/day_of_week.plot', 'w')
668 f.write(GNUPLOT_COMMON)
669 f.write(
671 set output 'day_of_week.png'
672 unset key
673 set xrange [0.5:7.5]
674 set xtics 1
675 set ylabel "Commits"
676 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
677 """)
678 f.close()
680 # Month of Year
681 f = open(path + '/month_of_year.plot', 'w')
682 f.write(GNUPLOT_COMMON)
683 f.write(
685 set output 'month_of_year.png'
686 unset key
687 set xrange [0.5:12.5]
688 set xtics 1
689 set ylabel "Commits"
690 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
691 """)
692 f.close()
694 # commits_by_year_month
695 f = open(path + '/commits_by_year_month.plot', 'w')
696 f.write(GNUPLOT_COMMON)
697 f.write(
699 set output 'commits_by_year_month.png'
700 unset key
701 set xdata time
702 set timefmt "%Y-%m"
703 set format x "%Y-%m"
704 set xtics rotate by 90 15768000
705 set bmargin 5
706 set ylabel "Commits"
707 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
708 """)
709 f.close()
711 # commits_by_year
712 f = open(path + '/commits_by_year.plot', 'w')
713 f.write(GNUPLOT_COMMON)
714 f.write(
716 set output 'commits_by_year.png'
717 unset key
718 set xtics 1
719 set ylabel "Commits"
720 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
721 """)
722 f.close()
724 # Files by date
725 f = open(path + '/files_by_date.plot', 'w')
726 f.write(GNUPLOT_COMMON)
727 f.write(
729 set output 'files_by_date.png'
730 unset key
731 set xdata time
732 set timefmt "%Y-%m-%d"
733 set format x "%Y-%m-%d"
734 set ylabel "Files"
735 set xtics rotate by 90
736 set bmargin 6
737 plot 'files_by_date.dat' using 1:2 smooth csplines
738 """)
739 f.close()
741 # Lines of Code
742 f = open(path + '/lines_of_code.plot', 'w')
743 f.write(GNUPLOT_COMMON)
744 f.write(
746 set output 'lines_of_code.png'
747 unset key
748 set xdata time
749 set timefmt "%s"
750 set format x "%Y-%m-%d"
751 set ylabel "Lines"
752 set xtics rotate by 90
753 set bmargin 6
754 plot 'lines_of_code.dat' using 1:2 w lines
755 """)
756 f.close()
758 os.chdir(path)
759 files = glob.glob(path + '/*.plot')
760 for f in files:
761 out = getoutput('gnuplot %s' % f)
762 if len(out) > 0:
763 print out
765 def printHeader(self, f, title = ''):
766 f.write(
767 """<?xml version="1.0" encoding="UTF-8"?>
768 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
769 <html xmlns="http://www.w3.org/1999/xhtml">
770 <head>
771 <title>GitStats - %s</title>
772 <link rel="stylesheet" href="gitstats.css" type="text/css" />
773 <meta name="generator" content="GitStats" />
774 </head>
775 <body>
776 """ % self.title)
778 def printNav(self, f):
779 f.write("""
780 <div class="nav">
781 <ul>
782 <li><a href="index.html">General</a></li>
783 <li><a href="activity.html">Activity</a></li>
784 <li><a href="authors.html">Authors</a></li>
785 <li><a href="files.html">Files</a></li>
786 <li><a href="lines.html">Lines</a></li>
787 <li><a href="tags.html">Tags</a></li>
788 </ul>
789 </div>
790 """)
793 usage = """
794 Usage: gitstats [options] <gitpath> <outputpath>
796 Options:
799 if len(sys.argv) < 3:
800 print usage
801 sys.exit(0)
803 gitpath = sys.argv[1]
804 outputpath = os.path.abspath(sys.argv[2])
805 rundir = os.getcwd()
807 try:
808 os.makedirs(outputpath)
809 except OSError:
810 pass
811 if not os.path.isdir(outputpath):
812 print 'FATAL: Output path is not a directory or does not exist'
813 sys.exit(1)
815 print 'Git path: %s' % gitpath
816 print 'Output path: %s' % outputpath
818 os.chdir(gitpath)
820 print 'Collecting data...'
821 data = GitDataCollector()
822 data.collect(gitpath)
824 os.chdir(rundir)
826 print 'Generating report...'
827 report = HTMLReportCreator()
828 report.create(data, outputpath)
830 time_end = time.time()
831 exectime_internal = time_end - time_start
832 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)