Improved extension handling.
[gitstats.git] / gitstats
blob29bbec6777ec28f6a1df2aa8338e9f30d57099c6
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, dir):
68 cachefile = os.path.join(dir, '.git', 'gitstats.cache')
69 if not os.path.exists(cachefile):
70 return
71 print 'Loading cache...'
72 f = open(cachefile)
73 try:
74 self.cache = pickle.loads(zlib.decompress(f.read()))
75 except:
76 # temporary hack to upgrade non-compressed caches
77 f.seek(0)
78 self.cache = pickle.load(f)
79 f.close()
82 # Produce any additional statistics from the extracted data.
83 def refine(self):
84 pass
87 # : get a dictionary of author
88 def getAuthorInfo(self, author):
89 return None
91 def getActivityByDayOfWeek(self):
92 return {}
94 def getActivityByHourOfDay(self):
95 return {}
98 # Get a list of authors
99 def getAuthors(self):
100 return []
102 def getFirstCommitDate(self):
103 return datetime.datetime.now()
105 def getLastCommitDate(self):
106 return datetime.datetime.now()
108 def getStampCreated(self):
109 return self.stamp_created
111 def getTags(self):
112 return []
114 def getTotalAuthors(self):
115 return -1
117 def getTotalCommits(self):
118 return -1
120 def getTotalFiles(self):
121 return -1
123 def getTotalLOC(self):
124 return -1
127 # Save cacheable data
128 def saveCache(self, dir):
129 print 'Saving cache...'
130 f = open(os.path.join(dir, '.git', 'gitstats.cache'), 'w')
131 #pickle.dump(self.cache, f)
132 data = zlib.compress(pickle.dumps(self.cache))
133 f.write(data)
134 f.close()
136 class GitDataCollector(DataCollector):
137 def collect(self, dir):
138 DataCollector.collect(self, dir)
140 try:
141 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
142 except:
143 self.total_authors = 0
144 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
146 self.activity_by_hour_of_day = {} # hour -> commits
147 self.activity_by_day_of_week = {} # day -> commits
148 self.activity_by_month_of_year = {} # month [1-12] -> commits
149 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
151 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
153 # author of the month
154 self.author_of_month = {} # month -> author -> commits
155 self.author_of_year = {} # year -> author -> commits
156 self.commits_by_month = {} # month -> commits
157 self.commits_by_year = {} # year -> commits
158 self.first_commit_stamp = 0
159 self.last_commit_stamp = 0
161 # tags
162 self.tags = {}
163 lines = getpipeoutput(['git show-ref --tags']).split('\n')
164 for line in lines:
165 if len(line) == 0:
166 continue
167 (hash, tag) = line.split(' ')
169 tag = tag.replace('refs/tags/', '')
170 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
171 if len(output) > 0:
172 parts = output.split(' ')
173 stamp = 0
174 try:
175 stamp = int(parts[0])
176 except ValueError:
177 stamp = 0
178 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d') }
180 # Collect revision statistics
181 # Outputs "<stamp> <author>"
182 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
183 for line in lines:
184 # linux-2.6 says "<unknown>" for one line O_o
185 parts = line.split(' ')
186 author = ''
187 try:
188 stamp = int(parts[0])
189 except ValueError:
190 stamp = 0
191 if len(parts) > 1:
192 author = ' '.join(parts[1:])
193 date = datetime.datetime.fromtimestamp(float(stamp))
195 # First and last commit stamp
196 if self.last_commit_stamp == 0:
197 self.last_commit_stamp = stamp
198 self.first_commit_stamp = stamp
200 # activity
201 # hour
202 hour = date.hour
203 if hour in self.activity_by_hour_of_day:
204 self.activity_by_hour_of_day[hour] += 1
205 else:
206 self.activity_by_hour_of_day[hour] = 1
208 # day of week
209 day = date.weekday()
210 if day in self.activity_by_day_of_week:
211 self.activity_by_day_of_week[day] += 1
212 else:
213 self.activity_by_day_of_week[day] = 1
215 # hour of week
216 if day not in self.activity_by_hour_of_week:
217 self.activity_by_hour_of_week[day] = {}
218 if hour not in self.activity_by_hour_of_week[day]:
219 self.activity_by_hour_of_week[day][hour] = 1
220 else:
221 self.activity_by_hour_of_week[day][hour] += 1
223 # month of year
224 month = date.month
225 if month in self.activity_by_month_of_year:
226 self.activity_by_month_of_year[month] += 1
227 else:
228 self.activity_by_month_of_year[month] = 1
230 # author stats
231 if author not in self.authors:
232 self.authors[author] = {}
233 # commits
234 if 'last_commit_stamp' not in self.authors[author]:
235 self.authors[author]['last_commit_stamp'] = stamp
236 self.authors[author]['first_commit_stamp'] = stamp
237 if 'commits' in self.authors[author]:
238 self.authors[author]['commits'] += 1
239 else:
240 self.authors[author]['commits'] = 1
242 # author of the month/year
243 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
244 if yymm in self.author_of_month:
245 if author in self.author_of_month[yymm]:
246 self.author_of_month[yymm][author] += 1
247 else:
248 self.author_of_month[yymm][author] = 1
249 else:
250 self.author_of_month[yymm] = {}
251 self.author_of_month[yymm][author] = 1
252 if yymm in self.commits_by_month:
253 self.commits_by_month[yymm] += 1
254 else:
255 self.commits_by_month[yymm] = 1
257 yy = datetime.datetime.fromtimestamp(stamp).year
258 if yy in self.author_of_year:
259 if author in self.author_of_year[yy]:
260 self.author_of_year[yy][author] += 1
261 else:
262 self.author_of_year[yy][author] = 1
263 else:
264 self.author_of_year[yy] = {}
265 self.author_of_year[yy][author] = 1
266 if yy in self.commits_by_year:
267 self.commits_by_year[yy] += 1
268 else:
269 self.commits_by_year[yy] = 1
271 # TODO Optimize this, it's the worst bottleneck
272 # outputs "<stamp> <files>" for each revision
273 self.files_by_stamp = {} # stamp -> files
274 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
275 lines = []
276 for revline in revlines:
277 time, rev = revline.split(' ')
278 #linecount = int(getpipeoutput(['git-ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
279 linecount = self.getFilesInCommit(rev)
280 lines.append('%d %d' % (int(time), linecount))
282 self.total_commits = len(lines)
283 for line in lines:
284 parts = line.split(' ')
285 if len(parts) != 2:
286 continue
287 (stamp, files) = parts[0:2]
288 try:
289 self.files_by_stamp[int(stamp)] = int(files)
290 except ValueError:
291 print 'Warning: failed to parse line "%s"' % line
293 # extensions
294 self.extensions = {} # extension -> files, lines
295 lines = getpipeoutput(['git ls-files']).split('\n')
296 self.total_files = len(lines)
297 for line in lines:
298 base = os.path.basename(line)
299 # Ignore extensionless (including .hidden files)
300 if base.find('.') == -1 or base.rfind('.') == 0:
301 ext = ''
302 else:
303 ext = base[(base.rfind('.') + 1):]
304 if len(ext) > MAX_EXT_LENGTH:
305 ext = ''
307 if ext not in self.extensions:
308 self.extensions[ext] = {'files': 0, 'lines': 0}
310 self.extensions[ext]['files'] += 1
311 try:
312 # Escaping could probably be improved here
313 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
314 except:
315 print 'Warning: Could not count lines for file "%s"' % line
317 # line statistics
318 # outputs:
319 # N files changed, N insertions (+), N deletions(-)
320 # <stamp> <author>
321 self.changes_by_date = {} # stamp -> { files, ins, del }
322 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
323 lines.reverse()
324 files = 0; inserted = 0; deleted = 0; total_lines = 0
325 for line in lines:
326 if len(line) == 0:
327 continue
329 # <stamp> <author>
330 if line.find('files changed,') == -1:
331 pos = line.find(' ')
332 if pos != -1:
333 try:
334 (stamp, author) = (int(line[:pos]), line[pos+1:])
335 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
336 except ValueError:
337 print 'Warning: unexpected line "%s"' % line
338 else:
339 print 'Warning: unexpected line "%s"' % line
340 else:
341 numbers = re.findall('\d+', line)
342 if len(numbers) == 3:
343 (files, inserted, deleted) = map(lambda el : int(el), numbers)
344 total_lines += inserted
345 total_lines -= deleted
346 else:
347 print 'Warning: failed to handle line "%s"' % line
348 (files, inserted, deleted) = (0, 0, 0)
349 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
350 self.total_lines = total_lines
352 def refine(self):
353 # authors
354 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
355 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
356 authors_by_commits.reverse() # most first
357 for i, name in enumerate(authors_by_commits):
358 self.authors[name]['place_by_commits'] = i + 1
360 for name in self.authors.keys():
361 a = self.authors[name]
362 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
363 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
364 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
365 delta = date_last - date_first
366 a['date_first'] = date_first.strftime('%Y-%m-%d')
367 a['date_last'] = date_last.strftime('%Y-%m-%d')
368 a['timedelta'] = delta
370 def getActivityByDayOfWeek(self):
371 return self.activity_by_day_of_week
373 def getActivityByHourOfDay(self):
374 return self.activity_by_hour_of_day
376 def getAuthorInfo(self, author):
377 return self.authors[author]
379 def getAuthors(self):
380 return self.authors.keys()
382 def getFilesInCommit(self, rev):
383 try:
384 res = self.cache['files_in_tree'][rev]
385 except:
386 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
387 if 'files_in_tree' not in self.cache:
388 self.cache['files_in_tree'] = {}
389 self.cache['files_in_tree'][rev] = res
391 return res
393 def getFirstCommitDate(self):
394 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
396 def getLastCommitDate(self):
397 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
399 def getTags(self):
400 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
401 return lines.split('\n')
403 def getTagDate(self, tag):
404 return self.revToDate('tags/' + tag)
406 def getTotalAuthors(self):
407 return self.total_authors
409 def getTotalCommits(self):
410 return self.total_commits
412 def getTotalFiles(self):
413 return self.total_files
415 def getTotalLOC(self):
416 return self.total_lines
418 def revToDate(self, rev):
419 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
420 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
422 class ReportCreator:
423 """Creates the actual report based on given data."""
424 def __init__(self):
425 pass
427 def create(self, data, path):
428 self.data = data
429 self.path = path
431 def html_linkify(text):
432 return text.lower().replace(' ', '_')
434 def html_header(level, text):
435 name = html_linkify(text)
436 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
438 class HTMLReportCreator(ReportCreator):
439 def create(self, data, path):
440 ReportCreator.create(self, data, path)
441 self.title = data.projectname
443 # copy static files if they do not exist
444 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
445 basedir = os.path.dirname(os.path.abspath(__file__))
446 shutil.copyfile(basedir + '/' + file, path + '/' + file)
448 f = open(path + "/index.html", 'w')
449 format = '%Y-%m-%d %H:%m:%S'
450 self.printHeader(f)
452 f.write('<h1>GitStats - %s</h1>' % data.projectname)
454 self.printNav(f)
456 f.write('<dl>');
457 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
458 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()));
459 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
460 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
461 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
462 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
463 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
464 f.write('</dl>');
466 f.write('</body>\n</html>');
467 f.close()
470 # Activity
471 f = open(path + '/activity.html', 'w')
472 self.printHeader(f)
473 f.write('<h1>Activity</h1>')
474 self.printNav(f)
476 #f.write('<h2>Last 30 days</h2>')
478 #f.write('<h2>Last 12 months</h2>')
480 # Hour of Day
481 f.write(html_header(2, 'Hour of Day'))
482 hour_of_day = data.getActivityByHourOfDay()
483 f.write('<table><tr><th>Hour</th>')
484 for i in range(1, 25):
485 f.write('<th>%d</th>' % i)
486 f.write('</tr>\n<tr><th>Commits</th>')
487 fp = open(path + '/hour_of_day.dat', 'w')
488 for i in range(0, 24):
489 if i in hour_of_day:
490 f.write('<td>%d</td>' % hour_of_day[i])
491 fp.write('%d %d\n' % (i, hour_of_day[i]))
492 else:
493 f.write('<td>0</td>')
494 fp.write('%d 0\n' % i)
495 fp.close()
496 f.write('</tr>\n<tr><th>%</th>')
497 totalcommits = data.getTotalCommits()
498 for i in range(0, 24):
499 if i in hour_of_day:
500 f.write('<td>%.2f</td>' % ((100.0 * hour_of_day[i]) / totalcommits))
501 else:
502 f.write('<td>0.00</td>')
503 f.write('</tr></table>')
504 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
505 fg = open(path + '/hour_of_day.dat', 'w')
506 for i in range(0, 24):
507 if i in hour_of_day:
508 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
509 else:
510 fg.write('%d 0\n' % (i + 1))
511 fg.close()
513 # Day of Week
514 f.write(html_header(2, 'Day of Week'))
515 day_of_week = data.getActivityByDayOfWeek()
516 f.write('<div class="vtable"><table>')
517 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
518 fp = open(path + '/day_of_week.dat', 'w')
519 for d in range(0, 7):
520 commits = 0
521 if d in day_of_week:
522 commits = day_of_week[d]
523 fp.write('%d %d\n' % (d + 1, commits))
524 f.write('<tr>')
525 f.write('<th>%d</th>' % (d + 1))
526 if d in day_of_week:
527 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
528 else:
529 f.write('<td>0</td>')
530 f.write('</tr>')
531 f.write('</table></div>')
532 f.write('<img src="day_of_week.png" alt="Day of Week" />')
533 fp.close()
535 # Hour of Week
536 f.write(html_header(2, 'Hour of Week'))
537 f.write('<table>')
539 f.write('<tr><th>Weekday</th>')
540 for hour in range(0, 24):
541 f.write('<th>%d</th>' % (hour + 1))
542 f.write('</tr>')
544 for weekday in range(0, 7):
545 f.write('<tr><th>%d</th>' % (weekday + 1))
546 for hour in range(0, 24):
547 try:
548 commits = data.activity_by_hour_of_week[weekday][hour]
549 except KeyError:
550 commits = 0
551 if commits != 0:
552 f.write('<td>%d</td>' % commits)
553 else:
554 f.write('<td></td>')
555 f.write('</tr>')
557 f.write('</table>')
559 # Month of Year
560 f.write(html_header(2, 'Month of Year'))
561 f.write('<div class="vtable"><table>')
562 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
563 fp = open (path + '/month_of_year.dat', 'w')
564 for mm in range(1, 13):
565 commits = 0
566 if mm in data.activity_by_month_of_year:
567 commits = data.activity_by_month_of_year[mm]
568 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
569 fp.write('%d %d\n' % (mm, commits))
570 fp.close()
571 f.write('</table></div>')
572 f.write('<img src="month_of_year.png" alt="Month of Year" />')
574 # Commits by year/month
575 f.write(html_header(2, 'Commits by year/month'))
576 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
577 for yymm in reversed(sorted(data.commits_by_month.keys())):
578 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
579 f.write('</table></div>')
580 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
581 fg = open(path + '/commits_by_year_month.dat', 'w')
582 for yymm in sorted(data.commits_by_month.keys()):
583 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
584 fg.close()
586 # Commits by year
587 f.write(html_header(2, 'Commits by Year'))
588 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
589 for yy in reversed(sorted(data.commits_by_year.keys())):
590 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()))
591 f.write('</table></div>')
592 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
593 fg = open(path + '/commits_by_year.dat', 'w')
594 for yy in sorted(data.commits_by_year.keys()):
595 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
596 fg.close()
598 f.write('</body></html>')
599 f.close()
602 # Authors
603 f = open(path + '/authors.html', 'w')
604 self.printHeader(f)
606 f.write('<h1>Authors</h1>')
607 self.printNav(f)
609 # Authors :: List of authors
610 f.write(html_header(2, 'List of Authors'))
612 f.write('<table class="authors sortable" id="authors">')
613 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>')
614 for author in sorted(data.getAuthors()):
615 info = data.getAuthorInfo(author)
616 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']))
617 f.write('</table>')
619 # Authors :: Author of Month
620 f.write(html_header(2, 'Author of Month'))
621 f.write('<table class="sortable" id="aom">')
622 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
623 for yymm in reversed(sorted(data.author_of_month.keys())):
624 authordict = data.author_of_month[yymm]
625 authors = getkeyssortedbyvalues(authordict)
626 authors.reverse()
627 commits = data.author_of_month[yymm][authors[0]]
628 next = ', '.join(authors[1:5])
629 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))
631 f.write('</table>')
633 f.write(html_header(2, 'Author of Year'))
634 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>')
635 for yy in reversed(sorted(data.author_of_year.keys())):
636 authordict = data.author_of_year[yy]
637 authors = getkeyssortedbyvalues(authordict)
638 authors.reverse()
639 commits = data.author_of_year[yy][authors[0]]
640 next = ', '.join(authors[1:5])
641 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))
642 f.write('</table>')
644 f.write('</body></html>')
645 f.close()
648 # Files
649 f = open(path + '/files.html', 'w')
650 self.printHeader(f)
651 f.write('<h1>Files</h1>')
652 self.printNav(f)
654 f.write('<dl>\n')
655 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
656 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
657 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
658 f.write('</dl>\n')
660 # Files :: File count by date
661 f.write(html_header(2, 'File count by date'))
663 fg = open(path + '/files_by_date.dat', 'w')
664 for stamp in sorted(data.files_by_stamp.keys()):
665 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
666 fg.close()
668 f.write('<img src="files_by_date.png" alt="Files by Date" />')
670 #f.write('<h2>Average file size by date</h2>')
672 # Files :: Extensions
673 f.write(html_header(2, 'Extensions'))
674 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
675 for ext in sorted(data.extensions.keys()):
676 files = data.extensions[ext]['files']
677 lines = data.extensions[ext]['lines']
678 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))
679 f.write('</table>')
681 f.write('</body></html>')
682 f.close()
685 # Lines
686 f = open(path + '/lines.html', 'w')
687 self.printHeader(f)
688 f.write('<h1>Lines</h1>')
689 self.printNav(f)
691 f.write('<dl>\n')
692 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
693 f.write('</dl>\n')
695 f.write(html_header(2, 'Lines of Code'))
696 f.write('<img src="lines_of_code.png" />')
698 fg = open(path + '/lines_of_code.dat', 'w')
699 for stamp in sorted(data.changes_by_date.keys()):
700 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
701 fg.close()
703 f.write('</body></html>')
704 f.close()
707 # tags.html
708 f = open(path + '/tags.html', 'w')
709 self.printHeader(f)
710 f.write('<h1>Tags</h1>')
711 self.printNav(f)
713 f.write('<dl>')
714 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
715 if len(data.tags) > 0:
716 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
717 f.write('</dl>')
719 f.write('<table>')
720 f.write('<tr><th>Name</th><th>Date</th></tr>')
721 # sort the tags by date desc
722 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
723 for tag in tags_sorted_by_date_desc:
724 f.write('<tr><td>%s</td><td>%s</td></tr>' % (tag, data.tags[tag]['date']))
725 f.write('</table>')
727 f.write('</body></html>')
728 f.close()
730 self.createGraphs(path)
732 def createGraphs(self, path):
733 print 'Generating graphs...'
735 # hour of day
736 f = open(path + '/hour_of_day.plot', 'w')
737 f.write(GNUPLOT_COMMON)
738 f.write(
740 set output 'hour_of_day.png'
741 unset key
742 set xrange [0.5:24.5]
743 set xtics 4
744 set ylabel "Commits"
745 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
746 """)
747 f.close()
749 # day of week
750 f = open(path + '/day_of_week.plot', 'w')
751 f.write(GNUPLOT_COMMON)
752 f.write(
754 set output 'day_of_week.png'
755 unset key
756 set xrange [0.5:7.5]
757 set xtics 1
758 set ylabel "Commits"
759 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
760 """)
761 f.close()
763 # Month of Year
764 f = open(path + '/month_of_year.plot', 'w')
765 f.write(GNUPLOT_COMMON)
766 f.write(
768 set output 'month_of_year.png'
769 unset key
770 set xrange [0.5:12.5]
771 set xtics 1
772 set ylabel "Commits"
773 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
774 """)
775 f.close()
777 # commits_by_year_month
778 f = open(path + '/commits_by_year_month.plot', 'w')
779 f.write(GNUPLOT_COMMON)
780 f.write(
782 set output 'commits_by_year_month.png'
783 unset key
784 set xdata time
785 set timefmt "%Y-%m"
786 set format x "%Y-%m"
787 set xtics rotate by 90 15768000
788 set bmargin 5
789 set ylabel "Commits"
790 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
791 """)
792 f.close()
794 # commits_by_year
795 f = open(path + '/commits_by_year.plot', 'w')
796 f.write(GNUPLOT_COMMON)
797 f.write(
799 set output 'commits_by_year.png'
800 unset key
801 set xtics 1
802 set ylabel "Commits"
803 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
804 """)
805 f.close()
807 # Files by date
808 f = open(path + '/files_by_date.plot', 'w')
809 f.write(GNUPLOT_COMMON)
810 f.write(
812 set output 'files_by_date.png'
813 unset key
814 set xdata time
815 set timefmt "%Y-%m-%d"
816 set format x "%Y-%m-%d"
817 set ylabel "Files"
818 set xtics rotate by 90
819 set bmargin 6
820 plot 'files_by_date.dat' using 1:2 smooth csplines
821 """)
822 f.close()
824 # Lines of Code
825 f = open(path + '/lines_of_code.plot', 'w')
826 f.write(GNUPLOT_COMMON)
827 f.write(
829 set output 'lines_of_code.png'
830 unset key
831 set xdata time
832 set timefmt "%s"
833 set format x "%Y-%m-%d"
834 set ylabel "Lines"
835 set xtics rotate by 90
836 set bmargin 6
837 plot 'lines_of_code.dat' using 1:2 w lines
838 """)
839 f.close()
841 os.chdir(path)
842 files = glob.glob(path + '/*.plot')
843 for f in files:
844 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
845 if len(out) > 0:
846 print out
848 def printHeader(self, f, title = ''):
849 f.write(
850 """<?xml version="1.0" encoding="UTF-8"?>
851 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
852 <html xmlns="http://www.w3.org/1999/xhtml">
853 <head>
854 <title>GitStats - %s</title>
855 <link rel="stylesheet" href="gitstats.css" type="text/css" />
856 <meta name="generator" content="GitStats" />
857 <script type="text/javascript" src="sortable.js"></script>
858 </head>
859 <body>
860 """ % self.title)
862 def printNav(self, f):
863 f.write("""
864 <div class="nav">
865 <ul>
866 <li><a href="index.html">General</a></li>
867 <li><a href="activity.html">Activity</a></li>
868 <li><a href="authors.html">Authors</a></li>
869 <li><a href="files.html">Files</a></li>
870 <li><a href="lines.html">Lines</a></li>
871 <li><a href="tags.html">Tags</a></li>
872 </ul>
873 </div>
874 """)
877 usage = """
878 Usage: gitstats [options] <gitpath> <outputpath>
880 Options:
883 if len(sys.argv) < 3:
884 print usage
885 sys.exit(0)
887 gitpath = sys.argv[1]
888 outputpath = os.path.abspath(sys.argv[2])
889 rundir = os.getcwd()
891 try:
892 os.makedirs(outputpath)
893 except OSError:
894 pass
895 if not os.path.isdir(outputpath):
896 print 'FATAL: Output path is not a directory or does not exist'
897 sys.exit(1)
899 print 'Git path: %s' % gitpath
900 print 'Output path: %s' % outputpath
902 os.chdir(gitpath)
904 print 'Collecting data...'
905 data = GitDataCollector()
906 data.loadCache(gitpath)
907 data.collect(gitpath)
908 print 'Refining data...'
909 data.saveCache(gitpath)
910 data.refine()
912 os.chdir(rundir)
914 print 'Generating report...'
915 report = HTMLReportCreator()
916 report.create(data, outputpath)
918 time_end = time.time()
919 exectime_internal = time_end - time_start
920 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)