Show sensible-browser command when running interactively.
[gitstats.git] / gitstats
blobc502dcb70acdbee4d45d6def65220c1a3db24ad1
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2011 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
3 # GPLv2 / GPLv3
4 import datetime
5 import getopt
6 import glob
7 import os
8 import pickle
9 import platform
10 import re
11 import shutil
12 import subprocess
13 import sys
14 import time
15 import zlib
17 GNUPLOT_COMMON = 'set terminal png transparent size 640,240\nset size 1.0,1.0\n'
18 ON_LINUX = (platform.system() == 'Linux')
19 WEEKDAYS = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
21 exectime_internal = 0.0
22 exectime_external = 0.0
23 time_start = time.time()
25 # By default, gnuplot is searched from path, but can be overridden with the
26 # environment variable "GNUPLOT"
27 gnuplot_cmd = 'gnuplot'
28 if 'GNUPLOT' in os.environ:
29 gnuplot_cmd = os.environ['GNUPLOT']
31 conf = {
32 'max_domains': 10,
33 'max_ext_length': 10,
34 'style': 'gitstats.css',
35 'max_authors': 20,
36 'authors_top': 5,
37 'commit_begin': '',
38 'commit_end': 'HEAD',
39 'linear_linestats': 1,
40 'project_name': '',
43 def getpipeoutput(cmds, quiet = False):
44 global exectime_external
45 start = time.time()
46 if not quiet and ON_LINUX and os.isatty(1):
47 print '>> ' + ' | '.join(cmds),
48 sys.stdout.flush()
49 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
50 p = p0
51 for x in cmds[1:]:
52 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
53 p0 = p
54 output = p.communicate()[0]
55 end = time.time()
56 if not quiet:
57 if ON_LINUX and os.isatty(1):
58 print '\r',
59 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
60 exectime_external += (end - start)
61 return output.rstrip('\n')
63 def getcommitrange(defaultrange = 'HEAD', end_only = False):
64 if len(conf['commit_end']) > 0:
65 if end_only or len(conf['commit_begin']) == 0:
66 return conf['commit_end']
67 return '%s..%s' % (conf['commit_begin'], conf['commit_end'])
68 return defaultrange
70 def getkeyssortedbyvalues(dict):
71 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
73 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
74 def getkeyssortedbyvaluekey(d, key):
75 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
77 VERSION = 0
78 def getversion():
79 global VERSION
80 if VERSION == 0:
81 VERSION = getpipeoutput(["git rev-parse --short %s" % getcommitrange('HEAD')]).split('\n')[0]
82 return VERSION
84 def getgitversion():
85 return getpipeoutput(['git --version']).split('\n')[0]
87 def getgnuplotversion():
88 return getpipeoutput(['gnuplot --version']).split('\n')[0]
90 class DataCollector:
91 """Manages data collection from a revision control repository."""
92 def __init__(self):
93 self.stamp_created = time.time()
94 self.cache = {}
95 self.total_authors = 0
96 self.activity_by_hour_of_day = {} # hour -> commits
97 self.activity_by_day_of_week = {} # day -> commits
98 self.activity_by_month_of_year = {} # month [1-12] -> commits
99 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
100 self.activity_by_hour_of_day_busiest = 0
101 self.activity_by_hour_of_week_busiest = 0
102 self.activity_by_year_week = {} # yy_wNN -> commits
103 self.activity_by_year_week_peak = 0
105 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
107 self.total_commits = 0
108 self.total_files = 0
109 self.authors_by_commits = 0
111 # domains
112 self.domains = {} # domain -> commits
114 # author of the month
115 self.author_of_month = {} # month -> author -> commits
116 self.author_of_year = {} # year -> author -> commits
117 self.commits_by_month = {} # month -> commits
118 self.commits_by_year = {} # year -> commits
119 self.lines_added_by_month = {} # month -> lines added
120 self.lines_added_by_year = {} # year -> lines added
121 self.lines_removed_by_month = {} # month -> lines removed
122 self.lines_removed_by_year = {} # year -> lines removed
123 self.first_commit_stamp = 0
124 self.last_commit_stamp = 0
125 self.last_active_day = None
126 self.active_days = set()
128 # lines
129 self.total_lines = 0
130 self.total_lines_added = 0
131 self.total_lines_removed = 0
133 # size
134 self.total_size = 0
136 # timezone
137 self.commits_by_timezone = {} # timezone -> commits
139 # tags
140 self.tags = {}
142 self.files_by_stamp = {} # stamp -> files
144 # extensions
145 self.extensions = {} # extension -> files, lines
147 # line statistics
148 self.changes_by_date = {} # stamp -> { files, ins, del }
151 # This should be the main function to extract data from the repository.
152 def collect(self, dir):
153 self.dir = dir
154 if len(conf['project_name']) == 0:
155 self.projectname = os.path.basename(os.path.abspath(dir))
156 else:
157 self.projectname = conf['project_name']
160 # Load cacheable data
161 def loadCache(self, cachefile):
162 if not os.path.exists(cachefile):
163 return
164 print 'Loading cache...'
165 f = open(cachefile, 'rb')
166 try:
167 self.cache = pickle.loads(zlib.decompress(f.read()))
168 except:
169 # temporary hack to upgrade non-compressed caches
170 f.seek(0)
171 self.cache = pickle.load(f)
172 f.close()
175 # Produce any additional statistics from the extracted data.
176 def refine(self):
177 pass
180 # : get a dictionary of author
181 def getAuthorInfo(self, author):
182 return None
184 def getActivityByDayOfWeek(self):
185 return {}
187 def getActivityByHourOfDay(self):
188 return {}
190 # : get a dictionary of domains
191 def getDomainInfo(self, domain):
192 return None
195 # Get a list of authors
196 def getAuthors(self):
197 return []
199 def getFirstCommitDate(self):
200 return datetime.datetime.now()
202 def getLastCommitDate(self):
203 return datetime.datetime.now()
205 def getStampCreated(self):
206 return self.stamp_created
208 def getTags(self):
209 return []
211 def getTotalAuthors(self):
212 return -1
214 def getTotalCommits(self):
215 return -1
217 def getTotalFiles(self):
218 return -1
220 def getTotalLOC(self):
221 return -1
224 # Save cacheable data
225 def saveCache(self, cachefile):
226 print 'Saving cache...'
227 f = open(cachefile, 'wb')
228 #pickle.dump(self.cache, f)
229 data = zlib.compress(pickle.dumps(self.cache))
230 f.write(data)
231 f.close()
233 class GitDataCollector(DataCollector):
234 def collect(self, dir):
235 DataCollector.collect(self, dir)
237 try:
238 self.total_authors += int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
239 except:
240 self.total_authors = 0
241 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
243 # tags
244 lines = getpipeoutput(['git show-ref --tags']).split('\n')
245 for line in lines:
246 if len(line) == 0:
247 continue
248 (hash, tag) = line.split(' ')
250 tag = tag.replace('refs/tags/', '')
251 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
252 if len(output) > 0:
253 parts = output.split(' ')
254 stamp = 0
255 try:
256 stamp = int(parts[0])
257 except ValueError:
258 stamp = 0
259 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
261 # collect info on tags, starting from latest
262 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
263 prev = None
264 for tag in reversed(tags_sorted_by_date_desc):
265 cmd = 'git shortlog -s "%s"' % tag
266 if prev != None:
267 cmd += ' "^%s"' % prev
268 output = getpipeoutput([cmd])
269 if len(output) == 0:
270 continue
271 prev = tag
272 for line in output.split('\n'):
273 parts = re.split('\s+', line, 2)
274 commits = int(parts[1])
275 author = parts[2]
276 self.tags[tag]['commits'] = commits
277 self.tags[tag]['authors'][author] = commits
279 # Collect revision statistics
280 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
281 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
282 for line in lines:
283 parts = line.split(' ', 4)
284 author = ''
285 try:
286 stamp = int(parts[0])
287 except ValueError:
288 stamp = 0
289 timezone = parts[3]
290 author, mail = parts[4].split('<', 1)
291 author = author.rstrip()
292 mail = mail.rstrip('>')
293 domain = '?'
294 if mail.find('@') != -1:
295 domain = mail.rsplit('@', 1)[1]
296 date = datetime.datetime.fromtimestamp(float(stamp))
298 # First and last commit stamp (may be in any order because of cherry-picking and patches)
299 if stamp > self.last_commit_stamp:
300 self.last_commit_stamp = stamp
301 if self.first_commit_stamp == 0 or stamp < self.first_commit_stamp:
302 self.first_commit_stamp = stamp
304 # activity
305 # hour
306 hour = date.hour
307 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
308 # most active hour?
309 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
310 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
312 # day of week
313 day = date.weekday()
314 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
316 # domain stats
317 if domain not in self.domains:
318 self.domains[domain] = {}
319 # commits
320 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
322 # hour of week
323 if day not in self.activity_by_hour_of_week:
324 self.activity_by_hour_of_week[day] = {}
325 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
326 # most active hour?
327 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
328 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
330 # month of year
331 month = date.month
332 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
334 # yearly/weekly activity
335 yyw = date.strftime('%Y-%W')
336 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
337 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
338 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
340 # author stats
341 if author not in self.authors:
342 self.authors[author] = {}
343 # commits, note again that commits may be in any date order because of cherry-picking and patches
344 if 'last_commit_stamp' not in self.authors[author]:
345 self.authors[author]['last_commit_stamp'] = stamp
346 if stamp > self.authors[author]['last_commit_stamp']:
347 self.authors[author]['last_commit_stamp'] = stamp
348 if 'first_commit_stamp' not in self.authors[author]:
349 self.authors[author]['first_commit_stamp'] = stamp
350 if stamp < self.authors[author]['first_commit_stamp']:
351 self.authors[author]['first_commit_stamp'] = stamp
353 # author of the month/year
354 yymm = date.strftime('%Y-%m')
355 if yymm in self.author_of_month:
356 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
357 else:
358 self.author_of_month[yymm] = {}
359 self.author_of_month[yymm][author] = 1
360 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
362 yy = date.year
363 if yy in self.author_of_year:
364 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
365 else:
366 self.author_of_year[yy] = {}
367 self.author_of_year[yy][author] = 1
368 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
370 # authors: active days
371 yymmdd = date.strftime('%Y-%m-%d')
372 if 'last_active_day' not in self.authors[author]:
373 self.authors[author]['last_active_day'] = yymmdd
374 self.authors[author]['active_days'] = set([yymmdd])
375 elif yymmdd != self.authors[author]['last_active_day']:
376 self.authors[author]['last_active_day'] = yymmdd
377 self.authors[author]['active_days'].add(yymmdd)
379 # project: active days
380 if yymmdd != self.last_active_day:
381 self.last_active_day = yymmdd
382 self.active_days.add(yymmdd)
384 # timezone
385 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
387 # TODO Optimize this, it's the worst bottleneck
388 # outputs "<stamp> <files>" for each revision
389 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
390 lines = []
391 for revline in revlines:
392 time, rev = revline.split(' ')
393 linecount = self.getFilesInCommit(rev)
394 lines.append('%d %d' % (int(time), linecount))
396 self.total_commits += len(lines)
397 for line in lines:
398 parts = line.split(' ')
399 if len(parts) != 2:
400 continue
401 (stamp, files) = parts[0:2]
402 try:
403 self.files_by_stamp[int(stamp)] = int(files)
404 except ValueError:
405 print 'Warning: failed to parse line "%s"' % line
407 # extensions and size of files
408 lines = getpipeoutput(['git ls-tree -r -l -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
409 for line in lines:
410 if len(line) == 0:
411 continue
412 parts = re.split('\s+', line, 5)
413 sha1 = parts[2]
414 size = int(parts[3])
415 fullpath = parts[4]
417 self.total_size += size
418 self.total_files += 1
420 filename = fullpath.split('/')[-1] # strip directories
421 if filename.find('.') == -1 or filename.rfind('.') == 0:
422 ext = ''
423 else:
424 ext = filename[(filename.rfind('.') + 1):]
425 if len(ext) > conf['max_ext_length']:
426 ext = ''
428 if ext not in self.extensions:
429 self.extensions[ext] = {'files': 0, 'lines': 0}
431 self.extensions[ext]['files'] += 1
432 try:
433 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
434 except:
435 print 'Warning: Could not count lines for file "%s"' % line
437 # line statistics
438 # outputs:
439 # N files changed, N insertions (+), N deletions(-)
440 # <stamp> <author>
441 self.changes_by_date = {} # stamp -> { files, ins, del }
442 # computation of lines of code by date is better done
443 # on a linear history.
444 extra = ''
445 if conf['linear_linestats']:
446 extra = '--first-parent -m'
447 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
448 lines.reverse()
449 files = 0; inserted = 0; deleted = 0; total_lines = 0
450 author = None
451 for line in lines:
452 if len(line) == 0:
453 continue
455 # <stamp> <author>
456 if line.find('files changed,') == -1:
457 pos = line.find(' ')
458 if pos != -1:
459 try:
460 (stamp, author) = (int(line[:pos]), line[pos+1:])
461 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
463 date = datetime.datetime.fromtimestamp(stamp)
464 yymm = date.strftime('%Y-%m')
465 self.lines_added_by_month[yymm] = self.lines_added_by_month.get(yymm, 0) + inserted
466 self.lines_removed_by_month[yymm] = self.lines_removed_by_month.get(yymm, 0) + deleted
468 yy = date.year
469 self.lines_added_by_year[yy] = self.lines_added_by_year.get(yy,0) + inserted
470 self.lines_removed_by_year[yy] = self.lines_removed_by_year.get(yy, 0) + deleted
472 files, inserted, deleted = 0, 0, 0
473 except ValueError:
474 print 'Warning: unexpected line "%s"' % line
475 else:
476 print 'Warning: unexpected line "%s"' % line
477 else:
478 numbers = re.findall('\d+', line)
479 if len(numbers) == 3:
480 (files, inserted, deleted) = map(lambda el : int(el), numbers)
481 total_lines += inserted
482 total_lines -= deleted
483 self.total_lines_added += inserted
484 self.total_lines_removed += deleted
486 else:
487 print 'Warning: failed to handle line "%s"' % line
488 (files, inserted, deleted) = (0, 0, 0)
489 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
490 self.total_lines = total_lines
492 # Per-author statistics
494 # defined for stamp, author only if author commited at this timestamp.
495 self.changes_by_date_by_author = {} # stamp -> author -> lines_added
497 # Similar to the above, but never use --first-parent
498 # (we need to walk through every commit to know who
499 # committed what, not just through mainline)
500 lines = getpipeoutput(['git log --shortstat --date-order --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
501 lines.reverse()
502 files = 0; inserted = 0; deleted = 0
503 author = None
504 stamp = 0
505 for line in lines:
506 if len(line) == 0:
507 continue
509 # <stamp> <author>
510 if line.find('files changed,') == -1:
511 pos = line.find(' ')
512 if pos != -1:
513 try:
514 oldstamp = stamp
515 (stamp, author) = (int(line[:pos]), line[pos+1:])
516 if oldstamp > stamp:
517 # clock skew, keep old timestamp to avoid having ugly graph
518 stamp = oldstamp
519 if author not in self.authors:
520 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
521 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
522 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
523 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
524 if stamp not in self.changes_by_date_by_author:
525 self.changes_by_date_by_author[stamp] = {}
526 if author not in self.changes_by_date_by_author[stamp]:
527 self.changes_by_date_by_author[stamp][author] = {}
528 self.changes_by_date_by_author[stamp][author]['lines_added'] = self.authors[author]['lines_added']
529 self.changes_by_date_by_author[stamp][author]['commits'] = self.authors[author]['commits']
530 files, inserted, deleted = 0, 0, 0
531 except ValueError:
532 print 'Warning: unexpected line "%s"' % line
533 else:
534 print 'Warning: unexpected line "%s"' % line
535 else:
536 numbers = re.findall('\d+', line)
537 if len(numbers) == 3:
538 (files, inserted, deleted) = map(lambda el : int(el), numbers)
539 else:
540 print 'Warning: failed to handle line "%s"' % line
541 (files, inserted, deleted) = (0, 0, 0)
543 def refine(self):
544 # authors
545 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
546 self.authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
547 self.authors_by_commits.reverse() # most first
548 for i, name in enumerate(self.authors_by_commits):
549 self.authors[name]['place_by_commits'] = i + 1
551 for name in self.authors.keys():
552 a = self.authors[name]
553 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
554 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
555 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
556 delta = date_last - date_first
557 a['date_first'] = date_first.strftime('%Y-%m-%d')
558 a['date_last'] = date_last.strftime('%Y-%m-%d')
559 a['timedelta'] = delta
560 if 'lines_added' not in a: a['lines_added'] = 0
561 if 'lines_removed' not in a: a['lines_removed'] = 0
563 def getActiveDays(self):
564 return self.active_days
566 def getActivityByDayOfWeek(self):
567 return self.activity_by_day_of_week
569 def getActivityByHourOfDay(self):
570 return self.activity_by_hour_of_day
572 def getAuthorInfo(self, author):
573 return self.authors[author]
575 def getAuthors(self, limit = None):
576 res = getkeyssortedbyvaluekey(self.authors, 'commits')
577 res.reverse()
578 return res[:limit]
580 def getCommitDeltaDays(self):
581 return (self.last_commit_stamp - self.first_commit_stamp) / 86400 + 1
583 def getDomainInfo(self, domain):
584 return self.domains[domain]
586 def getDomains(self):
587 return self.domains.keys()
589 def getFilesInCommit(self, rev):
590 try:
591 res = self.cache['files_in_tree'][rev]
592 except:
593 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
594 if 'files_in_tree' not in self.cache:
595 self.cache['files_in_tree'] = {}
596 self.cache['files_in_tree'][rev] = res
598 return res
600 def getFirstCommitDate(self):
601 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
603 def getLastCommitDate(self):
604 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
606 def getLinesInBlob(self, sha1):
607 try:
608 res = self.cache['lines_in_blob'][sha1]
609 except:
610 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
611 if 'lines_in_blob' not in self.cache:
612 self.cache['lines_in_blob'] = {}
613 self.cache['lines_in_blob'][sha1] = res
614 return res
616 def getTags(self):
617 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
618 return lines.split('\n')
620 def getTagDate(self, tag):
621 return self.revToDate('tags/' + tag)
623 def getTotalAuthors(self):
624 return self.total_authors
626 def getTotalCommits(self):
627 return self.total_commits
629 def getTotalFiles(self):
630 return self.total_files
632 def getTotalLOC(self):
633 return self.total_lines
635 def getTotalSize(self):
636 return self.total_size
638 def revToDate(self, rev):
639 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
640 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
642 class ReportCreator:
643 """Creates the actual report based on given data."""
644 def __init__(self):
645 pass
647 def create(self, data, path):
648 self.data = data
649 self.path = path
651 def html_linkify(text):
652 return text.lower().replace(' ', '_')
654 def html_header(level, text):
655 name = html_linkify(text)
656 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
658 class HTMLReportCreator(ReportCreator):
659 def create(self, data, path):
660 ReportCreator.create(self, data, path)
661 self.title = data.projectname
663 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
664 binarypath = os.path.dirname(os.path.abspath(__file__))
665 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
666 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
667 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
668 for base in basedirs:
669 src = base + '/' + file
670 if os.path.exists(src):
671 shutil.copyfile(src, path + '/' + file)
672 break
673 else:
674 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
676 f = open(path + "/index.html", 'w')
677 format = '%Y-%m-%d %H:%M:%S'
678 self.printHeader(f)
680 f.write('<h1>GitStats - %s</h1>' % data.projectname)
682 self.printNav(f)
684 f.write('<dl>')
685 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
686 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
687 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
688 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
689 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())))
690 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
691 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))
692 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()))
693 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
694 f.write('</dl>')
696 f.write('</body>\n</html>')
697 f.close()
700 # Activity
701 f = open(path + '/activity.html', 'w')
702 self.printHeader(f)
703 f.write('<h1>Activity</h1>')
704 self.printNav(f)
706 #f.write('<h2>Last 30 days</h2>')
708 #f.write('<h2>Last 12 months</h2>')
710 # Weekly activity
711 WEEKS = 32
712 f.write(html_header(2, 'Weekly activity'))
713 f.write('<p>Last %d weeks</p>' % WEEKS)
715 # generate weeks to show (previous N weeks from now)
716 now = datetime.datetime.now()
717 deltaweek = datetime.timedelta(7)
718 weeks = []
719 stampcur = now
720 for i in range(0, WEEKS):
721 weeks.insert(0, stampcur.strftime('%Y-%W'))
722 stampcur -= deltaweek
724 # top row: commits & bar
725 f.write('<table class="noborders"><tr>')
726 for i in range(0, WEEKS):
727 commits = 0
728 if weeks[i] in data.activity_by_year_week:
729 commits = data.activity_by_year_week[weeks[i]]
731 percentage = 0
732 if weeks[i] in data.activity_by_year_week:
733 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
734 height = max(1, int(200 * percentage))
735 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))
737 # bottom row: year/week
738 f.write('</tr><tr>')
739 for i in range(0, WEEKS):
740 f.write('<td>%s</td>' % (WEEKS - i))
741 f.write('</tr></table>')
743 # Hour of Day
744 f.write(html_header(2, 'Hour of Day'))
745 hour_of_day = data.getActivityByHourOfDay()
746 f.write('<table><tr><th>Hour</th>')
747 for i in range(0, 24):
748 f.write('<th>%d</th>' % i)
749 f.write('</tr>\n<tr><th>Commits</th>')
750 fp = open(path + '/hour_of_day.dat', 'w')
751 for i in range(0, 24):
752 if i in hour_of_day:
753 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
754 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
755 fp.write('%d %d\n' % (i, hour_of_day[i]))
756 else:
757 f.write('<td>0</td>')
758 fp.write('%d 0\n' % i)
759 fp.close()
760 f.write('</tr>\n<tr><th>%</th>')
761 totalcommits = data.getTotalCommits()
762 for i in range(0, 24):
763 if i in hour_of_day:
764 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
765 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
766 else:
767 f.write('<td>0.00</td>')
768 f.write('</tr></table>')
769 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
770 fg = open(path + '/hour_of_day.dat', 'w')
771 for i in range(0, 24):
772 if i in hour_of_day:
773 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
774 else:
775 fg.write('%d 0\n' % (i + 1))
776 fg.close()
778 # Day of Week
779 f.write(html_header(2, 'Day of Week'))
780 day_of_week = data.getActivityByDayOfWeek()
781 f.write('<div class="vtable"><table>')
782 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
783 fp = open(path + '/day_of_week.dat', 'w')
784 for d in range(0, 7):
785 commits = 0
786 if d in day_of_week:
787 commits = day_of_week[d]
788 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
789 f.write('<tr>')
790 f.write('<th>%s</th>' % (WEEKDAYS[d]))
791 if d in day_of_week:
792 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
793 else:
794 f.write('<td>0</td>')
795 f.write('</tr>')
796 f.write('</table></div>')
797 f.write('<img src="day_of_week.png" alt="Day of Week" />')
798 fp.close()
800 # Hour of Week
801 f.write(html_header(2, 'Hour of Week'))
802 f.write('<table>')
804 f.write('<tr><th>Weekday</th>')
805 for hour in range(0, 24):
806 f.write('<th>%d</th>' % (hour))
807 f.write('</tr>')
809 for weekday in range(0, 7):
810 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
811 for hour in range(0, 24):
812 try:
813 commits = data.activity_by_hour_of_week[weekday][hour]
814 except KeyError:
815 commits = 0
816 if commits != 0:
817 f.write('<td')
818 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
819 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
820 f.write('>%d</td>' % commits)
821 else:
822 f.write('<td></td>')
823 f.write('</tr>')
825 f.write('</table>')
827 # Month of Year
828 f.write(html_header(2, 'Month of Year'))
829 f.write('<div class="vtable"><table>')
830 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
831 fp = open (path + '/month_of_year.dat', 'w')
832 for mm in range(1, 13):
833 commits = 0
834 if mm in data.activity_by_month_of_year:
835 commits = data.activity_by_month_of_year[mm]
836 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
837 fp.write('%d %d\n' % (mm, commits))
838 fp.close()
839 f.write('</table></div>')
840 f.write('<img src="month_of_year.png" alt="Month of Year" />')
842 # Commits by year/month
843 f.write(html_header(2, 'Commits by year/month'))
844 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th><th>Lines added</th><th>Lines removed</th></tr>')
845 for yymm in reversed(sorted(data.commits_by_month.keys())):
846 f.write('<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td></tr>' % (yymm, data.commits_by_month.get(yymm,0), data.lines_added_by_month.get(yymm,0), data.lines_removed_by_month.get(yymm,0)))
847 f.write('</table></div>')
848 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
849 fg = open(path + '/commits_by_year_month.dat', 'w')
850 for yymm in sorted(data.commits_by_month.keys()):
851 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
852 fg.close()
854 # Commits by year
855 f.write(html_header(2, 'Commits by Year'))
856 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th><th>Lines added</th><th>Lines removed</th></tr>')
857 for yy in reversed(sorted(data.commits_by_year.keys())):
858 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%d</td><td>%d</td></tr>' % (yy, data.commits_by_year.get(yy,0), (100.0 * data.commits_by_year.get(yy,0)) / data.getTotalCommits(), data.lines_added_by_year.get(yy,0), data.lines_removed_by_year.get(yy,0)))
859 f.write('</table></div>')
860 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
861 fg = open(path + '/commits_by_year.dat', 'w')
862 for yy in sorted(data.commits_by_year.keys()):
863 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
864 fg.close()
866 # Commits by timezone
867 f.write(html_header(2, 'Commits by Timezone'))
868 f.write('<table><tr>')
869 f.write('<th>Timezone</th><th>Commits</th>')
870 max_commits_on_tz = max(data.commits_by_timezone.values())
871 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
872 commits = data.commits_by_timezone[i]
873 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
874 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
875 f.write('</tr></table>')
877 f.write('</body></html>')
878 f.close()
881 # Authors
882 f = open(path + '/authors.html', 'w')
883 self.printHeader(f)
885 f.write('<h1>Authors</h1>')
886 self.printNav(f)
888 # Authors :: List of authors
889 f.write(html_header(2, 'List of Authors'))
891 f.write('<table class="authors sortable" id="authors">')
892 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>')
893 for author in data.getAuthors(conf['max_authors']):
894 info = data.getAuthorInfo(author)
895 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (author, info['commits'], info['commits_frac'], info['lines_added'], info['lines_removed'], info['date_first'], info['date_last'], info['timedelta'], len(info['active_days']), info['place_by_commits']))
896 f.write('</table>')
898 allauthors = data.getAuthors()
899 if len(allauthors) > conf['max_authors']:
900 rest = allauthors[conf['max_authors']:]
901 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
903 f.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
904 f.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
905 if len(allauthors) > conf['max_authors']:
906 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
908 f.write(html_header(2, 'Commits per Author'))
909 f.write('<img src="commits_by_author.png" alt="Commits per Author" />')
910 if len(allauthors) > conf['max_authors']:
911 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
913 fgl = open(path + '/lines_of_code_by_author.dat', 'w')
914 fgc = open(path + '/commits_by_author.dat', 'w')
916 lines_by_authors = {} # cumulated added lines by
917 # author. to save memory,
918 # changes_by_date_by_author[stamp][author] is defined
919 # only at points where author commits.
920 # lines_by_authors allows us to generate all the
921 # points in the .dat file.
923 # Don't rely on getAuthors to give the same order each
924 # time. Be robust and keep the list in a variable.
925 commits_by_authors = {} # cumulated added lines by
927 self.authors_to_plot = data.getAuthors(conf['max_authors'])
928 for author in self.authors_to_plot:
929 lines_by_authors[author] = 0
930 commits_by_authors[author] = 0
931 for stamp in sorted(data.changes_by_date_by_author.keys()):
932 fgl.write('%d' % stamp)
933 fgc.write('%d' % stamp)
934 for author in self.authors_to_plot:
935 if author in data.changes_by_date_by_author[stamp].keys():
936 lines_by_authors[author] = data.changes_by_date_by_author[stamp][author]['lines_added']
937 commits_by_authors[author] = data.changes_by_date_by_author[stamp][author]['commits']
938 fgl.write(' %d' % lines_by_authors[author])
939 fgc.write(' %d' % commits_by_authors[author])
940 fgl.write('\n')
941 fgc.write('\n')
942 fgl.close()
943 fgc.close()
945 # Authors :: Author of Month
946 f.write(html_header(2, 'Author of Month'))
947 f.write('<table class="sortable" id="aom">')
948 f.write('<tr><th>Month</th><th>Author</th><th>Commits (%%)</th><th class="unsortable">Next top %d</th><th>Number of authors</th></tr>' % conf['authors_top'])
949 for yymm in reversed(sorted(data.author_of_month.keys())):
950 authordict = data.author_of_month[yymm]
951 authors = getkeyssortedbyvalues(authordict)
952 authors.reverse()
953 commits = data.author_of_month[yymm][authors[0]]
954 next = ', '.join(authors[1:conf['authors_top']+1])
955 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td><td>%d</td></tr>' % (yymm, authors[0], commits, (100.0 * commits) / data.commits_by_month[yymm], data.commits_by_month[yymm], next, len(authors)))
957 f.write('</table>')
959 f.write(html_header(2, 'Author of Year'))
960 f.write('<table class="sortable" id="aoy"><tr><th>Year</th><th>Author</th><th>Commits (%%)</th><th class="unsortable">Next top %d</th><th>Number of authors</th></tr>' % conf['authors_top'])
961 for yy in reversed(sorted(data.author_of_year.keys())):
962 authordict = data.author_of_year[yy]
963 authors = getkeyssortedbyvalues(authordict)
964 authors.reverse()
965 commits = data.author_of_year[yy][authors[0]]
966 next = ', '.join(authors[1:conf['authors_top']+1])
967 f.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td><td>%d</td></tr>' % (yy, authors[0], commits, (100.0 * commits) / data.commits_by_year[yy], data.commits_by_year[yy], next, len(authors)))
968 f.write('</table>')
970 # Domains
971 f.write(html_header(2, 'Commits by Domains'))
972 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
973 domains_by_commits.reverse() # most first
974 f.write('<div class="vtable"><table>')
975 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
976 fp = open(path + '/domains.dat', 'w')
977 n = 0
978 for domain in domains_by_commits:
979 if n == conf['max_domains']:
980 break
981 commits = 0
982 n += 1
983 info = data.getDomainInfo(domain)
984 fp.write('%s %d %d\n' % (domain, n , info['commits']))
985 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
986 f.write('</table></div>')
987 f.write('<img src="domains.png" alt="Commits by Domains" />')
988 fp.close()
990 f.write('</body></html>')
991 f.close()
994 # Files
995 f = open(path + '/files.html', 'w')
996 self.printHeader(f)
997 f.write('<h1>Files</h1>')
998 self.printNav(f)
1000 f.write('<dl>\n')
1001 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
1002 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1003 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % (float(data.getTotalSize()) / data.getTotalFiles()))
1004 f.write('</dl>\n')
1006 # Files :: File count by date
1007 f.write(html_header(2, 'File count by date'))
1009 # use set to get rid of duplicate/unnecessary entries
1010 files_by_date = set()
1011 for stamp in sorted(data.files_by_stamp.keys()):
1012 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1014 fg = open(path + '/files_by_date.dat', 'w')
1015 for line in sorted(list(files_by_date)):
1016 fg.write('%s\n' % line)
1017 #for stamp in sorted(data.files_by_stamp.keys()):
1018 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1019 fg.close()
1021 f.write('<img src="files_by_date.png" alt="Files by Date" />')
1023 #f.write('<h2>Average file size by date</h2>')
1025 # Files :: Extensions
1026 f.write(html_header(2, 'Extensions'))
1027 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
1028 for ext in sorted(data.extensions.keys()):
1029 files = data.extensions[ext]['files']
1030 lines = data.extensions[ext]['lines']
1031 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))
1032 f.write('</table>')
1034 f.write('</body></html>')
1035 f.close()
1038 # Lines
1039 f = open(path + '/lines.html', 'w')
1040 self.printHeader(f)
1041 f.write('<h1>Lines</h1>')
1042 self.printNav(f)
1044 f.write('<dl>\n')
1045 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1046 f.write('</dl>\n')
1048 f.write(html_header(2, 'Lines of Code'))
1049 f.write('<img src="lines_of_code.png" />')
1051 fg = open(path + '/lines_of_code.dat', 'w')
1052 for stamp in sorted(data.changes_by_date.keys()):
1053 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
1054 fg.close()
1056 f.write('</body></html>')
1057 f.close()
1060 # tags.html
1061 f = open(path + '/tags.html', 'w')
1062 self.printHeader(f)
1063 f.write('<h1>Tags</h1>')
1064 self.printNav(f)
1066 f.write('<dl>')
1067 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
1068 if len(data.tags) > 0:
1069 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
1070 f.write('</dl>')
1072 f.write('<table class="tags">')
1073 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1074 # sort the tags by date desc
1075 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
1076 for tag in tags_sorted_by_date_desc:
1077 authorinfo = []
1078 self.authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
1079 for i in reversed(self.authors_by_commits):
1080 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
1081 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)))
1082 f.write('</table>')
1084 f.write('</body></html>')
1085 f.close()
1087 self.createGraphs(path)
1089 def createGraphs(self, path):
1090 print 'Generating graphs...'
1092 # hour of day
1093 f = open(path + '/hour_of_day.plot', 'w')
1094 f.write(GNUPLOT_COMMON)
1095 f.write(
1097 set output 'hour_of_day.png'
1098 unset key
1099 set xrange [0.5:24.5]
1100 set xtics 4
1101 set grid y
1102 set ylabel "Commits"
1103 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1104 """)
1105 f.close()
1107 # day of week
1108 f = open(path + '/day_of_week.plot', 'w')
1109 f.write(GNUPLOT_COMMON)
1110 f.write(
1112 set output 'day_of_week.png'
1113 unset key
1114 set xrange [0.5:7.5]
1115 set xtics 1
1116 set grid y
1117 set ylabel "Commits"
1118 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1119 """)
1120 f.close()
1122 # Domains
1123 f = open(path + '/domains.plot', 'w')
1124 f.write(GNUPLOT_COMMON)
1125 f.write(
1127 set output 'domains.png'
1128 unset key
1129 unset xtics
1130 set yrange [0:]
1131 set grid y
1132 set ylabel "Commits"
1133 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1134 """)
1135 f.close()
1137 # Month of Year
1138 f = open(path + '/month_of_year.plot', 'w')
1139 f.write(GNUPLOT_COMMON)
1140 f.write(
1142 set output 'month_of_year.png'
1143 unset key
1144 set xrange [0.5:12.5]
1145 set xtics 1
1146 set grid y
1147 set ylabel "Commits"
1148 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1149 """)
1150 f.close()
1152 # commits_by_year_month
1153 f = open(path + '/commits_by_year_month.plot', 'w')
1154 f.write(GNUPLOT_COMMON)
1155 f.write(
1157 set output 'commits_by_year_month.png'
1158 unset key
1159 set xdata time
1160 set timefmt "%Y-%m"
1161 set format x "%Y-%m"
1162 set xtics rotate
1163 set bmargin 5
1164 set grid y
1165 set ylabel "Commits"
1166 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1167 """)
1168 f.close()
1170 # commits_by_year
1171 f = open(path + '/commits_by_year.plot', 'w')
1172 f.write(GNUPLOT_COMMON)
1173 f.write(
1175 set output 'commits_by_year.png'
1176 unset key
1177 set xtics 1 rotate
1178 set grid y
1179 set ylabel "Commits"
1180 set yrange [0:]
1181 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1182 """)
1183 f.close()
1185 # Files by date
1186 f = open(path + '/files_by_date.plot', 'w')
1187 f.write(GNUPLOT_COMMON)
1188 f.write(
1190 set output 'files_by_date.png'
1191 unset key
1192 set xdata time
1193 set timefmt "%Y-%m-%d"
1194 set format x "%Y-%m-%d"
1195 set grid y
1196 set ylabel "Files"
1197 set xtics rotate
1198 set ytics autofreq
1199 set bmargin 6
1200 plot 'files_by_date.dat' using 1:2 w steps
1201 """)
1202 f.close()
1204 # Lines of Code
1205 f = open(path + '/lines_of_code.plot', 'w')
1206 f.write(GNUPLOT_COMMON)
1207 f.write(
1209 set output 'lines_of_code.png'
1210 unset key
1211 set xdata time
1212 set timefmt "%s"
1213 set format x "%Y-%m-%d"
1214 set grid y
1215 set ylabel "Lines"
1216 set xtics rotate
1217 set bmargin 6
1218 plot 'lines_of_code.dat' using 1:2 w lines
1219 """)
1220 f.close()
1222 # Lines of Code Added per author
1223 f = open(path + '/lines_of_code_by_author.plot', 'w')
1224 f.write(GNUPLOT_COMMON)
1225 f.write(
1227 set terminal png transparent size 640,480
1228 set output 'lines_of_code_by_author.png'
1229 set key left top
1230 set xdata time
1231 set timefmt "%s"
1232 set format x "%Y-%m-%d"
1233 set grid y
1234 set ylabel "Lines"
1235 set xtics rotate
1236 set bmargin 6
1237 plot """
1239 i = 1
1240 plots = []
1241 for a in self.authors_to_plot:
1242 i = i + 1
1243 plots.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1244 f.write(", ".join(plots))
1245 f.write('\n')
1247 f.close()
1249 # Commits per author
1250 f = open(path + '/commits_by_author.plot', 'w')
1251 f.write(GNUPLOT_COMMON)
1252 f.write(
1254 set terminal png transparent size 640,480
1255 set output 'commits_by_author.png'
1256 set key left top
1257 set xdata time
1258 set timefmt "%s"
1259 set format x "%Y-%m-%d"
1260 set grid y
1261 set ylabel "Commits"
1262 set xtics rotate
1263 set bmargin 6
1264 plot """
1266 i = 1
1267 plots = []
1268 for a in self.authors_to_plot:
1269 i = i + 1
1270 plots.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1271 f.write(", ".join(plots))
1272 f.write('\n')
1274 f.close()
1276 os.chdir(path)
1277 files = glob.glob(path + '/*.plot')
1278 for f in files:
1279 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1280 if len(out) > 0:
1281 print out
1283 def printHeader(self, f, title = ''):
1284 f.write(
1285 """<?xml version="1.0" encoding="UTF-8"?>
1286 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1287 <html xmlns="http://www.w3.org/1999/xhtml">
1288 <head>
1289 <title>GitStats - %s</title>
1290 <link rel="stylesheet" href="%s" type="text/css" />
1291 <meta name="generator" content="GitStats %s" />
1292 <script type="text/javascript" src="sortable.js"></script>
1293 </head>
1294 <body>
1295 """ % (self.title, conf['style'], getversion()))
1297 def printNav(self, f):
1298 f.write("""
1299 <div class="nav">
1300 <ul>
1301 <li><a href="index.html">General</a></li>
1302 <li><a href="activity.html">Activity</a></li>
1303 <li><a href="authors.html">Authors</a></li>
1304 <li><a href="files.html">Files</a></li>
1305 <li><a href="lines.html">Lines</a></li>
1306 <li><a href="tags.html">Tags</a></li>
1307 </ul>
1308 </div>
1309 """)
1312 class GitStats:
1313 def run(self, args_orig):
1314 optlist, args = getopt.getopt(args_orig, 'c:')
1315 for o,v in optlist:
1316 if o == '-c':
1317 key, value = v.split('=', 1)
1318 if key not in conf:
1319 raise KeyError('no such key "%s" in config' % key)
1320 if isinstance(conf[key], int):
1321 conf[key] = int(value)
1322 else:
1323 conf[key] = value
1325 if len(args) < 2:
1326 print """
1327 Usage: gitstats [options] <gitpath..> <outputpath>
1329 Options:
1330 -c key=value Override configuration value
1332 Default config values:
1334 """ % conf
1335 sys.exit(0)
1337 outputpath = os.path.abspath(args[-1])
1338 rundir = os.getcwd()
1340 try:
1341 os.makedirs(outputpath)
1342 except OSError:
1343 pass
1344 if not os.path.isdir(outputpath):
1345 print 'FATAL: Output path is not a directory or does not exist'
1346 sys.exit(1)
1348 print 'Output path: %s' % outputpath
1349 cachefile = os.path.join(outputpath, 'gitstats.cache')
1351 data = GitDataCollector()
1352 data.loadCache(cachefile)
1354 for gitpath in args[0:-1]:
1355 print 'Git path: %s' % gitpath
1357 os.chdir(gitpath)
1359 print 'Collecting data...'
1360 data.collect(gitpath)
1362 print 'Refining data...'
1363 data.saveCache(cachefile)
1364 data.refine()
1366 os.chdir(rundir)
1368 print 'Generating report...'
1369 report = HTMLReportCreator()
1370 report.create(data, outputpath)
1372 time_end = time.time()
1373 exectime_internal = time_end - time_start
1374 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1375 if sys.stdin.isatty():
1376 print 'You may now run:'
1377 print
1378 print ' sensible-browser \'%s\'' % os.path.join(outputpath, 'index.html').replace("'", "'\\''")
1379 print
1381 if __name__=='__main__':
1382 g = GitStats()
1383 g.run(sys.argv[1:])