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