Set 'ytics 1' for files graph.
[gitstats.git] / gitstats
blob7bb9128335c05c35b2fed1e0289182b5e2febfdf
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 if they do not exist
485 basedirs = [os.path.dirname(os.path.abspath(__file__)), '/usr/share/gitstats']
486 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
487 for base in basedirs:
488 src = base + '/' + file
489 if os.path.exists(src):
490 shutil.copyfile(src, path + '/' + file)
491 break
492 else:
493 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
495 f = open(path + "/index.html", 'w')
496 format = '%Y-%m-%d %H:%M:%S'
497 self.printHeader(f)
499 f.write('<h1>GitStats - %s</h1>' % data.projectname)
501 self.printNav(f)
503 f.write('<dl>')
504 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
505 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
506 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
507 f.write('<dt>Report Period</dt><dd>%s to %s (%d days)</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format), data.getCommitDeltaDays()))
508 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
509 f.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data.getTotalLOC())
510 f.write('<dt>Total Commits</dt><dd>%s</dd>' % data.getTotalCommits())
511 f.write('<dt>Authors</dt><dd>%s</dd>' % data.getTotalAuthors())
512 f.write('</dl>')
514 f.write('</body>\n</html>')
515 f.close()
518 # Activity
519 f = open(path + '/activity.html', 'w')
520 self.printHeader(f)
521 f.write('<h1>Activity</h1>')
522 self.printNav(f)
524 #f.write('<h2>Last 30 days</h2>')
526 #f.write('<h2>Last 12 months</h2>')
528 # Hour of Day
529 f.write(html_header(2, 'Hour of Day'))
530 hour_of_day = data.getActivityByHourOfDay()
531 f.write('<table><tr><th>Hour</th>')
532 for i in range(0, 24):
533 f.write('<th>%d</th>' % i)
534 f.write('</tr>\n<tr><th>Commits</th>')
535 fp = open(path + '/hour_of_day.dat', 'w')
536 for i in range(0, 24):
537 if i in hour_of_day:
538 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
539 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
540 fp.write('%d %d\n' % (i, hour_of_day[i]))
541 else:
542 f.write('<td>0</td>')
543 fp.write('%d 0\n' % i)
544 fp.close()
545 f.write('</tr>\n<tr><th>%</th>')
546 totalcommits = data.getTotalCommits()
547 for i in range(0, 24):
548 if i in hour_of_day:
549 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
550 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
551 else:
552 f.write('<td>0.00</td>')
553 f.write('</tr></table>')
554 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
555 fg = open(path + '/hour_of_day.dat', 'w')
556 for i in range(0, 24):
557 if i in hour_of_day:
558 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
559 else:
560 fg.write('%d 0\n' % (i + 1))
561 fg.close()
563 # Day of Week
564 f.write(html_header(2, 'Day of Week'))
565 day_of_week = data.getActivityByDayOfWeek()
566 f.write('<div class="vtable"><table>')
567 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
568 fp = open(path + '/day_of_week.dat', 'w')
569 for d in range(0, 7):
570 commits = 0
571 if d in day_of_week:
572 commits = day_of_week[d]
573 fp.write('%d %d\n' % (d + 1, commits))
574 f.write('<tr>')
575 f.write('<th>%d</th>' % (d + 1))
576 if d in day_of_week:
577 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
578 else:
579 f.write('<td>0</td>')
580 f.write('</tr>')
581 f.write('</table></div>')
582 f.write('<img src="day_of_week.png" alt="Day of Week" />')
583 fp.close()
585 # Hour of Week
586 f.write(html_header(2, 'Hour of Week'))
587 f.write('<table>')
589 f.write('<tr><th>Weekday</th>')
590 for hour in range(0, 24):
591 f.write('<th>%d</th>' % (hour))
592 f.write('</tr>')
594 for weekday in range(0, 7):
595 f.write('<tr><th>%d</th>' % (weekday + 1))
596 for hour in range(0, 24):
597 try:
598 commits = data.activity_by_hour_of_week[weekday][hour]
599 except KeyError:
600 commits = 0
601 if commits != 0:
602 f.write('<td')
603 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
604 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
605 f.write('>%d</td>' % commits)
606 else:
607 f.write('<td></td>')
608 f.write('</tr>')
610 f.write('</table>')
612 # Month of Year
613 f.write(html_header(2, 'Month of Year'))
614 f.write('<div class="vtable"><table>')
615 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
616 fp = open (path + '/month_of_year.dat', 'w')
617 for mm in range(1, 13):
618 commits = 0
619 if mm in data.activity_by_month_of_year:
620 commits = data.activity_by_month_of_year[mm]
621 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
622 fp.write('%d %d\n' % (mm, commits))
623 fp.close()
624 f.write('</table></div>')
625 f.write('<img src="month_of_year.png" alt="Month of Year" />')
627 # Commits by year/month
628 f.write(html_header(2, 'Commits by year/month'))
629 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
630 for yymm in reversed(sorted(data.commits_by_month.keys())):
631 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
632 f.write('</table></div>')
633 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
634 fg = open(path + '/commits_by_year_month.dat', 'w')
635 for yymm in sorted(data.commits_by_month.keys()):
636 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
637 fg.close()
639 # Commits by year
640 f.write(html_header(2, 'Commits by Year'))
641 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
642 for yy in reversed(sorted(data.commits_by_year.keys())):
643 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()))
644 f.write('</table></div>')
645 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
646 fg = open(path + '/commits_by_year.dat', 'w')
647 for yy in sorted(data.commits_by_year.keys()):
648 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
649 fg.close()
651 f.write('</body></html>')
652 f.close()
655 # Authors
656 f = open(path + '/authors.html', 'w')
657 self.printHeader(f)
659 f.write('<h1>Authors</h1>')
660 self.printNav(f)
662 # Authors :: List of authors
663 f.write(html_header(2, 'List of Authors'))
665 f.write('<table class="authors sortable" id="authors">')
666 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>')
667 for author in sorted(data.getAuthors()):
668 info = data.getAuthorInfo(author)
669 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']))
670 f.write('</table>')
672 # Authors :: Author of Month
673 f.write(html_header(2, 'Author of Month'))
674 f.write('<table class="sortable" id="aom">')
675 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
676 for yymm in reversed(sorted(data.author_of_month.keys())):
677 authordict = data.author_of_month[yymm]
678 authors = getkeyssortedbyvalues(authordict)
679 authors.reverse()
680 commits = data.author_of_month[yymm][authors[0]]
681 next = ', '.join(authors[1:5])
682 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))
684 f.write('</table>')
686 f.write(html_header(2, 'Author of Year'))
687 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>')
688 for yy in reversed(sorted(data.author_of_year.keys())):
689 authordict = data.author_of_year[yy]
690 authors = getkeyssortedbyvalues(authordict)
691 authors.reverse()
692 commits = data.author_of_year[yy][authors[0]]
693 next = ', '.join(authors[1:5])
694 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))
695 f.write('</table>')
697 f.write('</body></html>')
698 f.close()
701 # Files
702 f = open(path + '/files.html', 'w')
703 self.printHeader(f)
704 f.write('<h1>Files</h1>')
705 self.printNav(f)
707 f.write('<dl>\n')
708 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
709 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
710 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
711 f.write('</dl>\n')
713 # Files :: File count by date
714 f.write(html_header(2, 'File count by date'))
716 fg = open(path + '/files_by_date.dat', 'w')
717 for stamp in sorted(data.files_by_stamp.keys()):
718 fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
719 fg.close()
721 f.write('<img src="files_by_date.png" alt="Files by Date" />')
723 #f.write('<h2>Average file size by date</h2>')
725 # Files :: Extensions
726 f.write(html_header(2, 'Extensions'))
727 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
728 for ext in sorted(data.extensions.keys()):
729 files = data.extensions[ext]['files']
730 lines = data.extensions[ext]['lines']
731 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))
732 f.write('</table>')
734 f.write('</body></html>')
735 f.close()
738 # Lines
739 f = open(path + '/lines.html', 'w')
740 self.printHeader(f)
741 f.write('<h1>Lines</h1>')
742 self.printNav(f)
744 f.write('<dl>\n')
745 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
746 f.write('</dl>\n')
748 f.write(html_header(2, 'Lines of Code'))
749 f.write('<img src="lines_of_code.png" />')
751 fg = open(path + '/lines_of_code.dat', 'w')
752 for stamp in sorted(data.changes_by_date.keys()):
753 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
754 fg.close()
756 f.write('</body></html>')
757 f.close()
760 # tags.html
761 f = open(path + '/tags.html', 'w')
762 self.printHeader(f)
763 f.write('<h1>Tags</h1>')
764 self.printNav(f)
766 f.write('<dl>')
767 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
768 if len(data.tags) > 0:
769 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
770 f.write('</dl>')
772 f.write('<table>')
773 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
774 # sort the tags by date desc
775 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
776 for tag in tags_sorted_by_date_desc:
777 authorinfo = []
778 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
779 for i in reversed(authors_by_commits):
780 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
781 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)))
782 f.write('</table>')
784 f.write('</body></html>')
785 f.close()
787 self.createGraphs(path)
789 def createGraphs(self, path):
790 print 'Generating graphs...'
792 # hour of day
793 f = open(path + '/hour_of_day.plot', 'w')
794 f.write(GNUPLOT_COMMON)
795 f.write(
797 set output 'hour_of_day.png'
798 unset key
799 set xrange [0.5:24.5]
800 set xtics 4
801 set ylabel "Commits"
802 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
803 """)
804 f.close()
806 # day of week
807 f = open(path + '/day_of_week.plot', 'w')
808 f.write(GNUPLOT_COMMON)
809 f.write(
811 set output 'day_of_week.png'
812 unset key
813 set xrange [0.5:7.5]
814 set xtics 1
815 set ylabel "Commits"
816 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
817 """)
818 f.close()
820 # Month of Year
821 f = open(path + '/month_of_year.plot', 'w')
822 f.write(GNUPLOT_COMMON)
823 f.write(
825 set output 'month_of_year.png'
826 unset key
827 set xrange [0.5:12.5]
828 set xtics 1
829 set ylabel "Commits"
830 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
831 """)
832 f.close()
834 # commits_by_year_month
835 f = open(path + '/commits_by_year_month.plot', 'w')
836 f.write(GNUPLOT_COMMON)
837 f.write(
839 set output 'commits_by_year_month.png'
840 unset key
841 set xdata time
842 set timefmt "%Y-%m"
843 set format x "%Y-%m"
844 set xtics rotate by 90 15768000
845 set bmargin 5
846 set ylabel "Commits"
847 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
848 """)
849 f.close()
851 # commits_by_year
852 f = open(path + '/commits_by_year.plot', 'w')
853 f.write(GNUPLOT_COMMON)
854 f.write(
856 set output 'commits_by_year.png'
857 unset key
858 set xtics 1
859 set ylabel "Commits"
860 set yrange [0:]
861 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
862 """)
863 f.close()
865 # Files by date
866 f = open(path + '/files_by_date.plot', 'w')
867 f.write(GNUPLOT_COMMON)
868 f.write(
870 set output 'files_by_date.png'
871 unset key
872 set xdata time
873 set timefmt "%Y-%m-%d"
874 set format x "%Y-%m-%d"
875 set ylabel "Files"
876 set xtics rotate by 90
877 set ytics 1
878 set bmargin 6
879 plot 'files_by_date.dat' using 1:2 w steps
880 """)
881 f.close()
883 # Lines of Code
884 f = open(path + '/lines_of_code.plot', 'w')
885 f.write(GNUPLOT_COMMON)
886 f.write(
888 set output 'lines_of_code.png'
889 unset key
890 set xdata time
891 set timefmt "%s"
892 set format x "%Y-%m-%d"
893 set ylabel "Lines"
894 set xtics rotate by 90
895 set bmargin 6
896 plot 'lines_of_code.dat' using 1:2 w lines
897 """)
898 f.close()
900 os.chdir(path)
901 files = glob.glob(path + '/*.plot')
902 for f in files:
903 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
904 if len(out) > 0:
905 print out
907 def printHeader(self, f, title = ''):
908 f.write(
909 """<?xml version="1.0" encoding="UTF-8"?>
910 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
911 <html xmlns="http://www.w3.org/1999/xhtml">
912 <head>
913 <title>GitStats - %s</title>
914 <link rel="stylesheet" href="gitstats.css" type="text/css" />
915 <meta name="generator" content="GitStats %s" />
916 <script type="text/javascript" src="sortable.js"></script>
917 </head>
918 <body>
919 """ % (self.title, getversion()))
921 def printNav(self, f):
922 f.write("""
923 <div class="nav">
924 <ul>
925 <li><a href="index.html">General</a></li>
926 <li><a href="activity.html">Activity</a></li>
927 <li><a href="authors.html">Authors</a></li>
928 <li><a href="files.html">Files</a></li>
929 <li><a href="lines.html">Lines</a></li>
930 <li><a href="tags.html">Tags</a></li>
931 </ul>
932 </div>
933 """)
936 usage = """
937 Usage: gitstats [options] <gitpath> <outputpath>
939 Options:
942 if len(sys.argv) < 3:
943 print usage
944 sys.exit(0)
946 gitpath = sys.argv[1]
947 outputpath = os.path.abspath(sys.argv[2])
948 rundir = os.getcwd()
950 try:
951 os.makedirs(outputpath)
952 except OSError:
953 pass
954 if not os.path.isdir(outputpath):
955 print 'FATAL: Output path is not a directory or does not exist'
956 sys.exit(1)
958 print 'Git path: %s' % gitpath
959 print 'Output path: %s' % outputpath
961 os.chdir(gitpath)
963 cachefile = os.path.join(outputpath, 'gitstats.cache')
965 print 'Collecting data...'
966 data = GitDataCollector()
967 data.loadCache(cachefile)
968 data.collect(gitpath)
969 print 'Refining data...'
970 data.saveCache(cachefile)
971 data.refine()
973 os.chdir(rundir)
975 print 'Generating report...'
976 report = HTMLReportCreator()
977 report.create(data, outputpath)
979 time_end = time.time()
980 exectime_internal = time_end - time_start
981 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)