Bugfix for files_by_stamp calculation.
[gitstats.git] / gitstats
blob9e505bda71edb3c9b5f131c20b013ef509435914
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 revlines = getpipeoutput(['git-rev-list --pretty=format:"%at %H" HEAD', 'grep -v ^commit']).strip().split('\n')
253 lines = []
254 for revline in revlines:
255 time, rev = revline.split(' ')
256 linecount = int(getpipeoutput(['git-ls-tree -r "%s"' % rev, 'wc -l']).split('\n')[0])
257 lines.append('%d %d' % (int(time), linecount))
259 self.total_commits = len(lines)
260 for line in lines:
261 parts = line.split(' ')
262 if len(parts) != 2:
263 continue
264 (stamp, files) = parts[0:2]
265 try:
266 self.files_by_stamp[int(stamp)] = int(files)
267 except ValueError:
268 print 'Warning: failed to parse line "%s"' % line
270 # extensions
271 self.extensions = {} # extension -> files, lines
272 lines = getpipeoutput(['git-ls-files']).split('\n')
273 self.total_files = len(lines)
274 for line in lines:
275 base = os.path.basename(line)
276 if base.find('.') == -1:
277 ext = ''
278 else:
279 ext = base[(base.rfind('.') + 1):]
281 if ext not in self.extensions:
282 self.extensions[ext] = {'files': 0, 'lines': 0}
284 self.extensions[ext]['files'] += 1
285 try:
286 # Escaping could probably be improved here
287 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
288 except:
289 print 'Warning: Could not count lines for file "%s"' % line
291 # line statistics
292 # outputs:
293 # N files changed, N insertions (+), N deletions(-)
294 # <stamp> <author>
295 self.changes_by_date = {} # stamp -> { files, ins, del }
296 lines = getpipeoutput(['git-log --shortstat --pretty=format:"%at %an"']).split('\n')
297 lines.reverse()
298 files = 0; inserted = 0; deleted = 0; total_lines = 0
299 for line in lines:
300 if len(line) == 0:
301 continue
303 # <stamp> <author>
304 if line.find('files changed,') == -1:
305 pos = line.find(' ')
306 if pos != -1:
307 (stamp, author) = (int(line[:pos]), line[pos+1:])
308 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
309 else:
310 print 'Warning: unexpected line "%s"' % line
311 else:
312 numbers = re.findall('\d+', line)
313 if len(numbers) == 3:
314 (files, inserted, deleted) = map(lambda el : int(el), numbers)
315 total_lines += inserted
316 total_lines -= deleted
317 else:
318 print 'Warning: failed to handle line "%s"' % line
319 (files, inserted, deleted) = (0, 0, 0)
320 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
321 self.total_lines = total_lines
323 def refine(self):
324 # authors
325 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
326 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
327 authors_by_commits.reverse() # most first
328 for i, name in enumerate(authors_by_commits):
329 self.authors[name]['place_by_commits'] = i + 1
331 for name in self.authors.keys():
332 a = self.authors[name]
333 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
334 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
335 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
336 delta = date_last - date_first
337 a['date_first'] = date_first.strftime('%Y-%m-%d')
338 a['date_last'] = date_last.strftime('%Y-%m-%d')
339 a['timedelta'] = delta
341 def getActivityByDayOfWeek(self):
342 return self.activity_by_day_of_week
344 def getActivityByHourOfDay(self):
345 return self.activity_by_hour_of_day
347 def getAuthorInfo(self, author):
348 return self.authors[author]
350 def getAuthors(self):
351 return self.authors.keys()
353 def getFirstCommitDate(self):
354 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
356 def getLastCommitDate(self):
357 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
359 def getTags(self):
360 lines = getpipeoutput(['git-show-ref --tags', 'cut -d/ -f3'])
361 return lines.split('\n')
363 def getTagDate(self, tag):
364 return self.revToDate('tags/' + tag)
366 def getTotalAuthors(self):
367 return self.total_authors
369 def getTotalCommits(self):
370 return self.total_commits
372 def getTotalFiles(self):
373 return self.total_files
375 def getTotalLOC(self):
376 return self.total_lines
378 def revToDate(self, rev):
379 stamp = int(getpipeoutput(['git-log --pretty=format:%%at "%s" -n 1' % rev]))
380 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
382 class ReportCreator:
383 """Creates the actual report based on given data."""
384 def __init__(self):
385 pass
387 def create(self, data, path):
388 self.data = data
389 self.path = path
391 def html_linkify(text):
392 return text.lower().replace(' ', '_')
394 def html_header(level, text):
395 name = html_linkify(text)
396 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
398 class HTMLReportCreator(ReportCreator):
399 def create(self, data, path):
400 ReportCreator.create(self, data, path)
401 self.title = data.projectname
403 # TODO copy the CSS if it does not exist
404 if not os.path.exists(path + '/gitstats.css'):
405 basedir = os.path.dirname(os.path.abspath(__file__))
406 shutil.copyfile(basedir + '/gitstats.css', path + '/gitstats.css')
407 pass
409 f = open(path + "/index.html", 'w')
410 format = '%Y-%m-%d %H:%m:%S'
411 self.printHeader(f)
413 f.write('<h1>GitStats - %s</h1>' % data.projectname)
415 self.printNav(f)
417 f.write('<dl>');
418 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
419 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
420 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
421 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
422 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
423 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
424 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
425 f.write('</dl>');
427 f.write('</body>\n</html>');
428 f.close()
431 # Activity
432 f = open(path + '/activity.html', 'w')
433 self.printHeader(f)
434 f.write('<h1>Activity</h1>')
435 self.printNav(f)
437 #f.write('<h2>Last 30 days</h2>')
439 #f.write('<h2>Last 12 months</h2>')
441 # Hour of Day
442 f.write(html_header(2, 'Hour of Day'))
443 hour_of_day = data.getActivityByHourOfDay()
444 f.write('<table><tr><th>Hour</th>')
445 for i in range(1, 25):
446 f.write('<th>%d</th>' % i)
447 f.write('</tr>\n<tr><th>Commits</th>')
448 fp = open(path + '/hour_of_day.dat', 'w')
449 for i in range(0, 24):
450 if i in hour_of_day:
451 f.write('<td>%d</td>' % hour_of_day[i])
452 fp.write('%d %d\n' % (i, hour_of_day[i]))
453 else:
454 f.write('<td>0</td>')
455 fp.write('%d 0\n' % i)
456 fp.close()
457 f.write('</tr>\n<tr><th>%</th>')
458 totalcommits = data.getTotalCommits()
459 for i in range(0, 24):
460 if i in hour_of_day:
461 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
462 else:
463 f.write('<td>0.00</td>')
464 f.write('</tr></table>')
465 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
466 fg = open(path + '/hour_of_day.dat', 'w')
467 for i in range(0, 24):
468 if i in hour_of_day:
469 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
470 else:
471 fg.write('%d 0\n' % (i + 1))
472 fg.close()
474 # Day of Week
475 f.write(html_header(2, 'Day of Week'))
476 day_of_week = data.getActivityByDayOfWeek()
477 f.write('<div class="vtable"><table>')
478 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
479 fp = open(path + '/day_of_week.dat', 'w')
480 for d in range(0, 7):
481 commits = 0
482 if d in day_of_week:
483 commits = day_of_week[d]
484 fp.write('%d %d\n' % (d + 1, commits))
485 f.write('<tr>')
486 f.write('<th>%d</th>' % (d + 1))
487 if d in day_of_week:
488 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
489 else:
490 f.write('<td>0</td>')
491 f.write('</tr>')
492 f.write('</table></div>')
493 f.write('<img src="day_of_week.png" alt="Day of Week" />')
494 fp.close()
496 # Hour of Week
497 f.write(html_header(2, 'Hour of Week'))
498 f.write('<table>')
500 f.write('<tr><th>Weekday</th>')
501 for hour in range(0, 24):
502 f.write('<th>%d</th>' % (hour + 1))
503 f.write('</tr>')
505 for weekday in range(0, 7):
506 f.write('<tr><th>%d</th>' % (weekday + 1))
507 for hour in range(0, 24):
508 try:
509 commits = data.activity_by_hour_of_week[weekday][hour]
510 except KeyError:
511 commits = 0
512 if commits != 0:
513 f.write('<td>%d</td>' % commits)
514 else:
515 f.write('<td></td>')
516 f.write('</tr>')
518 f.write('</table>')
520 # Month of Year
521 f.write(html_header(2, 'Month of Year'))
522 f.write('<div class="vtable"><table>')
523 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
524 fp = open (path + '/month_of_year.dat', 'w')
525 for mm in range(1, 13):
526 commits = 0
527 if mm in data.activity_by_month_of_year:
528 commits = data.activity_by_month_of_year[mm]
529 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
530 fp.write('%d %d\n' % (mm, commits))
531 fp.close()
532 f.write('</table></div>')
533 f.write('<img src="month_of_year.png" alt="Month of Year" />')
535 # Commits by year/month
536 f.write(html_header(2, 'Commits by year/month'))
537 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
538 for yymm in reversed(sorted(data.commits_by_month.keys())):
539 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
540 f.write('</table></div>')
541 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
542 fg = open(path + '/commits_by_year_month.dat', 'w')
543 for yymm in sorted(data.commits_by_month.keys()):
544 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
545 fg.close()
547 # Commits by year
548 f.write(html_header(2, 'Commits by Year'))
549 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
550 for yy in reversed(sorted(data.commits_by_year.keys())):
551 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()))
552 f.write('</table></div>')
553 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
554 fg = open(path + '/commits_by_year.dat', 'w')
555 for yy in sorted(data.commits_by_year.keys()):
556 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
557 fg.close()
559 f.write('</body></html>')
560 f.close()
563 # Authors
564 f = open(path + '/authors.html', 'w')
565 self.printHeader(f)
567 f.write('<h1>Authors</h1>')
568 self.printNav(f)
570 # Authors :: List of authors
571 f.write(html_header(2, 'List of Authors'))
573 f.write('<table class="authors">')
574 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>')
575 for author in sorted(data.getAuthors()):
576 info = data.getAuthorInfo(author)
577 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']))
578 f.write('</table>')
580 # Authors :: Author of Month
581 f.write(html_header(2, 'Author of Month'))
582 f.write('<table>')
583 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
584 for yymm in reversed(sorted(data.author_of_month.keys())):
585 authordict = data.author_of_month[yymm]
586 authors = getkeyssortedbyvalues(authordict)
587 authors.reverse()
588 commits = data.author_of_month[yymm][authors[0]]
589 next = ', '.join(authors[1:5])
590 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))
592 f.write('</table>')
594 f.write(html_header(2, 'Author of Year'))
595 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
596 for yy in reversed(sorted(data.author_of_year.keys())):
597 authordict = data.author_of_year[yy]
598 authors = getkeyssortedbyvalues(authordict)
599 authors.reverse()
600 commits = data.author_of_year[yy][authors[0]]
601 next = ', '.join(authors[1:5])
602 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))
603 f.write('</table>')
605 f.write('</body></html>')
606 f.close()
609 # Files
610 f = open(path + '/files.html', 'w')
611 self.printHeader(f)
612 f.write('<h1>Files</h1>')
613 self.printNav(f)
615 f.write('<dl>\n')
616 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
617 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
618 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
619 f.write('</dl>\n')
621 # Files :: File count by date
622 f.write(html_header(2, 'File count by date'))
624 fg = open(path + '/files_by_date.dat', 'w')
625 for stamp in sorted(data.files_by_stamp.keys()):
626 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
627 fg.close()
629 f.write('<img src="files_by_date.png" alt="Files by Date" />')
631 #f.write('<h2>Average file size by date</h2>')
633 # Files :: Extensions
634 f.write(html_header(2, 'Extensions'))
635 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
636 for ext in sorted(data.extensions.keys()):
637 files = data.extensions[ext]['files']
638 lines = data.extensions[ext]['lines']
639 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))
640 f.write('</table>')
642 f.write('</body></html>')
643 f.close()
646 # Lines
647 f = open(path + '/lines.html', 'w')
648 self.printHeader(f)
649 f.write('<h1>Lines</h1>')
650 self.printNav(f)
652 f.write('<dl>\n')
653 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
654 f.write('</dl>\n')
656 f.write(html_header(2, 'Lines of Code'))
657 f.write('<img src="lines_of_code.png" />')
659 fg = open(path + '/lines_of_code.dat', 'w')
660 for stamp in sorted(data.changes_by_date.keys()):
661 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
662 fg.close()
664 f.write('</body></html>')
665 f.close()
668 # tags.html
669 f = open(path + '/tags.html', 'w')
670 self.printHeader(f)
671 f.write('<h1>Tags</h1>')
672 self.printNav(f)
674 f.write('<dl>')
675 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
676 if len(data.tags) > 0:
677 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
678 f.write('</dl>')
680 f.write('<table>')
681 f.write('<tr><th>Name</th><th>Date</th></tr>')
682 # sort the tags by date desc
683 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
684 for tag in tags_sorted_by_date_desc:
685 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
686 f.write('</table>')
688 f.write('</body></html>')
689 f.close()
691 self.createGraphs(path)
692 pass
694 def createGraphs(self, path):
695 print 'Generating graphs...'
697 # hour of day
698 f = open(path + '/hour_of_day.plot', 'w')
699 f.write(GNUPLOT_COMMON)
700 f.write(
702 set output 'hour_of_day.png'
703 unset key
704 set xrange [0.5:24.5]
705 set xtics 4
706 set ylabel "Commits"
707 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
708 """)
709 f.close()
711 # day of week
712 f = open(path + '/day_of_week.plot', 'w')
713 f.write(GNUPLOT_COMMON)
714 f.write(
716 set output 'day_of_week.png'
717 unset key
718 set xrange [0.5:7.5]
719 set xtics 1
720 set ylabel "Commits"
721 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
722 """)
723 f.close()
725 # Month of Year
726 f = open(path + '/month_of_year.plot', 'w')
727 f.write(GNUPLOT_COMMON)
728 f.write(
730 set output 'month_of_year.png'
731 unset key
732 set xrange [0.5:12.5]
733 set xtics 1
734 set ylabel "Commits"
735 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
736 """)
737 f.close()
739 # commits_by_year_month
740 f = open(path + '/commits_by_year_month.plot', 'w')
741 f.write(GNUPLOT_COMMON)
742 f.write(
744 set output 'commits_by_year_month.png'
745 unset key
746 set xdata time
747 set timefmt "%Y-%m"
748 set format x "%Y-%m"
749 set xtics rotate by 90 15768000
750 set bmargin 5
751 set ylabel "Commits"
752 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
753 """)
754 f.close()
756 # commits_by_year
757 f = open(path + '/commits_by_year.plot', 'w')
758 f.write(GNUPLOT_COMMON)
759 f.write(
761 set output 'commits_by_year.png'
762 unset key
763 set xtics 1
764 set ylabel "Commits"
765 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
766 """)
767 f.close()
769 # Files by date
770 f = open(path + '/files_by_date.plot', 'w')
771 f.write(GNUPLOT_COMMON)
772 f.write(
774 set output 'files_by_date.png'
775 unset key
776 set xdata time
777 set timefmt "%Y-%m-%d"
778 set format x "%Y-%m-%d"
779 set ylabel "Files"
780 set xtics rotate by 90
781 set bmargin 6
782 plot 'files_by_date.dat' using 1:2 smooth csplines
783 """)
784 f.close()
786 # Lines of Code
787 f = open(path + '/lines_of_code.plot', 'w')
788 f.write(GNUPLOT_COMMON)
789 f.write(
791 set output 'lines_of_code.png'
792 unset key
793 set xdata time
794 set timefmt "%s"
795 set format x "%Y-%m-%d"
796 set ylabel "Lines"
797 set xtics rotate by 90
798 set bmargin 6
799 plot 'lines_of_code.dat' using 1:2 w lines
800 """)
801 f.close()
803 os.chdir(path)
804 files = glob.glob(path + '/*.plot')
805 for f in files:
806 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
807 if len(out) > 0:
808 print out
810 def printHeader(self, f, title = ''):
811 f.write(
812 """<?xml version="1.0" encoding="UTF-8"?>
813 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
814 <html xmlns="http://www.w3.org/1999/xhtml">
815 <head>
816 <title>GitStats - %s</title>
817 <link rel="stylesheet" href="gitstats.css" type="text/css" />
818 <meta name="generator" content="GitStats" />
819 </head>
820 <body>
821 """ % self.title)
823 def printNav(self, f):
824 f.write("""
825 <div class="nav">
826 <ul>
827 <li><a href="index.html">General</a></li>
828 <li><a href="activity.html">Activity</a></li>
829 <li><a href="authors.html">Authors</a></li>
830 <li><a href="files.html">Files</a></li>
831 <li><a href="lines.html">Lines</a></li>
832 <li><a href="tags.html">Tags</a></li>
833 </ul>
834 </div>
835 """)
838 usage = """
839 Usage: gitstats [options] <gitpath> <outputpath>
841 Options:
844 if len(sys.argv) < 3:
845 print usage
846 sys.exit(0)
848 gitpath = sys.argv[1]
849 outputpath = os.path.abspath(sys.argv[2])
850 rundir = os.getcwd()
852 try:
853 os.makedirs(outputpath)
854 except OSError:
855 pass
856 if not os.path.isdir(outputpath):
857 print 'FATAL: Output path is not a directory or does not exist'
858 sys.exit(1)
860 print 'Git path: %s' % gitpath
861 print 'Output path: %s' % outputpath
863 os.chdir(gitpath)
865 print 'Collecting data...'
866 data = GitDataCollector()
867 data.collect(gitpath)
868 print 'Refining data...'
869 data.refine()
871 os.chdir(rundir)
873 print 'Generating report...'
874 report = HTMLReportCreator()
875 report.create(data, outputpath)
877 time_end = time.time()
878 exectime_internal = time_end - time_start
879 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)