Use lists instead of tuples for better readability.
[gitstats.git] / gitstats
blobbe7d46ce307da3b06f380dd0e591ca0100095366
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2008 Heikki Hokkanen <hoxu@users.sf.net>
3 # GPLv2
4 import subprocess
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 # By default, gnuplot is searched from path, but can be overridden with the
20 # environment variable "GNUPLOT"
21 gnuplot_cmd = 'gnuplot'
22 if 'GNUPLOT' in os.environ:
23 gnuplot_cmd = os.environ['GNUPLOT']
25 def getpipeoutput(cmds, quiet = False):
26 global exectime_external
27 start = time.time()
28 if not quiet:
29 print '>> ' + ' | '.join(cmds),
30 sys.stdout.flush()
31 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
32 p = p0
33 for x in cmds[1:]:
34 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
35 p0 = p
36 output = p.communicate()[0]
37 end = time.time()
38 if not quiet:
39 print '\r[%.5f] >> %s' % (end - start, ' | '.join(cmds))
40 exectime_external += (end - start)
41 return output.rstrip('\n')
43 def getkeyssortedbyvalues(dict):
44 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
46 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
47 def getkeyssortedbyvaluekey(d, key):
48 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
50 class DataCollector:
51 """Manages data collection from a revision control repository."""
52 def __init__(self):
53 self.stamp_created = time.time()
54 pass
57 # This should be the main function to extract data from the repository.
58 def collect(self, dir):
59 self.dir = dir
60 self.projectname = os.path.basename(os.path.abspath(dir))
63 # Produce any additional statistics from the extracted data.
64 def refine(self):
65 pass
68 # : get a dictionary of author
69 def getAuthorInfo(self, author):
70 return None
72 def getActivityByDayOfWeek(self):
73 return {}
75 def getActivityByHourOfDay(self):
76 return {}
79 # Get a list of authors
80 def getAuthors(self):
81 return []
83 def getFirstCommitDate(self):
84 return datetime.datetime.now()
86 def getLastCommitDate(self):
87 return datetime.datetime.now()
89 def getStampCreated(self):
90 return self.stamp_created
92 def getTags(self):
93 return []
95 def getTotalAuthors(self):
96 return -1
98 def getTotalCommits(self):
99 return -1
101 def getTotalFiles(self):
102 return -1
104 def getTotalLOC(self):
105 return -1
107 class GitDataCollector(DataCollector):
108 def collect(self, dir):
109 DataCollector.collect(self, dir)
111 try:
112 self.total_authors = int(getpipeoutput(['git-log', 'git-shortlog -s', 'wc -l']))
113 except:
114 self.total_authors = 0
115 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
117 self.activity_by_hour_of_day = {} # hour -> commits
118 self.activity_by_day_of_week = {} # day -> commits
119 self.activity_by_month_of_year = {} # month [1-12] -> commits
120 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
122 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
124 # author of the month
125 self.author_of_month = {} # month -> author -> commits
126 self.author_of_year = {} # year -> author -> commits
127 self.commits_by_month = {} # month -> commits
128 self.commits_by_year = {} # year -> commits
129 self.first_commit_stamp = 0
130 self.last_commit_stamp = 0
132 # tags
133 self.tags = {}
134 lines = getpipeoutput(['git-show-ref --tags']).split('\n')
135 for line in lines:
136 if len(line) == 0:
137 continue
138 print "line = ", line
139 splitted_str = line.split(' ')
140 print "splitted_str = ", splitted_str
141 (hash, tag) = splitted_str
143 tag = tag.replace('refs/tags/', '')
144 output = getpipeoutput(['git-log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
145 if len(output) > 0:
146 parts = output.split(' ')
147 stamp = 0
148 try:
149 stamp = int(parts[0])
150 except ValueError:
151 stamp = 0
152 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
153 pass
155 # Collect revision statistics
156 # Outputs "<stamp> <author>"
157 lines = getpipeoutput(['git-rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
158 for line in lines:
159 # linux-2.6 says "<unknown>" for one line O_o
160 parts = line.split(' ')
161 author = ''
162 try:
163 stamp = int(parts[0])
164 except ValueError:
165 print "lines = ", lines
166 print "line = ", line
167 raise
168 stamp = 0
169 if len(parts) > 1:
170 author = ' '.join(parts[1:])
171 date = datetime.datetime.fromtimestamp(float(stamp))
173 # First and last commit stamp
174 if self.last_commit_stamp == 0:
175 self.last_commit_stamp = stamp
176 self.first_commit_stamp = stamp
178 # activity
179 # hour
180 hour = date.hour
181 if hour in self.activity_by_hour_of_day:
182 self.activity_by_hour_of_day[hour] += 1
183 else:
184 self.activity_by_hour_of_day[hour] = 1
186 # day of week
187 day = date.weekday()
188 if day in self.activity_by_day_of_week:
189 self.activity_by_day_of_week[day] += 1
190 else:
191 self.activity_by_day_of_week[day] = 1
193 # hour of week
194 if day not in self.activity_by_hour_of_week:
195 self.activity_by_hour_of_week[day] = {}
196 if hour not in self.activity_by_hour_of_week[day]:
197 self.activity_by_hour_of_week[day][hour] = 1
198 else:
199 self.activity_by_hour_of_week[day][hour] += 1
201 # month of year
202 month = date.month
203 if month in self.activity_by_month_of_year:
204 self.activity_by_month_of_year[month] += 1
205 else:
206 self.activity_by_month_of_year[month] = 1
208 # author stats
209 if author not in self.authors:
210 self.authors[author] = {}
211 # TODO commits
212 if 'last_commit_stamp' not in self.authors[author]:
213 self.authors[author]['last_commit_stamp'] = stamp
214 self.authors[author]['first_commit_stamp'] = stamp
215 if 'commits' in self.authors[author]:
216 self.authors[author]['commits'] += 1
217 else:
218 self.authors[author]['commits'] = 1
220 # author of the month/year
221 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
222 if yymm in self.author_of_month:
223 if author in self.author_of_month[yymm]:
224 self.author_of_month[yymm][author] += 1
225 else:
226 self.author_of_month[yymm][author] = 1
227 else:
228 self.author_of_month[yymm] = {}
229 self.author_of_month[yymm][author] = 1
230 if yymm in self.commits_by_month:
231 self.commits_by_month[yymm] += 1
232 else:
233 self.commits_by_month[yymm] = 1
235 yy = datetime.datetime.fromtimestamp(stamp).year
236 if yy in self.author_of_year:
237 if author in self.author_of_year[yy]:
238 self.author_of_year[yy][author] += 1
239 else:
240 self.author_of_year[yy][author] = 1
241 else:
242 self.author_of_year[yy] = {}
243 self.author_of_year[yy][author] = 1
244 if yy in self.commits_by_year:
245 self.commits_by_year[yy] += 1
246 else:
247 self.commits_by_year[yy] = 1
249 # TODO Optimize this, it's the worst bottleneck
250 # outputs "<stamp> <files>" for each revision
251 self.files_by_stamp = {} # stamp -> files
252 lines = getpipeoutput(['git-rev-list --pretty=format:"%at %H" HEAD', 'grep -v ^commit']).strip().split('\n')
253 #'sh while read line; do set $line; echo "$1 $(git-ls-tree -r "$2" |wc -l)"; done')).split('\n')
254 tmp = [None] * len(lines)
255 for idx in xrange(len(lines)):
256 (a, b) = lines[idx].split(" ")
257 tmp[idx] = a + getpipeoutput(['git-ls-tree -r ' + b, 'wc -l']).strip('\n')
258 lines = tmp
260 self.total_commits = len(lines)
261 for line in lines:
262 parts = line.split(' ')
263 if len(parts) != 2:
264 continue
265 (stamp, files) = parts[0:2]
266 try:
267 self.files_by_stamp[int(stamp)] = int(files)
268 except ValueError:
269 print 'Warning: failed to parse line "%s"' % line
271 # extensions
272 self.extensions = {} # extension -> files, lines
273 lines = getpipeoutput(['git-ls-files']).split('\n')
274 self.total_files = len(lines)
275 for line in lines:
276 base = os.path.basename(line)
277 if base.find('.') == -1:
278 ext = ''
279 else:
280 ext = base[(base.rfind('.') + 1):]
282 if ext not in self.extensions:
283 self.extensions[ext] = {'files': 0, 'lines': 0}
285 self.extensions[ext]['files'] += 1
286 try:
287 # Escaping could probably be improved here
288 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
289 except:
290 print 'Warning: Could not count lines for file "%s"' % line
292 # line statistics
293 # outputs:
294 # N files changed, N insertions (+), N deletions(-)
295 # <stamp> <author>
296 self.changes_by_date = {} # stamp -> { files, ins, del }
297 lines = getpipeoutput(['git-log --shortstat --pretty=format:"%at %an"']).split('\n')
298 lines.reverse()
299 files = 0; inserted = 0; deleted = 0; total_lines = 0
300 for line in lines:
301 if len(line) == 0:
302 continue
304 # <stamp> <author>
305 if line.find('files changed,') == -1:
306 pos = line.find(' ')
307 if pos != -1:
308 (stamp, author) = (int(line[:pos]), line[pos+1:])
309 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
310 else:
311 print 'Warning: unexpected line "%s"' % line
312 else:
313 numbers = re.findall('\d+', line)
314 if len(numbers) == 3:
315 (files, inserted, deleted) = map(lambda el : int(el), numbers)
316 total_lines += inserted
317 total_lines -= deleted
318 else:
319 print 'Warning: failed to handle line "%s"' % line
320 (files, inserted, deleted) = (0, 0, 0)
321 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
322 self.total_lines = total_lines
324 def refine(self):
325 # authors
326 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
327 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
328 authors_by_commits.reverse() # most first
329 for i, name in enumerate(authors_by_commits):
330 self.authors[name]['place_by_commits'] = i + 1
332 for name in self.authors.keys():
333 a = self.authors[name]
334 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
335 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
336 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
337 delta = date_last - date_first
338 a['date_first'] = date_first.strftime('%Y-%m-%d')
339 a['date_last'] = date_last.strftime('%Y-%m-%d')
340 a['timedelta'] = delta
342 def getActivityByDayOfWeek(self):
343 return self.activity_by_day_of_week
345 def getActivityByHourOfDay(self):
346 return self.activity_by_hour_of_day
348 def getAuthorInfo(self, author):
349 return self.authors[author]
351 def getAuthors(self):
352 return self.authors.keys()
354 def getFirstCommitDate(self):
355 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
357 def getLastCommitDate(self):
358 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
360 def getTags(self):
361 lines = getpipeoutput(['git-show-ref --tags', 'cut -d/ -f3'])
362 return lines.split('\n')
364 def getTagDate(self, tag):
365 return self.revToDate('tags/' + tag)
367 def getTotalAuthors(self):
368 return self.total_authors
370 def getTotalCommits(self):
371 return self.total_commits
373 def getTotalFiles(self):
374 return self.total_files
376 def getTotalLOC(self):
377 return self.total_lines
379 def revToDate(self, rev):
380 stamp = int(getpipeoutput(['git-log --pretty=format:%%at "%s" -n 1' % rev]))
381 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
383 class ReportCreator:
384 """Creates the actual report based on given data."""
385 def __init__(self):
386 pass
388 def create(self, data, path):
389 self.data = data
390 self.path = path
392 def html_linkify(text):
393 return text.lower().replace(' ', '_')
395 def html_header(level, text):
396 name = html_linkify(text)
397 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
399 class HTMLReportCreator(ReportCreator):
400 def create(self, data, path):
401 ReportCreator.create(self, data, path)
402 self.title = data.projectname
404 # TODO copy the CSS if it does not exist
405 if not os.path.exists(path + '/gitstats.css'):
406 basedir = os.path.dirname(os.path.abspath(__file__))
407 shutil.copyfile(basedir + '/gitstats.css', path + '/gitstats.css')
408 pass
410 f = open(path + "/index.html", 'w')
411 format = '%Y-%m-%d %H:%m:%S'
412 self.printHeader(f)
414 f.write('<h1>GitStats - %s</h1>' % data.projectname)
416 self.printNav(f)
418 f.write('<dl>');
419 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
420 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
421 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
422 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
423 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
424 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
425 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
426 f.write('</dl>');
428 f.write('</body>\n</html>');
429 f.close()
432 # Activity
433 f = open(path + '/activity.html', 'w')
434 self.printHeader(f)
435 f.write('<h1>Activity</h1>')
436 self.printNav(f)
438 #f.write('<h2>Last 30 days</h2>')
440 #f.write('<h2>Last 12 months</h2>')
442 # Hour of Day
443 f.write(html_header(2, 'Hour of Day'))
444 hour_of_day = data.getActivityByHourOfDay()
445 f.write('<table><tr><th>Hour</th>')
446 for i in range(1, 25):
447 f.write('<th>%d</th>' % i)
448 f.write('</tr>\n<tr><th>Commits</th>')
449 fp = open(path + '/hour_of_day.dat', 'w')
450 for i in range(0, 24):
451 if i in hour_of_day:
452 f.write('<td>%d</td>' % hour_of_day[i])
453 fp.write('%d %d\n' % (i, hour_of_day[i]))
454 else:
455 f.write('<td>0</td>')
456 fp.write('%d 0\n' % i)
457 fp.close()
458 f.write('</tr>\n<tr><th>%</th>')
459 totalcommits = data.getTotalCommits()
460 for i in range(0, 24):
461 if i in hour_of_day:
462 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
463 else:
464 f.write('<td>0.00</td>')
465 f.write('</tr></table>')
466 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
467 fg = open(path + '/hour_of_day.dat', 'w')
468 for i in range(0, 24):
469 if i in hour_of_day:
470 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
471 else:
472 fg.write('%d 0\n' % (i + 1))
473 fg.close()
475 # Day of Week
476 f.write(html_header(2, 'Day of Week'))
477 day_of_week = data.getActivityByDayOfWeek()
478 f.write('<div class="vtable"><table>')
479 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
480 fp = open(path + '/day_of_week.dat', 'w')
481 for d in range(0, 7):
482 commits = 0
483 if d in day_of_week:
484 commits = day_of_week[d]
485 fp.write('%d %d\n' % (d + 1, commits))
486 f.write('<tr>')
487 f.write('<th>%d</th>' % (d + 1))
488 if d in day_of_week:
489 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
490 else:
491 f.write('<td>0</td>')
492 f.write('</tr>')
493 f.write('</table></div>')
494 f.write('<img src="day_of_week.png" alt="Day of Week" />')
495 fp.close()
497 # Hour of Week
498 f.write(html_header(2, 'Hour of Week'))
499 f.write('<table>')
501 f.write('<tr><th>Weekday</th>')
502 for hour in range(0, 24):
503 f.write('<th>%d</th>' % (hour + 1))
504 f.write('</tr>')
506 for weekday in range(0, 7):
507 f.write('<tr><th>%d</th>' % (weekday + 1))
508 for hour in range(0, 24):
509 try:
510 commits = data.activity_by_hour_of_week[weekday][hour]
511 except KeyError:
512 commits = 0
513 if commits != 0:
514 f.write('<td>%d</td>' % commits)
515 else:
516 f.write('<td></td>')
517 f.write('</tr>')
519 f.write('</table>')
521 # Month of Year
522 f.write(html_header(2, 'Month of Year'))
523 f.write('<div class="vtable"><table>')
524 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
525 fp = open (path + '/month_of_year.dat', 'w')
526 for mm in range(1, 13):
527 commits = 0
528 if mm in data.activity_by_month_of_year:
529 commits = data.activity_by_month_of_year[mm]
530 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
531 fp.write('%d %d\n' % (mm, commits))
532 fp.close()
533 f.write('</table></div>')
534 f.write('<img src="month_of_year.png" alt="Month of Year" />')
536 # Commits by year/month
537 f.write(html_header(2, 'Commits by year/month'))
538 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
539 for yymm in reversed(sorted(data.commits_by_month.keys())):
540 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
541 f.write('</table></div>')
542 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
543 fg = open(path + '/commits_by_year_month.dat', 'w')
544 for yymm in sorted(data.commits_by_month.keys()):
545 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
546 fg.close()
548 # Commits by year
549 f.write(html_header(2, 'Commits by Year'))
550 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
551 for yy in reversed(sorted(data.commits_by_year.keys())):
552 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()))
553 f.write('</table></div>')
554 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
555 fg = open(path + '/commits_by_year.dat', 'w')
556 for yy in sorted(data.commits_by_year.keys()):
557 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
558 fg.close()
560 f.write('</body></html>')
561 f.close()
564 # Authors
565 f = open(path + '/authors.html', 'w')
566 self.printHeader(f)
568 f.write('<h1>Authors</h1>')
569 self.printNav(f)
571 # Authors :: List of authors
572 f.write(html_header(2, 'List of Authors'))
574 f.write('<table class="authors">')
575 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>')
576 for author in sorted(data.getAuthors()):
577 info = data.getAuthorInfo(author)
578 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']))
579 f.write('</table>')
581 # Authors :: Author of Month
582 f.write(html_header(2, 'Author of Month'))
583 f.write('<table>')
584 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
585 for yymm in reversed(sorted(data.author_of_month.keys())):
586 authordict = data.author_of_month[yymm]
587 authors = getkeyssortedbyvalues(authordict)
588 authors.reverse()
589 commits = data.author_of_month[yymm][authors[0]]
590 next = ', '.join(authors[1:5])
591 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))
593 f.write('</table>')
595 f.write(html_header(2, 'Author of Year'))
596 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
597 for yy in reversed(sorted(data.author_of_year.keys())):
598 authordict = data.author_of_year[yy]
599 authors = getkeyssortedbyvalues(authordict)
600 authors.reverse()
601 commits = data.author_of_year[yy][authors[0]]
602 next = ', '.join(authors[1:5])
603 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))
604 f.write('</table>')
606 f.write('</body></html>')
607 f.close()
610 # Files
611 f = open(path + '/files.html', 'w')
612 self.printHeader(f)
613 f.write('<h1>Files</h1>')
614 self.printNav(f)
616 f.write('<dl>\n')
617 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
618 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
619 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
620 f.write('</dl>\n')
622 # Files :: File count by date
623 f.write(html_header(2, 'File count by date'))
625 fg = open(path + '/files_by_date.dat', 'w')
626 for stamp in sorted(data.files_by_stamp.keys()):
627 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
628 fg.close()
630 f.write('<img src="files_by_date.png" alt="Files by Date" />')
632 #f.write('<h2>Average file size by date</h2>')
634 # Files :: Extensions
635 f.write(html_header(2, 'Extensions'))
636 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
637 for ext in sorted(data.extensions.keys()):
638 files = data.extensions[ext]['files']
639 lines = data.extensions[ext]['lines']
640 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))
641 f.write('</table>')
643 f.write('</body></html>')
644 f.close()
647 # Lines
648 f = open(path + '/lines.html', 'w')
649 self.printHeader(f)
650 f.write('<h1>Lines</h1>')
651 self.printNav(f)
653 f.write('<dl>\n')
654 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
655 f.write('</dl>\n')
657 f.write(html_header(2, 'Lines of Code'))
658 f.write('<img src="lines_of_code.png" />')
660 fg = open(path + '/lines_of_code.dat', 'w')
661 for stamp in sorted(data.changes_by_date.keys()):
662 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
663 fg.close()
665 f.write('</body></html>')
666 f.close()
669 # tags.html
670 f = open(path + '/tags.html', 'w')
671 self.printHeader(f)
672 f.write('<h1>Tags</h1>')
673 self.printNav(f)
675 f.write('<dl>')
676 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
677 if len(data.tags) > 0:
678 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
679 f.write('</dl>')
681 f.write('<table>')
682 f.write('<tr><th>Name</th><th>Date</th></tr>')
683 # sort the tags by date desc
684 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
685 for tag in tags_sorted_by_date_desc:
686 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
687 f.write('</table>')
689 f.write('</body></html>')
690 f.close()
692 self.createGraphs(path)
693 pass
695 def createGraphs(self, path):
696 print 'Generating graphs...'
698 # hour of day
699 f = open(path + '/hour_of_day.plot', 'w')
700 f.write(GNUPLOT_COMMON)
701 f.write(
703 set output 'hour_of_day.png'
704 unset key
705 set xrange [0.5:24.5]
706 set xtics 4
707 set ylabel "Commits"
708 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
709 """)
710 f.close()
712 # day of week
713 f = open(path + '/day_of_week.plot', 'w')
714 f.write(GNUPLOT_COMMON)
715 f.write(
717 set output 'day_of_week.png'
718 unset key
719 set xrange [0.5:7.5]
720 set xtics 1
721 set ylabel "Commits"
722 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
723 """)
724 f.close()
726 # Month of Year
727 f = open(path + '/month_of_year.plot', 'w')
728 f.write(GNUPLOT_COMMON)
729 f.write(
731 set output 'month_of_year.png'
732 unset key
733 set xrange [0.5:12.5]
734 set xtics 1
735 set ylabel "Commits"
736 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
737 """)
738 f.close()
740 # commits_by_year_month
741 f = open(path + '/commits_by_year_month.plot', 'w')
742 f.write(GNUPLOT_COMMON)
743 f.write(
745 set output 'commits_by_year_month.png'
746 unset key
747 set xdata time
748 set timefmt "%Y-%m"
749 set format x "%Y-%m"
750 set xtics rotate by 90 15768000
751 set bmargin 5
752 set ylabel "Commits"
753 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
754 """)
755 f.close()
757 # commits_by_year
758 f = open(path + '/commits_by_year.plot', 'w')
759 f.write(GNUPLOT_COMMON)
760 f.write(
762 set output 'commits_by_year.png'
763 unset key
764 set xtics 1
765 set ylabel "Commits"
766 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
767 """)
768 f.close()
770 # Files by date
771 f = open(path + '/files_by_date.plot', 'w')
772 f.write(GNUPLOT_COMMON)
773 f.write(
775 set output 'files_by_date.png'
776 unset key
777 set xdata time
778 set timefmt "%Y-%m-%d"
779 set format x "%Y-%m-%d"
780 set ylabel "Files"
781 set xtics rotate by 90
782 set bmargin 6
783 plot 'files_by_date.dat' using 1:2 smooth csplines
784 """)
785 f.close()
787 # Lines of Code
788 f = open(path + '/lines_of_code.plot', 'w')
789 f.write(GNUPLOT_COMMON)
790 f.write(
792 set output 'lines_of_code.png'
793 unset key
794 set xdata time
795 set timefmt "%s"
796 set format x "%Y-%m-%d"
797 set ylabel "Lines"
798 set xtics rotate by 90
799 set bmargin 6
800 plot 'lines_of_code.dat' using 1:2 w lines
801 """)
802 f.close()
804 os.chdir(path)
805 files = glob.glob(path + '/*.plot')
806 for f in files:
807 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
808 if len(out) > 0:
809 print out
811 def printHeader(self, f, title = ''):
812 f.write(
813 """<?xml version="1.0" encoding="UTF-8"?>
814 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
815 <html xmlns="http://www.w3.org/1999/xhtml">
816 <head>
817 <title>GitStats - %s</title>
818 <link rel="stylesheet" href="gitstats.css" type="text/css" />
819 <meta name="generator" content="GitStats" />
820 </head>
821 <body>
822 """ % self.title)
824 def printNav(self, f):
825 f.write("""
826 <div class="nav">
827 <ul>
828 <li><a href="index.html">General</a></li>
829 <li><a href="activity.html">Activity</a></li>
830 <li><a href="authors.html">Authors</a></li>
831 <li><a href="files.html">Files</a></li>
832 <li><a href="lines.html">Lines</a></li>
833 <li><a href="tags.html">Tags</a></li>
834 </ul>
835 </div>
836 """)
839 usage = """
840 Usage: gitstats [options] <gitpath> <outputpath>
842 Options:
845 if len(sys.argv) < 3:
846 print usage
847 sys.exit(0)
849 gitpath = sys.argv[1]
850 outputpath = os.path.abspath(sys.argv[2])
851 rundir = os.getcwd()
853 try:
854 os.makedirs(outputpath)
855 except OSError:
856 pass
857 if not os.path.isdir(outputpath):
858 print 'FATAL: Output path is not a directory or does not exist'
859 sys.exit(1)
861 print 'Git path: %s' % gitpath
862 print 'Output path: %s' % outputpath
864 os.chdir(gitpath)
866 print 'Collecting data...'
867 data = GitDataCollector()
868 data.collect(gitpath)
869 print 'Refining data...'
870 data.refine()
872 os.chdir(rundir)
874 print 'Generating report...'
875 report = HTMLReportCreator()
876 report.create(data, outputpath)
878 time_end = time.time()
879 exectime_internal = time_end - time_start
880 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)