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