Activate grids on y for all graphs.
[gitstats.git] / gitstats
blob18411d03b63290317cebcb58dc8f4ef30700a8f3
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2010 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
3 # GPLv2 / GPLv3
4 import datetime
5 import getopt
6 import glob
7 import os
8 import pickle
9 import platform
10 import re
11 import shutil
12 import subprocess
13 import sys
14 import time
15 import zlib
17 GNUPLOT_COMMON = 'set terminal png transparent\nset size 1.0,0.5\n'
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 conf = {
31 'max_domains': 10,
32 'max_ext_length': 10,
33 'style': 'gitstats.css',
34 'max_authors': 20,
37 def getpipeoutput(cmds, quiet = False):
38 global exectime_external
39 start = time.time()
40 if not quiet and ON_LINUX and os.isatty(1):
41 print '>> ' + ' | '.join(cmds),
42 sys.stdout.flush()
43 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
44 p = p0
45 for x in cmds[1:]:
46 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
47 p0 = p
48 output = p.communicate()[0]
49 end = time.time()
50 if not quiet:
51 if ON_LINUX and os.isatty(1):
52 print '\r',
53 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
54 exectime_external += (end - start)
55 return output.rstrip('\n')
57 def getkeyssortedbyvalues(dict):
58 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
60 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
61 def getkeyssortedbyvaluekey(d, key):
62 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
64 VERSION = 0
65 def getversion():
66 global VERSION
67 if VERSION == 0:
68 VERSION = getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
69 return VERSION
71 class DataCollector:
72 """Manages data collection from a revision control repository."""
73 def __init__(self):
74 self.stamp_created = time.time()
75 self.cache = {}
78 # This should be the main function to extract data from the repository.
79 def collect(self, dir):
80 self.dir = dir
81 self.projectname = os.path.basename(os.path.abspath(dir))
84 # Load cacheable data
85 def loadCache(self, cachefile):
86 if not os.path.exists(cachefile):
87 return
88 print 'Loading cache...'
89 f = open(cachefile)
90 try:
91 self.cache = pickle.loads(zlib.decompress(f.read()))
92 except:
93 # temporary hack to upgrade non-compressed caches
94 f.seek(0)
95 self.cache = pickle.load(f)
96 f.close()
99 # Produce any additional statistics from the extracted data.
100 def refine(self):
101 pass
104 # : get a dictionary of author
105 def getAuthorInfo(self, author):
106 return None
108 def getActivityByDayOfWeek(self):
109 return {}
111 def getActivityByHourOfDay(self):
112 return {}
114 # : get a dictionary of domains
115 def getDomainInfo(self, domain):
116 return None
119 # Get a list of authors
120 def getAuthors(self):
121 return []
123 def getFirstCommitDate(self):
124 return datetime.datetime.now()
126 def getLastCommitDate(self):
127 return datetime.datetime.now()
129 def getStampCreated(self):
130 return self.stamp_created
132 def getTags(self):
133 return []
135 def getTotalAuthors(self):
136 return -1
138 def getTotalCommits(self):
139 return -1
141 def getTotalFiles(self):
142 return -1
144 def getTotalLOC(self):
145 return -1
148 # Save cacheable data
149 def saveCache(self, cachefile):
150 print 'Saving cache...'
151 f = open(cachefile, 'w')
152 #pickle.dump(self.cache, f)
153 data = zlib.compress(pickle.dumps(self.cache))
154 f.write(data)
155 f.close()
157 class GitDataCollector(DataCollector):
158 def collect(self, dir):
159 DataCollector.collect(self, dir)
161 try:
162 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
163 except:
164 self.total_authors = 0
165 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
167 self.activity_by_hour_of_day = {} # hour -> commits
168 self.activity_by_day_of_week = {} # day -> commits
169 self.activity_by_month_of_year = {} # month [1-12] -> commits
170 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
171 self.activity_by_hour_of_day_busiest = 0
172 self.activity_by_hour_of_week_busiest = 0
173 self.activity_by_year_week = {} # yy_wNN -> commits
174 self.activity_by_year_week_peak = 0
176 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
178 # domains
179 self.domains = {} # domain -> commits
181 # author of the month
182 self.author_of_month = {} # month -> author -> commits
183 self.author_of_year = {} # year -> author -> commits
184 self.commits_by_month = {} # month -> commits
185 self.commits_by_year = {} # year -> commits
186 self.first_commit_stamp = 0
187 self.last_commit_stamp = 0
188 self.last_active_day = None
189 self.active_days = set()
191 # lines
192 self.total_lines = 0
193 self.total_lines_added = 0
194 self.total_lines_removed = 0
196 # timezone
197 self.commits_by_timezone = {} # timezone -> commits
199 # tags
200 self.tags = {}
201 lines = getpipeoutput(['git show-ref --tags']).split('\n')
202 for line in lines:
203 if len(line) == 0:
204 continue
205 (hash, tag) = line.split(' ')
207 tag = tag.replace('refs/tags/', '')
208 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
209 if len(output) > 0:
210 parts = output.split(' ')
211 stamp = 0
212 try:
213 stamp = int(parts[0])
214 except ValueError:
215 stamp = 0
216 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
218 # collect info on tags, starting from latest
219 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
220 prev = None
221 for tag in reversed(tags_sorted_by_date_desc):
222 cmd = 'git shortlog -s "%s"' % tag
223 if prev != None:
224 cmd += ' "^%s"' % prev
225 output = getpipeoutput([cmd])
226 if len(output) == 0:
227 continue
228 prev = tag
229 for line in output.split('\n'):
230 parts = re.split('\s+', line, 2)
231 commits = int(parts[1])
232 author = parts[2]
233 self.tags[tag]['commits'] += commits
234 self.tags[tag]['authors'][author] = commits
236 # Collect revision statistics
237 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
238 lines = getpipeoutput(['git rev-list --pretty=format:"%at %ai %an <%aE>" HEAD', 'grep -v ^commit']).split('\n')
239 for line in lines:
240 parts = line.split(' ', 4)
241 author = ''
242 try:
243 stamp = int(parts[0])
244 except ValueError:
245 stamp = 0
246 timezone = parts[3]
247 author, mail = parts[4].split('<', 1)
248 author = author.rstrip()
249 mail = mail.rstrip('>')
250 domain = '?'
251 if mail.find('@') != -1:
252 domain = mail.rsplit('@', 1)[1]
253 date = datetime.datetime.fromtimestamp(float(stamp))
255 # First and last commit stamp
256 if self.last_commit_stamp == 0:
257 self.last_commit_stamp = stamp
258 self.first_commit_stamp = stamp
260 # activity
261 # hour
262 hour = date.hour
263 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
264 # most active hour?
265 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
266 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
268 # day of week
269 day = date.weekday()
270 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
272 # domain stats
273 if domain not in self.domains:
274 self.domains[domain] = {}
275 # commits
276 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
278 # hour of week
279 if day not in self.activity_by_hour_of_week:
280 self.activity_by_hour_of_week[day] = {}
281 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
282 # most active hour?
283 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
284 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
286 # month of year
287 month = date.month
288 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
290 # yearly/weekly activity
291 yyw = date.strftime('%Y-%W')
292 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
293 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
294 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
296 # author stats
297 if author not in self.authors:
298 self.authors[author] = {}
299 # commits
300 if 'last_commit_stamp' not in self.authors[author]:
301 self.authors[author]['last_commit_stamp'] = stamp
302 self.authors[author]['first_commit_stamp'] = stamp
303 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
305 # author of the month/year
306 yymm = date.strftime('%Y-%m')
307 if yymm in self.author_of_month:
308 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
309 else:
310 self.author_of_month[yymm] = {}
311 self.author_of_month[yymm][author] = 1
312 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
314 yy = date.year
315 if yy in self.author_of_year:
316 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
317 else:
318 self.author_of_year[yy] = {}
319 self.author_of_year[yy][author] = 1
320 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
322 # authors: active days
323 yymmdd = date.strftime('%Y-%m-%d')
324 if 'last_active_day' not in self.authors[author]:
325 self.authors[author]['last_active_day'] = yymmdd
326 self.authors[author]['active_days'] = 1
327 elif yymmdd != self.authors[author]['last_active_day']:
328 self.authors[author]['last_active_day'] = yymmdd
329 self.authors[author]['active_days'] += 1
331 # project: active days
332 if yymmdd != self.last_active_day:
333 self.last_active_day = yymmdd
334 self.active_days.add(yymmdd)
336 # timezone
337 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
339 # TODO Optimize this, it's the worst bottleneck
340 # outputs "<stamp> <files>" for each revision
341 self.files_by_stamp = {} # stamp -> files
342 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
343 lines = []
344 for revline in revlines:
345 time, rev = revline.split(' ')
346 linecount = self.getFilesInCommit(rev)
347 lines.append('%d %d' % (int(time), linecount))
349 self.total_commits = len(lines)
350 for line in lines:
351 parts = line.split(' ')
352 if len(parts) != 2:
353 continue
354 (stamp, files) = parts[0:2]
355 try:
356 self.files_by_stamp[int(stamp)] = int(files)
357 except ValueError:
358 print 'Warning: failed to parse line "%s"' % line
360 # extensions
361 self.extensions = {} # extension -> files, lines
362 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
363 self.total_files = len(lines)
364 for line in lines:
365 if len(line) == 0:
366 continue
367 parts = re.split('\s+', line, 4)
368 sha1 = parts[2]
369 filename = parts[3]
371 if filename.find('.') == -1 or filename.rfind('.') == 0:
372 ext = ''
373 else:
374 ext = filename[(filename.rfind('.') + 1):]
375 if len(ext) > conf['max_ext_length']:
376 ext = ''
378 if ext not in self.extensions:
379 self.extensions[ext] = {'files': 0, 'lines': 0}
381 self.extensions[ext]['files'] += 1
382 try:
383 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
384 except:
385 print 'Warning: Could not count lines for file "%s"' % line
387 # line statistics
388 # outputs:
389 # N files changed, N insertions (+), N deletions(-)
390 # <stamp> <author>
391 self.changes_by_date = {} # stamp -> { files, ins, del }
392 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
393 lines.reverse()
394 files = 0; inserted = 0; deleted = 0; total_lines = 0
395 author = None
396 for line in lines:
397 if len(line) == 0:
398 continue
400 # <stamp> <author>
401 if line.find('files changed,') == -1:
402 pos = line.find(' ')
403 if pos != -1:
404 try:
405 (stamp, author) = (int(line[:pos]), line[pos+1:])
406 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
407 if author not in self.authors:
408 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
409 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
410 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
411 except ValueError:
412 print 'Warning: unexpected line "%s"' % line
413 else:
414 print 'Warning: unexpected line "%s"' % line
415 else:
416 numbers = re.findall('\d+', line)
417 if len(numbers) == 3:
418 (files, inserted, deleted) = map(lambda el : int(el), numbers)
419 total_lines += inserted
420 total_lines -= deleted
421 self.total_lines_added += inserted
422 self.total_lines_removed += deleted
423 else:
424 print 'Warning: failed to handle line "%s"' % line
425 (files, inserted, deleted) = (0, 0, 0)
426 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
427 self.total_lines = total_lines
429 def refine(self):
430 # authors
431 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
432 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
433 authors_by_commits.reverse() # most first
434 for i, name in enumerate(authors_by_commits):
435 self.authors[name]['place_by_commits'] = i + 1
437 for name in self.authors.keys():
438 a = self.authors[name]
439 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
440 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
441 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
442 delta = date_last - date_first
443 a['date_first'] = date_first.strftime('%Y-%m-%d')
444 a['date_last'] = date_last.strftime('%Y-%m-%d')
445 a['timedelta'] = delta
447 def getActiveDays(self):
448 return self.active_days
450 def getActivityByDayOfWeek(self):
451 return self.activity_by_day_of_week
453 def getActivityByHourOfDay(self):
454 return self.activity_by_hour_of_day
456 def getAuthorInfo(self, author):
457 return self.authors[author]
459 def getAuthors(self, limit = None):
460 res = getkeyssortedbyvaluekey(self.authors, 'commits')
461 res.reverse()
462 return res[:limit]
464 def getCommitDeltaDays(self):
465 return (self.last_commit_stamp - self.first_commit_stamp) / 86400 + 1
467 def getDomainInfo(self, domain):
468 return self.domains[domain]
470 def getDomains(self):
471 return self.domains.keys()
473 def getFilesInCommit(self, rev):
474 try:
475 res = self.cache['files_in_tree'][rev]
476 except:
477 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
478 if 'files_in_tree' not in self.cache:
479 self.cache['files_in_tree'] = {}
480 self.cache['files_in_tree'][rev] = res
482 return res
484 def getFirstCommitDate(self):
485 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
487 def getLastCommitDate(self):
488 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
490 def getLinesInBlob(self, sha1):
491 try:
492 res = self.cache['lines_in_blob'][sha1]
493 except:
494 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
495 if 'lines_in_blob' not in self.cache:
496 self.cache['lines_in_blob'] = {}
497 self.cache['lines_in_blob'][sha1] = res
498 return res
500 def getTags(self):
501 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
502 return lines.split('\n')
504 def getTagDate(self, tag):
505 return self.revToDate('tags/' + tag)
507 def getTotalAuthors(self):
508 return self.total_authors
510 def getTotalCommits(self):
511 return self.total_commits
513 def getTotalFiles(self):
514 return self.total_files
516 def getTotalLOC(self):
517 return self.total_lines
519 def revToDate(self, rev):
520 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
521 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
523 class ReportCreator:
524 """Creates the actual report based on given data."""
525 def __init__(self):
526 pass
528 def create(self, data, path):
529 self.data = data
530 self.path = path
532 def html_linkify(text):
533 return text.lower().replace(' ', '_')
535 def html_header(level, text):
536 name = html_linkify(text)
537 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
539 class HTMLReportCreator(ReportCreator):
540 def create(self, data, path):
541 ReportCreator.create(self, data, path)
542 self.title = data.projectname
544 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
545 binarypath = os.path.dirname(os.path.abspath(__file__))
546 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
547 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
548 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
549 for base in basedirs:
550 src = base + '/' + file
551 if os.path.exists(src):
552 shutil.copyfile(src, path + '/' + file)
553 break
554 else:
555 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
557 f = open(path + "/index.html", 'w')
558 format = '%Y-%m-%d %H:%M:%S'
559 self.printHeader(f)
561 f.write('<h1>GitStats - %s</h1>' % data.projectname)
563 self.printNav(f)
565 f.write('<dl>')
566 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
567 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
568 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
569 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
570 f.write('<dt>Age</dt><dd>%d days, %d active days (%3.2f%%)</dd>' % (data.getCommitDeltaDays(), len(data.getActiveDays()), (100.0 * len(data.getActiveDays()) / data.getCommitDeltaDays())))
571 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
572 f.write('<dt>Total Lines of Code</dt><dd>%s (%d added, %d removed)</dd>' % (data.getTotalLOC(), data.total_lines_added, data.total_lines_removed))
573 f.write('<dt>Total Commits</dt><dd>%s (average %.1f commits per active day, %.1f per all days)</dd>' % (data.getTotalCommits(), float(data.getTotalCommits()) / len(data.getActiveDays()), float(data.getTotalCommits()) / data.getCommitDeltaDays()))
574 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
575 f.write('</dl>')
577 f.write('</body>\n</html>')
578 f.close()
581 # Activity
582 f = open(path + '/activity.html', 'w')
583 self.printHeader(f)
584 f.write('<h1>Activity</h1>')
585 self.printNav(f)
587 #f.write('<h2>Last 30 days</h2>')
589 #f.write('<h2>Last 12 months</h2>')
591 # Weekly activity
592 WEEKS = 32
593 f.write(html_header(2, 'Weekly activity'))
594 f.write('<p>Last %d weeks</p>' % WEEKS)
596 # generate weeks to show (previous N weeks from now)
597 now = datetime.datetime.now()
598 deltaweek = datetime.timedelta(7)
599 weeks = []
600 stampcur = now
601 for i in range(0, WEEKS):
602 weeks.insert(0, stampcur.strftime('%Y-%W'))
603 stampcur -= deltaweek
605 # top row: commits & bar
606 f.write('<table class="noborders"><tr>')
607 for i in range(0, WEEKS):
608 commits = 0
609 if weeks[i] in data.activity_by_year_week:
610 commits = data.activity_by_year_week[weeks[i]]
612 percentage = 0
613 if weeks[i] in data.activity_by_year_week:
614 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
615 height = max(1, int(200 * percentage))
616 f.write('<td style="text-align: center; vertical-align: bottom">%d<div style="display: block; background-color: red; width: 20px; height: %dpx"></div></td>' % (commits, height))
618 # bottom row: year/week
619 f.write('</tr><tr>')
620 for i in range(0, WEEKS):
621 f.write('<td>%s</td>' % (WEEKS - i))
622 f.write('</tr></table>')
624 # Hour of Day
625 f.write(html_header(2, 'Hour of Day'))
626 hour_of_day = data.getActivityByHourOfDay()
627 f.write('<table><tr><th>Hour</th>')
628 for i in range(0, 24):
629 f.write('<th>%d</th>' % i)
630 f.write('</tr>\n<tr><th>Commits</th>')
631 fp = open(path + '/hour_of_day.dat', 'w')
632 for i in range(0, 24):
633 if i in hour_of_day:
634 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
635 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
636 fp.write('%d %d\n' % (i, hour_of_day[i]))
637 else:
638 f.write('<td>0</td>')
639 fp.write('%d 0\n' % i)
640 fp.close()
641 f.write('</tr>\n<tr><th>%</th>')
642 totalcommits = data.getTotalCommits()
643 for i in range(0, 24):
644 if i in hour_of_day:
645 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
646 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
647 else:
648 f.write('<td>0.00</td>')
649 f.write('</tr></table>')
650 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
651 fg = open(path + '/hour_of_day.dat', 'w')
652 for i in range(0, 24):
653 if i in hour_of_day:
654 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
655 else:
656 fg.write('%d 0\n' % (i + 1))
657 fg.close()
659 # Day of Week
660 f.write(html_header(2, 'Day of Week'))
661 day_of_week = data.getActivityByDayOfWeek()
662 f.write('<div class="vtable"><table>')
663 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
664 fp = open(path + '/day_of_week.dat', 'w')
665 for d in range(0, 7):
666 commits = 0
667 if d in day_of_week:
668 commits = day_of_week[d]
669 fp.write('%d %d\n' % (d + 1, commits))
670 f.write('<tr>')
671 f.write('<th>%d</th>' % (d + 1))
672 if d in day_of_week:
673 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
674 else:
675 f.write('<td>0</td>')
676 f.write('</tr>')
677 f.write('</table></div>')
678 f.write('<img src="day_of_week.png" alt="Day of Week" />')
679 fp.close()
681 # Hour of Week
682 f.write(html_header(2, 'Hour of Week'))
683 f.write('<table>')
685 f.write('<tr><th>Weekday</th>')
686 for hour in range(0, 24):
687 f.write('<th>%d</th>' % (hour))
688 f.write('</tr>')
690 for weekday in range(0, 7):
691 f.write('<tr><th>%d</th>' % (weekday + 1))
692 for hour in range(0, 24):
693 try:
694 commits = data.activity_by_hour_of_week[weekday][hour]
695 except KeyError:
696 commits = 0
697 if commits != 0:
698 f.write('<td')
699 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
700 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
701 f.write('>%d</td>' % commits)
702 else:
703 f.write('<td></td>')
704 f.write('</tr>')
706 f.write('</table>')
708 # Month of Year
709 f.write(html_header(2, 'Month of Year'))
710 f.write('<div class="vtable"><table>')
711 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
712 fp = open (path + '/month_of_year.dat', 'w')
713 for mm in range(1, 13):
714 commits = 0
715 if mm in data.activity_by_month_of_year:
716 commits = data.activity_by_month_of_year[mm]
717 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
718 fp.write('%d %d\n' % (mm, commits))
719 fp.close()
720 f.write('</table></div>')
721 f.write('<img src="month_of_year.png" alt="Month of Year" />')
723 # Commits by year/month
724 f.write(html_header(2, 'Commits by year/month'))
725 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
726 for yymm in reversed(sorted(data.commits_by_month.keys())):
727 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
728 f.write('</table></div>')
729 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
730 fg = open(path + '/commits_by_year_month.dat', 'w')
731 for yymm in sorted(data.commits_by_month.keys()):
732 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
733 fg.close()
735 # Commits by year
736 f.write(html_header(2, 'Commits by Year'))
737 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
738 for yy in reversed(sorted(data.commits_by_year.keys())):
739 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()))
740 f.write('</table></div>')
741 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
742 fg = open(path + '/commits_by_year.dat', 'w')
743 for yy in sorted(data.commits_by_year.keys()):
744 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
745 fg.close()
747 # Commits by timezone
748 f.write(html_header(2, 'Commits by Timezone'))
749 f.write('<table><tr>')
750 f.write('<th>Timezone</th><th>Commits</th>')
751 max_commits_on_tz = max(data.commits_by_timezone.values())
752 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
753 commits = data.commits_by_timezone[i]
754 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
755 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
756 f.write('</tr></table>')
758 f.write('</body></html>')
759 f.close()
762 # Authors
763 f = open(path + '/authors.html', 'w')
764 self.printHeader(f)
766 f.write('<h1>Authors</h1>')
767 self.printNav(f)
769 # Authors :: List of authors
770 f.write(html_header(2, 'List of Authors'))
772 f.write('<table class="authors sortable" id="authors">')
773 f.write('<tr><th>Author</th><th>Commits (%)</th><th>+ lines</th><th>- lines</th><th>First commit</th><th>Last commit</th><th class="unsortable">Age</th><th>Active days</th><th># by commits</th></tr>')
774 for author in sorted(data.getAuthors(conf['max_authors'])):
775 info = data.getAuthorInfo(author)
776 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (author, info['commits'], info['commits_frac'], info['lines_added'], info['lines_removed'], info['date_first'], info['date_last'], info['timedelta'], info['active_days'], info['place_by_commits']))
777 f.write('</table>')
779 allauthors = data.getAuthors()
780 if len(allauthors) > conf['max_authors']:
781 rest = allauthors[conf['max_authors']:]
782 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
784 # Authors :: Author of Month
785 f.write(html_header(2, 'Author of Month'))
786 f.write('<table class="sortable" id="aom">')
787 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
788 for yymm in reversed(sorted(data.author_of_month.keys())):
789 authordict = data.author_of_month[yymm]
790 authors = getkeyssortedbyvalues(authordict)
791 authors.reverse()
792 commits = data.author_of_month[yymm][authors[0]]
793 next = ', '.join(authors[1:5])
794 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))
796 f.write('</table>')
798 f.write(html_header(2, 'Author of Year'))
799 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>')
800 for yy in reversed(sorted(data.author_of_year.keys())):
801 authordict = data.author_of_year[yy]
802 authors = getkeyssortedbyvalues(authordict)
803 authors.reverse()
804 commits = data.author_of_year[yy][authors[0]]
805 next = ', '.join(authors[1:5])
806 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))
807 f.write('</table>')
809 # Domains
810 f.write(html_header(2, 'Commits by Domains'))
811 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
812 domains_by_commits.reverse() # most first
813 f.write('<div class="vtable"><table>')
814 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
815 fp = open(path + '/domains.dat', 'w')
816 n = 0
817 for domain in domains_by_commits:
818 if n == conf['max_domains']:
819 break
820 commits = 0
821 n += 1
822 info = data.getDomainInfo(domain)
823 fp.write('%s %d %d\n' % (domain, n , info['commits']))
824 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
825 f.write('</table></div>')
826 f.write('<img src="domains.png" alt="Commits by Domains" />')
827 fp.close()
829 f.write('</body></html>')
830 f.close()
833 # Files
834 f = open(path + '/files.html', 'w')
835 self.printHeader(f)
836 f.write('<h1>Files</h1>')
837 self.printNav(f)
839 f.write('<dl>\n')
840 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
841 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
842 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
843 f.write('</dl>\n')
845 # Files :: File count by date
846 f.write(html_header(2, 'File count by date'))
848 # use set to get rid of duplicate/unnecessary entries
849 files_by_date = set()
850 for stamp in sorted(data.files_by_stamp.keys()):
851 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
853 fg = open(path + '/files_by_date.dat', 'w')
854 for line in sorted(list(files_by_date)):
855 fg.write('%s\n' % line)
856 #for stamp in sorted(data.files_by_stamp.keys()):
857 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
858 fg.close()
860 f.write('<img src="files_by_date.png" alt="Files by Date" />')
862 #f.write('<h2>Average file size by date</h2>')
864 # Files :: Extensions
865 f.write(html_header(2, 'Extensions'))
866 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
867 for ext in sorted(data.extensions.keys()):
868 files = data.extensions[ext]['files']
869 lines = data.extensions[ext]['lines']
870 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))
871 f.write('</table>')
873 f.write('</body></html>')
874 f.close()
877 # Lines
878 f = open(path + '/lines.html', 'w')
879 self.printHeader(f)
880 f.write('<h1>Lines</h1>')
881 self.printNav(f)
883 f.write('<dl>\n')
884 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
885 f.write('</dl>\n')
887 f.write(html_header(2, 'Lines of Code'))
888 f.write('<img src="lines_of_code.png" />')
890 fg = open(path + '/lines_of_code.dat', 'w')
891 for stamp in sorted(data.changes_by_date.keys()):
892 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
893 fg.close()
895 f.write('</body></html>')
896 f.close()
899 # tags.html
900 f = open(path + '/tags.html', 'w')
901 self.printHeader(f)
902 f.write('<h1>Tags</h1>')
903 self.printNav(f)
905 f.write('<dl>')
906 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
907 if len(data.tags) > 0:
908 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
909 f.write('</dl>')
911 f.write('<table class="tags">')
912 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
913 # sort the tags by date desc
914 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
915 for tag in tags_sorted_by_date_desc:
916 authorinfo = []
917 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
918 for i in reversed(authors_by_commits):
919 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
920 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)))
921 f.write('</table>')
923 f.write('</body></html>')
924 f.close()
926 self.createGraphs(path)
928 def createGraphs(self, path):
929 print 'Generating graphs...'
931 # hour of day
932 f = open(path + '/hour_of_day.plot', 'w')
933 f.write(GNUPLOT_COMMON)
934 f.write(
936 set output 'hour_of_day.png'
937 unset key
938 set xrange [0.5:24.5]
939 set xtics 4
940 set grid y
941 set ylabel "Commits"
942 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
943 """)
944 f.close()
946 # day of week
947 f = open(path + '/day_of_week.plot', 'w')
948 f.write(GNUPLOT_COMMON)
949 f.write(
951 set output 'day_of_week.png'
952 unset key
953 set xrange [0.5:7.5]
954 set xtics 1
955 set grid y
956 set ylabel "Commits"
957 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
958 """)
959 f.close()
961 # Domains
962 f = open(path + '/domains.plot', 'w')
963 f.write(GNUPLOT_COMMON)
964 f.write(
966 set output 'domains.png'
967 unset key
968 unset xtics
969 set grid y
970 set ylabel "Commits"
971 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
972 """)
973 f.close()
975 # Month of Year
976 f = open(path + '/month_of_year.plot', 'w')
977 f.write(GNUPLOT_COMMON)
978 f.write(
980 set output 'month_of_year.png'
981 unset key
982 set xrange [0.5:12.5]
983 set xtics 1
984 set grid y
985 set ylabel "Commits"
986 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
987 """)
988 f.close()
990 # commits_by_year_month
991 f = open(path + '/commits_by_year_month.plot', 'w')
992 f.write(GNUPLOT_COMMON)
993 f.write(
995 set output 'commits_by_year_month.png'
996 unset key
997 set xdata time
998 set timefmt "%Y-%m"
999 set format x "%Y-%m"
1000 set xtics rotate by 90 15768000
1001 set bmargin 5
1002 set grid y
1003 set ylabel "Commits"
1004 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1005 """)
1006 f.close()
1008 # commits_by_year
1009 f = open(path + '/commits_by_year.plot', 'w')
1010 f.write(GNUPLOT_COMMON)
1011 f.write(
1013 set output 'commits_by_year.png'
1014 unset key
1015 set xtics 1 rotate by 90
1016 set grid y
1017 set ylabel "Commits"
1018 set yrange [0:]
1019 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1020 """)
1021 f.close()
1023 # Files by date
1024 f = open(path + '/files_by_date.plot', 'w')
1025 f.write(GNUPLOT_COMMON)
1026 f.write(
1028 set output 'files_by_date.png'
1029 unset key
1030 set xdata time
1031 set timefmt "%Y-%m-%d"
1032 set format x "%Y-%m-%d"
1033 set grid y
1034 set ylabel "Files"
1035 set xtics rotate by 90
1036 set ytics autofreq
1037 set bmargin 6
1038 plot 'files_by_date.dat' using 1:2 w steps
1039 """)
1040 f.close()
1042 # Lines of Code
1043 f = open(path + '/lines_of_code.plot', 'w')
1044 f.write(GNUPLOT_COMMON)
1045 f.write(
1047 set output 'lines_of_code.png'
1048 unset key
1049 set xdata time
1050 set timefmt "%s"
1051 set format x "%Y-%m-%d"
1052 set grid y
1053 set ylabel "Lines"
1054 set xtics rotate by 90
1055 set bmargin 6
1056 plot 'lines_of_code.dat' using 1:2 w lines
1057 """)
1058 f.close()
1060 os.chdir(path)
1061 files = glob.glob(path + '/*.plot')
1062 for f in files:
1063 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1064 if len(out) > 0:
1065 print out
1067 def printHeader(self, f, title = ''):
1068 f.write(
1069 """<?xml version="1.0" encoding="UTF-8"?>
1070 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1071 <html xmlns="http://www.w3.org/1999/xhtml">
1072 <head>
1073 <title>GitStats - %s</title>
1074 <link rel="stylesheet" href="%s" type="text/css" />
1075 <meta name="generator" content="GitStats %s" />
1076 <script type="text/javascript" src="sortable.js"></script>
1077 </head>
1078 <body>
1079 """ % (self.title, conf['style'], getversion()))
1081 def printNav(self, f):
1082 f.write("""
1083 <div class="nav">
1084 <ul>
1085 <li><a href="index.html">General</a></li>
1086 <li><a href="activity.html">Activity</a></li>
1087 <li><a href="authors.html">Authors</a></li>
1088 <li><a href="files.html">Files</a></li>
1089 <li><a href="lines.html">Lines</a></li>
1090 <li><a href="tags.html">Tags</a></li>
1091 </ul>
1092 </div>
1093 """)
1096 class GitStats:
1097 def run(self, args_orig):
1098 optlist, args = getopt.getopt(args_orig, 'c:')
1099 for o,v in optlist:
1100 if o == '-c':
1101 key, value = v.split('=', 1)
1102 if key not in conf:
1103 raise 'Error: no such key "%s" in config' % key
1104 if isinstance(conf[key], int):
1105 conf[key] = int(value)
1106 else:
1107 conf[key] = value
1109 if len(args) < 2:
1110 print """
1111 Usage: gitstats [options] <gitpath> <outputpath>
1113 Options:
1114 -c key=value Override configuration value
1116 Default config values:
1118 """ % conf
1119 sys.exit(0)
1121 gitpath = args[0]
1122 outputpath = os.path.abspath(args[1])
1123 rundir = os.getcwd()
1125 try:
1126 os.makedirs(outputpath)
1127 except OSError:
1128 pass
1129 if not os.path.isdir(outputpath):
1130 print 'FATAL: Output path is not a directory or does not exist'
1131 sys.exit(1)
1133 print 'Git path: %s' % gitpath
1134 print 'Output path: %s' % outputpath
1136 os.chdir(gitpath)
1138 cachefile = os.path.join(outputpath, 'gitstats.cache')
1140 print 'Collecting data...'
1141 data = GitDataCollector()
1142 data.loadCache(cachefile)
1143 data.collect(gitpath)
1144 print 'Refining data...'
1145 data.saveCache(cachefile)
1146 data.refine()
1148 os.chdir(rundir)
1150 print 'Generating report...'
1151 report = HTMLReportCreator()
1152 report.create(data, outputpath)
1154 time_end = time.time()
1155 exectime_internal = time_end - time_start
1156 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1158 g = GitStats()
1159 g.run(sys.argv[1:])