Handle case with no commits between tags.
[gitstats.git] / gitstats
blobd104a3c315a2d9dfabf9b54bd39fda1a71d2f4eb
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2009 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
3 # GPLv2 / GPLv3
4 import datetime
5 import glob
6 import os
7 import pickle
8 import re
9 import shutil
10 import subprocess
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 VERSION = 0
54 def getversion():
55 global VERSION
56 if VERSION == 0:
57 VERSION = getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
58 return VERSION
60 class DataCollector:
61 """Manages data collection from a revision control repository."""
62 def __init__(self):
63 self.stamp_created = time.time()
64 self.cache = {}
67 # This should be the main function to extract data from the repository.
68 def collect(self, dir):
69 self.dir = dir
70 self.projectname = os.path.basename(os.path.abspath(dir))
73 # Load cacheable data
74 def loadCache(self, cachefile):
75 if not os.path.exists(cachefile):
76 return
77 print 'Loading cache...'
78 f = open(cachefile)
79 try:
80 self.cache = pickle.loads(zlib.decompress(f.read()))
81 except:
82 # temporary hack to upgrade non-compressed caches
83 f.seek(0)
84 self.cache = pickle.load(f)
85 f.close()
88 # Produce any additional statistics from the extracted data.
89 def refine(self):
90 pass
93 # : get a dictionary of author
94 def getAuthorInfo(self, author):
95 return None
97 def getActivityByDayOfWeek(self):
98 return {}
100 def getActivityByHourOfDay(self):
101 return {}
104 # Get a list of authors
105 def getAuthors(self):
106 return []
108 def getFirstCommitDate(self):
109 return datetime.datetime.now()
111 def getLastCommitDate(self):
112 return datetime.datetime.now()
114 def getStampCreated(self):
115 return self.stamp_created
117 def getTags(self):
118 return []
120 def getTotalAuthors(self):
121 return -1
123 def getTotalCommits(self):
124 return -1
126 def getTotalFiles(self):
127 return -1
129 def getTotalLOC(self):
130 return -1
133 # Save cacheable data
134 def saveCache(self, filename):
135 print 'Saving cache...'
136 f = open(cachefile, 'w')
137 #pickle.dump(self.cache, f)
138 data = zlib.compress(pickle.dumps(self.cache))
139 f.write(data)
140 f.close()
142 class GitDataCollector(DataCollector):
143 def collect(self, dir):
144 DataCollector.collect(self, dir)
146 try:
147 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
148 except:
149 self.total_authors = 0
150 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
152 self.activity_by_hour_of_day = {} # hour -> commits
153 self.activity_by_day_of_week = {} # day -> commits
154 self.activity_by_month_of_year = {} # month [1-12] -> commits
155 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
156 self.activity_by_hour_of_day_busiest = 0
157 self.activity_by_hour_of_week_busiest = 0
159 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp}
161 # author of the month
162 self.author_of_month = {} # month -> author -> commits
163 self.author_of_year = {} # year -> author -> commits
164 self.commits_by_month = {} # month -> commits
165 self.commits_by_year = {} # year -> commits
166 self.first_commit_stamp = 0
167 self.last_commit_stamp = 0
169 # tags
170 self.tags = {}
171 lines = getpipeoutput(['git show-ref --tags']).split('\n')
172 for line in lines:
173 if len(line) == 0:
174 continue
175 (hash, tag) = line.split(' ')
177 tag = tag.replace('refs/tags/', '')
178 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
179 if len(output) > 0:
180 parts = output.split(' ')
181 stamp = 0
182 try:
183 stamp = int(parts[0])
184 except ValueError:
185 stamp = 0
186 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
188 # collect info on tags, starting from latest
189 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
190 prev = None
191 for tag in reversed(tags_sorted_by_date_desc):
192 #print prev, tag
193 cmd = 'git shortlog -s "%s"' % tag
194 if prev != None:
195 cmd += ' "^%s"' % prev
196 output = getpipeoutput([cmd])
197 if len(output) == 0:
198 continue
199 prev = tag
200 for line in output.split('\n'):
201 parts = re.split('\s+', line, 2)
202 #print parts
203 commits = int(parts[1])
204 author = parts[2]
205 self.tags[tag]['commits'] += commits
206 self.tags[tag]['authors'][author] = commits
207 #print self.tags
209 # Collect revision statistics
210 # Outputs "<stamp> <author>"
211 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
212 for line in lines:
213 # linux-2.6 says "<unknown>" for one line O_o
214 parts = line.split(' ')
215 author = ''
216 try:
217 stamp = int(parts[0])
218 except ValueError:
219 stamp = 0
220 if len(parts) > 1:
221 author = ' '.join(parts[1:])
222 date = datetime.datetime.fromtimestamp(float(stamp))
224 # First and last commit stamp
225 if self.last_commit_stamp == 0:
226 self.last_commit_stamp = stamp
227 self.first_commit_stamp = stamp
229 # activity
230 # hour
231 hour = date.hour
232 if hour in self.activity_by_hour_of_day:
233 self.activity_by_hour_of_day[hour] += 1
234 else:
235 self.activity_by_hour_of_day[hour] = 1
236 # most active hour?
237 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
238 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
240 # day of week
241 day = date.weekday()
242 if day in self.activity_by_day_of_week:
243 self.activity_by_day_of_week[day] += 1
244 else:
245 self.activity_by_day_of_week[day] = 1
247 # hour of week
248 if day not in self.activity_by_hour_of_week:
249 self.activity_by_hour_of_week[day] = {}
250 if hour not in self.activity_by_hour_of_week[day]:
251 self.activity_by_hour_of_week[day][hour] = 1
252 else:
253 self.activity_by_hour_of_week[day][hour] += 1
254 # most active hour?
255 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
256 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
258 # month of year
259 month = date.month
260 if month in self.activity_by_month_of_year:
261 self.activity_by_month_of_year[month] += 1
262 else:
263 self.activity_by_month_of_year[month] = 1
265 # author stats
266 if author not in self.authors:
267 self.authors[author] = {}
268 # commits
269 if 'last_commit_stamp' not in self.authors[author]:
270 self.authors[author]['last_commit_stamp'] = stamp
271 self.authors[author]['first_commit_stamp'] = stamp
272 if 'commits' in self.authors[author]:
273 self.authors[author]['commits'] += 1
274 else:
275 self.authors[author]['commits'] = 1
277 # author of the month/year
278 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
279 if yymm in self.author_of_month:
280 if author in self.author_of_month[yymm]:
281 self.author_of_month[yymm][author] += 1
282 else:
283 self.author_of_month[yymm][author] = 1
284 else:
285 self.author_of_month[yymm] = {}
286 self.author_of_month[yymm][author] = 1
287 if yymm in self.commits_by_month:
288 self.commits_by_month[yymm] += 1
289 else:
290 self.commits_by_month[yymm] = 1
292 yy = datetime.datetime.fromtimestamp(stamp).year
293 if yy in self.author_of_year:
294 if author in self.author_of_year[yy]:
295 self.author_of_year[yy][author] += 1
296 else:
297 self.author_of_year[yy][author] = 1
298 else:
299 self.author_of_year[yy] = {}
300 self.author_of_year[yy][author] = 1
301 if yy in self.commits_by_year:
302 self.commits_by_year[yy] += 1
303 else:
304 self.commits_by_year[yy] = 1
306 # TODO Optimize this, it's the worst bottleneck
307 # outputs "<stamp> <files>" for each revision
308 self.files_by_stamp = {} # stamp -> files
309 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
310 lines = []
311 for revline in revlines:
312 time, rev = revline.split(' ')
313 #linecount = int(getpipeoutput(['git-ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
314 linecount = self.getFilesInCommit(rev)
315 lines.append('%d %d' % (int(time), linecount))
317 self.total_commits = len(lines)
318 for line in lines:
319 parts = line.split(' ')
320 if len(parts) != 2:
321 continue
322 (stamp, files) = parts[0:2]
323 try:
324 self.files_by_stamp[int(stamp)] = int(files)
325 except ValueError:
326 print 'Warning: failed to parse line "%s"' % line
328 # extensions
329 self.extensions = {} # extension -> files, lines
330 lines = getpipeoutput(['git ls-files']).split('\n')
331 self.total_files = len(lines)
332 for line in lines:
333 base = os.path.basename(line)
334 # Ignore extensionless (including .hidden files)
335 if base.find('.') == -1 or base.rfind('.') == 0:
336 ext = ''
337 else:
338 ext = base[(base.rfind('.') + 1):]
339 if len(ext) > MAX_EXT_LENGTH:
340 ext = ''
342 if ext not in self.extensions:
343 self.extensions[ext] = {'files': 0, 'lines': 0}
345 self.extensions[ext]['files'] += 1
346 try:
347 # Escaping could probably be improved here
348 self.extensions[ext]['lines'] += int(getpipeoutput(['wc -l "%s"' % line]).split()[0])
349 except:
350 print 'Warning: Could not count lines for file "%s"' % line
352 # line statistics
353 # outputs:
354 # N files changed, N insertions (+), N deletions(-)
355 # <stamp> <author>
356 self.changes_by_date = {} # stamp -> { files, ins, del }
357 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
358 lines.reverse()
359 files = 0; inserted = 0; deleted = 0; total_lines = 0
360 for line in lines:
361 if len(line) == 0:
362 continue
364 # <stamp> <author>
365 if line.find('files changed,') == -1:
366 pos = line.find(' ')
367 if pos != -1:
368 try:
369 (stamp, author) = (int(line[:pos]), line[pos+1:])
370 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
371 except ValueError:
372 print 'Warning: unexpected line "%s"' % line
373 else:
374 print 'Warning: unexpected line "%s"' % line
375 else:
376 numbers = re.findall('\d+', line)
377 if len(numbers) == 3:
378 (files, inserted, deleted) = map(lambda el : int(el), numbers)
379 total_lines += inserted
380 total_lines -= deleted
381 else:
382 print 'Warning: failed to handle line "%s"' % line
383 (files, inserted, deleted) = (0, 0, 0)
384 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
385 self.total_lines = total_lines
387 def refine(self):
388 # authors
389 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
390 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
391 authors_by_commits.reverse() # most first
392 for i, name in enumerate(authors_by_commits):
393 self.authors[name]['place_by_commits'] = i + 1
395 for name in self.authors.keys():
396 a = self.authors[name]
397 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
398 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
399 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
400 delta = date_last - date_first
401 a['date_first'] = date_first.strftime('%Y-%m-%d')
402 a['date_last'] = date_last.strftime('%Y-%m-%d')
403 a['timedelta'] = delta
405 def getActivityByDayOfWeek(self):
406 return self.activity_by_day_of_week
408 def getActivityByHourOfDay(self):
409 return self.activity_by_hour_of_day
411 def getAuthorInfo(self, author):
412 return self.authors[author]
414 def getAuthors(self):
415 return self.authors.keys()
417 def getCommitDeltaDays(self):
418 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
420 def getFilesInCommit(self, rev):
421 try:
422 res = self.cache['files_in_tree'][rev]
423 except:
424 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
425 if 'files_in_tree' not in self.cache:
426 self.cache['files_in_tree'] = {}
427 self.cache['files_in_tree'][rev] = res
429 return res
431 def getFirstCommitDate(self):
432 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
434 def getLastCommitDate(self):
435 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
437 def getTags(self):
438 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
439 return lines.split('\n')
441 def getTagDate(self, tag):
442 return self.revToDate('tags/' + tag)
444 def getTotalAuthors(self):
445 return self.total_authors
447 def getTotalCommits(self):
448 return self.total_commits
450 def getTotalFiles(self):
451 return self.total_files
453 def getTotalLOC(self):
454 return self.total_lines
456 def revToDate(self, rev):
457 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
458 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
460 class ReportCreator:
461 """Creates the actual report based on given data."""
462 def __init__(self):
463 pass
465 def create(self, data, path):
466 self.data = data
467 self.path = path
469 def html_linkify(text):
470 return text.lower().replace(' ', '_')
472 def html_header(level, text):
473 name = html_linkify(text)
474 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
476 class HTMLReportCreator(ReportCreator):
477 def create(self, data, path):
478 ReportCreator.create(self, data, path)
479 self.title = data.projectname
481 # copy static files if they do not exist
482 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
483 basedir = os.path.dirname(os.path.abspath(__file__))
484 shutil.copyfile(basedir + '/' + file, path + '/' + file)
486 f = open(path + "/index.html", 'w')
487 format = '%Y-%m-%d %H:%M:%S'
488 self.printHeader(f)
490 f.write('<h1>GitStats - %s</h1>' % data.projectname)
492 self.printNav(f)
494 f.write('<dl>')
495 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
496 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
497 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
498 f.write('<dt>Report Period</dt><dd>%s to %s (%d days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays()))
499 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
500 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
501 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
502 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
503 f.write('</dl>')
505 f.write('</body>\n</html>')
506 f.close()
509 # Activity
510 f = open(path + '/activity.html', 'w')
511 self.printHeader(f)
512 f.write('<h1>Activity</h1>')
513 self.printNav(f)
515 #f.write('<h2>Last 30 days</h2>')
517 #f.write('<h2>Last 12 months</h2>')
519 # Hour of Day
520 f.write(html_header(2, 'Hour of Day'))
521 hour_of_day = data.getActivityByHourOfDay()
522 f.write('<table><tr><th>Hour</th>')
523 for i in range(0, 24):
524 f.write('<th>%d</th>' % i)
525 f.write('</tr>\n<tr><th>Commits</th>')
526 fp = open(path + '/hour_of_day.dat', 'w')
527 for i in range(0, 24):
528 if i in hour_of_day:
529 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
530 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
531 fp.write('%d %d\n' % (i, hour_of_day[i]))
532 else:
533 f.write('<td>0</td>')
534 fp.write('%d 0\n' % i)
535 fp.close()
536 f.write('</tr>\n<tr><th>%</th>')
537 totalcommits = data.getTotalCommits()
538 for i in range(0, 24):
539 if i in hour_of_day:
540 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
541 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
542 else:
543 f.write('<td>0.00</td>')
544 f.write('</tr></table>')
545 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
546 fg = open(path + '/hour_of_day.dat', 'w')
547 for i in range(0, 24):
548 if i in hour_of_day:
549 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
550 else:
551 fg.write('%d 0\n' % (i + 1))
552 fg.close()
554 # Day of Week
555 f.write(html_header(2, 'Day of Week'))
556 day_of_week = data.getActivityByDayOfWeek()
557 f.write('<div class="vtable"><table>')
558 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
559 fp = open(path + '/day_of_week.dat', 'w')
560 for d in range(0, 7):
561 commits = 0
562 if d in day_of_week:
563 commits = day_of_week[d]
564 fp.write('%d %d\n' % (d + 1, commits))
565 f.write('<tr>')
566 f.write('<th>%d</th>' % (d + 1))
567 if d in day_of_week:
568 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
569 else:
570 f.write('<td>0</td>')
571 f.write('</tr>')
572 f.write('</table></div>')
573 f.write('<img src="day_of_week.png" alt="Day of Week" />')
574 fp.close()
576 # Hour of Week
577 f.write(html_header(2, 'Hour of Week'))
578 f.write('<table>')
580 f.write('<tr><th>Weekday</th>')
581 for hour in range(0, 24):
582 f.write('<th>%d</th>' % (hour))
583 f.write('</tr>')
585 for weekday in range(0, 7):
586 f.write('<tr><th>%d</th>' % (weekday + 1))
587 for hour in range(0, 24):
588 try:
589 commits = data.activity_by_hour_of_week[weekday][hour]
590 except KeyError:
591 commits = 0
592 if commits != 0:
593 f.write('<td')
594 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
595 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
596 f.write('>%d</td>' % commits)
597 else:
598 f.write('<td></td>')
599 f.write('</tr>')
601 f.write('</table>')
603 # Month of Year
604 f.write(html_header(2, 'Month of Year'))
605 f.write('<div class="vtable"><table>')
606 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
607 fp = open (path + '/month_of_year.dat', 'w')
608 for mm in range(1, 13):
609 commits = 0
610 if mm in data.activity_by_month_of_year:
611 commits = data.activity_by_month_of_year[mm]
612 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
613 fp.write('%d %d\n' % (mm, commits))
614 fp.close()
615 f.write('</table></div>')
616 f.write('<img src="month_of_year.png" alt="Month of Year" />')
618 # Commits by year/month
619 f.write(html_header(2, 'Commits by year/month'))
620 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
621 for yymm in reversed(sorted(data.commits_by_month.keys())):
622 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
623 f.write('</table></div>')
624 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
625 fg = open(path + '/commits_by_year_month.dat', 'w')
626 for yymm in sorted(data.commits_by_month.keys()):
627 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
628 fg.close()
630 # Commits by year
631 f.write(html_header(2, 'Commits by Year'))
632 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
633 for yy in reversed(sorted(data.commits_by_year.keys())):
634 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()))
635 f.write('</table></div>')
636 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
637 fg = open(path + '/commits_by_year.dat', 'w')
638 for yy in sorted(data.commits_by_year.keys()):
639 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
640 fg.close()
642 f.write('</body></html>')
643 f.close()
646 # Authors
647 f = open(path + '/authors.html', 'w')
648 self.printHeader(f)
650 f.write('<h1>Authors</h1>')
651 self.printNav(f)
653 # Authors :: List of authors
654 f.write(html_header(2, 'List of Authors'))
656 f.write('<table class="authors sortable" id="authors">')
657 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>')
658 for author in sorted(data.getAuthors()):
659 info = data.getAuthorInfo(author)
660 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']))
661 f.write('</table>')
663 # Authors :: Author of Month
664 f.write(html_header(2, 'Author of Month'))
665 f.write('<table class="sortable" id="aom">')
666 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
667 for yymm in reversed(sorted(data.author_of_month.keys())):
668 authordict = data.author_of_month[yymm]
669 authors = getkeyssortedbyvalues(authordict)
670 authors.reverse()
671 commits = data.author_of_month[yymm][authors[0]]
672 next = ', '.join(authors[1:5])
673 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))
675 f.write('</table>')
677 f.write(html_header(2, 'Author of Year'))
678 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>')
679 for yy in reversed(sorted(data.author_of_year.keys())):
680 authordict = data.author_of_year[yy]
681 authors = getkeyssortedbyvalues(authordict)
682 authors.reverse()
683 commits = data.author_of_year[yy][authors[0]]
684 next = ', '.join(authors[1:5])
685 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))
686 f.write('</table>')
688 f.write('</body></html>')
689 f.close()
692 # Files
693 f = open(path + '/files.html', 'w')
694 self.printHeader(f)
695 f.write('<h1>Files</h1>')
696 self.printNav(f)
698 f.write('<dl>\n')
699 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
700 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
701 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
702 f.write('</dl>\n')
704 # Files :: File count by date
705 f.write(html_header(2, 'File count by date'))
707 fg = open(path + '/files_by_date.dat', 'w')
708 for stamp in sorted(data.files_by_stamp.keys()):
709 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
710 fg.close()
712 f.write('<img src="files_by_date.png" alt="Files by Date" />')
714 #f.write('<h2>Average file size by date</h2>')
716 # Files :: Extensions
717 f.write(html_header(2, 'Extensions'))
718 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
719 for ext in sorted(data.extensions.keys()):
720 files = data.extensions[ext]['files']
721 lines = data.extensions[ext]['lines']
722 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))
723 f.write('</table>')
725 f.write('</body></html>')
726 f.close()
729 # Lines
730 f = open(path + '/lines.html', 'w')
731 self.printHeader(f)
732 f.write('<h1>Lines</h1>')
733 self.printNav(f)
735 f.write('<dl>\n')
736 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
737 f.write('</dl>\n')
739 f.write(html_header(2, 'Lines of Code'))
740 f.write('<img src="lines_of_code.png" />')
742 fg = open(path + '/lines_of_code.dat', 'w')
743 for stamp in sorted(data.changes_by_date.keys()):
744 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
745 fg.close()
747 f.write('</body></html>')
748 f.close()
751 # tags.html
752 f = open(path + '/tags.html', 'w')
753 self.printHeader(f)
754 f.write('<h1>Tags</h1>')
755 self.printNav(f)
757 f.write('<dl>')
758 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
759 if len(data.tags) > 0:
760 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
761 f.write('</dl>')
763 f.write('<table>')
764 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
765 # sort the tags by date desc
766 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
767 for tag in tags_sorted_by_date_desc:
768 authorinfo = []
769 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
770 for i in reversed(authors_by_commits):
771 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
772 f.write('<tr><td>%s</td><td>%s</td><td>%d</td><td>%s</td></tr>' % (tag, data.tags[tag]['date'], data.tags[tag]['commits'], ', '.join(authorinfo)))
773 f.write('</table>')
775 f.write('</body></html>')
776 f.close()
778 self.createGraphs(path)
780 def createGraphs(self, path):
781 print 'Generating graphs...'
783 # hour of day
784 f = open(path + '/hour_of_day.plot', 'w')
785 f.write(GNUPLOT_COMMON)
786 f.write(
788 set output 'hour_of_day.png'
789 unset key
790 set xrange [0.5:24.5]
791 set xtics 4
792 set ylabel "Commits"
793 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
794 """)
795 f.close()
797 # day of week
798 f = open(path + '/day_of_week.plot', 'w')
799 f.write(GNUPLOT_COMMON)
800 f.write(
802 set output 'day_of_week.png'
803 unset key
804 set xrange [0.5:7.5]
805 set xtics 1
806 set ylabel "Commits"
807 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
808 """)
809 f.close()
811 # Month of Year
812 f = open(path + '/month_of_year.plot', 'w')
813 f.write(GNUPLOT_COMMON)
814 f.write(
816 set output 'month_of_year.png'
817 unset key
818 set xrange [0.5:12.5]
819 set xtics 1
820 set ylabel "Commits"
821 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
822 """)
823 f.close()
825 # commits_by_year_month
826 f = open(path + '/commits_by_year_month.plot', 'w')
827 f.write(GNUPLOT_COMMON)
828 f.write(
830 set output 'commits_by_year_month.png'
831 unset key
832 set xdata time
833 set timefmt "%Y-%m"
834 set format x "%Y-%m"
835 set xtics rotate by 90 15768000
836 set bmargin 5
837 set ylabel "Commits"
838 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
839 """)
840 f.close()
842 # commits_by_year
843 f = open(path + '/commits_by_year.plot', 'w')
844 f.write(GNUPLOT_COMMON)
845 f.write(
847 set output 'commits_by_year.png'
848 unset key
849 set xtics 1
850 set ylabel "Commits"
851 set yrange [0:]
852 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
853 """)
854 f.close()
856 # Files by date
857 f = open(path + '/files_by_date.plot', 'w')
858 f.write(GNUPLOT_COMMON)
859 f.write(
861 set output 'files_by_date.png'
862 unset key
863 set xdata time
864 set timefmt "%Y-%m-%d"
865 set format x "%Y-%m-%d"
866 set ylabel "Files"
867 set xtics rotate by 90
868 set bmargin 6
869 plot 'files_by_date.dat' using 1:2 w histeps
870 """)
871 f.close()
873 # Lines of Code
874 f = open(path + '/lines_of_code.plot', 'w')
875 f.write(GNUPLOT_COMMON)
876 f.write(
878 set output 'lines_of_code.png'
879 unset key
880 set xdata time
881 set timefmt "%s"
882 set format x "%Y-%m-%d"
883 set ylabel "Lines"
884 set xtics rotate by 90
885 set bmargin 6
886 plot 'lines_of_code.dat' using 1:2 w lines
887 """)
888 f.close()
890 os.chdir(path)
891 files = glob.glob(path + '/*.plot')
892 for f in files:
893 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
894 if len(out) > 0:
895 print out
897 def printHeader(self, f, title = ''):
898 f.write(
899 """<?xml version="1.0" encoding="UTF-8"?>
900 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
901 <html xmlns="http://www.w3.org/1999/xhtml">
902 <head>
903 <title>GitStats - %s</title>
904 <link rel="stylesheet" href="gitstats.css" type="text/css" />
905 <meta name="generator" content="GitStats %s" />
906 <script type="text/javascript" src="sortable.js"></script>
907 </head>
908 <body>
909 """ % (self.title, getversion()))
911 def printNav(self, f):
912 f.write("""
913 <div class="nav">
914 <ul>
915 <li><a href="index.html">General</a></li>
916 <li><a href="activity.html">Activity</a></li>
917 <li><a href="authors.html">Authors</a></li>
918 <li><a href="files.html">Files</a></li>
919 <li><a href="lines.html">Lines</a></li>
920 <li><a href="tags.html">Tags</a></li>
921 </ul>
922 </div>
923 """)
926 usage = """
927 Usage: gitstats [options] <gitpath> <outputpath>
929 Options:
932 if len(sys.argv) < 3:
933 print usage
934 sys.exit(0)
936 gitpath = sys.argv[1]
937 outputpath = os.path.abspath(sys.argv[2])
938 rundir = os.getcwd()
940 try:
941 os.makedirs(outputpath)
942 except OSError:
943 pass
944 if not os.path.isdir(outputpath):
945 print 'FATAL: Output path is not a directory or does not exist'
946 sys.exit(1)
948 print 'Git path: %s' % gitpath
949 print 'Output path: %s' % outputpath
951 os.chdir(gitpath)
953 cachefile = os.path.join(outputpath, 'gitstats.cache')
955 print 'Collecting data...'
956 data = GitDataCollector()
957 data.loadCache(cachefile)
958 data.collect(gitpath)
959 print 'Refining data...'
960 data.saveCache(cachefile)
961 data.refine()
963 os.chdir(rundir)
965 print 'Generating report...'
966 report = HTMLReportCreator()
967 report.create(data, outputpath)
969 time_end = time.time()
970 exectime_internal = time_end - time_start
971 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)