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