Fixed handling of weird author e-mails.
[gitstats.git] / gitstats
blob591c55a7c83d8e0985c67a4d36b271bd791e8d6a
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 {}
107 # : get a dictionary of domains
108 def getDomainInfo(self, domain):
109 return None
112 # Get a list of authors
113 def getAuthors(self):
114 return []
116 def getFirstCommitDate(self):
117 return datetime.datetime.now()
119 def getLastCommitDate(self):
120 return datetime.datetime.now()
122 def getStampCreated(self):
123 return self.stamp_created
125 def getTags(self):
126 return []
128 def getTotalAuthors(self):
129 return -1
131 def getTotalCommits(self):
132 return -1
134 def getTotalFiles(self):
135 return -1
137 def getTotalLOC(self):
138 return -1
141 # Save cacheable data
142 def saveCache(self, filename):
143 print 'Saving cache...'
144 f = open(cachefile, 'w')
145 #pickle.dump(self.cache, f)
146 data = zlib.compress(pickle.dumps(self.cache))
147 f.write(data)
148 f.close()
150 class GitDataCollector(DataCollector):
151 def collect(self, dir):
152 DataCollector.collect(self, dir)
154 try:
155 self.total_authors = int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
156 except:
157 self.total_authors = 0
158 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
160 self.activity_by_hour_of_day = {} # hour -> commits
161 self.activity_by_day_of_week = {} # day -> commits
162 self.activity_by_month_of_year = {} # month [1-12] -> commits
163 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
164 self.activity_by_hour_of_day_busiest = 0
165 self.activity_by_hour_of_week_busiest = 0
166 self.activity_by_year_week = {} # yy_wNN -> commits
167 self.activity_by_year_week_peak = 0
169 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
171 # domains
172 self.domains = {} # domain -> commits
174 # author of the month
175 self.author_of_month = {} # month -> author -> commits
176 self.author_of_year = {} # year -> author -> commits
177 self.commits_by_month = {} # month -> commits
178 self.commits_by_year = {} # year -> commits
179 self.first_commit_stamp = 0
180 self.last_commit_stamp = 0
181 self.last_active_day = None
182 self.active_days = set()
184 # lines
185 self.total_lines = 0
186 self.total_lines_added = 0
187 self.total_lines_removed = 0
189 # timezone
190 self.commits_by_timezone = {} # timezone -> commits
192 # tags
193 self.tags = {}
194 lines = getpipeoutput(['git show-ref --tags']).split('\n')
195 for line in lines:
196 if len(line) == 0:
197 continue
198 (hash, tag) = line.split(' ')
200 tag = tag.replace('refs/tags/', '')
201 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
202 if len(output) > 0:
203 parts = output.split(' ')
204 stamp = 0
205 try:
206 stamp = int(parts[0])
207 except ValueError:
208 stamp = 0
209 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
211 # collect info on tags, starting from latest
212 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
213 prev = None
214 for tag in reversed(tags_sorted_by_date_desc):
215 cmd = 'git shortlog -s "%s"' % tag
216 if prev != None:
217 cmd += ' "^%s"' % prev
218 output = getpipeoutput([cmd])
219 if len(output) == 0:
220 continue
221 prev = tag
222 for line in output.split('\n'):
223 parts = re.split('\s+', line, 2)
224 commits = int(parts[1])
225 author = parts[2]
226 self.tags[tag]['commits'] += commits
227 self.tags[tag]['authors'][author] = commits
229 # Collect revision statistics
230 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
231 lines = getpipeoutput(['git rev-list --pretty=format:"%at %ai %an <%aE>" HEAD', 'grep -v ^commit']).split('\n')
232 for line in lines:
233 parts = line.split(' ', 4)
234 author = ''
235 try:
236 stamp = int(parts[0])
237 except ValueError:
238 stamp = 0
239 timezone = parts[3]
240 author, mail = parts[4].split('<', 1)
241 author = author.rstrip()
242 mail = mail.rstrip('>')
243 domain = mail.rsplit('@', 1)[1]
244 date = datetime.datetime.fromtimestamp(float(stamp))
246 # First and last commit stamp
247 if self.last_commit_stamp == 0:
248 self.last_commit_stamp = stamp
249 self.first_commit_stamp = stamp
251 # activity
252 # hour
253 hour = date.hour
254 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
255 # most active hour?
256 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
257 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
259 # day of week
260 day = date.weekday()
261 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
263 # domain stats
264 if domain not in self.domains:
265 self.domains[domain] = {}
266 # commits
267 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
269 # hour of week
270 if day not in self.activity_by_hour_of_week:
271 self.activity_by_hour_of_week[day] = {}
272 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
273 # most active hour?
274 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
275 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
277 # month of year
278 month = date.month
279 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
281 # yearly/weekly activity
282 yyw = date.strftime('%Y-%W')
283 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
284 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
285 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
287 # author stats
288 if author not in self.authors:
289 self.authors[author] = {}
290 # commits
291 if 'last_commit_stamp' not in self.authors[author]:
292 self.authors[author]['last_commit_stamp'] = stamp
293 self.authors[author]['first_commit_stamp'] = stamp
294 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
296 # author of the month/year
297 yymm = date.strftime('%Y-%m')
298 if yymm in self.author_of_month:
299 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
300 else:
301 self.author_of_month[yymm] = {}
302 self.author_of_month[yymm][author] = 1
303 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
305 yy = date.year
306 if yy in self.author_of_year:
307 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
308 else:
309 self.author_of_year[yy] = {}
310 self.author_of_year[yy][author] = 1
311 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
313 # authors: active days
314 yymmdd = date.strftime('%Y-%m-%d')
315 if 'last_active_day' not in self.authors[author]:
316 self.authors[author]['last_active_day'] = yymmdd
317 self.authors[author]['active_days'] = 1
318 elif yymmdd != self.authors[author]['last_active_day']:
319 self.authors[author]['last_active_day'] = yymmdd
320 self.authors[author]['active_days'] += 1
322 # project: active days
323 if yymmdd != self.last_active_day:
324 self.last_active_day = yymmdd
325 self.active_days.add(yymmdd)
327 # timezone
328 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
330 # TODO Optimize this, it's the worst bottleneck
331 # outputs "<stamp> <files>" for each revision
332 self.files_by_stamp = {} # stamp -> files
333 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
334 lines = []
335 for revline in revlines:
336 time, rev = revline.split(' ')
337 linecount = self.getFilesInCommit(rev)
338 lines.append('%d %d' % (int(time), linecount))
340 self.total_commits = len(lines)
341 for line in lines:
342 parts = line.split(' ')
343 if len(parts) != 2:
344 continue
345 (stamp, files) = parts[0:2]
346 try:
347 self.files_by_stamp[int(stamp)] = int(files)
348 except ValueError:
349 print 'Warning: failed to parse line "%s"' % line
351 # extensions
352 self.extensions = {} # extension -> files, lines
353 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
354 self.total_files = len(lines)
355 for line in lines:
356 if len(line) == 0:
357 continue
358 parts = re.split('\s+', line, 4)
359 sha1 = parts[2]
360 filename = parts[3]
362 if filename.find('.') == -1 or filename.rfind('.') == 0:
363 ext = ''
364 else:
365 ext = filename[(filename.rfind('.') + 1):]
366 if len(ext) > MAX_EXT_LENGTH:
367 ext = ''
369 if ext not in self.extensions:
370 self.extensions[ext] = {'files': 0, 'lines': 0}
372 self.extensions[ext]['files'] += 1
373 try:
374 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
375 except:
376 print 'Warning: Could not count lines for file "%s"' % line
378 # line statistics
379 # outputs:
380 # N files changed, N insertions (+), N deletions(-)
381 # <stamp> <author>
382 self.changes_by_date = {} # stamp -> { files, ins, del }
383 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
384 lines.reverse()
385 files = 0; inserted = 0; deleted = 0; total_lines = 0
386 author = None
387 for line in lines:
388 if len(line) == 0:
389 continue
391 # <stamp> <author>
392 if line.find('files changed,') == -1:
393 pos = line.find(' ')
394 if pos != -1:
395 try:
396 (stamp, author) = (int(line[:pos]), line[pos+1:])
397 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
398 if author not in self.authors:
399 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
400 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
401 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
402 except ValueError:
403 print 'Warning: unexpected line "%s"' % line
404 else:
405 print 'Warning: unexpected line "%s"' % line
406 else:
407 numbers = re.findall('\d+', line)
408 if len(numbers) == 3:
409 (files, inserted, deleted) = map(lambda el : int(el), numbers)
410 total_lines += inserted
411 total_lines -= deleted
412 self.total_lines_added += inserted
413 self.total_lines_removed += deleted
414 else:
415 print 'Warning: failed to handle line "%s"' % line
416 (files, inserted, deleted) = (0, 0, 0)
417 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
418 self.total_lines = total_lines
420 def refine(self):
421 # authors
422 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
423 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
424 authors_by_commits.reverse() # most first
425 for i, name in enumerate(authors_by_commits):
426 self.authors[name]['place_by_commits'] = i + 1
428 for name in self.authors.keys():
429 a = self.authors[name]
430 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
431 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
432 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
433 delta = date_last - date_first
434 a['date_first'] = date_first.strftime('%Y-%m-%d')
435 a['date_last'] = date_last.strftime('%Y-%m-%d')
436 a['timedelta'] = delta
438 def getActiveDays(self):
439 return self.active_days
441 def getActivityByDayOfWeek(self):
442 return self.activity_by_day_of_week
444 def getActivityByHourOfDay(self):
445 return self.activity_by_hour_of_day
447 def getAuthorInfo(self, author):
448 return self.authors[author]
450 def getAuthors(self):
451 return self.authors.keys()
453 def getCommitDeltaDays(self):
454 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
456 def getDomainInfo(self, domain):
457 return self.domains[domain]
459 def getDomains(self):
460 return self.domains.keys()
462 def getFilesInCommit(self, rev):
463 try:
464 res = self.cache['files_in_tree'][rev]
465 except:
466 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
467 if 'files_in_tree' not in self.cache:
468 self.cache['files_in_tree'] = {}
469 self.cache['files_in_tree'][rev] = res
471 return res
473 def getFirstCommitDate(self):
474 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
476 def getLastCommitDate(self):
477 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
479 def getTags(self):
480 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
481 return lines.split('\n')
483 def getTagDate(self, tag):
484 return self.revToDate('tags/' + tag)
486 def getTotalAuthors(self):
487 return self.total_authors
489 def getTotalCommits(self):
490 return self.total_commits
492 def getTotalFiles(self):
493 return self.total_files
495 def getTotalLOC(self):
496 return self.total_lines
498 def revToDate(self, rev):
499 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
500 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
502 class ReportCreator:
503 """Creates the actual report based on given data."""
504 def __init__(self):
505 pass
507 def create(self, data, path):
508 self.data = data
509 self.path = path
511 def html_linkify(text):
512 return text.lower().replace(' ', '_')
514 def html_header(level, text):
515 name = html_linkify(text)
516 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
518 class HTMLReportCreator(ReportCreator):
519 def create(self, data, path):
520 ReportCreator.create(self, data, path)
521 self.title = data.projectname
523 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
524 binarypath = os.path.dirname(os.path.abspath(__file__))
525 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
526 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
527 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
528 for base in basedirs:
529 src = base + '/' + file
530 if os.path.exists(src):
531 shutil.copyfile(src, path + '/' + file)
532 break
533 else:
534 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
536 f = open(path + "/index.html", 'w')
537 format = '%Y-%m-%d %H:%M:%S'
538 self.printHeader(f)
540 f.write('<h1>GitStats - %s</h1>' % data.projectname)
542 self.printNav(f)
544 f.write('<dl>')
545 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
546 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
547 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
548 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
549 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())))
550 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
551 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))
552 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()))
553 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
554 f.write('</dl>')
556 f.write('</body>\n</html>')
557 f.close()
560 # Activity
561 f = open(path + '/activity.html', 'w')
562 self.printHeader(f)
563 f.write('<h1>Activity</h1>')
564 self.printNav(f)
566 #f.write('<h2>Last 30 days</h2>')
568 #f.write('<h2>Last 12 months</h2>')
570 # Weekly activity
571 WEEKS = 32
572 f.write(html_header(2, 'Weekly activity'))
573 f.write('<p>Last %d weeks</p>' % WEEKS)
575 # generate weeks to show (previous N weeks from now)
576 now = datetime.datetime.now()
577 deltaweek = datetime.timedelta(7)
578 weeks = []
579 stampcur = now
580 for i in range(0, WEEKS):
581 weeks.insert(0, stampcur.strftime('%Y-%W'))
582 stampcur -= deltaweek
584 # top row: commits & bar
585 f.write('<table class="noborders"><tr>')
586 for i in range(0, WEEKS):
587 commits = 0
588 if weeks[i] in data.activity_by_year_week:
589 commits = data.activity_by_year_week[weeks[i]]
591 percentage = 0
592 if weeks[i] in data.activity_by_year_week:
593 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
594 height = max(1, int(200 * percentage))
595 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))
597 # bottom row: year/week
598 f.write('</tr><tr>')
599 for i in range(0, WEEKS):
600 f.write('<td>%s</td>' % (WEEKS - i))
601 f.write('</tr></table>')
603 # Hour of Day
604 f.write(html_header(2, 'Hour of Day'))
605 hour_of_day = data.getActivityByHourOfDay()
606 f.write('<table><tr><th>Hour</th>')
607 for i in range(0, 24):
608 f.write('<th>%d</th>' % i)
609 f.write('</tr>\n<tr><th>Commits</th>')
610 fp = open(path + '/hour_of_day.dat', 'w')
611 for i in range(0, 24):
612 if i in hour_of_day:
613 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
614 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
615 fp.write('%d %d\n' % (i, hour_of_day[i]))
616 else:
617 f.write('<td>0</td>')
618 fp.write('%d 0\n' % i)
619 fp.close()
620 f.write('</tr>\n<tr><th>%</th>')
621 totalcommits = data.getTotalCommits()
622 for i in range(0, 24):
623 if i in hour_of_day:
624 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
625 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
626 else:
627 f.write('<td>0.00</td>')
628 f.write('</tr></table>')
629 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
630 fg = open(path + '/hour_of_day.dat', 'w')
631 for i in range(0, 24):
632 if i in hour_of_day:
633 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
634 else:
635 fg.write('%d 0\n' % (i + 1))
636 fg.close()
638 # Day of Week
639 f.write(html_header(2, 'Day of Week'))
640 day_of_week = data.getActivityByDayOfWeek()
641 f.write('<div class="vtable"><table>')
642 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
643 fp = open(path + '/day_of_week.dat', 'w')
644 for d in range(0, 7):
645 commits = 0
646 if d in day_of_week:
647 commits = day_of_week[d]
648 fp.write('%d %d\n' % (d + 1, commits))
649 f.write('<tr>')
650 f.write('<th>%d</th>' % (d + 1))
651 if d in day_of_week:
652 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
653 else:
654 f.write('<td>0</td>')
655 f.write('</tr>')
656 f.write('</table></div>')
657 f.write('<img src="day_of_week.png" alt="Day of Week" />')
658 fp.close()
660 # Hour of Week
661 f.write(html_header(2, 'Hour of Week'))
662 f.write('<table>')
664 f.write('<tr><th>Weekday</th>')
665 for hour in range(0, 24):
666 f.write('<th>%d</th>' % (hour))
667 f.write('</tr>')
669 for weekday in range(0, 7):
670 f.write('<tr><th>%d</th>' % (weekday + 1))
671 for hour in range(0, 24):
672 try:
673 commits = data.activity_by_hour_of_week[weekday][hour]
674 except KeyError:
675 commits = 0
676 if commits != 0:
677 f.write('<td')
678 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
679 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
680 f.write('>%d</td>' % commits)
681 else:
682 f.write('<td></td>')
683 f.write('</tr>')
685 f.write('</table>')
687 # Month of Year
688 f.write(html_header(2, 'Month of Year'))
689 f.write('<div class="vtable"><table>')
690 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
691 fp = open (path + '/month_of_year.dat', 'w')
692 for mm in range(1, 13):
693 commits = 0
694 if mm in data.activity_by_month_of_year:
695 commits = data.activity_by_month_of_year[mm]
696 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
697 fp.write('%d %d\n' % (mm, commits))
698 fp.close()
699 f.write('</table></div>')
700 f.write('<img src="month_of_year.png" alt="Month of Year" />')
702 # Commits by year/month
703 f.write(html_header(2, 'Commits by year/month'))
704 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
705 for yymm in reversed(sorted(data.commits_by_month.keys())):
706 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
707 f.write('</table></div>')
708 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
709 fg = open(path + '/commits_by_year_month.dat', 'w')
710 for yymm in sorted(data.commits_by_month.keys()):
711 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
712 fg.close()
714 # Commits by year
715 f.write(html_header(2, 'Commits by Year'))
716 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
717 for yy in reversed(sorted(data.commits_by_year.keys())):
718 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()))
719 f.write('</table></div>')
720 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
721 fg = open(path + '/commits_by_year.dat', 'w')
722 for yy in sorted(data.commits_by_year.keys()):
723 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
724 fg.close()
726 # Commits by timezone
727 f.write(html_header(2, 'Commits by Timezone'))
728 f.write('<table><tr>')
729 f.write('<th>Timezone</th><th>Commits</th>')
730 max_commits_on_tz = max(data.commits_by_timezone.values())
731 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
732 commits = data.commits_by_timezone[i]
733 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
734 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
735 f.write('</tr></table>')
737 f.write('</body></html>')
738 f.close()
741 # Authors
742 f = open(path + '/authors.html', 'w')
743 self.printHeader(f)
745 f.write('<h1>Authors</h1>')
746 self.printNav(f)
748 # Authors :: List of authors
749 f.write(html_header(2, 'List of Authors'))
751 f.write('<table class="authors sortable" id="authors">')
752 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>')
753 for author in sorted(data.getAuthors()):
754 info = data.getAuthorInfo(author)
755 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']))
756 f.write('</table>')
758 # Authors :: Author of Month
759 f.write(html_header(2, 'Author of Month'))
760 f.write('<table class="sortable" id="aom">')
761 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
762 for yymm in reversed(sorted(data.author_of_month.keys())):
763 authordict = data.author_of_month[yymm]
764 authors = getkeyssortedbyvalues(authordict)
765 authors.reverse()
766 commits = data.author_of_month[yymm][authors[0]]
767 next = ', '.join(authors[1:5])
768 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))
770 f.write('</table>')
772 f.write(html_header(2, 'Author of Year'))
773 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>')
774 for yy in reversed(sorted(data.author_of_year.keys())):
775 authordict = data.author_of_year[yy]
776 authors = getkeyssortedbyvalues(authordict)
777 authors.reverse()
778 commits = data.author_of_year[yy][authors[0]]
779 next = ', '.join(authors[1:5])
780 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))
781 f.write('</table>')
783 # Domains
784 f.write(html_header(2, 'Commits by Domains'))
785 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
786 domains_by_commits.reverse() # most first
787 f.write('<div class="vtable"><table>')
788 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
789 fp = open(path + '/domains.dat', 'w')
790 n = 0
791 max_domains = 10
792 for domain in domains_by_commits:
793 if n == max_domains:
794 break
795 commits = 0
796 n += 1
797 info = data.getDomainInfo(domain)
798 fp.write('%s %d %d\n' % (domain, n , info['commits']))
799 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
800 f.write('</table></div>')
801 f.write('<img src="domains.png" alt="Commits by Domains" />')
802 fp.close()
804 f.write('</body></html>')
805 f.close()
808 # Files
809 f = open(path + '/files.html', 'w')
810 self.printHeader(f)
811 f.write('<h1>Files</h1>')
812 self.printNav(f)
814 f.write('<dl>\n')
815 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
816 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
817 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
818 f.write('</dl>\n')
820 # Files :: File count by date
821 f.write(html_header(2, 'File count by date'))
823 # use set to get rid of duplicate/unnecessary entries
824 files_by_date = set()
825 for stamp in sorted(data.files_by_stamp.keys()):
826 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
828 fg = open(path + '/files_by_date.dat', 'w')
829 for line in sorted(list(files_by_date)):
830 fg.write('%s\n' % line)
831 #for stamp in sorted(data.files_by_stamp.keys()):
832 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
833 fg.close()
835 f.write('<img src="files_by_date.png" alt="Files by Date" />')
837 #f.write('<h2>Average file size by date</h2>')
839 # Files :: Extensions
840 f.write(html_header(2, 'Extensions'))
841 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
842 for ext in sorted(data.extensions.keys()):
843 files = data.extensions[ext]['files']
844 lines = data.extensions[ext]['lines']
845 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))
846 f.write('</table>')
848 f.write('</body></html>')
849 f.close()
852 # Lines
853 f = open(path + '/lines.html', 'w')
854 self.printHeader(f)
855 f.write('<h1>Lines</h1>')
856 self.printNav(f)
858 f.write('<dl>\n')
859 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
860 f.write('</dl>\n')
862 f.write(html_header(2, 'Lines of Code'))
863 f.write('<img src="lines_of_code.png" />')
865 fg = open(path + '/lines_of_code.dat', 'w')
866 for stamp in sorted(data.changes_by_date.keys()):
867 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
868 fg.close()
870 f.write('</body></html>')
871 f.close()
874 # tags.html
875 f = open(path + '/tags.html', 'w')
876 self.printHeader(f)
877 f.write('<h1>Tags</h1>')
878 self.printNav(f)
880 f.write('<dl>')
881 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
882 if len(data.tags) > 0:
883 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
884 f.write('</dl>')
886 f.write('<table class="tags">')
887 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
888 # sort the tags by date desc
889 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
890 for tag in tags_sorted_by_date_desc:
891 authorinfo = []
892 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
893 for i in reversed(authors_by_commits):
894 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
895 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)))
896 f.write('</table>')
898 f.write('</body></html>')
899 f.close()
901 self.createGraphs(path)
903 def createGraphs(self, path):
904 print 'Generating graphs...'
906 # hour of day
907 f = open(path + '/hour_of_day.plot', 'w')
908 f.write(GNUPLOT_COMMON)
909 f.write(
911 set output 'hour_of_day.png'
912 unset key
913 set xrange [0.5:24.5]
914 set xtics 4
915 set ylabel "Commits"
916 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
917 """)
918 f.close()
920 # day of week
921 f = open(path + '/day_of_week.plot', 'w')
922 f.write(GNUPLOT_COMMON)
923 f.write(
925 set output 'day_of_week.png'
926 unset key
927 set xrange [0.5:7.5]
928 set xtics 1
929 set ylabel "Commits"
930 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
931 """)
932 f.close()
934 # Domains
935 f = open(path + '/domains.plot', 'w')
936 f.write(GNUPLOT_COMMON)
937 f.write(
939 set output 'domains.png'
940 unset key
941 unset xtics
942 set grid y
943 set ylabel "Commits"
944 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
945 """)
946 f.close()
948 # Month of Year
949 f = open(path + '/month_of_year.plot', 'w')
950 f.write(GNUPLOT_COMMON)
951 f.write(
953 set output 'month_of_year.png'
954 unset key
955 set xrange [0.5:12.5]
956 set xtics 1
957 set ylabel "Commits"
958 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
959 """)
960 f.close()
962 # commits_by_year_month
963 f = open(path + '/commits_by_year_month.plot', 'w')
964 f.write(GNUPLOT_COMMON)
965 f.write(
967 set output 'commits_by_year_month.png'
968 unset key
969 set xdata time
970 set timefmt "%Y-%m"
971 set format x "%Y-%m"
972 set xtics rotate by 90 15768000
973 set bmargin 5
974 set ylabel "Commits"
975 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
976 """)
977 f.close()
979 # commits_by_year
980 f = open(path + '/commits_by_year.plot', 'w')
981 f.write(GNUPLOT_COMMON)
982 f.write(
984 set output 'commits_by_year.png'
985 unset key
986 set xtics 1
987 set ylabel "Commits"
988 set yrange [0:]
989 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
990 """)
991 f.close()
993 # Files by date
994 f = open(path + '/files_by_date.plot', 'w')
995 f.write(GNUPLOT_COMMON)
996 f.write(
998 set output 'files_by_date.png'
999 unset key
1000 set xdata time
1001 set timefmt "%Y-%m-%d"
1002 set format x "%Y-%m-%d"
1003 set ylabel "Files"
1004 set xtics rotate by 90
1005 set ytics autofreq
1006 set bmargin 6
1007 plot 'files_by_date.dat' using 1:2 w steps
1008 """)
1009 f.close()
1011 # Lines of Code
1012 f = open(path + '/lines_of_code.plot', 'w')
1013 f.write(GNUPLOT_COMMON)
1014 f.write(
1016 set output 'lines_of_code.png'
1017 unset key
1018 set xdata time
1019 set timefmt "%s"
1020 set format x "%Y-%m-%d"
1021 set ylabel "Lines"
1022 set xtics rotate by 90
1023 set bmargin 6
1024 plot 'lines_of_code.dat' using 1:2 w lines
1025 """)
1026 f.close()
1028 os.chdir(path)
1029 files = glob.glob(path + '/*.plot')
1030 for f in files:
1031 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1032 if len(out) > 0:
1033 print out
1035 def printHeader(self, f, title = ''):
1036 f.write(
1037 """<?xml version="1.0" encoding="UTF-8"?>
1038 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1039 <html xmlns="http://www.w3.org/1999/xhtml">
1040 <head>
1041 <title>GitStats - %s</title>
1042 <link rel="stylesheet" href="gitstats.css" type="text/css" />
1043 <meta name="generator" content="GitStats %s" />
1044 <script type="text/javascript" src="sortable.js"></script>
1045 </head>
1046 <body>
1047 """ % (self.title, getversion()))
1049 def printNav(self, f):
1050 f.write("""
1051 <div class="nav">
1052 <ul>
1053 <li><a href="index.html">General</a></li>
1054 <li><a href="activity.html">Activity</a></li>
1055 <li><a href="authors.html">Authors</a></li>
1056 <li><a href="files.html">Files</a></li>
1057 <li><a href="lines.html">Lines</a></li>
1058 <li><a href="tags.html">Tags</a></li>
1059 </ul>
1060 </div>
1061 """)
1064 usage = """
1065 Usage: gitstats [options] <gitpath> <outputpath>
1067 Options:
1070 if len(sys.argv) < 3:
1071 print usage
1072 sys.exit(0)
1074 gitpath = sys.argv[1]
1075 outputpath = os.path.abspath(sys.argv[2])
1076 rundir = os.getcwd()
1078 try:
1079 os.makedirs(outputpath)
1080 except OSError:
1081 pass
1082 if not os.path.isdir(outputpath):
1083 print 'FATAL: Output path is not a directory or does not exist'
1084 sys.exit(1)
1086 print 'Git path: %s' % gitpath
1087 print 'Output path: %s' % outputpath
1089 os.chdir(gitpath)
1091 cachefile = os.path.join(outputpath, 'gitstats.cache')
1093 print 'Collecting data...'
1094 data = GitDataCollector()
1095 data.loadCache(cachefile)
1096 data.collect(gitpath)
1097 print 'Refining data...'
1098 data.saveCache(cachefile)
1099 data.refine()
1101 os.chdir(rundir)
1103 print 'Generating report...'
1104 report = HTMLReportCreator()
1105 report.create(data, outputpath)
1107 time_end = time.time()
1108 exectime_internal = time_end - time_start
1109 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)