License is GPLv2 / GPLv3.
[gitstats.git] / gitstats
blobaf69473db3bd6746e40ca17e2428b068aa3c577b
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2008 Heikki Hokkanen <hoxu@users.sf.net>
3 # GPLv2 / GPLv3
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()
56 # This should be the main function to extract data from the repository.
57 def collect(self, dir):
58 self.dir = dir
59 self.projectname = os.path.basename(os.path.abspath(dir))
62 # Produce any additional statistics from the extracted data.
63 def refine(self):
64 pass
67 # : get a dictionary of author
68 def getAuthorInfo(self, author):
69 return None
71 def getActivityByDayOfWeek(self):
72 return {}
74 def getActivityByHourOfDay(self):
75 return {}
78 # Get a list of authors
79 def getAuthors(self):
80 return []
82 def getFirstCommitDate(self):
83 return datetime.datetime.now()
85 def getLastCommitDate(self):
86 return datetime.datetime.now()
88 def getStampCreated(self):
89 return self.stamp_created
91 def getTags(self):
92 return []
94 def getTotalAuthors(self):
95 return -1
97 def getTotalCommits(self):
98 return -1
100 def getTotalFiles(self):
101 return -1
103 def getTotalLOC(self):
104 return -1
106 class GitDataCollector(DataCollector):
107 def collect(self, dir):
108 DataCollector.collect(self, dir)
110 try:
111 self.total_authors = int(getpipeoutput(['git-log', 'git-shortlog -s', 'wc -l']))
112 except:
113 self.total_authors = 0
114 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
116 self.activity_by_hour_of_day = {} # hour -> commits
117 self.activity_by_day_of_week = {} # day -> commits
118 self.activity_by_month_of_year = {} # month [1-12] -> commits
119 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
121 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
123 # author of the month
124 self.author_of_month = {} # month -> author -> commits
125 self.author_of_year = {} # year -> author -> commits
126 self.commits_by_month = {} # month -> commits
127 self.commits_by_year = {} # year -> commits
128 self.first_commit_stamp = 0
129 self.last_commit_stamp = 0
131 # tags
132 self.tags = {}
133 lines = getpipeoutput(['git-show-ref --tags']).split('\n')
134 for line in lines:
135 if len(line) == 0:
136 continue
137 (hash, tag) = line.split(' ')
139 tag = tag.replace('refs/tags/', '')
140 output = getpipeoutput(['git-log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
141 if len(output) > 0:
142 parts = output.split(' ')
143 stamp = 0
144 try:
145 stamp = int(parts[0])
146 except ValueError:
147 stamp = 0
148 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
150 # Collect revision statistics
151 # Outputs "<stamp> <author>"
152 lines = getpipeoutput(['git-rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
153 for line in lines:
154 # linux-2.6 says "<unknown>" for one line O_o
155 parts = line.split(' ')
156 author = ''
157 try:
158 stamp = int(parts[0])
159 except ValueError:
160 stamp = 0
161 if len(parts) > 1:
162 author = ' '.join(parts[1:])
163 date = datetime.datetime.fromtimestamp(float(stamp))
165 # First and last commit stamp
166 if self.last_commit_stamp == 0:
167 self.last_commit_stamp = stamp
168 self.first_commit_stamp = stamp
170 # activity
171 # hour
172 hour = date.hour
173 if hour in self.activity_by_hour_of_day:
174 self.activity_by_hour_of_day[hour] += 1
175 else:
176 self.activity_by_hour_of_day[hour] = 1
178 # day of week
179 day = date.weekday()
180 if day in self.activity_by_day_of_week:
181 self.activity_by_day_of_week[day] += 1
182 else:
183 self.activity_by_day_of_week[day] = 1
185 # hour of week
186 if day not in self.activity_by_hour_of_week:
187 self.activity_by_hour_of_week[day] = {}
188 if hour not in self.activity_by_hour_of_week[day]:
189 self.activity_by_hour_of_week[day][hour] = 1
190 else:
191 self.activity_by_hour_of_week[day][hour] += 1
193 # month of year
194 month = date.month
195 if month in self.activity_by_month_of_year:
196 self.activity_by_month_of_year[month] += 1
197 else:
198 self.activity_by_month_of_year[month] = 1
200 # author stats
201 if author not in self.authors:
202 self.authors[author] = {}
203 # commits
204 if 'last_commit_stamp' not in self.authors[author]:
205 self.authors[author]['last_commit_stamp'] = stamp
206 self.authors[author]['first_commit_stamp'] = stamp
207 if 'commits' in self.authors[author]:
208 self.authors[author]['commits'] += 1
209 else:
210 self.authors[author]['commits'] = 1
212 # author of the month/year
213 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
214 if yymm in self.author_of_month:
215 if author in self.author_of_month[yymm]:
216 self.author_of_month[yymm][author] += 1
217 else:
218 self.author_of_month[yymm][author] = 1
219 else:
220 self.author_of_month[yymm] = {}
221 self.author_of_month[yymm][author] = 1
222 if yymm in self.commits_by_month:
223 self.commits_by_month[yymm] += 1
224 else:
225 self.commits_by_month[yymm] = 1
227 yy = datetime.datetime.fromtimestamp(stamp).year
228 if yy in self.author_of_year:
229 if author in self.author_of_year[yy]:
230 self.author_of_year[yy][author] += 1
231 else:
232 self.author_of_year[yy][author] = 1
233 else:
234 self.author_of_year[yy] = {}
235 self.author_of_year[yy][author] = 1
236 if yy in self.commits_by_year:
237 self.commits_by_year[yy] += 1
238 else:
239 self.commits_by_year[yy] = 1
241 # TODO Optimize this, it's the worst bottleneck
242 # outputs "<stamp> <files>" for each revision
243 self.files_by_stamp = {} # stamp -> files
244 revlines = getpipeoutput(['git-rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
245 lines = []
246 for revline in revlines:
247 time, rev = revline.split(' ')
248 linecount = int(getpipeoutput(['git-ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
249 lines.append('%d %d' % (int(time), linecount))
251 self.total_commits = len(lines)
252 for line in lines:
253 parts = line.split(' ')
254 if len(parts) != 2:
255 continue
256 (stamp, files) = parts[0:2]
257 try:
258 self.files_by_stamp[int(stamp)] = int(files)
259 except ValueError:
260 print 'Warning: failed to parse line "%s"' % line
262 # extensions
263 self.extensions = {} # extension -> files, lines
264 lines = getpipeoutput(['git-ls-files']).split('\n')
265 self.total_files = len(lines)
266 for line in lines:
267 base = os.path.basename(line)
268 if base.find('.') == -1:
269 ext = ''
270 else:
271 ext = base[(base.rfind('.') + 1):]
273 if ext not in self.extensions:
274 self.extensions[ext] = {'files': 0, 'lines': 0}
276 self.extensions[ext]['files'] += 1
277 try:
278 # Escaping could probably be improved here
279 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
280 except:
281 print 'Warning: Could not count lines for file "%s"' % line
283 # line statistics
284 # outputs:
285 # N files changed, N insertions (+), N deletions(-)
286 # <stamp> <author>
287 self.changes_by_date = {} # stamp -> { files, ins, del }
288 lines = getpipeoutput(['git-log --shortstat --pretty=format:"%at %an"']).split('\n')
289 lines.reverse()
290 files = 0; inserted = 0; deleted = 0; total_lines = 0
291 for line in lines:
292 if len(line) == 0:
293 continue
295 # <stamp> <author>
296 if line.find('files changed,') == -1:
297 pos = line.find(' ')
298 if pos != -1:
299 try:
300 (stamp, author) = (int(line[:pos]), line[pos+1:])
301 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
302 except ValueError:
303 print 'Warning: unexpected line "%s"' % line
304 else:
305 print 'Warning: unexpected line "%s"' % line
306 else:
307 numbers = re.findall('\d+', line)
308 if len(numbers) == 3:
309 (files, inserted, deleted) = map(lambda el : int(el), numbers)
310 total_lines += inserted
311 total_lines -= deleted
312 else:
313 print 'Warning: failed to handle line "%s"' % line
314 (files, inserted, deleted) = (0, 0, 0)
315 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
316 self.total_lines = total_lines
318 def refine(self):
319 # authors
320 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
321 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
322 authors_by_commits.reverse() # most first
323 for i, name in enumerate(authors_by_commits):
324 self.authors[name]['place_by_commits'] = i + 1
326 for name in self.authors.keys():
327 a = self.authors[name]
328 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
329 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
330 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
331 delta = date_last - date_first
332 a['date_first'] = date_first.strftime('%Y-%m-%d')
333 a['date_last'] = date_last.strftime('%Y-%m-%d')
334 a['timedelta'] = delta
336 def getActivityByDayOfWeek(self):
337 return self.activity_by_day_of_week
339 def getActivityByHourOfDay(self):
340 return self.activity_by_hour_of_day
342 def getAuthorInfo(self, author):
343 return self.authors[author]
345 def getAuthors(self):
346 return self.authors.keys()
348 def getFirstCommitDate(self):
349 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
351 def getLastCommitDate(self):
352 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
354 def getTags(self):
355 lines = getpipeoutput(['git-show-ref --tags', 'cut -d/ -f3'])
356 return lines.split('\n')
358 def getTagDate(self, tag):
359 return self.revToDate('tags/' + tag)
361 def getTotalAuthors(self):
362 return self.total_authors
364 def getTotalCommits(self):
365 return self.total_commits
367 def getTotalFiles(self):
368 return self.total_files
370 def getTotalLOC(self):
371 return self.total_lines
373 def revToDate(self, rev):
374 stamp = int(getpipeoutput(['git-log --pretty=format:%%at "%s" -n 1' % rev]))
375 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
377 class ReportCreator:
378 """Creates the actual report based on given data."""
379 def __init__(self):
380 pass
382 def create(self, data, path):
383 self.data = data
384 self.path = path
386 def html_linkify(text):
387 return text.lower().replace(' ', '_')
389 def html_header(level, text):
390 name = html_linkify(text)
391 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
393 class HTMLReportCreator(ReportCreator):
394 def create(self, data, path):
395 ReportCreator.create(self, data, path)
396 self.title = data.projectname
398 # copy the CSS if it does not exist
399 if not os.path.exists(path + '/gitstats.css'):
400 basedir = os.path.dirname(os.path.abspath(__file__))
401 shutil.copyfile(basedir + '/gitstats.css', path + '/gitstats.css')
403 f = open(path + "/index.html", 'w')
404 format = '%Y-%m-%d %H:%m:%S'
405 self.printHeader(f)
407 f.write('<h1>GitStats - %s</h1>' % data.projectname)
409 self.printNav(f)
411 f.write('<dl>');
412 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
413 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
414 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
415 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
416 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
417 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
418 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
419 f.write('</dl>');
421 f.write('</body>\n</html>');
422 f.close()
425 # Activity
426 f = open(path + '/activity.html', 'w')
427 self.printHeader(f)
428 f.write('<h1>Activity</h1>')
429 self.printNav(f)
431 #f.write('<h2>Last 30 days</h2>')
433 #f.write('<h2>Last 12 months</h2>')
435 # Hour of Day
436 f.write(html_header(2, 'Hour of Day'))
437 hour_of_day = data.getActivityByHourOfDay()
438 f.write('<table><tr><th>Hour</th>')
439 for i in range(1, 25):
440 f.write('<th>%d</th>' % i)
441 f.write('</tr>\n<tr><th>Commits</th>')
442 fp = open(path + '/hour_of_day.dat', 'w')
443 for i in range(0, 24):
444 if i in hour_of_day:
445 f.write('<td>%d</td>' % hour_of_day[i])
446 fp.write('%d %d\n' % (i, hour_of_day[i]))
447 else:
448 f.write('<td>0</td>')
449 fp.write('%d 0\n' % i)
450 fp.close()
451 f.write('</tr>\n<tr><th>%</th>')
452 totalcommits = data.getTotalCommits()
453 for i in range(0, 24):
454 if i in hour_of_day:
455 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
456 else:
457 f.write('<td>0.00</td>')
458 f.write('</tr></table>')
459 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
460 fg = open(path + '/hour_of_day.dat', 'w')
461 for i in range(0, 24):
462 if i in hour_of_day:
463 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
464 else:
465 fg.write('%d 0\n' % (i + 1))
466 fg.close()
468 # Day of Week
469 f.write(html_header(2, 'Day of Week'))
470 day_of_week = data.getActivityByDayOfWeek()
471 f.write('<div class="vtable"><table>')
472 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
473 fp = open(path + '/day_of_week.dat', 'w')
474 for d in range(0, 7):
475 commits = 0
476 if d in day_of_week:
477 commits = day_of_week[d]
478 fp.write('%d %d\n' % (d + 1, commits))
479 f.write('<tr>')
480 f.write('<th>%d</th>' % (d + 1))
481 if d in day_of_week:
482 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
483 else:
484 f.write('<td>0</td>')
485 f.write('</tr>')
486 f.write('</table></div>')
487 f.write('<img src="day_of_week.png" alt="Day of Week" />')
488 fp.close()
490 # Hour of Week
491 f.write(html_header(2, 'Hour of Week'))
492 f.write('<table>')
494 f.write('<tr><th>Weekday</th>')
495 for hour in range(0, 24):
496 f.write('<th>%d</th>' % (hour + 1))
497 f.write('</tr>')
499 for weekday in range(0, 7):
500 f.write('<tr><th>%d</th>' % (weekday + 1))
501 for hour in range(0, 24):
502 try:
503 commits = data.activity_by_hour_of_week[weekday][hour]
504 except KeyError:
505 commits = 0
506 if commits != 0:
507 f.write('<td>%d</td>' % commits)
508 else:
509 f.write('<td></td>')
510 f.write('</tr>')
512 f.write('</table>')
514 # Month of Year
515 f.write(html_header(2, 'Month of Year'))
516 f.write('<div class="vtable"><table>')
517 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
518 fp = open (path + '/month_of_year.dat', 'w')
519 for mm in range(1, 13):
520 commits = 0
521 if mm in data.activity_by_month_of_year:
522 commits = data.activity_by_month_of_year[mm]
523 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
524 fp.write('%d %d\n' % (mm, commits))
525 fp.close()
526 f.write('</table></div>')
527 f.write('<img src="month_of_year.png" alt="Month of Year" />')
529 # Commits by year/month
530 f.write(html_header(2, 'Commits by year/month'))
531 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
532 for yymm in reversed(sorted(data.commits_by_month.keys())):
533 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
534 f.write('</table></div>')
535 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
536 fg = open(path + '/commits_by_year_month.dat', 'w')
537 for yymm in sorted(data.commits_by_month.keys()):
538 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
539 fg.close()
541 # Commits by year
542 f.write(html_header(2, 'Commits by Year'))
543 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
544 for yy in reversed(sorted(data.commits_by_year.keys())):
545 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()))
546 f.write('</table></div>')
547 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
548 fg = open(path + '/commits_by_year.dat', 'w')
549 for yy in sorted(data.commits_by_year.keys()):
550 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
551 fg.close()
553 f.write('</body></html>')
554 f.close()
557 # Authors
558 f = open(path + '/authors.html', 'w')
559 self.printHeader(f)
561 f.write('<h1>Authors</h1>')
562 self.printNav(f)
564 # Authors :: List of authors
565 f.write(html_header(2, 'List of Authors'))
567 f.write('<table class="authors">')
568 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>')
569 for author in sorted(data.getAuthors()):
570 info = data.getAuthorInfo(author)
571 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']))
572 f.write('</table>')
574 # Authors :: Author of Month
575 f.write(html_header(2, 'Author of Month'))
576 f.write('<table>')
577 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
578 for yymm in reversed(sorted(data.author_of_month.keys())):
579 authordict = data.author_of_month[yymm]
580 authors = getkeyssortedbyvalues(authordict)
581 authors.reverse()
582 commits = data.author_of_month[yymm][authors[0]]
583 next = ', '.join(authors[1:5])
584 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))
586 f.write('</table>')
588 f.write(html_header(2, 'Author of Year'))
589 f.write('<table><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th>Next top 5</th></tr>')
590 for yy in reversed(sorted(data.author_of_year.keys())):
591 authordict = data.author_of_year[yy]
592 authors = getkeyssortedbyvalues(authordict)
593 authors.reverse()
594 commits = data.author_of_year[yy][authors[0]]
595 next = ', '.join(authors[1:5])
596 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))
597 f.write('</table>')
599 f.write('</body></html>')
600 f.close()
603 # Files
604 f = open(path + '/files.html', 'w')
605 self.printHeader(f)
606 f.write('<h1>Files</h1>')
607 self.printNav(f)
609 f.write('<dl>\n')
610 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
611 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
612 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
613 f.write('</dl>\n')
615 # Files :: File count by date
616 f.write(html_header(2, 'File count by date'))
618 fg = open(path + '/files_by_date.dat', 'w')
619 for stamp in sorted(data.files_by_stamp.keys()):
620 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
621 fg.close()
623 f.write('<img src="files_by_date.png" alt="Files by Date" />')
625 #f.write('<h2>Average file size by date</h2>')
627 # Files :: Extensions
628 f.write(html_header(2, 'Extensions'))
629 f.write('<table><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
630 for ext in sorted(data.extensions.keys()):
631 files = data.extensions[ext]['files']
632 lines = data.extensions[ext]['lines']
633 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))
634 f.write('</table>')
636 f.write('</body></html>')
637 f.close()
640 # Lines
641 f = open(path + '/lines.html', 'w')
642 self.printHeader(f)
643 f.write('<h1>Lines</h1>')
644 self.printNav(f)
646 f.write('<dl>\n')
647 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
648 f.write('</dl>\n')
650 f.write(html_header(2, 'Lines of Code'))
651 f.write('<img src="lines_of_code.png" />')
653 fg = open(path + '/lines_of_code.dat', 'w')
654 for stamp in sorted(data.changes_by_date.keys()):
655 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
656 fg.close()
658 f.write('</body></html>')
659 f.close()
662 # tags.html
663 f = open(path + '/tags.html', 'w')
664 self.printHeader(f)
665 f.write('<h1>Tags</h1>')
666 self.printNav(f)
668 f.write('<dl>')
669 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
670 if len(data.tags) > 0:
671 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
672 f.write('</dl>')
674 f.write('<table>')
675 f.write('<tr><th>Name</th><th>Date</th></tr>')
676 # sort the tags by date desc
677 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
678 for tag in tags_sorted_by_date_desc:
679 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
680 f.write('</table>')
682 f.write('</body></html>')
683 f.close()
685 self.createGraphs(path)
687 def createGraphs(self, path):
688 print 'Generating graphs...'
690 # hour of day
691 f = open(path + '/hour_of_day.plot', 'w')
692 f.write(GNUPLOT_COMMON)
693 f.write(
695 set output 'hour_of_day.png'
696 unset key
697 set xrange [0.5:24.5]
698 set xtics 4
699 set ylabel "Commits"
700 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
701 """)
702 f.close()
704 # day of week
705 f = open(path + '/day_of_week.plot', 'w')
706 f.write(GNUPLOT_COMMON)
707 f.write(
709 set output 'day_of_week.png'
710 unset key
711 set xrange [0.5:7.5]
712 set xtics 1
713 set ylabel "Commits"
714 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
715 """)
716 f.close()
718 # Month of Year
719 f = open(path + '/month_of_year.plot', 'w')
720 f.write(GNUPLOT_COMMON)
721 f.write(
723 set output 'month_of_year.png'
724 unset key
725 set xrange [0.5:12.5]
726 set xtics 1
727 set ylabel "Commits"
728 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
729 """)
730 f.close()
732 # commits_by_year_month
733 f = open(path + '/commits_by_year_month.plot', 'w')
734 f.write(GNUPLOT_COMMON)
735 f.write(
737 set output 'commits_by_year_month.png'
738 unset key
739 set xdata time
740 set timefmt "%Y-%m"
741 set format x "%Y-%m"
742 set xtics rotate by 90 15768000
743 set bmargin 5
744 set ylabel "Commits"
745 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
746 """)
747 f.close()
749 # commits_by_year
750 f = open(path + '/commits_by_year.plot', 'w')
751 f.write(GNUPLOT_COMMON)
752 f.write(
754 set output 'commits_by_year.png'
755 unset key
756 set xtics 1
757 set ylabel "Commits"
758 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
759 """)
760 f.close()
762 # Files by date
763 f = open(path + '/files_by_date.plot', 'w')
764 f.write(GNUPLOT_COMMON)
765 f.write(
767 set output 'files_by_date.png'
768 unset key
769 set xdata time
770 set timefmt "%Y-%m-%d"
771 set format x "%Y-%m-%d"
772 set ylabel "Files"
773 set xtics rotate by 90
774 set bmargin 6
775 plot 'files_by_date.dat' using 1:2 smooth csplines
776 """)
777 f.close()
779 # Lines of Code
780 f = open(path + '/lines_of_code.plot', 'w')
781 f.write(GNUPLOT_COMMON)
782 f.write(
784 set output 'lines_of_code.png'
785 unset key
786 set xdata time
787 set timefmt "%s"
788 set format x "%Y-%m-%d"
789 set ylabel "Lines"
790 set xtics rotate by 90
791 set bmargin 6
792 plot 'lines_of_code.dat' using 1:2 w lines
793 """)
794 f.close()
796 os.chdir(path)
797 files = glob.glob(path + '/*.plot')
798 for f in files:
799 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
800 if len(out) > 0:
801 print out
803 def printHeader(self, f, title = ''):
804 f.write(
805 """<?xml version="1.0" encoding="UTF-8"?>
806 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
807 <html xmlns="http://www.w3.org/1999/xhtml">
808 <head>
809 <title>GitStats - %s</title>
810 <link rel="stylesheet" href="gitstats.css" type="text/css" />
811 <meta name="generator" content="GitStats" />
812 </head>
813 <body>
814 """ % self.title)
816 def printNav(self, f):
817 f.write("""
818 <div class="nav">
819 <ul>
820 <li><a href="index.html">General</a></li>
821 <li><a href="activity.html">Activity</a></li>
822 <li><a href="authors.html">Authors</a></li>
823 <li><a href="files.html">Files</a></li>
824 <li><a href="lines.html">Lines</a></li>
825 <li><a href="tags.html">Tags</a></li>
826 </ul>
827 </div>
828 """)
831 usage = """
832 Usage: gitstats [options] <gitpath> <outputpath>
834 Options:
837 if len(sys.argv) < 3:
838 print usage
839 sys.exit(0)
841 gitpath = sys.argv[1]
842 outputpath = os.path.abspath(sys.argv[2])
843 rundir = os.getcwd()
845 try:
846 os.makedirs(outputpath)
847 except OSError:
848 pass
849 if not os.path.isdir(outputpath):
850 print 'FATAL: Output path is not a directory or does not exist'
851 sys.exit(1)
853 print 'Git path: %s' % gitpath
854 print 'Output path: %s' % outputpath
856 os.chdir(gitpath)
858 print 'Collecting data...'
859 data = GitDataCollector()
860 data.collect(gitpath)
861 print 'Refining data...'
862 data.refine()
864 os.chdir(rundir)
866 print 'Generating report...'
867 report = HTMLReportCreator()
868 report.create(data, outputpath)
870 time_end = time.time()
871 exectime_internal = time_end - time_start
872 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)