Per-author added lines graph
[gitstats.git] / gitstats
blobf4bc25f74070e600d7c68f79c5a5d3875b1f897f
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2010 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': '',
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 = {}
97 # This should be the main function to extract data from the repository.
98 def collect(self, dir):
99 self.dir = dir
100 if len(conf['project_name']) == 0:
101 self.projectname = os.path.basename(os.path.abspath(dir))
102 else:
103 self.projectname = conf['project_name']
106 # Load cacheable data
107 def loadCache(self, cachefile):
108 if not os.path.exists(cachefile):
109 return
110 print 'Loading cache...'
111 f = open(cachefile, 'rb')
112 try:
113 self.cache = pickle.loads(zlib.decompress(f.read()))
114 except:
115 # temporary hack to upgrade non-compressed caches
116 f.seek(0)
117 self.cache = pickle.load(f)
118 f.close()
121 # Produce any additional statistics from the extracted data.
122 def refine(self):
123 pass
126 # : get a dictionary of author
127 def getAuthorInfo(self, author):
128 return None
130 def getActivityByDayOfWeek(self):
131 return {}
133 def getActivityByHourOfDay(self):
134 return {}
136 # : get a dictionary of domains
137 def getDomainInfo(self, domain):
138 return None
141 # Get a list of authors
142 def getAuthors(self):
143 return []
145 def getFirstCommitDate(self):
146 return datetime.datetime.now()
148 def getLastCommitDate(self):
149 return datetime.datetime.now()
151 def getStampCreated(self):
152 return self.stamp_created
154 def getTags(self):
155 return []
157 def getTotalAuthors(self):
158 return -1
160 def getTotalCommits(self):
161 return -1
163 def getTotalFiles(self):
164 return -1
166 def getTotalLOC(self):
167 return -1
170 # Save cacheable data
171 def saveCache(self, cachefile):
172 print 'Saving cache...'
173 f = open(cachefile, 'wb')
174 #pickle.dump(self.cache, f)
175 data = zlib.compress(pickle.dumps(self.cache))
176 f.write(data)
177 f.close()
179 class GitDataCollector(DataCollector):
180 def collect(self, dir):
181 DataCollector.collect(self, dir)
183 try:
184 self.total_authors = int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
185 except:
186 self.total_authors = 0
187 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
189 self.activity_by_hour_of_day = {} # hour -> commits
190 self.activity_by_day_of_week = {} # day -> commits
191 self.activity_by_month_of_year = {} # month [1-12] -> commits
192 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
193 self.activity_by_hour_of_day_busiest = 0
194 self.activity_by_hour_of_week_busiest = 0
195 self.activity_by_year_week = {} # yy_wNN -> commits
196 self.activity_by_year_week_peak = 0
198 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
200 # domains
201 self.domains = {} # domain -> commits
203 # author of the month
204 self.author_of_month = {} # month -> author -> commits
205 self.author_of_year = {} # year -> author -> commits
206 self.commits_by_month = {} # month -> commits
207 self.commits_by_year = {} # year -> commits
208 self.first_commit_stamp = 0
209 self.last_commit_stamp = 0
210 self.last_active_day = None
211 self.active_days = set()
213 # lines
214 self.total_lines = 0
215 self.total_lines_added = 0
216 self.total_lines_removed = 0
218 # timezone
219 self.commits_by_timezone = {} # timezone -> commits
221 # tags
222 self.tags = {}
223 lines = getpipeoutput(['git show-ref --tags']).split('\n')
224 for line in lines:
225 if len(line) == 0:
226 continue
227 (hash, tag) = line.split(' ')
229 tag = tag.replace('refs/tags/', '')
230 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
231 if len(output) > 0:
232 parts = output.split(' ')
233 stamp = 0
234 try:
235 stamp = int(parts[0])
236 except ValueError:
237 stamp = 0
238 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
240 # collect info on tags, starting from latest
241 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
242 prev = None
243 for tag in reversed(tags_sorted_by_date_desc):
244 cmd = 'git shortlog -s "%s"' % tag
245 if prev != None:
246 cmd += ' "^%s"' % prev
247 output = getpipeoutput([cmd])
248 if len(output) == 0:
249 continue
250 prev = tag
251 for line in output.split('\n'):
252 parts = re.split('\s+', line, 2)
253 commits = int(parts[1])
254 author = parts[2]
255 self.tags[tag]['commits'] += commits
256 self.tags[tag]['authors'][author] = commits
258 # Collect revision statistics
259 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
260 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
261 for line in lines:
262 parts = line.split(' ', 4)
263 author = ''
264 try:
265 stamp = int(parts[0])
266 except ValueError:
267 stamp = 0
268 timezone = parts[3]
269 author, mail = parts[4].split('<', 1)
270 author = author.rstrip()
271 mail = mail.rstrip('>')
272 domain = '?'
273 if mail.find('@') != -1:
274 domain = mail.rsplit('@', 1)[1]
275 date = datetime.datetime.fromtimestamp(float(stamp))
277 # First and last commit stamp
278 if self.last_commit_stamp == 0:
279 self.last_commit_stamp = stamp
280 self.first_commit_stamp = stamp
282 # activity
283 # hour
284 hour = date.hour
285 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
286 # most active hour?
287 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
288 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
290 # day of week
291 day = date.weekday()
292 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
294 # domain stats
295 if domain not in self.domains:
296 self.domains[domain] = {}
297 # commits
298 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
300 # hour of week
301 if day not in self.activity_by_hour_of_week:
302 self.activity_by_hour_of_week[day] = {}
303 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
304 # most active hour?
305 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
306 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
308 # month of year
309 month = date.month
310 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
312 # yearly/weekly activity
313 yyw = date.strftime('%Y-%W')
314 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
315 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
316 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
318 # author stats
319 if author not in self.authors:
320 self.authors[author] = {}
321 # commits
322 if 'last_commit_stamp' not in self.authors[author]:
323 self.authors[author]['last_commit_stamp'] = stamp
324 self.authors[author]['first_commit_stamp'] = stamp
325 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
327 # author of the month/year
328 yymm = date.strftime('%Y-%m')
329 if yymm in self.author_of_month:
330 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
331 else:
332 self.author_of_month[yymm] = {}
333 self.author_of_month[yymm][author] = 1
334 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
336 yy = date.year
337 if yy in self.author_of_year:
338 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
339 else:
340 self.author_of_year[yy] = {}
341 self.author_of_year[yy][author] = 1
342 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
344 # authors: active days
345 yymmdd = date.strftime('%Y-%m-%d')
346 if 'last_active_day' not in self.authors[author]:
347 self.authors[author]['last_active_day'] = yymmdd
348 self.authors[author]['active_days'] = 1
349 elif yymmdd != self.authors[author]['last_active_day']:
350 self.authors[author]['last_active_day'] = yymmdd
351 self.authors[author]['active_days'] += 1
353 # project: active days
354 if yymmdd != self.last_active_day:
355 self.last_active_day = yymmdd
356 self.active_days.add(yymmdd)
358 # timezone
359 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
361 # TODO Optimize this, it's the worst bottleneck
362 # outputs "<stamp> <files>" for each revision
363 self.files_by_stamp = {} # stamp -> files
364 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
365 lines = []
366 for revline in revlines:
367 time, rev = revline.split(' ')
368 linecount = self.getFilesInCommit(rev)
369 lines.append('%d %d' % (int(time), linecount))
371 self.total_commits = len(lines)
372 for line in lines:
373 parts = line.split(' ')
374 if len(parts) != 2:
375 continue
376 (stamp, files) = parts[0:2]
377 try:
378 self.files_by_stamp[int(stamp)] = int(files)
379 except ValueError:
380 print 'Warning: failed to parse line "%s"' % line
382 # extensions
383 self.extensions = {} # extension -> files, lines
384 lines = getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
385 self.total_files = len(lines)
386 for line in lines:
387 if len(line) == 0:
388 continue
389 parts = re.split('\s+', line, 4)
390 sha1 = parts[2]
391 filename = parts[3]
393 if filename.find('.') == -1 or filename.rfind('.') == 0:
394 ext = ''
395 else:
396 ext = filename[(filename.rfind('.') + 1):]
397 if len(ext) > conf['max_ext_length']:
398 ext = ''
400 if ext not in self.extensions:
401 self.extensions[ext] = {'files': 0, 'lines': 0}
403 self.extensions[ext]['files'] += 1
404 try:
405 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
406 except:
407 print 'Warning: Could not count lines for file "%s"' % line
409 # line statistics
410 # outputs:
411 # N files changed, N insertions (+), N deletions(-)
412 # <stamp> <author>
413 self.changes_by_date = {} # stamp -> { files, ins, del }
414 # computation of lines of code by date is better done
415 # on a linear history.
416 extra = ''
417 if conf['linear_linestats']:
418 extra = '--first-parent -m'
419 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
420 lines.reverse()
421 files = 0; inserted = 0; deleted = 0; total_lines = 0
422 author = None
423 for line in lines:
424 if len(line) == 0:
425 continue
427 # <stamp> <author>
428 if line.find('files changed,') == -1:
429 pos = line.find(' ')
430 if pos != -1:
431 try:
432 (stamp, author) = (int(line[:pos]), line[pos+1:])
433 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
434 files, inserted, deleted = 0, 0, 0
435 except ValueError:
436 print 'Warning: unexpected line "%s"' % line
437 else:
438 print 'Warning: unexpected line "%s"' % line
439 else:
440 numbers = re.findall('\d+', line)
441 if len(numbers) == 3:
442 (files, inserted, deleted) = map(lambda el : int(el), numbers)
443 total_lines += inserted
444 total_lines -= deleted
445 self.total_lines_added += inserted
446 self.total_lines_removed += deleted
447 else:
448 print 'Warning: failed to handle line "%s"' % line
449 (files, inserted, deleted) = (0, 0, 0)
450 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
451 self.total_lines = total_lines
453 # Per-author statistics
454 self.changes_by_date_by_author = {} # stamp -> author -> lines_added
455 # defined for stamp, author only if
456 # author commited at this timestamp.
457 # Similar to the above, but never use --first-parent
458 # (we need to walk through every commits to know who
459 # commited what, not just through mainline)
460 lines = getpipeoutput(['git log --shortstat --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
461 lines.reverse()
462 files = 0; inserted = 0; deleted = 0;
463 author = None
464 for line in lines:
465 if len(line) == 0:
466 continue
468 # <stamp> <author>
469 if line.find('files changed,') == -1:
470 pos = line.find(' ')
471 if pos != -1:
472 try:
473 (stamp, author) = (int(line[:pos]), line[pos+1:])
474 if author not in self.authors:
475 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0 }
476 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
477 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
478 if stamp not in self.changes_by_date_by_author:
479 self.changes_by_date_by_author[stamp] = {}
480 self.changes_by_date_by_author[stamp][author] = self.authors[author]['lines_added']
481 files, inserted, deleted = 0, 0, 0
482 except ValueError:
483 print 'Warning: unexpected line "%s"' % line
484 else:
485 print 'Warning: unexpected line "%s"' % line
486 else:
487 numbers = re.findall('\d+', line)
488 if len(numbers) == 3:
489 (files, inserted, deleted) = map(lambda el : int(el), numbers)
490 else:
491 print 'Warning: failed to handle line "%s"' % line
492 (files, inserted, deleted) = (0, 0, 0)
494 def refine(self):
495 # authors
496 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
497 authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
498 authors_by_commits.reverse() # most first
499 for i, name in enumerate(authors_by_commits):
500 self.authors[name]['place_by_commits'] = i + 1
502 for name in self.authors.keys():
503 a = self.authors[name]
504 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
505 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
506 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
507 delta = date_last - date_first
508 a['date_first'] = date_first.strftime('%Y-%m-%d')
509 a['date_last'] = date_last.strftime('%Y-%m-%d')
510 a['timedelta'] = delta
511 if 'lines_added' not in a: a['lines_added'] = 0
512 if 'lines_removed' not in a: a['lines_removed'] = 0
514 def getActiveDays(self):
515 return self.active_days
517 def getActivityByDayOfWeek(self):
518 return self.activity_by_day_of_week
520 def getActivityByHourOfDay(self):
521 return self.activity_by_hour_of_day
523 def getAuthorInfo(self, author):
524 return self.authors[author]
526 def getAuthors(self, limit = None):
527 res = getkeyssortedbyvaluekey(self.authors, 'commits')
528 res.reverse()
529 return res[:limit]
531 def getCommitDeltaDays(self):
532 return (self.last_commit_stamp - self.first_commit_stamp) / 86400 + 1
534 def getDomainInfo(self, domain):
535 return self.domains[domain]
537 def getDomains(self):
538 return self.domains.keys()
540 def getFilesInCommit(self, rev):
541 try:
542 res = self.cache['files_in_tree'][rev]
543 except:
544 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
545 if 'files_in_tree' not in self.cache:
546 self.cache['files_in_tree'] = {}
547 self.cache['files_in_tree'][rev] = res
549 return res
551 def getFirstCommitDate(self):
552 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
554 def getLastCommitDate(self):
555 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
557 def getLinesInBlob(self, sha1):
558 try:
559 res = self.cache['lines_in_blob'][sha1]
560 except:
561 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
562 if 'lines_in_blob' not in self.cache:
563 self.cache['lines_in_blob'] = {}
564 self.cache['lines_in_blob'][sha1] = res
565 return res
567 def getTags(self):
568 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
569 return lines.split('\n')
571 def getTagDate(self, tag):
572 return self.revToDate('tags/' + tag)
574 def getTotalAuthors(self):
575 return self.total_authors
577 def getTotalCommits(self):
578 return self.total_commits
580 def getTotalFiles(self):
581 return self.total_files
583 def getTotalLOC(self):
584 return self.total_lines
586 def revToDate(self, rev):
587 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
588 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
590 class ReportCreator:
591 """Creates the actual report based on given data."""
592 def __init__(self):
593 pass
595 def create(self, data, path):
596 self.data = data
597 self.path = path
599 def html_linkify(text):
600 return text.lower().replace(' ', '_')
602 def html_header(level, text):
603 name = html_linkify(text)
604 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
606 class HTMLReportCreator(ReportCreator):
607 def create(self, data, path):
608 ReportCreator.create(self, data, path)
609 self.title = data.projectname
611 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
612 binarypath = os.path.dirname(os.path.abspath(__file__))
613 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
614 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
615 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
616 for base in basedirs:
617 src = base + '/' + file
618 if os.path.exists(src):
619 shutil.copyfile(src, path + '/' + file)
620 break
621 else:
622 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
624 f = open(path + "/index.html", 'w')
625 format = '%Y-%m-%d %H:%M:%S'
626 self.printHeader(f)
628 f.write('<h1>GitStats - %s</h1>' % data.projectname)
630 self.printNav(f)
632 f.write('<dl>')
633 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
634 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
635 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
636 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
637 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())))
638 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
639 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))
640 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()))
641 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
642 f.write('</dl>')
644 f.write('</body>\n</html>')
645 f.close()
648 # Activity
649 f = open(path + '/activity.html', 'w')
650 self.printHeader(f)
651 f.write('<h1>Activity</h1>')
652 self.printNav(f)
654 #f.write('<h2>Last 30 days</h2>')
656 #f.write('<h2>Last 12 months</h2>')
658 # Weekly activity
659 WEEKS = 32
660 f.write(html_header(2, 'Weekly activity'))
661 f.write('<p>Last %d weeks</p>' % WEEKS)
663 # generate weeks to show (previous N weeks from now)
664 now = datetime.datetime.now()
665 deltaweek = datetime.timedelta(7)
666 weeks = []
667 stampcur = now
668 for i in range(0, WEEKS):
669 weeks.insert(0, stampcur.strftime('%Y-%W'))
670 stampcur -= deltaweek
672 # top row: commits & bar
673 f.write('<table class="noborders"><tr>')
674 for i in range(0, WEEKS):
675 commits = 0
676 if weeks[i] in data.activity_by_year_week:
677 commits = data.activity_by_year_week[weeks[i]]
679 percentage = 0
680 if weeks[i] in data.activity_by_year_week:
681 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
682 height = max(1, int(200 * percentage))
683 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))
685 # bottom row: year/week
686 f.write('</tr><tr>')
687 for i in range(0, WEEKS):
688 f.write('<td>%s</td>' % (WEEKS - i))
689 f.write('</tr></table>')
691 # Hour of Day
692 f.write(html_header(2, 'Hour of Day'))
693 hour_of_day = data.getActivityByHourOfDay()
694 f.write('<table><tr><th>Hour</th>')
695 for i in range(0, 24):
696 f.write('<th>%d</th>' % i)
697 f.write('</tr>\n<tr><th>Commits</th>')
698 fp = open(path + '/hour_of_day.dat', 'w')
699 for i in range(0, 24):
700 if i in hour_of_day:
701 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
702 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
703 fp.write('%d %d\n' % (i, hour_of_day[i]))
704 else:
705 f.write('<td>0</td>')
706 fp.write('%d 0\n' % i)
707 fp.close()
708 f.write('</tr>\n<tr><th>%</th>')
709 totalcommits = data.getTotalCommits()
710 for i in range(0, 24):
711 if i in hour_of_day:
712 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
713 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
714 else:
715 f.write('<td>0.00</td>')
716 f.write('</tr></table>')
717 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
718 fg = open(path + '/hour_of_day.dat', 'w')
719 for i in range(0, 24):
720 if i in hour_of_day:
721 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
722 else:
723 fg.write('%d 0\n' % (i + 1))
724 fg.close()
726 # Day of Week
727 f.write(html_header(2, 'Day of Week'))
728 day_of_week = data.getActivityByDayOfWeek()
729 f.write('<div class="vtable"><table>')
730 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
731 fp = open(path + '/day_of_week.dat', 'w')
732 for d in range(0, 7):
733 commits = 0
734 if d in day_of_week:
735 commits = day_of_week[d]
736 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
737 f.write('<tr>')
738 f.write('<th>%s</th>' % (WEEKDAYS[d]))
739 if d in day_of_week:
740 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
741 else:
742 f.write('<td>0</td>')
743 f.write('</tr>')
744 f.write('</table></div>')
745 f.write('<img src="day_of_week.png" alt="Day of Week" />')
746 fp.close()
748 # Hour of Week
749 f.write(html_header(2, 'Hour of Week'))
750 f.write('<table>')
752 f.write('<tr><th>Weekday</th>')
753 for hour in range(0, 24):
754 f.write('<th>%d</th>' % (hour))
755 f.write('</tr>')
757 for weekday in range(0, 7):
758 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
759 for hour in range(0, 24):
760 try:
761 commits = data.activity_by_hour_of_week[weekday][hour]
762 except KeyError:
763 commits = 0
764 if commits != 0:
765 f.write('<td')
766 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
767 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
768 f.write('>%d</td>' % commits)
769 else:
770 f.write('<td></td>')
771 f.write('</tr>')
773 f.write('</table>')
775 # Month of Year
776 f.write(html_header(2, 'Month of Year'))
777 f.write('<div class="vtable"><table>')
778 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
779 fp = open (path + '/month_of_year.dat', 'w')
780 for mm in range(1, 13):
781 commits = 0
782 if mm in data.activity_by_month_of_year:
783 commits = data.activity_by_month_of_year[mm]
784 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
785 fp.write('%d %d\n' % (mm, commits))
786 fp.close()
787 f.write('</table></div>')
788 f.write('<img src="month_of_year.png" alt="Month of Year" />')
790 # Commits by year/month
791 f.write(html_header(2, 'Commits by year/month'))
792 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
793 for yymm in reversed(sorted(data.commits_by_month.keys())):
794 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
795 f.write('</table></div>')
796 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
797 fg = open(path + '/commits_by_year_month.dat', 'w')
798 for yymm in sorted(data.commits_by_month.keys()):
799 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
800 fg.close()
802 # Commits by year
803 f.write(html_header(2, 'Commits by Year'))
804 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
805 for yy in reversed(sorted(data.commits_by_year.keys())):
806 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()))
807 f.write('</table></div>')
808 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
809 fg = open(path + '/commits_by_year.dat', 'w')
810 for yy in sorted(data.commits_by_year.keys()):
811 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
812 fg.close()
814 # Commits by timezone
815 f.write(html_header(2, 'Commits by Timezone'))
816 f.write('<table><tr>')
817 f.write('<th>Timezone</th><th>Commits</th>')
818 max_commits_on_tz = max(data.commits_by_timezone.values())
819 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
820 commits = data.commits_by_timezone[i]
821 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
822 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
823 f.write('</tr></table>')
825 f.write('</body></html>')
826 f.close()
829 # Authors
830 f = open(path + '/authors.html', 'w')
831 self.printHeader(f)
833 f.write('<h1>Authors</h1>')
834 self.printNav(f)
836 # Authors :: List of authors
837 f.write(html_header(2, 'List of Authors'))
839 f.write('<table class="authors sortable" id="authors">')
840 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>')
841 for author in data.getAuthors(conf['max_authors']):
842 info = data.getAuthorInfo(author)
843 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (author, info['commits'], info['commits_frac'], info['lines_added'], info['lines_removed'], info['date_first'], info['date_last'], info['timedelta'], info['active_days'], info['place_by_commits']))
844 f.write('</table>')
846 allauthors = data.getAuthors()
847 if len(allauthors) > conf['max_authors']:
848 rest = allauthors[conf['max_authors']:]
849 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
851 f.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
852 f.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
853 if len(allauthors) > conf['max_authors']:
854 rest = allauthors[conf['max_authors']:]
855 f.write('<p class="moreauthors">These didn\'t make it to the graph: %s</p>' % ', '.join(rest))
857 fg = open(path + '/lines_of_code_by_author.dat', 'w')
858 lines_by_authors = {} # cumulated added lines by
859 # author. to save memory,
860 # changes_by_date_by_author[stamp][author] is defined
861 # only at points where author commits.
862 # lines_by_authors allows us to generate all the
863 # points in the .dat file.
865 # Don't rely on getAuthors to give the same order each
866 # time. Be robust and keep the list in a variable.
867 self.authors_to_plot = data.getAuthors(conf['max_authors'])
868 for author in self.authors_to_plot:
869 lines_by_authors[author] = 0
870 for stamp in sorted(data.changes_by_date_by_author.keys()):
871 fg.write('%d' % stamp)
872 for author in self.authors_to_plot:
873 if author in data.changes_by_date_by_author[stamp].keys():
874 lines_by_authors[author] = data.changes_by_date_by_author[stamp][author]
875 fg.write(' %d' % lines_by_authors[author])
876 fg.write('\n');
877 fg.close()
879 # Authors :: Author of Month
880 f.write(html_header(2, 'Author of Month'))
881 f.write('<table class="sortable" id="aom">')
882 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'])
883 for yymm in reversed(sorted(data.author_of_month.keys())):
884 authordict = data.author_of_month[yymm]
885 authors = getkeyssortedbyvalues(authordict)
886 authors.reverse()
887 commits = data.author_of_month[yymm][authors[0]]
888 next = ', '.join(authors[1:conf['authors_top']+1])
889 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)))
891 f.write('</table>')
893 f.write(html_header(2, 'Author of Year'))
894 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'])
895 for yy in reversed(sorted(data.author_of_year.keys())):
896 authordict = data.author_of_year[yy]
897 authors = getkeyssortedbyvalues(authordict)
898 authors.reverse()
899 commits = data.author_of_year[yy][authors[0]]
900 next = ', '.join(authors[1:conf['authors_top']+1])
901 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)))
902 f.write('</table>')
904 # Domains
905 f.write(html_header(2, 'Commits by Domains'))
906 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
907 domains_by_commits.reverse() # most first
908 f.write('<div class="vtable"><table>')
909 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
910 fp = open(path + '/domains.dat', 'w')
911 n = 0
912 for domain in domains_by_commits:
913 if n == conf['max_domains']:
914 break
915 commits = 0
916 n += 1
917 info = data.getDomainInfo(domain)
918 fp.write('%s %d %d\n' % (domain, n , info['commits']))
919 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
920 f.write('</table></div>')
921 f.write('<img src="domains.png" alt="Commits by Domains" />')
922 fp.close()
924 f.write('</body></html>')
925 f.close()
928 # Files
929 f = open(path + '/files.html', 'w')
930 self.printHeader(f)
931 f.write('<h1>Files</h1>')
932 self.printNav(f)
934 f.write('<dl>\n')
935 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
936 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
937 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
938 f.write('</dl>\n')
940 # Files :: File count by date
941 f.write(html_header(2, 'File count by date'))
943 # use set to get rid of duplicate/unnecessary entries
944 files_by_date = set()
945 for stamp in sorted(data.files_by_stamp.keys()):
946 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
948 fg = open(path + '/files_by_date.dat', 'w')
949 for line in sorted(list(files_by_date)):
950 fg.write('%s\n' % line)
951 #for stamp in sorted(data.files_by_stamp.keys()):
952 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
953 fg.close()
955 f.write('<img src="files_by_date.png" alt="Files by Date" />')
957 #f.write('<h2>Average file size by date</h2>')
959 # Files :: Extensions
960 f.write(html_header(2, 'Extensions'))
961 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
962 for ext in sorted(data.extensions.keys()):
963 files = data.extensions[ext]['files']
964 lines = data.extensions[ext]['lines']
965 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))
966 f.write('</table>')
968 f.write('</body></html>')
969 f.close()
972 # Lines
973 f = open(path + '/lines.html', 'w')
974 self.printHeader(f)
975 f.write('<h1>Lines</h1>')
976 self.printNav(f)
978 f.write('<dl>\n')
979 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
980 f.write('</dl>\n')
982 f.write(html_header(2, 'Lines of Code'))
983 f.write('<img src="lines_of_code.png" />')
985 fg = open(path + '/lines_of_code.dat', 'w')
986 for stamp in sorted(data.changes_by_date.keys()):
987 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
988 fg.close()
990 f.write('</body></html>')
991 f.close()
994 # tags.html
995 f = open(path + '/tags.html', 'w')
996 self.printHeader(f)
997 f.write('<h1>Tags</h1>')
998 self.printNav(f)
1000 f.write('<dl>')
1001 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
1002 if len(data.tags) > 0:
1003 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
1004 f.write('</dl>')
1006 f.write('<table class="tags">')
1007 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1008 # sort the tags by date desc
1009 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
1010 for tag in tags_sorted_by_date_desc:
1011 authorinfo = []
1012 authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
1013 for i in reversed(authors_by_commits):
1014 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
1015 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)))
1016 f.write('</table>')
1018 f.write('</body></html>')
1019 f.close()
1021 self.createGraphs(path)
1023 def createGraphs(self, path):
1024 print 'Generating graphs...'
1026 # hour of day
1027 f = open(path + '/hour_of_day.plot', 'w')
1028 f.write(GNUPLOT_COMMON)
1029 f.write(
1031 set output 'hour_of_day.png'
1032 unset key
1033 set xrange [0.5:24.5]
1034 set xtics 4
1035 set grid y
1036 set ylabel "Commits"
1037 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1038 """)
1039 f.close()
1041 # day of week
1042 f = open(path + '/day_of_week.plot', 'w')
1043 f.write(GNUPLOT_COMMON)
1044 f.write(
1046 set output 'day_of_week.png'
1047 unset key
1048 set xrange [0.5:7.5]
1049 set xtics 1
1050 set grid y
1051 set ylabel "Commits"
1052 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1053 """)
1054 f.close()
1056 # Domains
1057 f = open(path + '/domains.plot', 'w')
1058 f.write(GNUPLOT_COMMON)
1059 f.write(
1061 set output 'domains.png'
1062 unset key
1063 unset xtics
1064 set yrange [0:]
1065 set grid y
1066 set ylabel "Commits"
1067 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1068 """)
1069 f.close()
1071 # Month of Year
1072 f = open(path + '/month_of_year.plot', 'w')
1073 f.write(GNUPLOT_COMMON)
1074 f.write(
1076 set output 'month_of_year.png'
1077 unset key
1078 set xrange [0.5:12.5]
1079 set xtics 1
1080 set grid y
1081 set ylabel "Commits"
1082 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1083 """)
1084 f.close()
1086 # commits_by_year_month
1087 f = open(path + '/commits_by_year_month.plot', 'w')
1088 f.write(GNUPLOT_COMMON)
1089 f.write(
1091 set output 'commits_by_year_month.png'
1092 unset key
1093 set xdata time
1094 set timefmt "%Y-%m"
1095 set format x "%Y-%m"
1096 set xtics rotate
1097 set bmargin 5
1098 set grid y
1099 set ylabel "Commits"
1100 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1101 """)
1102 f.close()
1104 # commits_by_year
1105 f = open(path + '/commits_by_year.plot', 'w')
1106 f.write(GNUPLOT_COMMON)
1107 f.write(
1109 set output 'commits_by_year.png'
1110 unset key
1111 set xtics 1 rotate
1112 set grid y
1113 set ylabel "Commits"
1114 set yrange [0:]
1115 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1116 """)
1117 f.close()
1119 # Files by date
1120 f = open(path + '/files_by_date.plot', 'w')
1121 f.write(GNUPLOT_COMMON)
1122 f.write(
1124 set output 'files_by_date.png'
1125 unset key
1126 set xdata time
1127 set timefmt "%Y-%m-%d"
1128 set format x "%Y-%m-%d"
1129 set grid y
1130 set ylabel "Files"
1131 set xtics rotate
1132 set ytics autofreq
1133 set bmargin 6
1134 plot 'files_by_date.dat' using 1:2 w steps
1135 """)
1136 f.close()
1138 # Lines of Code
1139 f = open(path + '/lines_of_code.plot', 'w')
1140 f.write(GNUPLOT_COMMON)
1141 f.write(
1143 set output 'lines_of_code.png'
1144 unset key
1145 set xdata time
1146 set timefmt "%s"
1147 set format x "%Y-%m-%d"
1148 set grid y
1149 set ylabel "Lines"
1150 set xtics rotate
1151 set bmargin 6
1152 plot 'lines_of_code.dat' using 1:2 w lines
1153 """)
1154 f.close()
1156 # Lines of Code Added per author
1157 f = open(path + '/lines_of_code_by_author.plot', 'w')
1158 f.write(GNUPLOT_COMMON)
1159 f.write(
1161 set terminal png transparent size 640,480
1162 set output 'lines_of_code_by_author.png'
1163 set key left top
1164 set xdata time
1165 set timefmt "%s"
1166 set format x "%Y-%m-%d"
1167 set grid y
1168 set ylabel "Lines"
1169 set xtics rotate
1170 set bmargin 6
1171 plot """
1173 i = 1
1174 plots = []
1175 for a in self.authors_to_plot:
1176 i = i + 1
1177 plots.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1178 f.write(", ".join(plots))
1179 f.write('\n')
1181 f.close()
1183 os.chdir(path)
1184 files = glob.glob(path + '/*.plot')
1185 for f in files:
1186 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1187 if len(out) > 0:
1188 print out
1190 def printHeader(self, f, title = ''):
1191 f.write(
1192 """<?xml version="1.0" encoding="UTF-8"?>
1193 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1194 <html xmlns="http://www.w3.org/1999/xhtml">
1195 <head>
1196 <title>GitStats - %s</title>
1197 <link rel="stylesheet" href="%s" type="text/css" />
1198 <meta name="generator" content="GitStats %s" />
1199 <script type="text/javascript" src="sortable.js"></script>
1200 </head>
1201 <body>
1202 """ % (self.title, conf['style'], getversion()))
1204 def printNav(self, f):
1205 f.write("""
1206 <div class="nav">
1207 <ul>
1208 <li><a href="index.html">General</a></li>
1209 <li><a href="activity.html">Activity</a></li>
1210 <li><a href="authors.html">Authors</a></li>
1211 <li><a href="files.html">Files</a></li>
1212 <li><a href="lines.html">Lines</a></li>
1213 <li><a href="tags.html">Tags</a></li>
1214 </ul>
1215 </div>
1216 """)
1219 class GitStats:
1220 def run(self, args_orig):
1221 optlist, args = getopt.getopt(args_orig, 'c:')
1222 for o,v in optlist:
1223 if o == '-c':
1224 key, value = v.split('=', 1)
1225 if key not in conf:
1226 raise KeyError('no such key "%s" in config' % key)
1227 if isinstance(conf[key], int):
1228 conf[key] = int(value)
1229 else:
1230 conf[key] = value
1232 if len(args) < 2:
1233 print """
1234 Usage: gitstats [options] <gitpath> <outputpath>
1236 Options:
1237 -c key=value Override configuration value
1239 Default config values:
1241 """ % conf
1242 sys.exit(0)
1244 gitpath = args[0]
1245 outputpath = os.path.abspath(args[1])
1246 rundir = os.getcwd()
1248 try:
1249 os.makedirs(outputpath)
1250 except OSError:
1251 pass
1252 if not os.path.isdir(outputpath):
1253 print 'FATAL: Output path is not a directory or does not exist'
1254 sys.exit(1)
1256 print 'Git path: %s' % gitpath
1257 print 'Output path: %s' % outputpath
1259 os.chdir(gitpath)
1261 cachefile = os.path.join(outputpath, 'gitstats.cache')
1263 print 'Collecting data...'
1264 data = GitDataCollector()
1265 data.loadCache(cachefile)
1266 data.collect(gitpath)
1267 print 'Refining data...'
1268 data.saveCache(cachefile)
1269 data.refine()
1271 os.chdir(rundir)
1273 print 'Generating report...'
1274 report = HTMLReportCreator()
1275 report.create(data, outputpath)
1277 time_end = time.time()
1278 exectime_internal = time_end - time_start
1279 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1281 if __name__=='__main__':
1282 g = GitStats()
1283 g.run(sys.argv[1:])