Minor optimization for line counting.
[gitstats.git] / gitstats
blob886950013f974e54592f0e6f2255a7720a40981d
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 %T" HEAD |grep -v ^commit |while read line; do set $line; echo "$1 $(git-ls-tree -r --name-only "$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 try:
281 (stamp, author) = (int(line[:pos]), line[pos+1:])
282 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
283 except ValueError:
284 print 'Warning: unexpected line "%s"' % line
285 else:
286 print 'Warning: unexpected line "%s"' % line
287 else:
288 numbers = re.findall('\d+', line)
289 if len(numbers) == 3:
290 (files, inserted, deleted) = map(lambda el : int(el), numbers)
291 total_lines += inserted
292 total_lines -= deleted
293 else:
294 print 'Warning: failed to handle line "%s"' % line
295 (files, inserted, deleted) = (0, 0, 0)
296 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
297 self.total_lines = total_lines
299 def refine(self):
300 # authors
301 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
302 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
303 authors_by_commits.reverse() # most first
304 for i, name in enumerate(authors_by_commits):
305 self.authors[name]['place_by_commits'] = i + 1
307 for name in self.authors.keys():
308 a = self.authors[name]
309 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
310 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
311 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
312 delta = date_last - date_first
313 a['date_first'] = date_first.strftime('%Y-%m-%d')
314 a['date_last'] = date_last.strftime('%Y-%m-%d')
315 a['timedelta'] = delta
317 def getActivityByDayOfWeek(self):
318 return self.activity_by_day_of_week
320 def getActivityByHourOfDay(self):
321 return self.activity_by_hour_of_day
323 def getAuthorInfo(self, author):
324 return self.authors[author]
326 def getAuthors(self):
327 return self.authors.keys()
329 def getFirstCommitDate(self):
330 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
332 def getLastCommitDate(self):
333 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
335 def getTags(self):
336 lines = getoutput('git-show-ref --tags |cut -d/ -f3')
337 return lines.split('\n')
339 def getTagDate(self, tag):
340 return self.revToDate('tags/' + tag)
342 def getTotalAuthors(self):
343 return self.total_authors
345 def getTotalCommits(self):
346 return self.total_commits
348 def getTotalFiles(self):
349 return self.total_files
351 def getTotalLOC(self):
352 return self.total_lines
354 def revToDate(self, rev):
355 stamp = int(getoutput('git-log --pretty=format:%%at "%s" -n 1' % rev))
356 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
358 class ReportCreator:
359 """Creates the actual report based on given data."""
360 def __init__(self):
361 pass
363 def create(self, data, path):
364 self.data = data
365 self.path = path
367 def html_linkify(text):
368 return text.lower().replace(' ', '_')
370 def html_header(level, text):
371 name = html_linkify(text)
372 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
374 class HTMLReportCreator(ReportCreator):
375 def create(self, data, path):
376 ReportCreator.create(self, data, path)
377 self.title = data.projectname
379 # TODO copy the CSS if it does not exist
380 if not os.path.exists(path + '/gitstats.css'):
381 shutil.copyfile('gitstats.css', path + '/gitstats.css')
382 pass
384 f = open(path + "/index.html", 'w')
385 format = '%Y-%m-%d %H:%m:%S'
386 self.printHeader(f)
388 f.write('<h1>GitStats - %s</h1>' % data.projectname)
390 self.printNav(f)
392 f.write('<dl>');
393 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
394 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
395 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
396 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
397 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
398 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
399 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
400 f.write('</dl>');
402 f.write('</body>\n</html>');
403 f.close()
406 # Activity
407 f = open(path + '/activity.html', 'w')
408 self.printHeader(f)
409 f.write('<h1>Activity</h1>')
410 self.printNav(f)
412 #f.write('<h2>Last 30 days</h2>')
414 #f.write('<h2>Last 12 months</h2>')
416 # Hour of Day
417 f.write(html_header(2, 'Hour of Day'))
418 hour_of_day = data.getActivityByHourOfDay()
419 f.write('<table><tr><th>Hour</th>')
420 for i in range(1, 25):
421 f.write('<th>%d</th>' % i)
422 f.write('</tr>\n<tr><th>Commits</th>')
423 fp = open(path + '/hour_of_day.dat', 'w')
424 for i in range(0, 24):
425 if i in hour_of_day:
426 f.write('<td>%d</td>' % hour_of_day[i])
427 fp.write('%d %d\n' % (i, hour_of_day[i]))
428 else:
429 f.write('<td>0</td>')
430 fp.write('%d 0\n' % i)
431 fp.close()
432 f.write('</tr>\n<tr><th>%</th>')
433 totalcommits = data.getTotalCommits()
434 for i in range(0, 24):
435 if i in hour_of_day:
436 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
437 else:
438 f.write('<td>0.00</td>')
439 f.write('</tr></table>')
440 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
441 fg = open(path + '/hour_of_day.dat', 'w')
442 for i in range(0, 24):
443 if i in hour_of_day:
444 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
445 else:
446 fg.write('%d 0\n' % (i + 1))
447 fg.close()
449 # Day of Week
450 f.write(html_header(2, 'Day of Week'))
451 day_of_week = data.getActivityByDayOfWeek()
452 f.write('<div class="vtable"><table>')
453 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
454 fp = open(path + '/day_of_week.dat', 'w')
455 for d in range(0, 7):
456 commits = 0
457 if d in day_of_week:
458 commits = day_of_week[d]
459 fp.write('%d %d\n' % (d + 1, commits))
460 f.write('<tr>')
461 f.write('<th>%d</th>' % (d + 1))
462 if d in day_of_week:
463 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
464 else:
465 f.write('<td>0</td>')
466 f.write('</tr>')
467 f.write('</table></div>')
468 f.write('<img src="day_of_week.png" alt="Day of Week" />')
469 fp.close()
471 # Hour of Week
472 f.write(html_header(2, 'Hour of Week'))
473 f.write('<table>')
475 f.write('<tr><th>Weekday</th>')
476 for hour in range(0, 24):
477 f.write('<th>%d</th>' % (hour + 1))
478 f.write('</tr>')
480 for weekday in range(0, 7):
481 f.write('<tr><th>%d</th>' % (weekday + 1))
482 for hour in range(0, 24):
483 try:
484 commits = data.activity_by_hour_of_week[weekday][hour]
485 except KeyError:
486 commits = 0
487 if commits != 0:
488 f.write('<td>%d</td>' % commits)
489 else:
490 f.write('<td></td>')
491 f.write('</tr>')
493 f.write('</table>')
495 # Month of Year
496 f.write(html_header(2, 'Month of Year'))
497 f.write('<div class="vtable"><table>')
498 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
499 fp = open (path + '/month_of_year.dat', 'w')
500 for mm in range(1, 13):
501 commits = 0
502 if mm in data.activity_by_month_of_year:
503 commits = data.activity_by_month_of_year[mm]
504 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
505 fp.write('%d %d\n' % (mm, commits))
506 fp.close()
507 f.write('</table></div>')
508 f.write('<img src="month_of_year.png" alt="Month of Year" />')
510 # Commits by year/month
511 f.write(html_header(2, 'Commits by year/month'))
512 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
513 for yymm in reversed(sorted(data.commits_by_month.keys())):
514 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
515 f.write('</table></div>')
516 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
517 fg = open(path + '/commits_by_year_month.dat', 'w')
518 for yymm in sorted(data.commits_by_month.keys()):
519 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
520 fg.close()
522 # Commits by year
523 f.write(html_header(2, 'Commits by Year'))
524 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
525 for yy in reversed(sorted(data.commits_by_year.keys())):
526 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()))
527 f.write('</table></div>')
528 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
529 fg = open(path + '/commits_by_year.dat', 'w')
530 for yy in sorted(data.commits_by_year.keys()):
531 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
532 fg.close()
534 f.write('</body></html>')
535 f.close()
538 # Authors
539 f = open(path + '/authors.html', 'w')
540 self.printHeader(f)
542 f.write('<h1>Authors</h1>')
543 self.printNav(f)
545 # Authors :: List of authors
546 f.write(html_header(2, 'List of Authors'))
548 f.write('<table class="authors">')
549 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>')
550 for author in sorted(data.getAuthors()):
551 info = data.getAuthorInfo(author)
552 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']))
553 f.write('</table>')
555 # Authors :: Author of Month
556 f.write(html_header(2, 'Author of Month'))
557 f.write('<table>')
558 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
559 for yymm in reversed(sorted(data.author_of_month.keys())):
560 authordict = data.author_of_month[yymm]
561 authors = getkeyssortedbyvalues(authordict)
562 authors.reverse()
563 commits = data.author_of_month[yymm][authors[0]]
564 next = ', '.join(authors[1:5])
565 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))
567 f.write('</table>')
569 f.write(html_header(2, 'Author of Year'))
570 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
571 for yy in reversed(sorted(data.author_of_year.keys())):
572 authordict = data.author_of_year[yy]
573 authors = getkeyssortedbyvalues(authordict)
574 authors.reverse()
575 commits = data.author_of_year[yy][authors[0]]
576 next = ', '.join(authors[1:5])
577 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))
578 f.write('</table>')
580 f.write('</body></html>')
581 f.close()
584 # Files
585 f = open(path + '/files.html', 'w')
586 self.printHeader(f)
587 f.write('<h1>Files</h1>')
588 self.printNav(f)
590 f.write('<dl>\n')
591 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
592 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
593 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
594 f.write('</dl>\n')
596 # Files :: File count by date
597 f.write(html_header(2, 'File count by date'))
599 fg = open(path + '/files_by_date.dat', 'w')
600 for stamp in sorted(data.files_by_stamp.keys()):
601 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
602 fg.close()
604 f.write('<img src="files_by_date.png" alt="Files by Date" />')
606 #f.write('<h2>Average file size by date</h2>')
608 # Files :: Extensions
609 f.write(html_header(2, 'Extensions'))
610 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
611 for ext in sorted(data.extensions.keys()):
612 files = data.extensions[ext]['files']
613 lines = data.extensions[ext]['lines']
614 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))
615 f.write('</table>')
617 f.write('</body></html>')
618 f.close()
621 # Lines
622 f = open(path + '/lines.html', 'w')
623 self.printHeader(f)
624 f.write('<h1>Lines</h1>')
625 self.printNav(f)
627 f.write('<dl>\n')
628 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
629 f.write('</dl>\n')
631 f.write(html_header(2, 'Lines of Code'))
632 f.write('<img src="lines_of_code.png" />')
634 fg = open(path + '/lines_of_code.dat', 'w')
635 for stamp in sorted(data.changes_by_date.keys()):
636 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
637 fg.close()
639 f.write('</body></html>')
640 f.close()
643 # tags.html
644 f = open(path + '/tags.html', 'w')
645 self.printHeader(f)
646 f.write('<h1>Tags</h1>')
647 self.printNav(f)
649 f.write('<dl>')
650 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
651 if len(data.tags) > 0:
652 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
653 f.write('</dl>')
655 f.write('<table>')
656 f.write('<tr><th>Name</th><th>Date</th></tr>')
657 # sort the tags by date desc
658 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
659 for tag in tags_sorted_by_date_desc:
660 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
661 f.write('</table>')
663 f.write('</body></html>')
664 f.close()
666 self.createGraphs(path)
667 pass
669 def createGraphs(self, path):
670 print 'Generating graphs...'
672 # hour of day
673 f = open(path + '/hour_of_day.plot', 'w')
674 f.write(GNUPLOT_COMMON)
675 f.write(
677 set output 'hour_of_day.png'
678 unset key
679 set xrange [0.5:24.5]
680 set xtics 4
681 set ylabel "Commits"
682 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
683 """)
684 f.close()
686 # day of week
687 f = open(path + '/day_of_week.plot', 'w')
688 f.write(GNUPLOT_COMMON)
689 f.write(
691 set output 'day_of_week.png'
692 unset key
693 set xrange [0.5:7.5]
694 set xtics 1
695 set ylabel "Commits"
696 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
697 """)
698 f.close()
700 # Month of Year
701 f = open(path + '/month_of_year.plot', 'w')
702 f.write(GNUPLOT_COMMON)
703 f.write(
705 set output 'month_of_year.png'
706 unset key
707 set xrange [0.5:12.5]
708 set xtics 1
709 set ylabel "Commits"
710 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
711 """)
712 f.close()
714 # commits_by_year_month
715 f = open(path + '/commits_by_year_month.plot', 'w')
716 f.write(GNUPLOT_COMMON)
717 f.write(
719 set output 'commits_by_year_month.png'
720 unset key
721 set xdata time
722 set timefmt "%Y-%m"
723 set format x "%Y-%m"
724 set xtics rotate by 90 15768000
725 set bmargin 5
726 set ylabel "Commits"
727 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
728 """)
729 f.close()
731 # commits_by_year
732 f = open(path + '/commits_by_year.plot', 'w')
733 f.write(GNUPLOT_COMMON)
734 f.write(
736 set output 'commits_by_year.png'
737 unset key
738 set xtics 1
739 set ylabel "Commits"
740 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
741 """)
742 f.close()
744 # Files by date
745 f = open(path + '/files_by_date.plot', 'w')
746 f.write(GNUPLOT_COMMON)
747 f.write(
749 set output 'files_by_date.png'
750 unset key
751 set xdata time
752 set timefmt "%Y-%m-%d"
753 set format x "%Y-%m-%d"
754 set ylabel "Files"
755 set xtics rotate by 90
756 set bmargin 6
757 plot 'files_by_date.dat' using 1:2 smooth csplines
758 """)
759 f.close()
761 # Lines of Code
762 f = open(path + '/lines_of_code.plot', 'w')
763 f.write(GNUPLOT_COMMON)
764 f.write(
766 set output 'lines_of_code.png'
767 unset key
768 set xdata time
769 set timefmt "%s"
770 set format x "%Y-%m-%d"
771 set ylabel "Lines"
772 set xtics rotate by 90
773 set bmargin 6
774 plot 'lines_of_code.dat' using 1:2 w lines
775 """)
776 f.close()
778 os.chdir(path)
779 files = glob.glob(path + '/*.plot')
780 for f in files:
781 out = getoutput('gnuplot %s' % f)
782 if len(out) > 0:
783 print out
785 def printHeader(self, f, title = ''):
786 f.write(
787 """<?xml version="1.0" encoding="UTF-8"?>
788 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
789 <html xmlns="http://www.w3.org/1999/xhtml">
790 <head>
791 <title>GitStats - %s</title>
792 <link rel="stylesheet" href="gitstats.css" type="text/css" />
793 <meta name="generator" content="GitStats" />
794 </head>
795 <body>
796 """ % self.title)
798 def printNav(self, f):
799 f.write("""
800 <div class="nav">
801 <ul>
802 <li><a href="index.html">General</a></li>
803 <li><a href="activity.html">Activity</a></li>
804 <li><a href="authors.html">Authors</a></li>
805 <li><a href="files.html">Files</a></li>
806 <li><a href="lines.html">Lines</a></li>
807 <li><a href="tags.html">Tags</a></li>
808 </ul>
809 </div>
810 """)
813 usage = """
814 Usage: gitstats [options] <gitpath> <outputpath>
816 Options:
819 if len(sys.argv) < 3:
820 print usage
821 sys.exit(0)
823 gitpath = sys.argv[1]
824 outputpath = os.path.abspath(sys.argv[2])
825 rundir = os.getcwd()
827 try:
828 os.makedirs(outputpath)
829 except OSError:
830 pass
831 if not os.path.isdir(outputpath):
832 print 'FATAL: Output path is not a directory or does not exist'
833 sys.exit(1)
835 print 'Git path: %s' % gitpath
836 print 'Output path: %s' % outputpath
838 os.chdir(gitpath)
840 print 'Collecting data...'
841 data = GitDataCollector()
842 data.collect(gitpath)
843 print 'Refining data...'
844 data.refine()
846 os.chdir(rundir)
848 print 'Generating report...'
849 report = HTMLReportCreator()
850 report.create(data, outputpath)
852 time_end = time.time()
853 exectime_internal = time_end - time_start
854 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)