Added 'active days' for authors.
[gitstats.git] / gitstats
blob866bd587b5e3b1696b86caff445d835fe79ea860
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 platform
9 import re
10 import shutil
11 import subprocess
12 import sys
13 import time
14 import zlib
16 GNUPLOT_COMMON = 'set terminal png transparent\nset size 0.5,0.5\n'
17 MAX_EXT_LENGTH = 10 # maximum file extension length
18 ON_LINUX = (platform.system() == 'Linux')
20 exectime_internal = 0.0
21 exectime_external = 0.0
22 time_start = time.time()
24 # By default, gnuplot is searched from path, but can be overridden with the
25 # environment variable "GNUPLOT"
26 gnuplot_cmd = 'gnuplot'
27 if 'GNUPLOT' in os.environ:
28 gnuplot_cmd = os.environ['GNUPLOT']
30 def getpipeoutput(cmds, quiet = False):
31 global exectime_external
32 start = time.time()
33 if not quiet and ON_LINUX and os.isatty(1):
34 print '>> ' + ' | '.join(cmds),
35 sys.stdout.flush()
36 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
37 p = p0
38 for x in cmds[1:]:
39 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
40 p0 = p
41 output = p.communicate()[0]
42 end = time.time()
43 if not quiet:
44 if ON_LINUX and os.isatty(1):
45 print '\r',
46 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
47 exectime_external += (end - start)
48 return output.rstrip('\n')
50 def getkeyssortedbyvalues(dict):
51 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
53 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
54 def getkeyssortedbyvaluekey(d, key):
55 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
57 VERSION = 0
58 def getversion():
59 global VERSION
60 if VERSION == 0:
61 VERSION = getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
62 return VERSION
64 class DataCollector:
65 """Manages data collection from a revision control repository."""
66 def __init__(self):
67 self.stamp_created = time.time()
68 self.cache = {}
71 # This should be the main function to extract data from the repository.
72 def collect(self, dir):
73 self.dir = dir
74 self.projectname = os.path.basename(os.path.abspath(dir))
77 # Load cacheable data
78 def loadCache(self, cachefile):
79 if not os.path.exists(cachefile):
80 return
81 print 'Loading cache...'
82 f = open(cachefile)
83 try:
84 self.cache = pickle.loads(zlib.decompress(f.read()))
85 except:
86 # temporary hack to upgrade non-compressed caches
87 f.seek(0)
88 self.cache = pickle.load(f)
89 f.close()
92 # Produce any additional statistics from the extracted data.
93 def refine(self):
94 pass
97 # : get a dictionary of author
98 def getAuthorInfo(self, author):
99 return None
101 def getActivityByDayOfWeek(self):
102 return {}
104 def getActivityByHourOfDay(self):
105 return {}
108 # Get a list of authors
109 def getAuthors(self):
110 return []
112 def getFirstCommitDate(self):
113 return datetime.datetime.now()
115 def getLastCommitDate(self):
116 return datetime.datetime.now()
118 def getStampCreated(self):
119 return self.stamp_created
121 def getTags(self):
122 return []
124 def getTotalAuthors(self):
125 return -1
127 def getTotalCommits(self):
128 return -1
130 def getTotalFiles(self):
131 return -1
133 def getTotalLOC(self):
134 return -1
137 # Save cacheable data
138 def saveCache(self, filename):
139 print 'Saving cache...'
140 f = open(cachefile, 'w')
141 #pickle.dump(self.cache, f)
142 data = zlib.compress(pickle.dumps(self.cache))
143 f.write(data)
144 f.close()
146 class GitDataCollector(DataCollector):
147 def collect(self, dir):
148 DataCollector.collect(self, dir)
150 try:
151 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
152 except:
153 self.total_authors = 0
154 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
156 self.activity_by_hour_of_day = {} # hour -> commits
157 self.activity_by_day_of_week = {} # day -> commits
158 self.activity_by_month_of_year = {} # month [1-12] -> commits
159 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
160 self.activity_by_hour_of_day_busiest = 0
161 self.activity_by_hour_of_week_busiest = 0
163 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days}
165 # author of the month
166 self.author_of_month = {} # month -> author -> commits
167 self.author_of_year = {} # year -> author -> commits
168 self.commits_by_month = {} # month -> commits
169 self.commits_by_year = {} # year -> commits
170 self.first_commit_stamp = 0
171 self.last_commit_stamp = 0
173 # tags
174 self.tags = {}
175 lines = getpipeoutput(['git show-ref --tags']).split('\n')
176 for line in lines:
177 if len(line) == 0:
178 continue
179 (hash, tag) = line.split(' ')
181 tag = tag.replace('refs/tags/', '')
182 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
183 if len(output) > 0:
184 parts = output.split(' ')
185 stamp = 0
186 try:
187 stamp = int(parts[0])
188 except ValueError:
189 stamp = 0
190 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
192 # collect info on tags, starting from latest
193 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
194 prev = None
195 for tag in reversed(tags_sorted_by_date_desc):
196 cmd = 'git shortlog -s "%s"' % tag
197 if prev != None:
198 cmd += ' "^%s"' % prev
199 output = getpipeoutput([cmd])
200 if len(output) == 0:
201 continue
202 prev = tag
203 for line in output.split('\n'):
204 parts = re.split('\s+', line, 2)
205 commits = int(parts[1])
206 author = parts[2]
207 self.tags[tag]['commits'] += commits
208 self.tags[tag]['authors'][author] = commits
210 # Collect revision statistics
211 # Outputs "<stamp> <author>"
212 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
213 for line in lines:
214 # linux-2.6 says "<unknown>" for one line O_o
215 parts = line.split(' ')
216 author = ''
217 try:
218 stamp = int(parts[0])
219 except ValueError:
220 stamp = 0
221 if len(parts) > 1:
222 author = ' '.join(parts[1:])
223 date = datetime.datetime.fromtimestamp(float(stamp))
225 # First and last commit stamp
226 if self.last_commit_stamp == 0:
227 self.last_commit_stamp = stamp
228 self.first_commit_stamp = stamp
230 # activity
231 # hour
232 hour = date.hour
233 if hour in self.activity_by_hour_of_day:
234 self.activity_by_hour_of_day[hour] += 1
235 else:
236 self.activity_by_hour_of_day[hour] = 1
237 # most active hour?
238 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
239 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
241 # day of week
242 day = date.weekday()
243 if day in self.activity_by_day_of_week:
244 self.activity_by_day_of_week[day] += 1
245 else:
246 self.activity_by_day_of_week[day] = 1
248 # hour of week
249 if day not in self.activity_by_hour_of_week:
250 self.activity_by_hour_of_week[day] = {}
251 if hour not in self.activity_by_hour_of_week[day]:
252 self.activity_by_hour_of_week[day][hour] = 1
253 else:
254 self.activity_by_hour_of_week[day][hour] += 1
255 # most active hour?
256 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
257 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
259 # month of year
260 month = date.month
261 if month in self.activity_by_month_of_year:
262 self.activity_by_month_of_year[month] += 1
263 else:
264 self.activity_by_month_of_year[month] = 1
266 # author stats
267 if author not in self.authors:
268 self.authors[author] = {}
269 # commits
270 if 'last_commit_stamp' not in self.authors[author]:
271 self.authors[author]['last_commit_stamp'] = stamp
272 self.authors[author]['first_commit_stamp'] = stamp
273 if 'commits' in self.authors[author]:
274 self.authors[author]['commits'] += 1
275 else:
276 self.authors[author]['commits'] = 1
278 # author of the month/year
279 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
280 if yymm in self.author_of_month:
281 if author in self.author_of_month[yymm]:
282 self.author_of_month[yymm][author] += 1
283 else:
284 self.author_of_month[yymm][author] = 1
285 else:
286 self.author_of_month[yymm] = {}
287 self.author_of_month[yymm][author] = 1
288 if yymm in self.commits_by_month:
289 self.commits_by_month[yymm] += 1
290 else:
291 self.commits_by_month[yymm] = 1
293 yy = datetime.datetime.fromtimestamp(stamp).year
294 if yy in self.author_of_year:
295 if author in self.author_of_year[yy]:
296 self.author_of_year[yy][author] += 1
297 else:
298 self.author_of_year[yy][author] = 1
299 else:
300 self.author_of_year[yy] = {}
301 self.author_of_year[yy][author] = 1
302 if yy in self.commits_by_year:
303 self.commits_by_year[yy] += 1
304 else:
305 self.commits_by_year[yy] = 1
307 # authors: active days
308 yymmdd = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
309 if 'last_active_day' not in self.authors[author]:
310 self.authors[author]['last_active_day'] = yymmdd
311 self.authors[author]['active_days'] = 1
312 elif yymmdd != self.authors[author]['last_active_day']:
313 self.authors[author]['last_active_day'] = yymmdd
314 self.authors[author]['active_days'] += 1
316 # TODO Optimize this, it's the worst bottleneck
317 # outputs "<stamp> <files>" for each revision
318 self.files_by_stamp = {} # stamp -> files
319 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
320 lines = []
321 for revline in revlines:
322 time, rev = revline.split(' ')
323 linecount = self.getFilesInCommit(rev)
324 lines.append('%d %d' % (int(time), linecount))
326 self.total_commits = len(lines)
327 for line in lines:
328 parts = line.split(' ')
329 if len(parts) != 2:
330 continue
331 (stamp, files) = parts[0:2]
332 try:
333 self.files_by_stamp[int(stamp)] = int(files)
334 except ValueError:
335 print 'Warning: failed to parse line "%s"' % line
337 # extensions
338 self.extensions = {} # extension -> files, lines
339 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
340 self.total_files = len(lines)
341 for line in lines:
342 if len(line) == 0:
343 continue
344 parts = re.split('\s+', line, 4)
345 sha1 = parts[2]
346 filename = parts[3]
348 if filename.find('.') == -1 or filename.rfind('.') == 0:
349 ext = ''
350 else:
351 ext = filename[(filename.rfind('.') + 1):]
352 if len(ext) > MAX_EXT_LENGTH:
353 ext = ''
355 if ext not in self.extensions:
356 self.extensions[ext] = {'files': 0, 'lines': 0}
358 self.extensions[ext]['files'] += 1
359 try:
360 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
361 except:
362 print 'Warning: Could not count lines for file "%s"' % line
364 # line statistics
365 # outputs:
366 # N files changed, N insertions (+), N deletions(-)
367 # <stamp> <author>
368 self.changes_by_date = {} # stamp -> { files, ins, del }
369 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
370 lines.reverse()
371 files = 0; inserted = 0; deleted = 0; total_lines = 0
372 for line in lines:
373 if len(line) == 0:
374 continue
376 # <stamp> <author>
377 if line.find('files changed,') == -1:
378 pos = line.find(' ')
379 if pos != -1:
380 try:
381 (stamp, author) = (int(line[:pos]), line[pos+1:])
382 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
383 except ValueError:
384 print 'Warning: unexpected line "%s"' % line
385 else:
386 print 'Warning: unexpected line "%s"' % line
387 else:
388 numbers = re.findall('\d+', line)
389 if len(numbers) == 3:
390 (files, inserted, deleted) = map(lambda el : int(el), numbers)
391 total_lines += inserted
392 total_lines -= deleted
393 else:
394 print 'Warning: failed to handle line "%s"' % line
395 (files, inserted, deleted) = (0, 0, 0)
396 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
397 self.total_lines = total_lines
399 def refine(self):
400 # authors
401 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
402 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
403 authors_by_commits.reverse() # most first
404 for i, name in enumerate(authors_by_commits):
405 self.authors[name]['place_by_commits'] = i + 1
407 for name in self.authors.keys():
408 a = self.authors[name]
409 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
410 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
411 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
412 delta = date_last - date_first
413 a['date_first'] = date_first.strftime('%Y-%m-%d')
414 a['date_last'] = date_last.strftime('%Y-%m-%d')
415 a['timedelta'] = delta
417 def getActivityByDayOfWeek(self):
418 return self.activity_by_day_of_week
420 def getActivityByHourOfDay(self):
421 return self.activity_by_hour_of_day
423 def getAuthorInfo(self, author):
424 return self.authors[author]
426 def getAuthors(self):
427 return self.authors.keys()
429 def getCommitDeltaDays(self):
430 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
432 def getFilesInCommit(self, rev):
433 try:
434 res = self.cache['files_in_tree'][rev]
435 except:
436 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
437 if 'files_in_tree' not in self.cache:
438 self.cache['files_in_tree'] = {}
439 self.cache['files_in_tree'][rev] = res
441 return res
443 def getFirstCommitDate(self):
444 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
446 def getLastCommitDate(self):
447 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
449 def getTags(self):
450 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
451 return lines.split('\n')
453 def getTagDate(self, tag):
454 return self.revToDate('tags/' + tag)
456 def getTotalAuthors(self):
457 return self.total_authors
459 def getTotalCommits(self):
460 return self.total_commits
462 def getTotalFiles(self):
463 return self.total_files
465 def getTotalLOC(self):
466 return self.total_lines
468 def revToDate(self, rev):
469 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
470 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
472 class ReportCreator:
473 """Creates the actual report based on given data."""
474 def __init__(self):
475 pass
477 def create(self, data, path):
478 self.data = data
479 self.path = path
481 def html_linkify(text):
482 return text.lower().replace(' ', '_')
484 def html_header(level, text):
485 name = html_linkify(text)
486 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
488 class HTMLReportCreator(ReportCreator):
489 def create(self, data, path):
490 ReportCreator.create(self, data, path)
491 self.title = data.projectname
493 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
494 binarypath = os.path.dirname(os.path.abspath(__file__))
495 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
496 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
497 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
498 for base in basedirs:
499 src = base + '/' + file
500 if os.path.exists(src):
501 shutil.copyfile(src, path + '/' + file)
502 break
503 else:
504 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
506 f = open(path + "/index.html", 'w')
507 format = '%Y-%m-%d %H:%M:%S'
508 self.printHeader(f)
510 f.write('<h1>GitStats - %s</h1>' % data.projectname)
512 self.printNav(f)
514 f.write('<dl>')
515 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
516 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
517 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
518 f.write('<dt>Report Period</dt><dd>%s to %s (%d days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays()))
519 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
520 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
521 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
522 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
523 f.write('</dl>')
525 f.write('</body>\n</html>')
526 f.close()
529 # Activity
530 f = open(path + '/activity.html', 'w')
531 self.printHeader(f)
532 f.write('<h1>Activity</h1>')
533 self.printNav(f)
535 #f.write('<h2>Last 30 days</h2>')
537 #f.write('<h2>Last 12 months</h2>')
539 # Hour of Day
540 f.write(html_header(2, 'Hour of Day'))
541 hour_of_day = data.getActivityByHourOfDay()
542 f.write('<table><tr><th>Hour</th>')
543 for i in range(0, 24):
544 f.write('<th>%d</th>' % i)
545 f.write('</tr>\n<tr><th>Commits</th>')
546 fp = open(path + '/hour_of_day.dat', 'w')
547 for i in range(0, 24):
548 if i in hour_of_day:
549 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
550 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
551 fp.write('%d %d\n' % (i, hour_of_day[i]))
552 else:
553 f.write('<td>0</td>')
554 fp.write('%d 0\n' % i)
555 fp.close()
556 f.write('</tr>\n<tr><th>%</th>')
557 totalcommits = data.getTotalCommits()
558 for i in range(0, 24):
559 if i in hour_of_day:
560 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
561 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
562 else:
563 f.write('<td>0.00</td>')
564 f.write('</tr></table>')
565 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
566 fg = open(path + '/hour_of_day.dat', 'w')
567 for i in range(0, 24):
568 if i in hour_of_day:
569 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
570 else:
571 fg.write('%d 0\n' % (i + 1))
572 fg.close()
574 # Day of Week
575 f.write(html_header(2, 'Day of Week'))
576 day_of_week = data.getActivityByDayOfWeek()
577 f.write('<div class="vtable"><table>')
578 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
579 fp = open(path + '/day_of_week.dat', 'w')
580 for d in range(0, 7):
581 commits = 0
582 if d in day_of_week:
583 commits = day_of_week[d]
584 fp.write('%d %d\n' % (d + 1, commits))
585 f.write('<tr>')
586 f.write('<th>%d</th>' % (d + 1))
587 if d in day_of_week:
588 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
589 else:
590 f.write('<td>0</td>')
591 f.write('</tr>')
592 f.write('</table></div>')
593 f.write('<img src="day_of_week.png" alt="Day of Week" />')
594 fp.close()
596 # Hour of Week
597 f.write(html_header(2, 'Hour of Week'))
598 f.write('<table>')
600 f.write('<tr><th>Weekday</th>')
601 for hour in range(0, 24):
602 f.write('<th>%d</th>' % (hour))
603 f.write('</tr>')
605 for weekday in range(0, 7):
606 f.write('<tr><th>%d</th>' % (weekday + 1))
607 for hour in range(0, 24):
608 try:
609 commits = data.activity_by_hour_of_week[weekday][hour]
610 except KeyError:
611 commits = 0
612 if commits != 0:
613 f.write('<td')
614 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
615 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
616 f.write('>%d</td>' % commits)
617 else:
618 f.write('<td></td>')
619 f.write('</tr>')
621 f.write('</table>')
623 # Month of Year
624 f.write(html_header(2, 'Month of Year'))
625 f.write('<div class="vtable"><table>')
626 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
627 fp = open (path + '/month_of_year.dat', 'w')
628 for mm in range(1, 13):
629 commits = 0
630 if mm in data.activity_by_month_of_year:
631 commits = data.activity_by_month_of_year[mm]
632 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
633 fp.write('%d %d\n' % (mm, commits))
634 fp.close()
635 f.write('</table></div>')
636 f.write('<img src="month_of_year.png" alt="Month of Year" />')
638 # Commits by year/month
639 f.write(html_header(2, 'Commits by year/month'))
640 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
641 for yymm in reversed(sorted(data.commits_by_month.keys())):
642 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
643 f.write('</table></div>')
644 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
645 fg = open(path + '/commits_by_year_month.dat', 'w')
646 for yymm in sorted(data.commits_by_month.keys()):
647 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
648 fg.close()
650 # Commits by year
651 f.write(html_header(2, 'Commits by Year'))
652 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
653 for yy in reversed(sorted(data.commits_by_year.keys())):
654 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()))
655 f.write('</table></div>')
656 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
657 fg = open(path + '/commits_by_year.dat', 'w')
658 for yy in sorted(data.commits_by_year.keys()):
659 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
660 fg.close()
662 f.write('</body></html>')
663 f.close()
666 # Authors
667 f = open(path + '/authors.html', 'w')
668 self.printHeader(f)
670 f.write('<h1>Authors</h1>')
671 self.printNav(f)
673 # Authors :: List of authors
674 f.write(html_header(2, 'List of Authors'))
676 f.write('<table class="authors sortable" id="authors">')
677 f.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th class="unsortable">Age</th><th>Active days</th><th># by commits</th></tr>')
678 for author in sorted(data.getAuthors()):
679 info = data.getAuthorInfo(author)
680 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (author, info['commits'], info['commits_frac'], info['date_first'], info['date_last'], info['timedelta'], info['active_days'], info['place_by_commits']))
681 f.write('</table>')
683 # Authors :: Author of Month
684 f.write(html_header(2, 'Author of Month'))
685 f.write('<table class="sortable" id="aom">')
686 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
687 for yymm in reversed(sorted(data.author_of_month.keys())):
688 authordict = data.author_of_month[yymm]
689 authors = getkeyssortedbyvalues(authordict)
690 authors.reverse()
691 commits = data.author_of_month[yymm][authors[0]]
692 next = ', '.join(authors[1:5])
693 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yymm, authors[0], commits, (100.0 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm], next))
695 f.write('</table>')
697 f.write(html_header(2, 'Author of Year'))
698 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>')
699 for yy in reversed(sorted(data.author_of_year.keys())):
700 authordict = data.author_of_year[yy]
701 authors = getkeyssortedbyvalues(authordict)
702 authors.reverse()
703 commits = data.author_of_year[yy][authors[0]]
704 next = ', '.join(authors[1:5])
705 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yy, authors[0], commits, (100.0 * commits) / data.commits_by_year[yy], data.commits_by_year[yy], next))
706 f.write('</table>')
708 f.write('</body></html>')
709 f.close()
712 # Files
713 f = open(path + '/files.html', 'w')
714 self.printHeader(f)
715 f.write('<h1>Files</h1>')
716 self.printNav(f)
718 f.write('<dl>\n')
719 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
720 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
721 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
722 f.write('</dl>\n')
724 # Files :: File count by date
725 f.write(html_header(2, 'File count by date'))
727 fg = open(path + '/files_by_date.dat', 'w')
728 for stamp in sorted(data.files_by_stamp.keys()):
729 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
730 fg.close()
732 f.write('<img src="files_by_date.png" alt="Files by Date" />')
734 #f.write('<h2>Average file size by date</h2>')
736 # Files :: Extensions
737 f.write(html_header(2, 'Extensions'))
738 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
739 for ext in sorted(data.extensions.keys()):
740 files = data.extensions[ext]['files']
741 lines = data.extensions[ext]['lines']
742 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))
743 f.write('</table>')
745 f.write('</body></html>')
746 f.close()
749 # Lines
750 f = open(path + '/lines.html', 'w')
751 self.printHeader(f)
752 f.write('<h1>Lines</h1>')
753 self.printNav(f)
755 f.write('<dl>\n')
756 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
757 f.write('</dl>\n')
759 f.write(html_header(2, 'Lines of Code'))
760 f.write('<img src="lines_of_code.png" />')
762 fg = open(path + '/lines_of_code.dat', 'w')
763 for stamp in sorted(data.changes_by_date.keys()):
764 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
765 fg.close()
767 f.write('</body></html>')
768 f.close()
771 # tags.html
772 f = open(path + '/tags.html', 'w')
773 self.printHeader(f)
774 f.write('<h1>Tags</h1>')
775 self.printNav(f)
777 f.write('<dl>')
778 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
779 if len(data.tags) > 0:
780 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
781 f.write('</dl>')
783 f.write('<table>')
784 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
785 # sort the tags by date desc
786 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
787 for tag in tags_sorted_by_date_desc:
788 authorinfo = []
789 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
790 for i in reversed(authors_by_commits):
791 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
792 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)))
793 f.write('</table>')
795 f.write('</body></html>')
796 f.close()
798 self.createGraphs(path)
800 def createGraphs(self, path):
801 print 'Generating graphs...'
803 # hour of day
804 f = open(path + '/hour_of_day.plot', 'w')
805 f.write(GNUPLOT_COMMON)
806 f.write(
808 set output 'hour_of_day.png'
809 unset key
810 set xrange [0.5:24.5]
811 set xtics 4
812 set ylabel "Commits"
813 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
814 """)
815 f.close()
817 # day of week
818 f = open(path + '/day_of_week.plot', 'w')
819 f.write(GNUPLOT_COMMON)
820 f.write(
822 set output 'day_of_week.png'
823 unset key
824 set xrange [0.5:7.5]
825 set xtics 1
826 set ylabel "Commits"
827 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
828 """)
829 f.close()
831 # Month of Year
832 f = open(path + '/month_of_year.plot', 'w')
833 f.write(GNUPLOT_COMMON)
834 f.write(
836 set output 'month_of_year.png'
837 unset key
838 set xrange [0.5:12.5]
839 set xtics 1
840 set ylabel "Commits"
841 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
842 """)
843 f.close()
845 # commits_by_year_month
846 f = open(path + '/commits_by_year_month.plot', 'w')
847 f.write(GNUPLOT_COMMON)
848 f.write(
850 set output 'commits_by_year_month.png'
851 unset key
852 set xdata time
853 set timefmt "%Y-%m"
854 set format x "%Y-%m"
855 set xtics rotate by 90 15768000
856 set bmargin 5
857 set ylabel "Commits"
858 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
859 """)
860 f.close()
862 # commits_by_year
863 f = open(path + '/commits_by_year.plot', 'w')
864 f.write(GNUPLOT_COMMON)
865 f.write(
867 set output 'commits_by_year.png'
868 unset key
869 set xtics 1
870 set ylabel "Commits"
871 set yrange [0:]
872 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
873 """)
874 f.close()
876 # Files by date
877 f = open(path + '/files_by_date.plot', 'w')
878 f.write(GNUPLOT_COMMON)
879 f.write(
881 set output 'files_by_date.png'
882 unset key
883 set xdata time
884 set timefmt "%Y-%m-%d"
885 set format x "%Y-%m-%d"
886 set ylabel "Files"
887 set xtics rotate by 90
888 set ytics 1
889 set bmargin 6
890 plot 'files_by_date.dat' using 1:2 w steps
891 """)
892 f.close()
894 # Lines of Code
895 f = open(path + '/lines_of_code.plot', 'w')
896 f.write(GNUPLOT_COMMON)
897 f.write(
899 set output 'lines_of_code.png'
900 unset key
901 set xdata time
902 set timefmt "%s"
903 set format x "%Y-%m-%d"
904 set ylabel "Lines"
905 set xtics rotate by 90
906 set bmargin 6
907 plot 'lines_of_code.dat' using 1:2 w lines
908 """)
909 f.close()
911 os.chdir(path)
912 files = glob.glob(path + '/*.plot')
913 for f in files:
914 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
915 if len(out) > 0:
916 print out
918 def printHeader(self, f, title = ''):
919 f.write(
920 """<?xml version="1.0" encoding="UTF-8"?>
921 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
922 <html xmlns="http://www.w3.org/1999/xhtml">
923 <head>
924 <title>GitStats - %s</title>
925 <link rel="stylesheet" href="gitstats.css" type="text/css" />
926 <meta name="generator" content="GitStats %s" />
927 <script type="text/javascript" src="sortable.js"></script>
928 </head>
929 <body>
930 """ % (self.title, getversion()))
932 def printNav(self, f):
933 f.write("""
934 <div class="nav">
935 <ul>
936 <li><a href="index.html">General</a></li>
937 <li><a href="activity.html">Activity</a></li>
938 <li><a href="authors.html">Authors</a></li>
939 <li><a href="files.html">Files</a></li>
940 <li><a href="lines.html">Lines</a></li>
941 <li><a href="tags.html">Tags</a></li>
942 </ul>
943 </div>
944 """)
947 usage = """
948 Usage: gitstats [options] <gitpath> <outputpath>
950 Options:
953 if len(sys.argv) < 3:
954 print usage
955 sys.exit(0)
957 gitpath = sys.argv[1]
958 outputpath = os.path.abspath(sys.argv[2])
959 rundir = os.getcwd()
961 try:
962 os.makedirs(outputpath)
963 except OSError:
964 pass
965 if not os.path.isdir(outputpath):
966 print 'FATAL: Output path is not a directory or does not exist'
967 sys.exit(1)
969 print 'Git path: %s' % gitpath
970 print 'Output path: %s' % outputpath
972 os.chdir(gitpath)
974 cachefile = os.path.join(outputpath, 'gitstats.cache')
976 print 'Collecting data...'
977 data = GitDataCollector()
978 data.loadCache(cachefile)
979 data.collect(gitpath)
980 print 'Refining data...'
981 data.saveCache(cachefile)
982 data.refine()
984 os.chdir(rundir)
986 print 'Generating report...'
987 report = HTMLReportCreator()
988 report.create(data, outputpath)
990 time_end = time.time()
991 exectime_internal = time_end - time_start
992 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)