CSS: margin 'none' -> '0'.
[gitstats.git] / gitstats
blobe06c3a5c3878c9fda5fab051e85bee939b864951
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 cmd = 'git shortlog -s "%s"' % tag
193 if prev != None:
194 cmd += ' "^%s"' % prev
195 output = getpipeoutput([cmd])
196 if len(output) == 0:
197 continue
198 prev = tag
199 for line in output.split('\n'):
200 parts = re.split('\s+', line, 2)
201 commits = int(parts[1])
202 author = parts[2]
203 self.tags[tag]['commits'] += commits
204 self.tags[tag]['authors'][author] = commits
206 # Collect revision statistics
207 # Outputs "<stamp> <author>"
208 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
209 for line in lines:
210 # linux-2.6 says "<unknown>" for one line O_o
211 parts = line.split(' ')
212 author = ''
213 try:
214 stamp = int(parts[0])
215 except ValueError:
216 stamp = 0
217 if len(parts) > 1:
218 author = ' '.join(parts[1:])
219 date = datetime.datetime.fromtimestamp(float(stamp))
221 # First and last commit stamp
222 if self.last_commit_stamp == 0:
223 self.last_commit_stamp = stamp
224 self.first_commit_stamp = stamp
226 # activity
227 # hour
228 hour = date.hour
229 if hour in self.activity_by_hour_of_day:
230 self.activity_by_hour_of_day[hour] += 1
231 else:
232 self.activity_by_hour_of_day[hour] = 1
233 # most active hour?
234 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
235 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
237 # day of week
238 day = date.weekday()
239 if day in self.activity_by_day_of_week:
240 self.activity_by_day_of_week[day] += 1
241 else:
242 self.activity_by_day_of_week[day] = 1
244 # hour of week
245 if day not in self.activity_by_hour_of_week:
246 self.activity_by_hour_of_week[day] = {}
247 if hour not in self.activity_by_hour_of_week[day]:
248 self.activity_by_hour_of_week[day][hour] = 1
249 else:
250 self.activity_by_hour_of_week[day][hour] += 1
251 # most active hour?
252 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
253 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
255 # month of year
256 month = date.month
257 if month in self.activity_by_month_of_year:
258 self.activity_by_month_of_year[month] += 1
259 else:
260 self.activity_by_month_of_year[month] = 1
262 # author stats
263 if author not in self.authors:
264 self.authors[author] = {}
265 # commits
266 if 'last_commit_stamp' not in self.authors[author]:
267 self.authors[author]['last_commit_stamp'] = stamp
268 self.authors[author]['first_commit_stamp'] = stamp
269 if 'commits' in self.authors[author]:
270 self.authors[author]['commits'] += 1
271 else:
272 self.authors[author]['commits'] = 1
274 # author of the month/year
275 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
276 if yymm in self.author_of_month:
277 if author in self.author_of_month[yymm]:
278 self.author_of_month[yymm][author] += 1
279 else:
280 self.author_of_month[yymm][author] = 1
281 else:
282 self.author_of_month[yymm] = {}
283 self.author_of_month[yymm][author] = 1
284 if yymm in self.commits_by_month:
285 self.commits_by_month[yymm] += 1
286 else:
287 self.commits_by_month[yymm] = 1
289 yy = datetime.datetime.fromtimestamp(stamp).year
290 if yy in self.author_of_year:
291 if author in self.author_of_year[yy]:
292 self.author_of_year[yy][author] += 1
293 else:
294 self.author_of_year[yy][author] = 1
295 else:
296 self.author_of_year[yy] = {}
297 self.author_of_year[yy][author] = 1
298 if yy in self.commits_by_year:
299 self.commits_by_year[yy] += 1
300 else:
301 self.commits_by_year[yy] = 1
303 # TODO Optimize this, it's the worst bottleneck
304 # outputs "<stamp> <files>" for each revision
305 self.files_by_stamp = {} # stamp -> files
306 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
307 lines = []
308 for revline in revlines:
309 time, rev = revline.split(' ')
310 linecount = self.getFilesInCommit(rev)
311 lines.append('%d %d' % (int(time), linecount))
313 self.total_commits = len(lines)
314 for line in lines:
315 parts = line.split(' ')
316 if len(parts) != 2:
317 continue
318 (stamp, files) = parts[0:2]
319 try:
320 self.files_by_stamp[int(stamp)] = int(files)
321 except ValueError:
322 print 'Warning: failed to parse line "%s"' % line
324 # extensions
325 self.extensions = {} # extension -> files, lines
326 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
327 self.total_files = len(lines)
328 for line in lines:
329 if len(line) == 0:
330 continue
331 parts = re.split('\s+', line, 4)
332 sha1 = parts[2]
333 filename = parts[3]
335 if filename.find('.') == -1 or filename.rfind('.') == 0:
336 ext = ''
337 else:
338 ext = filename[(filename.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 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
348 except:
349 print 'Warning: Could not count lines for file "%s"' % line
351 # line statistics
352 # outputs:
353 # N files changed, N insertions (+), N deletions(-)
354 # <stamp> <author>
355 self.changes_by_date = {} # stamp -> { files, ins, del }
356 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
357 lines.reverse()
358 files = 0; inserted = 0; deleted = 0; total_lines = 0
359 for line in lines:
360 if len(line) == 0:
361 continue
363 # <stamp> <author>
364 if line.find('files changed,') == -1:
365 pos = line.find(' ')
366 if pos != -1:
367 try:
368 (stamp, author) = (int(line[:pos]), line[pos+1:])
369 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
370 except ValueError:
371 print 'Warning: unexpected line "%s"' % line
372 else:
373 print 'Warning: unexpected line "%s"' % line
374 else:
375 numbers = re.findall('\d+', line)
376 if len(numbers) == 3:
377 (files, inserted, deleted) = map(lambda el : int(el), numbers)
378 total_lines += inserted
379 total_lines -= deleted
380 else:
381 print 'Warning: failed to handle line "%s"' % line
382 (files, inserted, deleted) = (0, 0, 0)
383 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
384 self.total_lines = total_lines
386 def refine(self):
387 # authors
388 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
389 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
390 authors_by_commits.reverse() # most first
391 for i, name in enumerate(authors_by_commits):
392 self.authors[name]['place_by_commits'] = i + 1
394 for name in self.authors.keys():
395 a = self.authors[name]
396 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
397 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
398 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
399 delta = date_last - date_first
400 a['date_first'] = date_first.strftime('%Y-%m-%d')
401 a['date_last'] = date_last.strftime('%Y-%m-%d')
402 a['timedelta'] = delta
404 def getActivityByDayOfWeek(self):
405 return self.activity_by_day_of_week
407 def getActivityByHourOfDay(self):
408 return self.activity_by_hour_of_day
410 def getAuthorInfo(self, author):
411 return self.authors[author]
413 def getAuthors(self):
414 return self.authors.keys()
416 def getCommitDeltaDays(self):
417 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
419 def getFilesInCommit(self, rev):
420 try:
421 res = self.cache['files_in_tree'][rev]
422 except:
423 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
424 if 'files_in_tree' not in self.cache:
425 self.cache['files_in_tree'] = {}
426 self.cache['files_in_tree'][rev] = res
428 return res
430 def getFirstCommitDate(self):
431 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
433 def getLastCommitDate(self):
434 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
436 def getTags(self):
437 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
438 return lines.split('\n')
440 def getTagDate(self, tag):
441 return self.revToDate('tags/' + tag)
443 def getTotalAuthors(self):
444 return self.total_authors
446 def getTotalCommits(self):
447 return self.total_commits
449 def getTotalFiles(self):
450 return self.total_files
452 def getTotalLOC(self):
453 return self.total_lines
455 def revToDate(self, rev):
456 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
457 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
459 class ReportCreator:
460 """Creates the actual report based on given data."""
461 def __init__(self):
462 pass
464 def create(self, data, path):
465 self.data = data
466 self.path = path
468 def html_linkify(text):
469 return text.lower().replace(' ', '_')
471 def html_header(level, text):
472 name = html_linkify(text)
473 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
475 class HTMLReportCreator(ReportCreator):
476 def create(self, data, path):
477 ReportCreator.create(self, data, path)
478 self.title = data.projectname
480 # copy static files if they do not exist
481 basedirs = [os.path.dirname(os.path.abspath(__file__)), '/usr/share/gitstats']
482 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
483 for base in basedirs:
484 src = base + '/' + file
485 if os.path.exists(src):
486 shutil.copyfile(src, path + '/' + file)
487 break
488 else:
489 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
491 f = open(path + "/index.html", 'w')
492 format = '%Y-%m-%d %H:%M:%S'
493 self.printHeader(f)
495 f.write('<h1>GitStats - %s</h1>' % data.projectname)
497 self.printNav(f)
499 f.write('<dl>')
500 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
501 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
502 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
503 f.write('<dt>Report Period</dt><dd>%s to %s (%d days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays()))
504 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
505 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
506 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
507 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
508 f.write('</dl>')
510 f.write('</body>\n</html>')
511 f.close()
514 # Activity
515 f = open(path + '/activity.html', 'w')
516 self.printHeader(f)
517 f.write('<h1>Activity</h1>')
518 self.printNav(f)
520 #f.write('<h2>Last 30 days</h2>')
522 #f.write('<h2>Last 12 months</h2>')
524 # Hour of Day
525 f.write(html_header(2, 'Hour of Day'))
526 hour_of_day = data.getActivityByHourOfDay()
527 f.write('<table><tr><th>Hour</th>')
528 for i in range(0, 24):
529 f.write('<th>%d</th>' % i)
530 f.write('</tr>\n<tr><th>Commits</th>')
531 fp = open(path + '/hour_of_day.dat', 'w')
532 for i in range(0, 24):
533 if i in hour_of_day:
534 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
535 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
536 fp.write('%d %d\n' % (i, hour_of_day[i]))
537 else:
538 f.write('<td>0</td>')
539 fp.write('%d 0\n' % i)
540 fp.close()
541 f.write('</tr>\n<tr><th>%</th>')
542 totalcommits = data.getTotalCommits()
543 for i in range(0, 24):
544 if i in hour_of_day:
545 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
546 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
547 else:
548 f.write('<td>0.00</td>')
549 f.write('</tr></table>')
550 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
551 fg = open(path + '/hour_of_day.dat', 'w')
552 for i in range(0, 24):
553 if i in hour_of_day:
554 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
555 else:
556 fg.write('%d 0\n' % (i + 1))
557 fg.close()
559 # Day of Week
560 f.write(html_header(2, 'Day of Week'))
561 day_of_week = data.getActivityByDayOfWeek()
562 f.write('<div class="vtable"><table>')
563 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
564 fp = open(path + '/day_of_week.dat', 'w')
565 for d in range(0, 7):
566 commits = 0
567 if d in day_of_week:
568 commits = day_of_week[d]
569 fp.write('%d %d\n' % (d + 1, commits))
570 f.write('<tr>')
571 f.write('<th>%d</th>' % (d + 1))
572 if d in day_of_week:
573 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
574 else:
575 f.write('<td>0</td>')
576 f.write('</tr>')
577 f.write('</table></div>')
578 f.write('<img src="day_of_week.png" alt="Day of Week" />')
579 fp.close()
581 # Hour of Week
582 f.write(html_header(2, 'Hour of Week'))
583 f.write('<table>')
585 f.write('<tr><th>Weekday</th>')
586 for hour in range(0, 24):
587 f.write('<th>%d</th>' % (hour))
588 f.write('</tr>')
590 for weekday in range(0, 7):
591 f.write('<tr><th>%d</th>' % (weekday + 1))
592 for hour in range(0, 24):
593 try:
594 commits = data.activity_by_hour_of_week[weekday][hour]
595 except KeyError:
596 commits = 0
597 if commits != 0:
598 f.write('<td')
599 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
600 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
601 f.write('>%d</td>' % commits)
602 else:
603 f.write('<td></td>')
604 f.write('</tr>')
606 f.write('</table>')
608 # Month of Year
609 f.write(html_header(2, 'Month of Year'))
610 f.write('<div class="vtable"><table>')
611 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
612 fp = open (path + '/month_of_year.dat', 'w')
613 for mm in range(1, 13):
614 commits = 0
615 if mm in data.activity_by_month_of_year:
616 commits = data.activity_by_month_of_year[mm]
617 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
618 fp.write('%d %d\n' % (mm, commits))
619 fp.close()
620 f.write('</table></div>')
621 f.write('<img src="month_of_year.png" alt="Month of Year" />')
623 # Commits by year/month
624 f.write(html_header(2, 'Commits by year/month'))
625 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
626 for yymm in reversed(sorted(data.commits_by_month.keys())):
627 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
628 f.write('</table></div>')
629 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
630 fg = open(path + '/commits_by_year_month.dat', 'w')
631 for yymm in sorted(data.commits_by_month.keys()):
632 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
633 fg.close()
635 # Commits by year
636 f.write(html_header(2, 'Commits by Year'))
637 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
638 for yy in reversed(sorted(data.commits_by_year.keys())):
639 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()))
640 f.write('</table></div>')
641 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
642 fg = open(path + '/commits_by_year.dat', 'w')
643 for yy in sorted(data.commits_by_year.keys()):
644 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
645 fg.close()
647 f.write('</body></html>')
648 f.close()
651 # Authors
652 f = open(path + '/authors.html', 'w')
653 self.printHeader(f)
655 f.write('<h1>Authors</h1>')
656 self.printNav(f)
658 # Authors :: List of authors
659 f.write(html_header(2, 'List of Authors'))
661 f.write('<table class="authors sortable" id="authors">')
662 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>')
663 for author in sorted(data.getAuthors()):
664 info = data.getAuthorInfo(author)
665 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']))
666 f.write('</table>')
668 # Authors :: Author of Month
669 f.write(html_header(2, 'Author of Month'))
670 f.write('<table class="sortable" id="aom">')
671 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
672 for yymm in reversed(sorted(data.author_of_month.keys())):
673 authordict = data.author_of_month[yymm]
674 authors = getkeyssortedbyvalues(authordict)
675 authors.reverse()
676 commits = data.author_of_month[yymm][authors[0]]
677 next = ', '.join(authors[1:5])
678 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))
680 f.write('</table>')
682 f.write(html_header(2, 'Author of Year'))
683 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>')
684 for yy in reversed(sorted(data.author_of_year.keys())):
685 authordict = data.author_of_year[yy]
686 authors = getkeyssortedbyvalues(authordict)
687 authors.reverse()
688 commits = data.author_of_year[yy][authors[0]]
689 next = ', '.join(authors[1:5])
690 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))
691 f.write('</table>')
693 f.write('</body></html>')
694 f.close()
697 # Files
698 f = open(path + '/files.html', 'w')
699 self.printHeader(f)
700 f.write('<h1>Files</h1>')
701 self.printNav(f)
703 f.write('<dl>\n')
704 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
705 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
706 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
707 f.write('</dl>\n')
709 # Files :: File count by date
710 f.write(html_header(2, 'File count by date'))
712 fg = open(path + '/files_by_date.dat', 'w')
713 for stamp in sorted(data.files_by_stamp.keys()):
714 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
715 fg.close()
717 f.write('<img src="files_by_date.png" alt="Files by Date" />')
719 #f.write('<h2>Average file size by date</h2>')
721 # Files :: Extensions
722 f.write(html_header(2, 'Extensions'))
723 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
724 for ext in sorted(data.extensions.keys()):
725 files = data.extensions[ext]['files']
726 lines = data.extensions[ext]['lines']
727 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))
728 f.write('</table>')
730 f.write('</body></html>')
731 f.close()
734 # Lines
735 f = open(path + '/lines.html', 'w')
736 self.printHeader(f)
737 f.write('<h1>Lines</h1>')
738 self.printNav(f)
740 f.write('<dl>\n')
741 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
742 f.write('</dl>\n')
744 f.write(html_header(2, 'Lines of Code'))
745 f.write('<img src="lines_of_code.png" />')
747 fg = open(path + '/lines_of_code.dat', 'w')
748 for stamp in sorted(data.changes_by_date.keys()):
749 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
750 fg.close()
752 f.write('</body></html>')
753 f.close()
756 # tags.html
757 f = open(path + '/tags.html', 'w')
758 self.printHeader(f)
759 f.write('<h1>Tags</h1>')
760 self.printNav(f)
762 f.write('<dl>')
763 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
764 if len(data.tags) > 0:
765 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (data.getTotalCommits() / len(data.tags)))
766 f.write('</dl>')
768 f.write('<table>')
769 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
770 # sort the tags by date desc
771 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
772 for tag in tags_sorted_by_date_desc:
773 authorinfo = []
774 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
775 for i in reversed(authors_by_commits):
776 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
777 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)))
778 f.write('</table>')
780 f.write('</body></html>')
781 f.close()
783 self.createGraphs(path)
785 def createGraphs(self, path):
786 print 'Generating graphs...'
788 # hour of day
789 f = open(path + '/hour_of_day.plot', 'w')
790 f.write(GNUPLOT_COMMON)
791 f.write(
793 set output 'hour_of_day.png'
794 unset key
795 set xrange [0.5:24.5]
796 set xtics 4
797 set ylabel "Commits"
798 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
799 """)
800 f.close()
802 # day of week
803 f = open(path + '/day_of_week.plot', 'w')
804 f.write(GNUPLOT_COMMON)
805 f.write(
807 set output 'day_of_week.png'
808 unset key
809 set xrange [0.5:7.5]
810 set xtics 1
811 set ylabel "Commits"
812 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
813 """)
814 f.close()
816 # Month of Year
817 f = open(path + '/month_of_year.plot', 'w')
818 f.write(GNUPLOT_COMMON)
819 f.write(
821 set output 'month_of_year.png'
822 unset key
823 set xrange [0.5:12.5]
824 set xtics 1
825 set ylabel "Commits"
826 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
827 """)
828 f.close()
830 # commits_by_year_month
831 f = open(path + '/commits_by_year_month.plot', 'w')
832 f.write(GNUPLOT_COMMON)
833 f.write(
835 set output 'commits_by_year_month.png'
836 unset key
837 set xdata time
838 set timefmt "%Y-%m"
839 set format x "%Y-%m"
840 set xtics rotate by 90 15768000
841 set bmargin 5
842 set ylabel "Commits"
843 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
844 """)
845 f.close()
847 # commits_by_year
848 f = open(path + '/commits_by_year.plot', 'w')
849 f.write(GNUPLOT_COMMON)
850 f.write(
852 set output 'commits_by_year.png'
853 unset key
854 set xtics 1
855 set ylabel "Commits"
856 set yrange [0:]
857 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
858 """)
859 f.close()
861 # Files by date
862 f = open(path + '/files_by_date.plot', 'w')
863 f.write(GNUPLOT_COMMON)
864 f.write(
866 set output 'files_by_date.png'
867 unset key
868 set xdata time
869 set timefmt "%Y-%m-%d"
870 set format x "%Y-%m-%d"
871 set ylabel "Files"
872 set xtics rotate by 90
873 set bmargin 6
874 plot 'files_by_date.dat' using 1:2 w steps
875 """)
876 f.close()
878 # Lines of Code
879 f = open(path + '/lines_of_code.plot', 'w')
880 f.write(GNUPLOT_COMMON)
881 f.write(
883 set output 'lines_of_code.png'
884 unset key
885 set xdata time
886 set timefmt "%s"
887 set format x "%Y-%m-%d"
888 set ylabel "Lines"
889 set xtics rotate by 90
890 set bmargin 6
891 plot 'lines_of_code.dat' using 1:2 w lines
892 """)
893 f.close()
895 os.chdir(path)
896 files = glob.glob(path + '/*.plot')
897 for f in files:
898 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
899 if len(out) > 0:
900 print out
902 def printHeader(self, f, title = ''):
903 f.write(
904 """<?xml version="1.0" encoding="UTF-8"?>
905 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
906 <html xmlns="http://www.w3.org/1999/xhtml">
907 <head>
908 <title>GitStats - %s</title>
909 <link rel="stylesheet" href="gitstats.css" type="text/css" />
910 <meta name="generator" content="GitStats %s" />
911 <script type="text/javascript" src="sortable.js"></script>
912 </head>
913 <body>
914 """ % (self.title, getversion()))
916 def printNav(self, f):
917 f.write("""
918 <div class="nav">
919 <ul>
920 <li><a href="index.html">General</a></li>
921 <li><a href="activity.html">Activity</a></li>
922 <li><a href="authors.html">Authors</a></li>
923 <li><a href="files.html">Files</a></li>
924 <li><a href="lines.html">Lines</a></li>
925 <li><a href="tags.html">Tags</a></li>
926 </ul>
927 </div>
928 """)
931 usage = """
932 Usage: gitstats [options] <gitpath> <outputpath>
934 Options:
937 if len(sys.argv) < 3:
938 print usage
939 sys.exit(0)
941 gitpath = sys.argv[1]
942 outputpath = os.path.abspath(sys.argv[2])
943 rundir = os.getcwd()
945 try:
946 os.makedirs(outputpath)
947 except OSError:
948 pass
949 if not os.path.isdir(outputpath):
950 print 'FATAL: Output path is not a directory or does not exist'
951 sys.exit(1)
953 print 'Git path: %s' % gitpath
954 print 'Output path: %s' % outputpath
956 os.chdir(gitpath)
958 cachefile = os.path.join(outputpath, 'gitstats.cache')
960 print 'Collecting data...'
961 data = GitDataCollector()
962 data.loadCache(cachefile)
963 data.collect(gitpath)
964 print 'Refining data...'
965 data.saveCache(cachefile)
966 data.refine()
968 os.chdir(rundir)
970 print 'Generating report...'
971 report = HTMLReportCreator()
972 report.create(data, outputpath)
974 time_end = time.time()
975 exectime_internal = time_end - time_start
976 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)