todo: remove some items.
[gitstats.git] / gitstats
blob25e704b159a86ecf410ecdd0b3e035ef4bb105a4
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
172 self.last_active_day = None
173 self.active_days = 0
175 # tags
176 self.tags = {}
177 lines = getpipeoutput(['git show-ref --tags']).split('\n')
178 for line in lines:
179 if len(line) == 0:
180 continue
181 (hash, tag) = line.split(' ')
183 tag = tag.replace('refs/tags/', '')
184 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
185 if len(output) > 0:
186 parts = output.split(' ')
187 stamp = 0
188 try:
189 stamp = int(parts[0])
190 except ValueError:
191 stamp = 0
192 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
194 # collect info on tags, starting from latest
195 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
196 prev = None
197 for tag in reversed(tags_sorted_by_date_desc):
198 cmd = 'git shortlog -s "%s"' % tag
199 if prev != None:
200 cmd += ' "^%s"' % prev
201 output = getpipeoutput([cmd])
202 if len(output) == 0:
203 continue
204 prev = tag
205 for line in output.split('\n'):
206 parts = re.split('\s+', line, 2)
207 commits = int(parts[1])
208 author = parts[2]
209 self.tags[tag]['commits'] += commits
210 self.tags[tag]['authors'][author] = commits
212 # Collect revision statistics
213 # Outputs "<stamp> <author>"
214 lines = getpipeoutput(['git rev-list --pretty=format:"%at %an" HEAD', 'grep -v ^commit']).split('\n')
215 for line in lines:
216 # linux-2.6 says "<unknown>" for one line O_o
217 parts = line.split(' ')
218 author = ''
219 try:
220 stamp = int(parts[0])
221 except ValueError:
222 stamp = 0
223 if len(parts) > 1:
224 author = ' '.join(parts[1:])
225 date = datetime.datetime.fromtimestamp(float(stamp))
227 # First and last commit stamp
228 if self.last_commit_stamp == 0:
229 self.last_commit_stamp = stamp
230 self.first_commit_stamp = stamp
232 # activity
233 # hour
234 hour = date.hour
235 if hour in self.activity_by_hour_of_day:
236 self.activity_by_hour_of_day[hour] += 1
237 else:
238 self.activity_by_hour_of_day[hour] = 1
239 # most active hour?
240 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
241 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
243 # day of week
244 day = date.weekday()
245 if day in self.activity_by_day_of_week:
246 self.activity_by_day_of_week[day] += 1
247 else:
248 self.activity_by_day_of_week[day] = 1
250 # hour of week
251 if day not in self.activity_by_hour_of_week:
252 self.activity_by_hour_of_week[day] = {}
253 if hour not in self.activity_by_hour_of_week[day]:
254 self.activity_by_hour_of_week[day][hour] = 1
255 else:
256 self.activity_by_hour_of_week[day][hour] += 1
257 # most active hour?
258 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
259 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
261 # month of year
262 month = date.month
263 if month in self.activity_by_month_of_year:
264 self.activity_by_month_of_year[month] += 1
265 else:
266 self.activity_by_month_of_year[month] = 1
268 # author stats
269 if author not in self.authors:
270 self.authors[author] = {}
271 # commits
272 if 'last_commit_stamp' not in self.authors[author]:
273 self.authors[author]['last_commit_stamp'] = stamp
274 self.authors[author]['first_commit_stamp'] = stamp
275 if 'commits' in self.authors[author]:
276 self.authors[author]['commits'] += 1
277 else:
278 self.authors[author]['commits'] = 1
280 # author of the month/year
281 yymm = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m')
282 if yymm in self.author_of_month:
283 if author in self.author_of_month[yymm]:
284 self.author_of_month[yymm][author] += 1
285 else:
286 self.author_of_month[yymm][author] = 1
287 else:
288 self.author_of_month[yymm] = {}
289 self.author_of_month[yymm][author] = 1
290 if yymm in self.commits_by_month:
291 self.commits_by_month[yymm] += 1
292 else:
293 self.commits_by_month[yymm] = 1
295 yy = datetime.datetime.fromtimestamp(stamp).year
296 if yy in self.author_of_year:
297 if author in self.author_of_year[yy]:
298 self.author_of_year[yy][author] += 1
299 else:
300 self.author_of_year[yy][author] = 1
301 else:
302 self.author_of_year[yy] = {}
303 self.author_of_year[yy][author] = 1
304 if yy in self.commits_by_year:
305 self.commits_by_year[yy] += 1
306 else:
307 self.commits_by_year[yy] = 1
309 # authors: active days
310 yymmdd = datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
311 if 'last_active_day' not in self.authors[author]:
312 self.authors[author]['last_active_day'] = yymmdd
313 self.authors[author]['active_days'] = 1
314 elif yymmdd != self.authors[author]['last_active_day']:
315 self.authors[author]['last_active_day'] = yymmdd
316 self.authors[author]['active_days'] += 1
318 # project: active days
319 if yymmdd != self.last_active_day:
320 self.last_active_day = yymmdd
321 self.active_days += 1
323 # TODO Optimize this, it's the worst bottleneck
324 # outputs "<stamp> <files>" for each revision
325 self.files_by_stamp = {} # stamp -> files
326 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
327 lines = []
328 for revline in revlines:
329 time, rev = revline.split(' ')
330 linecount = self.getFilesInCommit(rev)
331 lines.append('%d %d' % (int(time), linecount))
333 self.total_commits = len(lines)
334 for line in lines:
335 parts = line.split(' ')
336 if len(parts) != 2:
337 continue
338 (stamp, files) = parts[0:2]
339 try:
340 self.files_by_stamp[int(stamp)] = int(files)
341 except ValueError:
342 print 'Warning: failed to parse line "%s"' % line
344 # extensions
345 self.extensions = {} # extension -> files, lines
346 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
347 self.total_files = len(lines)
348 for line in lines:
349 if len(line) == 0:
350 continue
351 parts = re.split('\s+', line, 4)
352 sha1 = parts[2]
353 filename = parts[3]
355 if filename.find('.') == -1 or filename.rfind('.') == 0:
356 ext = ''
357 else:
358 ext = filename[(filename.rfind('.') + 1):]
359 if len(ext) > MAX_EXT_LENGTH:
360 ext = ''
362 if ext not in self.extensions:
363 self.extensions[ext] = {'files': 0, 'lines': 0}
365 self.extensions[ext]['files'] += 1
366 try:
367 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
368 except:
369 print 'Warning: Could not count lines for file "%s"' % line
371 # line statistics
372 # outputs:
373 # N files changed, N insertions (+), N deletions(-)
374 # <stamp> <author>
375 self.changes_by_date = {} # stamp -> { files, ins, del }
376 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
377 lines.reverse()
378 files = 0; inserted = 0; deleted = 0; total_lines = 0
379 for line in lines:
380 if len(line) == 0:
381 continue
383 # <stamp> <author>
384 if line.find('files changed,') == -1:
385 pos = line.find(' ')
386 if pos != -1:
387 try:
388 (stamp, author) = (int(line[:pos]), line[pos+1:])
389 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
390 except ValueError:
391 print 'Warning: unexpected line "%s"' % line
392 else:
393 print 'Warning: unexpected line "%s"' % line
394 else:
395 numbers = re.findall('\d+', line)
396 if len(numbers) == 3:
397 (files, inserted, deleted) = map(lambda el : int(el), numbers)
398 total_lines += inserted
399 total_lines -= deleted
400 else:
401 print 'Warning: failed to handle line "%s"' % line
402 (files, inserted, deleted) = (0, 0, 0)
403 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
404 self.total_lines = total_lines
406 def refine(self):
407 # authors
408 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
409 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
410 authors_by_commits.reverse() # most first
411 for i, name in enumerate(authors_by_commits):
412 self.authors[name]['place_by_commits'] = i + 1
414 for name in self.authors.keys():
415 a = self.authors[name]
416 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
417 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
418 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
419 delta = date_last - date_first
420 a['date_first'] = date_first.strftime('%Y-%m-%d')
421 a['date_last'] = date_last.strftime('%Y-%m-%d')
422 a['timedelta'] = delta
424 def getActiveDays(self):
425 return self.active_days
427 def getActivityByDayOfWeek(self):
428 return self.activity_by_day_of_week
430 def getActivityByHourOfDay(self):
431 return self.activity_by_hour_of_day
433 def getAuthorInfo(self, author):
434 return self.authors[author]
436 def getAuthors(self):
437 return self.authors.keys()
439 def getCommitDeltaDays(self):
440 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
442 def getFilesInCommit(self, rev):
443 try:
444 res = self.cache['files_in_tree'][rev]
445 except:
446 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
447 if 'files_in_tree' not in self.cache:
448 self.cache['files_in_tree'] = {}
449 self.cache['files_in_tree'][rev] = res
451 return res
453 def getFirstCommitDate(self):
454 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
456 def getLastCommitDate(self):
457 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
459 def getTags(self):
460 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
461 return lines.split('\n')
463 def getTagDate(self, tag):
464 return self.revToDate('tags/' + tag)
466 def getTotalAuthors(self):
467 return self.total_authors
469 def getTotalCommits(self):
470 return self.total_commits
472 def getTotalFiles(self):
473 return self.total_files
475 def getTotalLOC(self):
476 return self.total_lines
478 def revToDate(self, rev):
479 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
480 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
482 class ReportCreator:
483 """Creates the actual report based on given data."""
484 def __init__(self):
485 pass
487 def create(self, data, path):
488 self.data = data
489 self.path = path
491 def html_linkify(text):
492 return text.lower().replace(' ', '_')
494 def html_header(level, text):
495 name = html_linkify(text)
496 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
498 class HTMLReportCreator(ReportCreator):
499 def create(self, data, path):
500 ReportCreator.create(self, data, path)
501 self.title = data.projectname
503 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
504 binarypath = os.path.dirname(os.path.abspath(__file__))
505 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
506 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
507 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
508 for base in basedirs:
509 src = base + '/' + file
510 if os.path.exists(src):
511 shutil.copyfile(src, path + '/' + file)
512 break
513 else:
514 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
516 f = open(path + "/index.html", 'w')
517 format = '%Y-%m-%d %H:%M:%S'
518 self.printHeader(f)
520 f.write('<h1>GitStats - %s</h1>' % data.projectname)
522 self.printNav(f)
524 f.write('<dl>')
525 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
526 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
527 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
528 f.write('<dt>Report Period</dt><dd>%s to %s (%d days, %d active days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays(), data.getActiveDays()))
529 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
530 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
531 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
532 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
533 f.write('</dl>')
535 f.write('</body>\n</html>')
536 f.close()
539 # Activity
540 f = open(path + '/activity.html', 'w')
541 self.printHeader(f)
542 f.write('<h1>Activity</h1>')
543 self.printNav(f)
545 #f.write('<h2>Last 30 days</h2>')
547 #f.write('<h2>Last 12 months</h2>')
549 # Hour of Day
550 f.write(html_header(2, 'Hour of Day'))
551 hour_of_day = data.getActivityByHourOfDay()
552 f.write('<table><tr><th>Hour</th>')
553 for i in range(0, 24):
554 f.write('<th>%d</th>' % i)
555 f.write('</tr>\n<tr><th>Commits</th>')
556 fp = open(path + '/hour_of_day.dat', 'w')
557 for i in range(0, 24):
558 if i in hour_of_day:
559 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
560 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
561 fp.write('%d %d\n' % (i, hour_of_day[i]))
562 else:
563 f.write('<td>0</td>')
564 fp.write('%d 0\n' % i)
565 fp.close()
566 f.write('</tr>\n<tr><th>%</th>')
567 totalcommits = data.getTotalCommits()
568 for i in range(0, 24):
569 if i in hour_of_day:
570 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
571 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
572 else:
573 f.write('<td>0.00</td>')
574 f.write('</tr></table>')
575 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
576 fg = open(path + '/hour_of_day.dat', 'w')
577 for i in range(0, 24):
578 if i in hour_of_day:
579 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
580 else:
581 fg.write('%d 0\n' % (i + 1))
582 fg.close()
584 # Day of Week
585 f.write(html_header(2, 'Day of Week'))
586 day_of_week = data.getActivityByDayOfWeek()
587 f.write('<div class="vtable"><table>')
588 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
589 fp = open(path + '/day_of_week.dat', 'w')
590 for d in range(0, 7):
591 commits = 0
592 if d in day_of_week:
593 commits = day_of_week[d]
594 fp.write('%d %d\n' % (d + 1, commits))
595 f.write('<tr>')
596 f.write('<th>%d</th>' % (d + 1))
597 if d in day_of_week:
598 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
599 else:
600 f.write('<td>0</td>')
601 f.write('</tr>')
602 f.write('</table></div>')
603 f.write('<img src="day_of_week.png" alt="Day of Week" />')
604 fp.close()
606 # Hour of Week
607 f.write(html_header(2, 'Hour of Week'))
608 f.write('<table>')
610 f.write('<tr><th>Weekday</th>')
611 for hour in range(0, 24):
612 f.write('<th>%d</th>' % (hour))
613 f.write('</tr>')
615 for weekday in range(0, 7):
616 f.write('<tr><th>%d</th>' % (weekday + 1))
617 for hour in range(0, 24):
618 try:
619 commits = data.activity_by_hour_of_week[weekday][hour]
620 except KeyError:
621 commits = 0
622 if commits != 0:
623 f.write('<td')
624 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
625 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
626 f.write('>%d</td>' % commits)
627 else:
628 f.write('<td></td>')
629 f.write('</tr>')
631 f.write('</table>')
633 # Month of Year
634 f.write(html_header(2, 'Month of Year'))
635 f.write('<div class="vtable"><table>')
636 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
637 fp = open (path + '/month_of_year.dat', 'w')
638 for mm in range(1, 13):
639 commits = 0
640 if mm in data.activity_by_month_of_year:
641 commits = data.activity_by_month_of_year[mm]
642 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
643 fp.write('%d %d\n' % (mm, commits))
644 fp.close()
645 f.write('</table></div>')
646 f.write('<img src="month_of_year.png" alt="Month of Year" />')
648 # Commits by year/month
649 f.write(html_header(2, 'Commits by year/month'))
650 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
651 for yymm in reversed(sorted(data.commits_by_month.keys())):
652 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
653 f.write('</table></div>')
654 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
655 fg = open(path + '/commits_by_year_month.dat', 'w')
656 for yymm in sorted(data.commits_by_month.keys()):
657 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
658 fg.close()
660 # Commits by year
661 f.write(html_header(2, 'Commits by Year'))
662 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
663 for yy in reversed(sorted(data.commits_by_year.keys())):
664 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()))
665 f.write('</table></div>')
666 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
667 fg = open(path + '/commits_by_year.dat', 'w')
668 for yy in sorted(data.commits_by_year.keys()):
669 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
670 fg.close()
672 f.write('</body></html>')
673 f.close()
676 # Authors
677 f = open(path + '/authors.html', 'w')
678 self.printHeader(f)
680 f.write('<h1>Authors</h1>')
681 self.printNav(f)
683 # Authors :: List of authors
684 f.write(html_header(2, 'List of Authors'))
686 f.write('<table class="authors sortable" id="authors">')
687 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>')
688 for author in sorted(data.getAuthors()):
689 info = data.getAuthorInfo(author)
690 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']))
691 f.write('</table>')
693 # Authors :: Author of Month
694 f.write(html_header(2, 'Author of Month'))
695 f.write('<table class="sortable" id="aom">')
696 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
697 for yymm in reversed(sorted(data.author_of_month.keys())):
698 authordict = data.author_of_month[yymm]
699 authors = getkeyssortedbyvalues(authordict)
700 authors.reverse()
701 commits = data.author_of_month[yymm][authors[0]]
702 next = ', '.join(authors[1:5])
703 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))
705 f.write('</table>')
707 f.write(html_header(2, 'Author of Year'))
708 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>')
709 for yy in reversed(sorted(data.author_of_year.keys())):
710 authordict = data.author_of_year[yy]
711 authors = getkeyssortedbyvalues(authordict)
712 authors.reverse()
713 commits = data.author_of_year[yy][authors[0]]
714 next = ', '.join(authors[1:5])
715 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))
716 f.write('</table>')
718 f.write('</body></html>')
719 f.close()
722 # Files
723 f = open(path + '/files.html', 'w')
724 self.printHeader(f)
725 f.write('<h1>Files</h1>')
726 self.printNav(f)
728 f.write('<dl>\n')
729 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
730 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
731 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
732 f.write('</dl>\n')
734 # Files :: File count by date
735 f.write(html_header(2, 'File count by date'))
737 fg = open(path + '/files_by_date.dat', 'w')
738 for stamp in sorted(data.files_by_stamp.keys()):
739 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
740 fg.close()
742 f.write('<img src="files_by_date.png" alt="Files by Date" />')
744 #f.write('<h2>Average file size by date</h2>')
746 # Files :: Extensions
747 f.write(html_header(2, 'Extensions'))
748 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
749 for ext in sorted(data.extensions.keys()):
750 files = data.extensions[ext]['files']
751 lines = data.extensions[ext]['lines']
752 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))
753 f.write('</table>')
755 f.write('</body></html>')
756 f.close()
759 # Lines
760 f = open(path + '/lines.html', 'w')
761 self.printHeader(f)
762 f.write('<h1>Lines</h1>')
763 self.printNav(f)
765 f.write('<dl>\n')
766 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
767 f.write('</dl>\n')
769 f.write(html_header(2, 'Lines of Code'))
770 f.write('<img src="lines_of_code.png" />')
772 fg = open(path + '/lines_of_code.dat', 'w')
773 for stamp in sorted(data.changes_by_date.keys()):
774 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
775 fg.close()
777 f.write('</body></html>')
778 f.close()
781 # tags.html
782 f = open(path + '/tags.html', 'w')
783 self.printHeader(f)
784 f.write('<h1>Tags</h1>')
785 self.printNav(f)
787 f.write('<dl>')
788 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
789 if len(data.tags) > 0:
790 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
791 f.write('</dl>')
793 f.write('<table>')
794 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
795 # sort the tags by date desc
796 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
797 for tag in tags_sorted_by_date_desc:
798 authorinfo = []
799 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
800 for i in reversed(authors_by_commits):
801 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
802 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)))
803 f.write('</table>')
805 f.write('</body></html>')
806 f.close()
808 self.createGraphs(path)
810 def createGraphs(self, path):
811 print 'Generating graphs...'
813 # hour of day
814 f = open(path + '/hour_of_day.plot', 'w')
815 f.write(GNUPLOT_COMMON)
816 f.write(
818 set output 'hour_of_day.png'
819 unset key
820 set xrange [0.5:24.5]
821 set xtics 4
822 set ylabel "Commits"
823 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
824 """)
825 f.close()
827 # day of week
828 f = open(path + '/day_of_week.plot', 'w')
829 f.write(GNUPLOT_COMMON)
830 f.write(
832 set output 'day_of_week.png'
833 unset key
834 set xrange [0.5:7.5]
835 set xtics 1
836 set ylabel "Commits"
837 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
838 """)
839 f.close()
841 # Month of Year
842 f = open(path + '/month_of_year.plot', 'w')
843 f.write(GNUPLOT_COMMON)
844 f.write(
846 set output 'month_of_year.png'
847 unset key
848 set xrange [0.5:12.5]
849 set xtics 1
850 set ylabel "Commits"
851 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
852 """)
853 f.close()
855 # commits_by_year_month
856 f = open(path + '/commits_by_year_month.plot', 'w')
857 f.write(GNUPLOT_COMMON)
858 f.write(
860 set output 'commits_by_year_month.png'
861 unset key
862 set xdata time
863 set timefmt "%Y-%m"
864 set format x "%Y-%m"
865 set xtics rotate by 90 15768000
866 set bmargin 5
867 set ylabel "Commits"
868 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
869 """)
870 f.close()
872 # commits_by_year
873 f = open(path + '/commits_by_year.plot', 'w')
874 f.write(GNUPLOT_COMMON)
875 f.write(
877 set output 'commits_by_year.png'
878 unset key
879 set xtics 1
880 set ylabel "Commits"
881 set yrange [0:]
882 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
883 """)
884 f.close()
886 # Files by date
887 f = open(path + '/files_by_date.plot', 'w')
888 f.write(GNUPLOT_COMMON)
889 f.write(
891 set output 'files_by_date.png'
892 unset key
893 set xdata time
894 set timefmt "%Y-%m-%d"
895 set format x "%Y-%m-%d"
896 set ylabel "Files"
897 set xtics rotate by 90
898 set ytics 1
899 set bmargin 6
900 plot 'files_by_date.dat' using 1:2 w steps
901 """)
902 f.close()
904 # Lines of Code
905 f = open(path + '/lines_of_code.plot', 'w')
906 f.write(GNUPLOT_COMMON)
907 f.write(
909 set output 'lines_of_code.png'
910 unset key
911 set xdata time
912 set timefmt "%s"
913 set format x "%Y-%m-%d"
914 set ylabel "Lines"
915 set xtics rotate by 90
916 set bmargin 6
917 plot 'lines_of_code.dat' using 1:2 w lines
918 """)
919 f.close()
921 os.chdir(path)
922 files = glob.glob(path + '/*.plot')
923 for f in files:
924 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
925 if len(out) > 0:
926 print out
928 def printHeader(self, f, title = ''):
929 f.write(
930 """<?xml version="1.0" encoding="UTF-8"?>
931 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
932 <html xmlns="http://www.w3.org/1999/xhtml">
933 <head>
934 <title>GitStats - %s</title>
935 <link rel="stylesheet" href="gitstats.css" type="text/css" />
936 <meta name="generator" content="GitStats %s" />
937 <script type="text/javascript" src="sortable.js"></script>
938 </head>
939 <body>
940 """ % (self.title, getversion()))
942 def printNav(self, f):
943 f.write("""
944 <div class="nav">
945 <ul>
946 <li><a href="index.html">General</a></li>
947 <li><a href="activity.html">Activity</a></li>
948 <li><a href="authors.html">Authors</a></li>
949 <li><a href="files.html">Files</a></li>
950 <li><a href="lines.html">Lines</a></li>
951 <li><a href="tags.html">Tags</a></li>
952 </ul>
953 </div>
954 """)
957 usage = """
958 Usage: gitstats [options] <gitpath> <outputpath>
960 Options:
963 if len(sys.argv) < 3:
964 print usage
965 sys.exit(0)
967 gitpath = sys.argv[1]
968 outputpath = os.path.abspath(sys.argv[2])
969 rundir = os.getcwd()
971 try:
972 os.makedirs(outputpath)
973 except OSError:
974 pass
975 if not os.path.isdir(outputpath):
976 print 'FATAL: Output path is not a directory or does not exist'
977 sys.exit(1)
979 print 'Git path: %s' % gitpath
980 print 'Output path: %s' % outputpath
982 os.chdir(gitpath)
984 cachefile = os.path.join(outputpath, 'gitstats.cache')
986 print 'Collecting data...'
987 data = GitDataCollector()
988 data.loadCache(cachefile)
989 data.collect(gitpath)
990 print 'Refining data...'
991 data.saveCache(cachefile)
992 data.refine()
994 os.chdir(rundir)
996 print 'Generating report...'
997 report = HTMLReportCreator()
998 report.create(data, outputpath)
1000 time_end = time.time()
1001 exectime_internal = time_end - time_start
1002 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)