Save cache to output directory, not git repository.
[gitstats.git] / gitstats
blob5a977410fb7a550deeee05a5047d17458bff7d48
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 pickle
9 import re
10 import shutil
11 import sys
12 import time
13 import zlib
15 GNUPLOT_COMMON = 'set terminal png transparent\nset size 0.5,0.5\n'
16 MAX_EXT_LENGTH = 10 # maximum file extension length
18 exectime_internal = 0.0
19 exectime_external = 0.0
20 time_start = time.time()
22 # By default, gnuplot is searched from path, but can be overridden with the
23 # environment variable "GNUPLOT"
24 gnuplot_cmd = 'gnuplot'
25 if 'GNUPLOT' in os.environ:
26 gnuplot_cmd = os.environ['GNUPLOT']
28 def getpipeoutput(cmds, quiet = False):
29 global exectime_external
30 start = time.time()
31 if not quiet:
32 print '>> ' + ' | '.join(cmds),
33 sys.stdout.flush()
34 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
35 p = p0
36 for x in cmds[1:]:
37 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
38 p0 = p
39 output = p.communicate()[0]
40 end = time.time()
41 if not quiet:
42 print '\r[%.5f] >> %s' % (end - start, ' | '.join(cmds))
43 exectime_external += (end - start)
44 return output.rstrip('\n')
46 def getkeyssortedbyvalues(dict):
47 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
49 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
50 def getkeyssortedbyvaluekey(d, key):
51 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
53 class DataCollector:
54 """Manages data collection from a revision control repository."""
55 def __init__(self):
56 self.stamp_created = time.time()
57 self.cache = {}
60 # This should be the main function to extract data from the repository.
61 def collect(self, dir):
62 self.dir = dir
63 self.projectname = os.path.basename(os.path.abspath(dir))
66 # Load cacheable data
67 def loadCache(self, cachefile):
68 if not os.path.exists(cachefile):
69 return
70 print 'Loading cache...'
71 f = open(cachefile)
72 try:
73 self.cache = pickle.loads(zlib.decompress(f.read()))
74 except:
75 # temporary hack to upgrade non-compressed caches
76 f.seek(0)
77 self.cache = pickle.load(f)
78 f.close()
81 # Produce any additional statistics from the extracted data.
82 def refine(self):
83 pass
86 # : get a dictionary of author
87 def getAuthorInfo(self, author):
88 return None
90 def getActivityByDayOfWeek(self):
91 return {}
93 def getActivityByHourOfDay(self):
94 return {}
97 # Get a list of authors
98 def getAuthors(self):
99 return []
101 def getFirstCommitDate(self):
102 return datetime.datetime.now()
104 def getLastCommitDate(self):
105 return datetime.datetime.now()
107 def getStampCreated(self):
108 return self.stamp_created
110 def getTags(self):
111 return []
113 def getTotalAuthors(self):
114 return -1
116 def getTotalCommits(self):
117 return -1
119 def getTotalFiles(self):
120 return -1
122 def getTotalLOC(self):
123 return -1
126 # Save cacheable data
127 def saveCache(self, filename):
128 print 'Saving cache...'
129 f = open(cachefile, 'w')
130 #pickle.dump(self.cache, f)
131 data = zlib.compress(pickle.dumps(self.cache))
132 f.write(data)
133 f.close()
135 class GitDataCollector(DataCollector):
136 def collect(self, dir):
137 DataCollector.collect(self, dir)
139 try:
140 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
141 except:
142 self.total_authors = 0
143 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
145 self.activity_by_hour_of_day = {} # hour -> commits
146 self.activity_by_day_of_week = {} # day -> commits
147 self.activity_by_month_of_year = {} # month [1-12] -> commits
148 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
150 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
152 # author of the month
153 self.author_of_month = {} # month -> author -> commits
154 self.author_of_year = {} # year -> author -> commits
155 self.commits_by_month = {} # month -> commits
156 self.commits_by_year = {} # year -> commits
157 self.first_commit_stamp = 0
158 self.last_commit_stamp = 0
160 # tags
161 self.tags = {}
162 lines = getpipeoutput(['git show-ref --tags']).split('\n')
163 for line in lines:
164 if len(line) == 0:
165 continue
166 (hash, tag) = line.split(' ')
168 tag = tag.replace('refs/tags/', '')
169 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
170 if len(output) > 0:
171 parts = output.split(' ')
172 stamp = 0
173 try:
174 stamp = int(parts[0])
175 except ValueError:
176 stamp = 0
177 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
179 # Collect revision statistics
180 # Outputs "<stamp> <author>"
181 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
182 for line in lines:
183 # linux-2.6 says "<unknown>" for one line O_o
184 parts = line.split(' ')
185 author = ''
186 try:
187 stamp = int(parts[0])
188 except ValueError:
189 stamp = 0
190 if len(parts) > 1:
191 author = ' '.join(parts[1:])
192 date = datetime.datetime.fromtimestamp(float(stamp))
194 # First and last commit stamp
195 if self.last_commit_stamp == 0:
196 self.last_commit_stamp = stamp
197 self.first_commit_stamp = stamp
199 # activity
200 # hour
201 hour = date.hour
202 if hour in self.activity_by_hour_of_day:
203 self.activity_by_hour_of_day[hour] += 1
204 else:
205 self.activity_by_hour_of_day[hour] = 1
207 # day of week
208 day = date.weekday()
209 if day in self.activity_by_day_of_week:
210 self.activity_by_day_of_week[day] += 1
211 else:
212 self.activity_by_day_of_week[day] = 1
214 # hour of week
215 if day not in self.activity_by_hour_of_week:
216 self.activity_by_hour_of_week[day] = {}
217 if hour not in self.activity_by_hour_of_week[day]:
218 self.activity_by_hour_of_week[day][hour] = 1
219 else:
220 self.activity_by_hour_of_week[day][hour] += 1
222 # month of year
223 month = date.month
224 if month in self.activity_by_month_of_year:
225 self.activity_by_month_of_year[month] += 1
226 else:
227 self.activity_by_month_of_year[month] = 1
229 # author stats
230 if author not in self.authors:
231 self.authors[author] = {}
232 # commits
233 if 'last_commit_stamp' not in self.authors[author]:
234 self.authors[author]['last_commit_stamp'] = stamp
235 self.authors[author]['first_commit_stamp'] = stamp
236 if 'commits' in self.authors[author]:
237 self.authors[author]['commits'] += 1
238 else:
239 self.authors[author]['commits'] = 1
241 # author of the month/year
242 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
243 if yymm in self.author_of_month:
244 if author in self.author_of_month[yymm]:
245 self.author_of_month[yymm][author] += 1
246 else:
247 self.author_of_month[yymm][author] = 1
248 else:
249 self.author_of_month[yymm] = {}
250 self.author_of_month[yymm][author] = 1
251 if yymm in self.commits_by_month:
252 self.commits_by_month[yymm] += 1
253 else:
254 self.commits_by_month[yymm] = 1
256 yy = datetime.datetime.fromtimestamp(stamp).year
257 if yy in self.author_of_year:
258 if author in self.author_of_year[yy]:
259 self.author_of_year[yy][author] += 1
260 else:
261 self.author_of_year[yy][author] = 1
262 else:
263 self.author_of_year[yy] = {}
264 self.author_of_year[yy][author] = 1
265 if yy in self.commits_by_year:
266 self.commits_by_year[yy] += 1
267 else:
268 self.commits_by_year[yy] = 1
270 # TODO Optimize this, it's the worst bottleneck
271 # outputs "<stamp> <files>" for each revision
272 self.files_by_stamp = {} # stamp -> files
273 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
274 lines = []
275 for revline in revlines:
276 time, rev = revline.split(' ')
277 #linecount = int(getpipeoutput(['git-ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
278 linecount = self.getFilesInCommit(rev)
279 lines.append('%d %d' % (int(time), linecount))
281 self.total_commits = len(lines)
282 for line in lines:
283 parts = line.split(' ')
284 if len(parts) != 2:
285 continue
286 (stamp, files) = parts[0:2]
287 try:
288 self.files_by_stamp[int(stamp)] = int(files)
289 except ValueError:
290 print 'Warning: failed to parse line "%s"' % line
292 # extensions
293 self.extensions = {} # extension -> files, lines
294 lines = getpipeoutput(['git ls-files']).split('\n')
295 self.total_files = len(lines)
296 for line in lines:
297 base = os.path.basename(line)
298 # Ignore extensionless (including .hidden files)
299 if base.find('.') == -1 or base.rfind('.') == 0:
300 ext = ''
301 else:
302 ext = base[(base.rfind('.') + 1):]
303 if len(ext) > MAX_EXT_LENGTH:
304 ext = ''
306 if ext not in self.extensions:
307 self.extensions[ext] = {'files': 0, 'lines': 0}
309 self.extensions[ext]['files'] += 1
310 try:
311 # Escaping could probably be improved here
312 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
313 except:
314 print 'Warning: Could not count lines for file "%s"' % line
316 # line statistics
317 # outputs:
318 # N files changed, N insertions (+), N deletions(-)
319 # <stamp> <author>
320 self.changes_by_date = {} # stamp -> { files, ins, del }
321 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
322 lines.reverse()
323 files = 0; inserted = 0; deleted = 0; total_lines = 0
324 for line in lines:
325 if len(line) == 0:
326 continue
328 # <stamp> <author>
329 if line.find('files changed,') == -1:
330 pos = line.find(' ')
331 if pos != -1:
332 try:
333 (stamp, author) = (int(line[:pos]), line[pos+1:])
334 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
335 except ValueError:
336 print 'Warning: unexpected line "%s"' % line
337 else:
338 print 'Warning: unexpected line "%s"' % line
339 else:
340 numbers = re.findall('\d+', line)
341 if len(numbers) == 3:
342 (files, inserted, deleted) = map(lambda el : int(el), numbers)
343 total_lines += inserted
344 total_lines -= deleted
345 else:
346 print 'Warning: failed to handle line "%s"' % line
347 (files, inserted, deleted) = (0, 0, 0)
348 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
349 self.total_lines = total_lines
351 def refine(self):
352 # authors
353 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
354 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
355 authors_by_commits.reverse() # most first
356 for i, name in enumerate(authors_by_commits):
357 self.authors[name]['place_by_commits'] = i + 1
359 for name in self.authors.keys():
360 a = self.authors[name]
361 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
362 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
363 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
364 delta = date_last - date_first
365 a['date_first'] = date_first.strftime('%Y-%m-%d')
366 a['date_last'] = date_last.strftime('%Y-%m-%d')
367 a['timedelta'] = delta
369 def getActivityByDayOfWeek(self):
370 return self.activity_by_day_of_week
372 def getActivityByHourOfDay(self):
373 return self.activity_by_hour_of_day
375 def getAuthorInfo(self, author):
376 return self.authors[author]
378 def getAuthors(self):
379 return self.authors.keys()
381 def getFilesInCommit(self, rev):
382 try:
383 res = self.cache['files_in_tree'][rev]
384 except:
385 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
386 if 'files_in_tree' not in self.cache:
387 self.cache['files_in_tree'] = {}
388 self.cache['files_in_tree'][rev] = res
390 return res
392 def getFirstCommitDate(self):
393 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
395 def getLastCommitDate(self):
396 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
398 def getTags(self):
399 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
400 return lines.split('\n')
402 def getTagDate(self, tag):
403 return self.revToDate('tags/' + tag)
405 def getTotalAuthors(self):
406 return self.total_authors
408 def getTotalCommits(self):
409 return self.total_commits
411 def getTotalFiles(self):
412 return self.total_files
414 def getTotalLOC(self):
415 return self.total_lines
417 def revToDate(self, rev):
418 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
419 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
421 class ReportCreator:
422 """Creates the actual report based on given data."""
423 def __init__(self):
424 pass
426 def create(self, data, path):
427 self.data = data
428 self.path = path
430 def html_linkify(text):
431 return text.lower().replace(' ', '_')
433 def html_header(level, text):
434 name = html_linkify(text)
435 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
437 class HTMLReportCreator(ReportCreator):
438 def create(self, data, path):
439 ReportCreator.create(self, data, path)
440 self.title = data.projectname
442 # copy static files if they do not exist
443 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
444 basedir = os.path.dirname(os.path.abspath(__file__))
445 shutil.copyfile(basedir + '/' + file, path + '/' + file)
447 f = open(path + "/index.html", 'w')
448 format = '%Y-%m-%d %H:%m:%S'
449 self.printHeader(f)
451 f.write('<h1>GitStats - %s</h1>' % data.projectname)
453 self.printNav(f)
455 f.write('<dl>');
456 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
457 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
458 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
459 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
460 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
461 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
462 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
463 f.write('</dl>');
465 f.write('</body>\n</html>');
466 f.close()
469 # Activity
470 f = open(path + '/activity.html', 'w')
471 self.printHeader(f)
472 f.write('<h1>Activity</h1>')
473 self.printNav(f)
475 #f.write('<h2>Last 30 days</h2>')
477 #f.write('<h2>Last 12 months</h2>')
479 # Hour of Day
480 f.write(html_header(2, 'Hour of Day'))
481 hour_of_day = data.getActivityByHourOfDay()
482 f.write('<table><tr><th>Hour</th>')
483 for i in range(1, 25):
484 f.write('<th>%d</th>' % i)
485 f.write('</tr>\n<tr><th>Commits</th>')
486 fp = open(path + '/hour_of_day.dat', 'w')
487 for i in range(0, 24):
488 if i in hour_of_day:
489 f.write('<td>%d</td>' % hour_of_day[i])
490 fp.write('%d %d\n' % (i, hour_of_day[i]))
491 else:
492 f.write('<td>0</td>')
493 fp.write('%d 0\n' % i)
494 fp.close()
495 f.write('</tr>\n<tr><th>%</th>')
496 totalcommits = data.getTotalCommits()
497 for i in range(0, 24):
498 if i in hour_of_day:
499 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
500 else:
501 f.write('<td>0.00</td>')
502 f.write('</tr></table>')
503 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
504 fg = open(path + '/hour_of_day.dat', 'w')
505 for i in range(0, 24):
506 if i in hour_of_day:
507 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
508 else:
509 fg.write('%d 0\n' % (i + 1))
510 fg.close()
512 # Day of Week
513 f.write(html_header(2, 'Day of Week'))
514 day_of_week = data.getActivityByDayOfWeek()
515 f.write('<div class="vtable"><table>')
516 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
517 fp = open(path + '/day_of_week.dat', 'w')
518 for d in range(0, 7):
519 commits = 0
520 if d in day_of_week:
521 commits = day_of_week[d]
522 fp.write('%d %d\n' % (d + 1, commits))
523 f.write('<tr>')
524 f.write('<th>%d</th>' % (d + 1))
525 if d in day_of_week:
526 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
527 else:
528 f.write('<td>0</td>')
529 f.write('</tr>')
530 f.write('</table></div>')
531 f.write('<img src="day_of_week.png" alt="Day of Week" />')
532 fp.close()
534 # Hour of Week
535 f.write(html_header(2, 'Hour of Week'))
536 f.write('<table>')
538 f.write('<tr><th>Weekday</th>')
539 for hour in range(0, 24):
540 f.write('<th>%d</th>' % (hour + 1))
541 f.write('</tr>')
543 for weekday in range(0, 7):
544 f.write('<tr><th>%d</th>' % (weekday + 1))
545 for hour in range(0, 24):
546 try:
547 commits = data.activity_by_hour_of_week[weekday][hour]
548 except KeyError:
549 commits = 0
550 if commits != 0:
551 f.write('<td>%d</td>' % commits)
552 else:
553 f.write('<td></td>')
554 f.write('</tr>')
556 f.write('</table>')
558 # Month of Year
559 f.write(html_header(2, 'Month of Year'))
560 f.write('<div class="vtable"><table>')
561 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
562 fp = open (path + '/month_of_year.dat', 'w')
563 for mm in range(1, 13):
564 commits = 0
565 if mm in data.activity_by_month_of_year:
566 commits = data.activity_by_month_of_year[mm]
567 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
568 fp.write('%d %d\n' % (mm, commits))
569 fp.close()
570 f.write('</table></div>')
571 f.write('<img src="month_of_year.png" alt="Month of Year" />')
573 # Commits by year/month
574 f.write(html_header(2, 'Commits by year/month'))
575 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
576 for yymm in reversed(sorted(data.commits_by_month.keys())):
577 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
578 f.write('</table></div>')
579 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
580 fg = open(path + '/commits_by_year_month.dat', 'w')
581 for yymm in sorted(data.commits_by_month.keys()):
582 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
583 fg.close()
585 # Commits by year
586 f.write(html_header(2, 'Commits by Year'))
587 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
588 for yy in reversed(sorted(data.commits_by_year.keys())):
589 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()))
590 f.write('</table></div>')
591 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
592 fg = open(path + '/commits_by_year.dat', 'w')
593 for yy in sorted(data.commits_by_year.keys()):
594 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
595 fg.close()
597 f.write('</body></html>')
598 f.close()
601 # Authors
602 f = open(path + '/authors.html', 'w')
603 self.printHeader(f)
605 f.write('<h1>Authors</h1>')
606 self.printNav(f)
608 # Authors :: List of authors
609 f.write(html_header(2, 'List of Authors'))
611 f.write('<table class="authors sortable" id="authors">')
612 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th class="unsortable">Age</th><th># by commits</th></tr>')
613 for author in sorted(data.getAuthors()):
614 info = data.getAuthorInfo(author)
615 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']))
616 f.write('</table>')
618 # Authors :: Author of Month
619 f.write(html_header(2, 'Author of Month'))
620 f.write('<table class="sortable" id="aom">')
621 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
622 for yymm in reversed(sorted(data.author_of_month.keys())):
623 authordict = data.author_of_month[yymm]
624 authors = getkeyssortedbyvalues(authordict)
625 authors.reverse()
626 commits = data.author_of_month[yymm][authors[0]]
627 next = ', '.join(authors[1:5])
628 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))
630 f.write('</table>')
632 f.write(html_header(2, 'Author of Year'))
633 f.write('<table class="sortable" id="aoy"><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
634 for yy in reversed(sorted(data.author_of_year.keys())):
635 authordict = data.author_of_year[yy]
636 authors = getkeyssortedbyvalues(authordict)
637 authors.reverse()
638 commits = data.author_of_year[yy][authors[0]]
639 next = ', '.join(authors[1:5])
640 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))
641 f.write('</table>')
643 f.write('</body></html>')
644 f.close()
647 # Files
648 f = open(path + '/files.html', 'w')
649 self.printHeader(f)
650 f.write('<h1>Files</h1>')
651 self.printNav(f)
653 f.write('<dl>\n')
654 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
655 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
656 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
657 f.write('</dl>\n')
659 # Files :: File count by date
660 f.write(html_header(2, 'File count by date'))
662 fg = open(path + '/files_by_date.dat', 'w')
663 for stamp in sorted(data.files_by_stamp.keys()):
664 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
665 fg.close()
667 f.write('<img src="files_by_date.png" alt="Files by Date" />')
669 #f.write('<h2>Average file size by date</h2>')
671 # Files :: Extensions
672 f.write(html_header(2, 'Extensions'))
673 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
674 for ext in sorted(data.extensions.keys()):
675 files = data.extensions[ext]['files']
676 lines = data.extensions[ext]['lines']
677 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))
678 f.write('</table>')
680 f.write('</body></html>')
681 f.close()
684 # Lines
685 f = open(path + '/lines.html', 'w')
686 self.printHeader(f)
687 f.write('<h1>Lines</h1>')
688 self.printNav(f)
690 f.write('<dl>\n')
691 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
692 f.write('</dl>\n')
694 f.write(html_header(2, 'Lines of Code'))
695 f.write('<img src="lines_of_code.png" />')
697 fg = open(path + '/lines_of_code.dat', 'w')
698 for stamp in sorted(data.changes_by_date.keys()):
699 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
700 fg.close()
702 f.write('</body></html>')
703 f.close()
706 # tags.html
707 f = open(path + '/tags.html', 'w')
708 self.printHeader(f)
709 f.write('<h1>Tags</h1>')
710 self.printNav(f)
712 f.write('<dl>')
713 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
714 if len(data.tags) > 0:
715 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
716 f.write('</dl>')
718 f.write('<table>')
719 f.write('<tr><th>Name</th><th>Date</th></tr>')
720 # sort the tags by date desc
721 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
722 for tag in tags_sorted_by_date_desc:
723 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
724 f.write('</table>')
726 f.write('</body></html>')
727 f.close()
729 self.createGraphs(path)
731 def createGraphs(self, path):
732 print 'Generating graphs...'
734 # hour of day
735 f = open(path + '/hour_of_day.plot', 'w')
736 f.write(GNUPLOT_COMMON)
737 f.write(
739 set output 'hour_of_day.png'
740 unset key
741 set xrange [0.5:24.5]
742 set xtics 4
743 set ylabel "Commits"
744 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
745 """)
746 f.close()
748 # day of week
749 f = open(path + '/day_of_week.plot', 'w')
750 f.write(GNUPLOT_COMMON)
751 f.write(
753 set output 'day_of_week.png'
754 unset key
755 set xrange [0.5:7.5]
756 set xtics 1
757 set ylabel "Commits"
758 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
759 """)
760 f.close()
762 # Month of Year
763 f = open(path + '/month_of_year.plot', 'w')
764 f.write(GNUPLOT_COMMON)
765 f.write(
767 set output 'month_of_year.png'
768 unset key
769 set xrange [0.5:12.5]
770 set xtics 1
771 set ylabel "Commits"
772 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
773 """)
774 f.close()
776 # commits_by_year_month
777 f = open(path + '/commits_by_year_month.plot', 'w')
778 f.write(GNUPLOT_COMMON)
779 f.write(
781 set output 'commits_by_year_month.png'
782 unset key
783 set xdata time
784 set timefmt "%Y-%m"
785 set format x "%Y-%m"
786 set xtics rotate by 90 15768000
787 set bmargin 5
788 set ylabel "Commits"
789 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
790 """)
791 f.close()
793 # commits_by_year
794 f = open(path + '/commits_by_year.plot', 'w')
795 f.write(GNUPLOT_COMMON)
796 f.write(
798 set output 'commits_by_year.png'
799 unset key
800 set xtics 1
801 set ylabel "Commits"
802 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
803 """)
804 f.close()
806 # Files by date
807 f = open(path + '/files_by_date.plot', 'w')
808 f.write(GNUPLOT_COMMON)
809 f.write(
811 set output 'files_by_date.png'
812 unset key
813 set xdata time
814 set timefmt "%Y-%m-%d"
815 set format x "%Y-%m-%d"
816 set ylabel "Files"
817 set xtics rotate by 90
818 set bmargin 6
819 plot 'files_by_date.dat' using 1:2 smooth csplines
820 """)
821 f.close()
823 # Lines of Code
824 f = open(path + '/lines_of_code.plot', 'w')
825 f.write(GNUPLOT_COMMON)
826 f.write(
828 set output 'lines_of_code.png'
829 unset key
830 set xdata time
831 set timefmt "%s"
832 set format x "%Y-%m-%d"
833 set ylabel "Lines"
834 set xtics rotate by 90
835 set bmargin 6
836 plot 'lines_of_code.dat' using 1:2 w lines
837 """)
838 f.close()
840 os.chdir(path)
841 files = glob.glob(path + '/*.plot')
842 for f in files:
843 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
844 if len(out) > 0:
845 print out
847 def printHeader(self, f, title = ''):
848 f.write(
849 """<?xml version="1.0" encoding="UTF-8"?>
850 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
851 <html xmlns="http://www.w3.org/1999/xhtml">
852 <head>
853 <title>GitStats - %s</title>
854 <link rel="stylesheet" href="gitstats.css" type="text/css" />
855 <meta name="generator" content="GitStats" />
856 <script type="text/javascript" src="sortable.js"></script>
857 </head>
858 <body>
859 """ % self.title)
861 def printNav(self, f):
862 f.write("""
863 <div class="nav">
864 <ul>
865 <li><a href="index.html">General</a></li>
866 <li><a href="activity.html">Activity</a></li>
867 <li><a href="authors.html">Authors</a></li>
868 <li><a href="files.html">Files</a></li>
869 <li><a href="lines.html">Lines</a></li>
870 <li><a href="tags.html">Tags</a></li>
871 </ul>
872 </div>
873 """)
876 usage = """
877 Usage: gitstats [options] <gitpath> <outputpath>
879 Options:
882 if len(sys.argv) < 3:
883 print usage
884 sys.exit(0)
886 gitpath = sys.argv[1]
887 outputpath = os.path.abspath(sys.argv[2])
888 rundir = os.getcwd()
890 try:
891 os.makedirs(outputpath)
892 except OSError:
893 pass
894 if not os.path.isdir(outputpath):
895 print 'FATAL: Output path is not a directory or does not exist'
896 sys.exit(1)
898 print 'Git path: %s' % gitpath
899 print 'Output path: %s' % outputpath
901 os.chdir(gitpath)
903 cachefile = os.path.join(outputpath, 'gitstats.cache')
905 print 'Collecting data...'
906 data = GitDataCollector()
907 data.loadCache(cachefile)
908 data.collect(gitpath)
909 print 'Refining data...'
910 data.saveCache(cachefile)
911 data.refine()
913 os.chdir(rundir)
915 print 'Generating report...'
916 report = HTMLReportCreator()
917 report.create(data, outputpath)
919 time_end = time.time()
920 exectime_internal = time_end - time_start
921 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)