Oops, actually fix the handling of mails without '@'.
[gitstats.git] / gitstats
blob8404e2aa15f6d5c6995ee0d8e4b061480cafda8d
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 = '?'
244 if mail.find('@') != -1:
245 domain = mail.rsplit('@', 1)[1]
246 date = datetime.datetime.fromtimestamp(float(stamp))
248 # First and last commit stamp
249 if self.last_commit_stamp == 0:
250 self.last_commit_stamp = stamp
251 self.first_commit_stamp = stamp
253 # activity
254 # hour
255 hour = date.hour
256 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
257 # most active hour?
258 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
259 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
261 # day of week
262 day = date.weekday()
263 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
265 # domain stats
266 if domain not in self.domains:
267 self.domains[domain] = {}
268 # commits
269 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
271 # hour of week
272 if day not in self.activity_by_hour_of_week:
273 self.activity_by_hour_of_week[day] = {}
274 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
275 # most active hour?
276 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
277 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
279 # month of year
280 month = date.month
281 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
283 # yearly/weekly activity
284 yyw = date.strftime('%Y-%W')
285 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
286 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
287 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
289 # author stats
290 if author not in self.authors:
291 self.authors[author] = {}
292 # commits
293 if 'last_commit_stamp' not in self.authors[author]:
294 self.authors[author]['last_commit_stamp'] = stamp
295 self.authors[author]['first_commit_stamp'] = stamp
296 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
298 # author of the month/year
299 yymm = date.strftime('%Y-%m')
300 if yymm in self.author_of_month:
301 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
302 else:
303 self.author_of_month[yymm] = {}
304 self.author_of_month[yymm][author] = 1
305 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
307 yy = date.year
308 if yy in self.author_of_year:
309 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
310 else:
311 self.author_of_year[yy] = {}
312 self.author_of_year[yy][author] = 1
313 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
315 # authors: active days
316 yymmdd = date.strftime('%Y-%m-%d')
317 if 'last_active_day' not in self.authors[author]:
318 self.authors[author]['last_active_day'] = yymmdd
319 self.authors[author]['active_days'] = 1
320 elif yymmdd != self.authors[author]['last_active_day']:
321 self.authors[author]['last_active_day'] = yymmdd
322 self.authors[author]['active_days'] += 1
324 # project: active days
325 if yymmdd != self.last_active_day:
326 self.last_active_day = yymmdd
327 self.active_days.add(yymmdd)
329 # timezone
330 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
332 # TODO Optimize this, it's the worst bottleneck
333 # outputs "<stamp> <files>" for each revision
334 self.files_by_stamp = {} # stamp -> files
335 revlines = getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
336 lines = []
337 for revline in revlines:
338 time, rev = revline.split(' ')
339 linecount = self.getFilesInCommit(rev)
340 lines.append('%d %d' % (int(time), linecount))
342 self.total_commits = len(lines)
343 for line in lines:
344 parts = line.split(' ')
345 if len(parts) != 2:
346 continue
347 (stamp, files) = parts[0:2]
348 try:
349 self.files_by_stamp[int(stamp)] = int(files)
350 except ValueError:
351 print 'Warning: failed to parse line "%s"' % line
353 # extensions
354 self.extensions = {} # extension -> files, lines
355 lines = getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
356 self.total_files = len(lines)
357 for line in lines:
358 if len(line) == 0:
359 continue
360 parts = re.split('\s+', line, 4)
361 sha1 = parts[2]
362 filename = parts[3]
364 if filename.find('.') == -1 or filename.rfind('.') == 0:
365 ext = ''
366 else:
367 ext = filename[(filename.rfind('.') + 1):]
368 if len(ext) > MAX_EXT_LENGTH:
369 ext = ''
371 if ext not in self.extensions:
372 self.extensions[ext] = {'files': 0, 'lines': 0}
374 self.extensions[ext]['files'] += 1
375 try:
376 self.extensions[ext]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
377 except:
378 print 'Warning: Could not count lines for file "%s"' % line
380 # line statistics
381 # outputs:
382 # N files changed, N insertions (+), N deletions(-)
383 # <stamp> <author>
384 self.changes_by_date = {} # stamp -> { files, ins, del }
385 lines = getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
386 lines.reverse()
387 files = 0; inserted = 0; deleted = 0; total_lines = 0
388 author = None
389 for line in lines:
390 if len(line) == 0:
391 continue
393 # <stamp> <author>
394 if line.find('files changed,') == -1:
395 pos = line.find(' ')
396 if pos != -1:
397 try:
398 (stamp, author) = (int(line[:pos]), line[pos+1:])
399 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
400 if author not in self.authors:
401 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
402 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
403 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
404 except ValueError:
405 print 'Warning: unexpected line "%s"' % line
406 else:
407 print 'Warning: unexpected line "%s"' % line
408 else:
409 numbers = re.findall('\d+', line)
410 if len(numbers) == 3:
411 (files, inserted, deleted) = map(lambda el : int(el), numbers)
412 total_lines += inserted
413 total_lines -= deleted
414 self.total_lines_added += inserted
415 self.total_lines_removed += deleted
416 else:
417 print 'Warning: failed to handle line "%s"' % line
418 (files, inserted, deleted) = (0, 0, 0)
419 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
420 self.total_lines = total_lines
422 def refine(self):
423 # authors
424 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
425 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
426 authors_by_commits.reverse() # most first
427 for i, name in enumerate(authors_by_commits):
428 self.authors[name]['place_by_commits'] = i + 1
430 for name in self.authors.keys():
431 a = self.authors[name]
432 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
433 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
434 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
435 delta = date_last - date_first
436 a['date_first'] = date_first.strftime('%Y-%m-%d')
437 a['date_last'] = date_last.strftime('%Y-%m-%d')
438 a['timedelta'] = delta
440 def getActiveDays(self):
441 return self.active_days
443 def getActivityByDayOfWeek(self):
444 return self.activity_by_day_of_week
446 def getActivityByHourOfDay(self):
447 return self.activity_by_hour_of_day
449 def getAuthorInfo(self, author):
450 return self.authors[author]
452 def getAuthors(self):
453 return self.authors.keys()
455 def getCommitDeltaDays(self):
456 return (self.last_commit_stamp - self.first_commit_stamp) / 86400
458 def getDomainInfo(self, domain):
459 return self.domains[domain]
461 def getDomains(self):
462 return self.domains.keys()
464 def getFilesInCommit(self, rev):
465 try:
466 res = self.cache['files_in_tree'][rev]
467 except:
468 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
469 if 'files_in_tree' not in self.cache:
470 self.cache['files_in_tree'] = {}
471 self.cache['files_in_tree'][rev] = res
473 return res
475 def getFirstCommitDate(self):
476 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
478 def getLastCommitDate(self):
479 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
481 def getTags(self):
482 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
483 return lines.split('\n')
485 def getTagDate(self, tag):
486 return self.revToDate('tags/' + tag)
488 def getTotalAuthors(self):
489 return self.total_authors
491 def getTotalCommits(self):
492 return self.total_commits
494 def getTotalFiles(self):
495 return self.total_files
497 def getTotalLOC(self):
498 return self.total_lines
500 def revToDate(self, rev):
501 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
502 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
504 class ReportCreator:
505 """Creates the actual report based on given data."""
506 def __init__(self):
507 pass
509 def create(self, data, path):
510 self.data = data
511 self.path = path
513 def html_linkify(text):
514 return text.lower().replace(' ', '_')
516 def html_header(level, text):
517 name = html_linkify(text)
518 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
520 class HTMLReportCreator(ReportCreator):
521 def create(self, data, path):
522 ReportCreator.create(self, data, path)
523 self.title = data.projectname
525 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
526 binarypath = os.path.dirname(os.path.abspath(__file__))
527 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
528 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
529 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
530 for base in basedirs:
531 src = base + '/' + file
532 if os.path.exists(src):
533 shutil.copyfile(src, path + '/' + file)
534 break
535 else:
536 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
538 f = open(path + "/index.html", 'w')
539 format = '%Y-%m-%d %H:%M:%S'
540 self.printHeader(f)
542 f.write('<h1>GitStats - %s</h1>' % data.projectname)
544 self.printNav(f)
546 f.write('<dl>')
547 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
548 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
549 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
550 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
551 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())))
552 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
553 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))
554 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()))
555 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
556 f.write('</dl>')
558 f.write('</body>\n</html>')
559 f.close()
562 # Activity
563 f = open(path + '/activity.html', 'w')
564 self.printHeader(f)
565 f.write('<h1>Activity</h1>')
566 self.printNav(f)
568 #f.write('<h2>Last 30 days</h2>')
570 #f.write('<h2>Last 12 months</h2>')
572 # Weekly activity
573 WEEKS = 32
574 f.write(html_header(2, 'Weekly activity'))
575 f.write('<p>Last %d weeks</p>' % WEEKS)
577 # generate weeks to show (previous N weeks from now)
578 now = datetime.datetime.now()
579 deltaweek = datetime.timedelta(7)
580 weeks = []
581 stampcur = now
582 for i in range(0, WEEKS):
583 weeks.insert(0, stampcur.strftime('%Y-%W'))
584 stampcur -= deltaweek
586 # top row: commits & bar
587 f.write('<table class="noborders"><tr>')
588 for i in range(0, WEEKS):
589 commits = 0
590 if weeks[i] in data.activity_by_year_week:
591 commits = data.activity_by_year_week[weeks[i]]
593 percentage = 0
594 if weeks[i] in data.activity_by_year_week:
595 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
596 height = max(1, int(200 * percentage))
597 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))
599 # bottom row: year/week
600 f.write('</tr><tr>')
601 for i in range(0, WEEKS):
602 f.write('<td>%s</td>' % (WEEKS - i))
603 f.write('</tr></table>')
605 # Hour of Day
606 f.write(html_header(2, 'Hour of Day'))
607 hour_of_day = data.getActivityByHourOfDay()
608 f.write('<table><tr><th>Hour</th>')
609 for i in range(0, 24):
610 f.write('<th>%d</th>' % i)
611 f.write('</tr>\n<tr><th>Commits</th>')
612 fp = open(path + '/hour_of_day.dat', 'w')
613 for i in range(0, 24):
614 if i in hour_of_day:
615 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
616 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
617 fp.write('%d %d\n' % (i, hour_of_day[i]))
618 else:
619 f.write('<td>0</td>')
620 fp.write('%d 0\n' % i)
621 fp.close()
622 f.write('</tr>\n<tr><th>%</th>')
623 totalcommits = data.getTotalCommits()
624 for i in range(0, 24):
625 if i in hour_of_day:
626 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
627 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
628 else:
629 f.write('<td>0.00</td>')
630 f.write('</tr></table>')
631 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
632 fg = open(path + '/hour_of_day.dat', 'w')
633 for i in range(0, 24):
634 if i in hour_of_day:
635 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
636 else:
637 fg.write('%d 0\n' % (i + 1))
638 fg.close()
640 # Day of Week
641 f.write(html_header(2, 'Day of Week'))
642 day_of_week = data.getActivityByDayOfWeek()
643 f.write('<div class="vtable"><table>')
644 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
645 fp = open(path + '/day_of_week.dat', 'w')
646 for d in range(0, 7):
647 commits = 0
648 if d in day_of_week:
649 commits = day_of_week[d]
650 fp.write('%d %d\n' % (d + 1, commits))
651 f.write('<tr>')
652 f.write('<th>%d</th>' % (d + 1))
653 if d in day_of_week:
654 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
655 else:
656 f.write('<td>0</td>')
657 f.write('</tr>')
658 f.write('</table></div>')
659 f.write('<img src="day_of_week.png" alt="Day of Week" />')
660 fp.close()
662 # Hour of Week
663 f.write(html_header(2, 'Hour of Week'))
664 f.write('<table>')
666 f.write('<tr><th>Weekday</th>')
667 for hour in range(0, 24):
668 f.write('<th>%d</th>' % (hour))
669 f.write('</tr>')
671 for weekday in range(0, 7):
672 f.write('<tr><th>%d</th>' % (weekday + 1))
673 for hour in range(0, 24):
674 try:
675 commits = data.activity_by_hour_of_week[weekday][hour]
676 except KeyError:
677 commits = 0
678 if commits != 0:
679 f.write('<td')
680 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
681 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
682 f.write('>%d</td>' % commits)
683 else:
684 f.write('<td></td>')
685 f.write('</tr>')
687 f.write('</table>')
689 # Month of Year
690 f.write(html_header(2, 'Month of Year'))
691 f.write('<div class="vtable"><table>')
692 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
693 fp = open (path + '/month_of_year.dat', 'w')
694 for mm in range(1, 13):
695 commits = 0
696 if mm in data.activity_by_month_of_year:
697 commits = data.activity_by_month_of_year[mm]
698 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
699 fp.write('%d %d\n' % (mm, commits))
700 fp.close()
701 f.write('</table></div>')
702 f.write('<img src="month_of_year.png" alt="Month of Year" />')
704 # Commits by year/month
705 f.write(html_header(2, 'Commits by year/month'))
706 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
707 for yymm in reversed(sorted(data.commits_by_month.keys())):
708 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
709 f.write('</table></div>')
710 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
711 fg = open(path + '/commits_by_year_month.dat', 'w')
712 for yymm in sorted(data.commits_by_month.keys()):
713 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
714 fg.close()
716 # Commits by year
717 f.write(html_header(2, 'Commits by Year'))
718 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
719 for yy in reversed(sorted(data.commits_by_year.keys())):
720 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()))
721 f.write('</table></div>')
722 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
723 fg = open(path + '/commits_by_year.dat', 'w')
724 for yy in sorted(data.commits_by_year.keys()):
725 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
726 fg.close()
728 # Commits by timezone
729 f.write(html_header(2, 'Commits by Timezone'))
730 f.write('<table><tr>')
731 f.write('<th>Timezone</th><th>Commits</th>')
732 max_commits_on_tz = max(data.commits_by_timezone.values())
733 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
734 commits = data.commits_by_timezone[i]
735 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
736 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
737 f.write('</tr></table>')
739 f.write('</body></html>')
740 f.close()
743 # Authors
744 f = open(path + '/authors.html', 'w')
745 self.printHeader(f)
747 f.write('<h1>Authors</h1>')
748 self.printNav(f)
750 # Authors :: List of authors
751 f.write(html_header(2, 'List of Authors'))
753 f.write('<table class="authors sortable" id="authors">')
754 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>')
755 for author in sorted(data.getAuthors()):
756 info = data.getAuthorInfo(author)
757 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']))
758 f.write('</table>')
760 # Authors :: Author of Month
761 f.write(html_header(2, 'Author of Month'))
762 f.write('<table class="sortable" id="aom">')
763 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
764 for yymm in reversed(sorted(data.author_of_month.keys())):
765 authordict = data.author_of_month[yymm]
766 authors = getkeyssortedbyvalues(authordict)
767 authors.reverse()
768 commits = data.author_of_month[yymm][authors[0]]
769 next = ', '.join(authors[1:5])
770 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))
772 f.write('</table>')
774 f.write(html_header(2, 'Author of Year'))
775 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>')
776 for yy in reversed(sorted(data.author_of_year.keys())):
777 authordict = data.author_of_year[yy]
778 authors = getkeyssortedbyvalues(authordict)
779 authors.reverse()
780 commits = data.author_of_year[yy][authors[0]]
781 next = ', '.join(authors[1:5])
782 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))
783 f.write('</table>')
785 # Domains
786 f.write(html_header(2, 'Commits by Domains'))
787 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
788 domains_by_commits.reverse() # most first
789 f.write('<div class="vtable"><table>')
790 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
791 fp = open(path + '/domains.dat', 'w')
792 n = 0
793 max_domains = 10
794 for domain in domains_by_commits:
795 if n == max_domains:
796 break
797 commits = 0
798 n += 1
799 info = data.getDomainInfo(domain)
800 fp.write('%s %d %d\n' % (domain, n , info['commits']))
801 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
802 f.write('</table></div>')
803 f.write('<img src="domains.png" alt="Commits by Domains" />')
804 fp.close()
806 f.write('</body></html>')
807 f.close()
810 # Files
811 f = open(path + '/files.html', 'w')
812 self.printHeader(f)
813 f.write('<h1>Files</h1>')
814 self.printNav(f)
816 f.write('<dl>\n')
817 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
818 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
819 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
820 f.write('</dl>\n')
822 # Files :: File count by date
823 f.write(html_header(2, 'File count by date'))
825 # use set to get rid of duplicate/unnecessary entries
826 files_by_date = set()
827 for stamp in sorted(data.files_by_stamp.keys()):
828 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
830 fg = open(path + '/files_by_date.dat', 'w')
831 for line in sorted(list(files_by_date)):
832 fg.write('%s\n' % line)
833 #for stamp in sorted(data.files_by_stamp.keys()):
834 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
835 fg.close()
837 f.write('<img src="files_by_date.png" alt="Files by Date" />')
839 #f.write('<h2>Average file size by date</h2>')
841 # Files :: Extensions
842 f.write(html_header(2, 'Extensions'))
843 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
844 for ext in sorted(data.extensions.keys()):
845 files = data.extensions[ext]['files']
846 lines = data.extensions[ext]['lines']
847 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))
848 f.write('</table>')
850 f.write('</body></html>')
851 f.close()
854 # Lines
855 f = open(path + '/lines.html', 'w')
856 self.printHeader(f)
857 f.write('<h1>Lines</h1>')
858 self.printNav(f)
860 f.write('<dl>\n')
861 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
862 f.write('</dl>\n')
864 f.write(html_header(2, 'Lines of Code'))
865 f.write('<img src="lines_of_code.png" />')
867 fg = open(path + '/lines_of_code.dat', 'w')
868 for stamp in sorted(data.changes_by_date.keys()):
869 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
870 fg.close()
872 f.write('</body></html>')
873 f.close()
876 # tags.html
877 f = open(path + '/tags.html', 'w')
878 self.printHeader(f)
879 f.write('<h1>Tags</h1>')
880 self.printNav(f)
882 f.write('<dl>')
883 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
884 if len(data.tags) > 0:
885 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
886 f.write('</dl>')
888 f.write('<table class="tags">')
889 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
890 # sort the tags by date desc
891 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
892 for tag in tags_sorted_by_date_desc:
893 authorinfo = []
894 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
895 for i in reversed(authors_by_commits):
896 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
897 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)))
898 f.write('</table>')
900 f.write('</body></html>')
901 f.close()
903 self.createGraphs(path)
905 def createGraphs(self, path):
906 print 'Generating graphs...'
908 # hour of day
909 f = open(path + '/hour_of_day.plot', 'w')
910 f.write(GNUPLOT_COMMON)
911 f.write(
913 set output 'hour_of_day.png'
914 unset key
915 set xrange [0.5:24.5]
916 set xtics 4
917 set ylabel "Commits"
918 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
919 """)
920 f.close()
922 # day of week
923 f = open(path + '/day_of_week.plot', 'w')
924 f.write(GNUPLOT_COMMON)
925 f.write(
927 set output 'day_of_week.png'
928 unset key
929 set xrange [0.5:7.5]
930 set xtics 1
931 set ylabel "Commits"
932 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
933 """)
934 f.close()
936 # Domains
937 f = open(path + '/domains.plot', 'w')
938 f.write(GNUPLOT_COMMON)
939 f.write(
941 set output 'domains.png'
942 unset key
943 unset xtics
944 set grid y
945 set ylabel "Commits"
946 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
947 """)
948 f.close()
950 # Month of Year
951 f = open(path + '/month_of_year.plot', 'w')
952 f.write(GNUPLOT_COMMON)
953 f.write(
955 set output 'month_of_year.png'
956 unset key
957 set xrange [0.5:12.5]
958 set xtics 1
959 set ylabel "Commits"
960 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
961 """)
962 f.close()
964 # commits_by_year_month
965 f = open(path + '/commits_by_year_month.plot', 'w')
966 f.write(GNUPLOT_COMMON)
967 f.write(
969 set output 'commits_by_year_month.png'
970 unset key
971 set xdata time
972 set timefmt "%Y-%m"
973 set format x "%Y-%m"
974 set xtics rotate by 90 15768000
975 set bmargin 5
976 set ylabel "Commits"
977 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
978 """)
979 f.close()
981 # commits_by_year
982 f = open(path + '/commits_by_year.plot', 'w')
983 f.write(GNUPLOT_COMMON)
984 f.write(
986 set output 'commits_by_year.png'
987 unset key
988 set xtics 1
989 set ylabel "Commits"
990 set yrange [0:]
991 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
992 """)
993 f.close()
995 # Files by date
996 f = open(path + '/files_by_date.plot', 'w')
997 f.write(GNUPLOT_COMMON)
998 f.write(
1000 set output 'files_by_date.png'
1001 unset key
1002 set xdata time
1003 set timefmt "%Y-%m-%d"
1004 set format x "%Y-%m-%d"
1005 set ylabel "Files"
1006 set xtics rotate by 90
1007 set ytics autofreq
1008 set bmargin 6
1009 plot 'files_by_date.dat' using 1:2 w steps
1010 """)
1011 f.close()
1013 # Lines of Code
1014 f = open(path + '/lines_of_code.plot', 'w')
1015 f.write(GNUPLOT_COMMON)
1016 f.write(
1018 set output 'lines_of_code.png'
1019 unset key
1020 set xdata time
1021 set timefmt "%s"
1022 set format x "%Y-%m-%d"
1023 set ylabel "Lines"
1024 set xtics rotate by 90
1025 set bmargin 6
1026 plot 'lines_of_code.dat' using 1:2 w lines
1027 """)
1028 f.close()
1030 os.chdir(path)
1031 files = glob.glob(path + '/*.plot')
1032 for f in files:
1033 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1034 if len(out) > 0:
1035 print out
1037 def printHeader(self, f, title = ''):
1038 f.write(
1039 """<?xml version="1.0" encoding="UTF-8"?>
1040 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1041 <html xmlns="http://www.w3.org/1999/xhtml">
1042 <head>
1043 <title>GitStats - %s</title>
1044 <link rel="stylesheet" href="gitstats.css" type="text/css" />
1045 <meta name="generator" content="GitStats %s" />
1046 <script type="text/javascript" src="sortable.js"></script>
1047 </head>
1048 <body>
1049 """ % (self.title, getversion()))
1051 def printNav(self, f):
1052 f.write("""
1053 <div class="nav">
1054 <ul>
1055 <li><a href="index.html">General</a></li>
1056 <li><a href="activity.html">Activity</a></li>
1057 <li><a href="authors.html">Authors</a></li>
1058 <li><a href="files.html">Files</a></li>
1059 <li><a href="lines.html">Lines</a></li>
1060 <li><a href="tags.html">Tags</a></li>
1061 </ul>
1062 </div>
1063 """)
1066 usage = """
1067 Usage: gitstats [options] <gitpath> <outputpath>
1069 Options:
1072 if len(sys.argv) < 3:
1073 print usage
1074 sys.exit(0)
1076 gitpath = sys.argv[1]
1077 outputpath = os.path.abspath(sys.argv[2])
1078 rundir = os.getcwd()
1080 try:
1081 os.makedirs(outputpath)
1082 except OSError:
1083 pass
1084 if not os.path.isdir(outputpath):
1085 print 'FATAL: Output path is not a directory or does not exist'
1086 sys.exit(1)
1088 print 'Git path: %s' % gitpath
1089 print 'Output path: %s' % outputpath
1091 os.chdir(gitpath)
1093 cachefile = os.path.join(outputpath, 'gitstats.cache')
1095 print 'Collecting data...'
1096 data = GitDataCollector()
1097 data.loadCache(cachefile)
1098 data.collect(gitpath)
1099 print 'Refining data...'
1100 data.saveCache(cachefile)
1101 data.refine()
1103 os.chdir(rundir)
1105 print 'Generating report...'
1106 report = HTMLReportCreator()
1107 report.create(data, outputpath)
1109 time_end = time.time()
1110 exectime_internal = time_end - time_start
1111 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)