Don't create ugly graphs on clock skew
[gitstats.git] / gitstats
blob27e7ddec910b58b6d40c8db6863ed7d6e8bd8b34
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': '',
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.first_commit_stamp = 0
120 self.last_commit_stamp = 0
121 self.last_active_day = None
122 self.active_days = set()
124 # lines
125 self.total_lines = 0
126 self.total_lines_added = 0
127 self.total_lines_removed = 0
129 # timezone
130 self.commits_by_timezone = {} # timezone -> commits
132 # tags
133 self.tags = {}
135 self.files_by_stamp = {} # stamp -> files
137 # extensions
138 self.extensions = {} # extension -> files, lines
140 # line statistics
141 self.changes_by_date = {} # stamp -> { files, ins, del }
144 # This should be the main function to extract data from the repository.
145 def collect(self, dir):
146 self.dir = dir
147 if len(conf['project_name']) == 0:
148 self.projectname = os.path.basename(os.path.abspath(dir))
149 else:
150 self.projectname = conf['project_name']
153 # Load cacheable data
154 def loadCache(self, cachefile):
155 if not os.path.exists(cachefile):
156 return
157 print 'Loading cache...'
158 f = open(cachefile, 'rb')
159 try:
160 self.cache = pickle.loads(zlib.decompress(f.read()))
161 except:
162 # temporary hack to upgrade non-compressed caches
163 f.seek(0)
164 self.cache = pickle.load(f)
165 f.close()
168 # Produce any additional statistics from the extracted data.
169 def refine(self):
170 pass
173 # : get a dictionary of author
174 def getAuthorInfo(self, author):
175 return None
177 def getActivityByDayOfWeek(self):
178 return {}
180 def getActivityByHourOfDay(self):
181 return {}
183 # : get a dictionary of domains
184 def getDomainInfo(self, domain):
185 return None
188 # Get a list of authors
189 def getAuthors(self):
190 return []
192 def getFirstCommitDate(self):
193 return datetime.datetime.now()
195 def getLastCommitDate(self):
196 return datetime.datetime.now()
198 def getStampCreated(self):
199 return self.stamp_created
201 def getTags(self):
202 return []
204 def getTotalAuthors(self):
205 return -1
207 def getTotalCommits(self):
208 return -1
210 def getTotalFiles(self):
211 return -1
213 def getTotalLOC(self):
214 return -1
217 # Save cacheable data
218 def saveCache(self, cachefile):
219 print 'Saving cache...'
220 f = open(cachefile, 'wb')
221 #pickle.dump(self.cache, f)
222 data = zlib.compress(pickle.dumps(self.cache))
223 f.write(data)
224 f.close()
226 class GitDataCollector(DataCollector):
227 def collect(self, dir):
228 DataCollector.collect(self, dir)
230 try:
231 self.total_authors += int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
232 except:
233 self.total_authors = 0
234 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
236 # tags
237 lines = getpipeoutput(['git show-ref --tags']).split('\n')
238 for line in lines:
239 if len(line) == 0:
240 continue
241 (hash, tag) = line.split(' ')
243 tag = tag.replace('refs/tags/', '')
244 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
245 if len(output) > 0:
246 parts = output.split(' ')
247 stamp = 0
248 try:
249 stamp = int(parts[0])
250 except ValueError:
251 stamp = 0
252 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
254 # collect info on tags, starting from latest
255 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
256 prev = None
257 for tag in reversed(tags_sorted_by_date_desc):
258 cmd = 'git shortlog -s "%s"' % tag
259 if prev != None:
260 cmd += ' "^%s"' % prev
261 output = getpipeoutput([cmd])
262 if len(output) == 0:
263 continue
264 prev = tag
265 for line in output.split('\n'):
266 parts = re.split('\s+', line, 2)
267 commits = int(parts[1])
268 author = parts[2]
269 self.tags[tag]['commits'] = commits
270 self.tags[tag]['authors'][author] = commits
272 # Collect revision statistics
273 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
274 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
275 for line in lines:
276 parts = line.split(' ', 4)
277 author = ''
278 try:
279 stamp = int(parts[0])
280 except ValueError:
281 stamp = 0
282 timezone = parts[3]
283 author, mail = parts[4].split('<', 1)
284 author = author.rstrip()
285 mail = mail.rstrip('>')
286 domain = '?'
287 if mail.find('@') != -1:
288 domain = mail.rsplit('@', 1)[1]
289 date = datetime.datetime.fromtimestamp(float(stamp))
291 # First and last commit stamp (may be in any order because of cherry-picking and patches)
292 if stamp > self.last_commit_stamp:
293 self.last_commit_stamp = stamp
294 if self.first_commit_stamp == 0 or stamp < self.first_commit_stamp:
295 self.first_commit_stamp = stamp
297 # activity
298 # hour
299 hour = date.hour
300 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
301 # most active hour?
302 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
303 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
305 # day of week
306 day = date.weekday()
307 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
309 # domain stats
310 if domain not in self.domains:
311 self.domains[domain] = {}
312 # commits
313 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
315 # hour of week
316 if day not in self.activity_by_hour_of_week:
317 self.activity_by_hour_of_week[day] = {}
318 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
319 # most active hour?
320 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
321 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
323 # month of year
324 month = date.month
325 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
327 # yearly/weekly activity
328 yyw = date.strftime('%Y-%W')
329 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
330 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
331 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
333 # author stats
334 if author not in self.authors:
335 self.authors[author] = {}
336 # commits, note again that commits may be in any date order because of cherry-picking and patches
337 if 'last_commit_stamp' not in self.authors[author]:
338 self.authors[author]['last_commit_stamp'] = stamp
339 if stamp > self.authors[author]['last_commit_stamp']:
340 self.authors[author]['last_commit_stamp'] = stamp
341 if 'first_commit_stamp' not in self.authors[author]:
342 self.authors[author]['first_commit_stamp'] = stamp
343 if stamp < self.authors[author]['first_commit_stamp']:
344 self.authors[author]['first_commit_stamp'] = stamp
346 # author of the month/year
347 yymm = date.strftime('%Y-%m')
348 if yymm in self.author_of_month:
349 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
350 else:
351 self.author_of_month[yymm] = {}
352 self.author_of_month[yymm][author] = 1
353 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
355 yy = date.year
356 if yy in self.author_of_year:
357 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
358 else:
359 self.author_of_year[yy] = {}
360 self.author_of_year[yy][author] = 1
361 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
363 # authors: active days
364 yymmdd = date.strftime('%Y-%m-%d')
365 if 'last_active_day' not in self.authors[author]:
366 self.authors[author]['last_active_day'] = yymmdd
367 self.authors[author]['active_days'] = set([yymmdd])
368 elif yymmdd != self.authors[author]['last_active_day']:
369 self.authors[author]['last_active_day'] = yymmdd
370 self.authors[author]['active_days'].add(yymmdd)
372 # project: active days
373 if yymmdd != self.last_active_day:
374 self.last_active_day = yymmdd
375 self.active_days.add(yymmdd)
377 # timezone
378 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
380 # TODO Optimize this, it's the worst bottleneck
381 # outputs "<stamp> <files>" for each revision
382 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
383 lines = []
384 for revline in revlines:
385 time, rev = revline.split(' ')
386 linecount = self.getFilesInCommit(rev)
387 lines.append('%d %d' % (int(time), linecount))
389 self.total_commits += len(lines)
390 for line in lines:
391 parts = line.split(' ')
392 if len(parts) != 2:
393 continue
394 (stamp, files) = parts[0:2]
395 try:
396 self.files_by_stamp[int(stamp)] = int(files)
397 except ValueError:
398 print 'Warning: failed to parse line "%s"' % line
400 # extensions
401 lines = getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
402 self.total_files += len(lines)
403 for line in lines:
404 if len(line) == 0:
405 continue
406 parts = re.split('\s+', line, 4)
407 sha1 = parts[2]
408 filename = parts[3]
410 if filename.find('.') == -1 or filename.rfind('.') == 0:
411 ext = ''
412 else:
413 ext = filename[(filename.rfind('.') + 1):]
414 if len(ext) > conf['max_ext_length']:
415 ext = ''
417 if ext not in self.extensions:
418 self.extensions[ext] = {'files': 0, 'lines': 0}
420 self.extensions[ext]['files'] += 1
421 try:
422 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
423 except:
424 print 'Warning: Could not count lines for file "%s"' % line
426 # line statistics
427 # outputs:
428 # N files changed, N insertions (+), N deletions(-)
429 # <stamp> <author>
430 self.changes_by_date = {} # stamp -> { files, ins, del }
431 # computation of lines of code by date is better done
432 # on a linear history.
433 extra = ''
434 if conf['linear_linestats']:
435 extra = '--first-parent -m'
436 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
437 lines.reverse()
438 files = 0; inserted = 0; deleted = 0; total_lines = 0
439 author = None
440 for line in lines:
441 if len(line) == 0:
442 continue
444 # <stamp> <author>
445 if line.find('files changed,') == -1:
446 pos = line.find(' ')
447 if pos != -1:
448 try:
449 (stamp, author) = (int(line[:pos]), line[pos+1:])
450 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
451 files, inserted, deleted = 0, 0, 0
452 except ValueError:
453 print 'Warning: unexpected line "%s"' % line
454 else:
455 print 'Warning: unexpected line "%s"' % line
456 else:
457 numbers = re.findall('\d+', line)
458 if len(numbers) == 3:
459 (files, inserted, deleted) = map(lambda el : int(el), numbers)
460 total_lines += inserted
461 total_lines -= deleted
462 self.total_lines_added += inserted
463 self.total_lines_removed += deleted
464 else:
465 print 'Warning: failed to handle line "%s"' % line
466 (files, inserted, deleted) = (0, 0, 0)
467 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
468 self.total_lines = total_lines
470 # Per-author statistics
472 # defined for stamp, author only if author commited at this timestamp.
473 self.changes_by_date_by_author = {} # stamp -> author -> lines_added
475 # Similar to the above, but never use --first-parent
476 # (we need to walk through every commit to know who
477 # committed what, not just through mainline)
478 lines = getpipeoutput(['git log --shortstat --date-order --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
479 lines.reverse()
480 files = 0; inserted = 0; deleted = 0
481 author = None
482 stamp = 0
483 for line in lines:
484 if len(line) == 0:
485 continue
487 # <stamp> <author>
488 if line.find('files changed,') == -1:
489 pos = line.find(' ')
490 if pos != -1:
491 try:
492 oldstamp = stamp
493 (stamp, author) = (int(line[:pos]), line[pos+1:])
494 if oldstamp > stamp:
495 # clock skew, keep old timestamp to avoid having ugly graph
496 stamp = oldstamp
497 if author not in self.authors:
498 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
499 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
500 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
501 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
502 if stamp not in self.changes_by_date_by_author:
503 self.changes_by_date_by_author[stamp] = {}
504 if author not in self.changes_by_date_by_author[stamp]:
505 self.changes_by_date_by_author[stamp][author] = {}
506 self.changes_by_date_by_author[stamp][author]['lines_added'] = self.authors[author]['lines_added']
507 self.changes_by_date_by_author[stamp][author]['commits'] = self.authors[author]['commits']
508 files, inserted, deleted = 0, 0, 0
509 except ValueError:
510 print 'Warning: unexpected line "%s"' % line
511 else:
512 print 'Warning: unexpected line "%s"' % line
513 else:
514 numbers = re.findall('\d+', line)
515 if len(numbers) == 3:
516 (files, inserted, deleted) = map(lambda el : int(el), numbers)
517 else:
518 print 'Warning: failed to handle line "%s"' % line
519 (files, inserted, deleted) = (0, 0, 0)
521 def refine(self):
522 # authors
523 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
524 self.authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
525 self.authors_by_commits.reverse() # most first
526 for i, name in enumerate(self.authors_by_commits):
527 self.authors[name]['place_by_commits'] = i + 1
529 for name in self.authors.keys():
530 a = self.authors[name]
531 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
532 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
533 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
534 delta = date_last - date_first
535 a['date_first'] = date_first.strftime('%Y-%m-%d')
536 a['date_last'] = date_last.strftime('%Y-%m-%d')
537 a['timedelta'] = delta
538 if 'lines_added' not in a: a['lines_added'] = 0
539 if 'lines_removed' not in a: a['lines_removed'] = 0
541 def getActiveDays(self):
542 return self.active_days
544 def getActivityByDayOfWeek(self):
545 return self.activity_by_day_of_week
547 def getActivityByHourOfDay(self):
548 return self.activity_by_hour_of_day
550 def getAuthorInfo(self, author):
551 return self.authors[author]
553 def getAuthors(self, limit = None):
554 res = getkeyssortedbyvaluekey(self.authors, 'commits')
555 res.reverse()
556 return res[:limit]
558 def getCommitDeltaDays(self):
559 return (self.last_commit_stamp - self.first_commit_stamp) / 86400 + 1
561 def getDomainInfo(self, domain):
562 return self.domains[domain]
564 def getDomains(self):
565 return self.domains.keys()
567 def getFilesInCommit(self, rev):
568 try:
569 res = self.cache['files_in_tree'][rev]
570 except:
571 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
572 if 'files_in_tree' not in self.cache:
573 self.cache['files_in_tree'] = {}
574 self.cache['files_in_tree'][rev] = res
576 return res
578 def getFirstCommitDate(self):
579 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
581 def getLastCommitDate(self):
582 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
584 def getLinesInBlob(self, sha1):
585 try:
586 res = self.cache['lines_in_blob'][sha1]
587 except:
588 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
589 if 'lines_in_blob' not in self.cache:
590 self.cache['lines_in_blob'] = {}
591 self.cache['lines_in_blob'][sha1] = res
592 return res
594 def getTags(self):
595 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
596 return lines.split('\n')
598 def getTagDate(self, tag):
599 return self.revToDate('tags/' + tag)
601 def getTotalAuthors(self):
602 return self.total_authors
604 def getTotalCommits(self):
605 return self.total_commits
607 def getTotalFiles(self):
608 return self.total_files
610 def getTotalLOC(self):
611 return self.total_lines
613 def revToDate(self, rev):
614 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
615 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
617 class ReportCreator:
618 """Creates the actual report based on given data."""
619 def __init__(self):
620 pass
622 def create(self, data, path):
623 self.data = data
624 self.path = path
626 def html_linkify(text):
627 return text.lower().replace(' ', '_')
629 def html_header(level, text):
630 name = html_linkify(text)
631 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
633 class HTMLReportCreator(ReportCreator):
634 def create(self, data, path):
635 ReportCreator.create(self, data, path)
636 self.title = data.projectname
638 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
639 binarypath = os.path.dirname(os.path.abspath(__file__))
640 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
641 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
642 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
643 for base in basedirs:
644 src = base + '/' + file
645 if os.path.exists(src):
646 shutil.copyfile(src, path + '/' + file)
647 break
648 else:
649 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
651 f = open(path + "/index.html", 'w')
652 format = '%Y-%m-%d %H:%M:%S'
653 self.printHeader(f)
655 f.write('<h1>GitStats - %s</h1>' % data.projectname)
657 self.printNav(f)
659 f.write('<dl>')
660 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
661 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
662 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
663 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
664 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())))
665 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
666 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))
667 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()))
668 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
669 f.write('</dl>')
671 f.write('</body>\n</html>')
672 f.close()
675 # Activity
676 f = open(path + '/activity.html', 'w')
677 self.printHeader(f)
678 f.write('<h1>Activity</h1>')
679 self.printNav(f)
681 #f.write('<h2>Last 30 days</h2>')
683 #f.write('<h2>Last 12 months</h2>')
685 # Weekly activity
686 WEEKS = 32
687 f.write(html_header(2, 'Weekly activity'))
688 f.write('<p>Last %d weeks</p>' % WEEKS)
690 # generate weeks to show (previous N weeks from now)
691 now = datetime.datetime.now()
692 deltaweek = datetime.timedelta(7)
693 weeks = []
694 stampcur = now
695 for i in range(0, WEEKS):
696 weeks.insert(0, stampcur.strftime('%Y-%W'))
697 stampcur -= deltaweek
699 # top row: commits & bar
700 f.write('<table class="noborders"><tr>')
701 for i in range(0, WEEKS):
702 commits = 0
703 if weeks[i] in data.activity_by_year_week:
704 commits = data.activity_by_year_week[weeks[i]]
706 percentage = 0
707 if weeks[i] in data.activity_by_year_week:
708 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
709 height = max(1, int(200 * percentage))
710 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))
712 # bottom row: year/week
713 f.write('</tr><tr>')
714 for i in range(0, WEEKS):
715 f.write('<td>%s</td>' % (WEEKS - i))
716 f.write('</tr></table>')
718 # Hour of Day
719 f.write(html_header(2, 'Hour of Day'))
720 hour_of_day = data.getActivityByHourOfDay()
721 f.write('<table><tr><th>Hour</th>')
722 for i in range(0, 24):
723 f.write('<th>%d</th>' % i)
724 f.write('</tr>\n<tr><th>Commits</th>')
725 fp = open(path + '/hour_of_day.dat', 'w')
726 for i in range(0, 24):
727 if i in hour_of_day:
728 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
729 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
730 fp.write('%d %d\n' % (i, hour_of_day[i]))
731 else:
732 f.write('<td>0</td>')
733 fp.write('%d 0\n' % i)
734 fp.close()
735 f.write('</tr>\n<tr><th>%</th>')
736 totalcommits = data.getTotalCommits()
737 for i in range(0, 24):
738 if i in hour_of_day:
739 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
740 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
741 else:
742 f.write('<td>0.00</td>')
743 f.write('</tr></table>')
744 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
745 fg = open(path + '/hour_of_day.dat', 'w')
746 for i in range(0, 24):
747 if i in hour_of_day:
748 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
749 else:
750 fg.write('%d 0\n' % (i + 1))
751 fg.close()
753 # Day of Week
754 f.write(html_header(2, 'Day of Week'))
755 day_of_week = data.getActivityByDayOfWeek()
756 f.write('<div class="vtable"><table>')
757 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
758 fp = open(path + '/day_of_week.dat', 'w')
759 for d in range(0, 7):
760 commits = 0
761 if d in day_of_week:
762 commits = day_of_week[d]
763 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
764 f.write('<tr>')
765 f.write('<th>%s</th>' % (WEEKDAYS[d]))
766 if d in day_of_week:
767 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
768 else:
769 f.write('<td>0</td>')
770 f.write('</tr>')
771 f.write('</table></div>')
772 f.write('<img src="day_of_week.png" alt="Day of Week" />')
773 fp.close()
775 # Hour of Week
776 f.write(html_header(2, 'Hour of Week'))
777 f.write('<table>')
779 f.write('<tr><th>Weekday</th>')
780 for hour in range(0, 24):
781 f.write('<th>%d</th>' % (hour))
782 f.write('</tr>')
784 for weekday in range(0, 7):
785 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
786 for hour in range(0, 24):
787 try:
788 commits = data.activity_by_hour_of_week[weekday][hour]
789 except KeyError:
790 commits = 0
791 if commits != 0:
792 f.write('<td')
793 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
794 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
795 f.write('>%d</td>' % commits)
796 else:
797 f.write('<td></td>')
798 f.write('</tr>')
800 f.write('</table>')
802 # Month of Year
803 f.write(html_header(2, 'Month of Year'))
804 f.write('<div class="vtable"><table>')
805 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
806 fp = open (path + '/month_of_year.dat', 'w')
807 for mm in range(1, 13):
808 commits = 0
809 if mm in data.activity_by_month_of_year:
810 commits = data.activity_by_month_of_year[mm]
811 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
812 fp.write('%d %d\n' % (mm, commits))
813 fp.close()
814 f.write('</table></div>')
815 f.write('<img src="month_of_year.png" alt="Month of Year" />')
817 # Commits by year/month
818 f.write(html_header(2, 'Commits by year/month'))
819 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
820 for yymm in reversed(sorted(data.commits_by_month.keys())):
821 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
822 f.write('</table></div>')
823 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
824 fg = open(path + '/commits_by_year_month.dat', 'w')
825 for yymm in sorted(data.commits_by_month.keys()):
826 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
827 fg.close()
829 # Commits by year
830 f.write(html_header(2, 'Commits by Year'))
831 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
832 for yy in reversed(sorted(data.commits_by_year.keys())):
833 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()))
834 f.write('</table></div>')
835 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
836 fg = open(path + '/commits_by_year.dat', 'w')
837 for yy in sorted(data.commits_by_year.keys()):
838 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
839 fg.close()
841 # Commits by timezone
842 f.write(html_header(2, 'Commits by Timezone'))
843 f.write('<table><tr>')
844 f.write('<th>Timezone</th><th>Commits</th>')
845 max_commits_on_tz = max(data.commits_by_timezone.values())
846 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
847 commits = data.commits_by_timezone[i]
848 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
849 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
850 f.write('</tr></table>')
852 f.write('</body></html>')
853 f.close()
856 # Authors
857 f = open(path + '/authors.html', 'w')
858 self.printHeader(f)
860 f.write('<h1>Authors</h1>')
861 self.printNav(f)
863 # Authors :: List of authors
864 f.write(html_header(2, 'List of Authors'))
866 f.write('<table class="authors sortable" id="authors">')
867 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>')
868 for author in data.getAuthors(conf['max_authors']):
869 info = data.getAuthorInfo(author)
870 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']))
871 f.write('</table>')
873 allauthors = data.getAuthors()
874 if len(allauthors) > conf['max_authors']:
875 rest = allauthors[conf['max_authors']:]
876 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
878 f.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
879 f.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
880 if len(allauthors) > conf['max_authors']:
881 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
883 f.write(html_header(2, 'Commits per Author'))
884 f.write('<img src="commits_by_author.png" alt="Commits per Author" />')
885 if len(allauthors) > conf['max_authors']:
886 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
888 fgl = open(path + '/lines_of_code_by_author.dat', 'w')
889 fgc = open(path + '/commits_by_author.dat', 'w')
891 lines_by_authors = {} # cumulated added lines by
892 # author. to save memory,
893 # changes_by_date_by_author[stamp][author] is defined
894 # only at points where author commits.
895 # lines_by_authors allows us to generate all the
896 # points in the .dat file.
898 # Don't rely on getAuthors to give the same order each
899 # time. Be robust and keep the list in a variable.
900 commits_by_authors = {} # cumulated added lines by
902 self.authors_to_plot = data.getAuthors(conf['max_authors'])
903 for author in self.authors_to_plot:
904 lines_by_authors[author] = 0
905 commits_by_authors[author] = 0
906 for stamp in sorted(data.changes_by_date_by_author.keys()):
907 fgl.write('%d' % stamp)
908 fgc.write('%d' % stamp)
909 for author in self.authors_to_plot:
910 if author in data.changes_by_date_by_author[stamp].keys():
911 lines_by_authors[author] = data.changes_by_date_by_author[stamp][author]['lines_added']
912 commits_by_authors[author] = data.changes_by_date_by_author[stamp][author]['commits']
913 fgl.write(' %d' % lines_by_authors[author])
914 fgc.write(' %d' % commits_by_authors[author])
915 fgl.write('\n')
916 fgc.write('\n')
917 fgl.close()
918 fgc.close()
920 # Authors :: Author of Month
921 f.write(html_header(2, 'Author of Month'))
922 f.write('<table class="sortable" id="aom">')
923 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'])
924 for yymm in reversed(sorted(data.author_of_month.keys())):
925 authordict = data.author_of_month[yymm]
926 authors = getkeyssortedbyvalues(authordict)
927 authors.reverse()
928 commits = data.author_of_month[yymm][authors[0]]
929 next = ', '.join(authors[1:conf['authors_top']+1])
930 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)))
932 f.write('</table>')
934 f.write(html_header(2, 'Author of Year'))
935 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'])
936 for yy in reversed(sorted(data.author_of_year.keys())):
937 authordict = data.author_of_year[yy]
938 authors = getkeyssortedbyvalues(authordict)
939 authors.reverse()
940 commits = data.author_of_year[yy][authors[0]]
941 next = ', '.join(authors[1:conf['authors_top']+1])
942 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)))
943 f.write('</table>')
945 # Domains
946 f.write(html_header(2, 'Commits by Domains'))
947 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
948 domains_by_commits.reverse() # most first
949 f.write('<div class="vtable"><table>')
950 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
951 fp = open(path + '/domains.dat', 'w')
952 n = 0
953 for domain in domains_by_commits:
954 if n == conf['max_domains']:
955 break
956 commits = 0
957 n += 1
958 info = data.getDomainInfo(domain)
959 fp.write('%s %d %d\n' % (domain, n , info['commits']))
960 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
961 f.write('</table></div>')
962 f.write('<img src="domains.png" alt="Commits by Domains" />')
963 fp.close()
965 f.write('</body></html>')
966 f.close()
969 # Files
970 f = open(path + '/files.html', 'w')
971 self.printHeader(f)
972 f.write('<h1>Files</h1>')
973 self.printNav(f)
975 f.write('<dl>\n')
976 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
977 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
978 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
979 f.write('</dl>\n')
981 # Files :: File count by date
982 f.write(html_header(2, 'File count by date'))
984 # use set to get rid of duplicate/unnecessary entries
985 files_by_date = set()
986 for stamp in sorted(data.files_by_stamp.keys()):
987 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
989 fg = open(path + '/files_by_date.dat', 'w')
990 for line in sorted(list(files_by_date)):
991 fg.write('%s\n' % line)
992 #for stamp in sorted(data.files_by_stamp.keys()):
993 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
994 fg.close()
996 f.write('<img src="files_by_date.png" alt="Files by Date" />')
998 #f.write('<h2>Average file size by date</h2>')
1000 # Files :: Extensions
1001 f.write(html_header(2, 'Extensions'))
1002 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
1003 for ext in sorted(data.extensions.keys()):
1004 files = data.extensions[ext]['files']
1005 lines = data.extensions[ext]['lines']
1006 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))
1007 f.write('</table>')
1009 f.write('</body></html>')
1010 f.close()
1013 # Lines
1014 f = open(path + '/lines.html', 'w')
1015 self.printHeader(f)
1016 f.write('<h1>Lines</h1>')
1017 self.printNav(f)
1019 f.write('<dl>\n')
1020 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1021 f.write('</dl>\n')
1023 f.write(html_header(2, 'Lines of Code'))
1024 f.write('<img src="lines_of_code.png" />')
1026 fg = open(path + '/lines_of_code.dat', 'w')
1027 for stamp in sorted(data.changes_by_date.keys()):
1028 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
1029 fg.close()
1031 f.write('</body></html>')
1032 f.close()
1035 # tags.html
1036 f = open(path + '/tags.html', 'w')
1037 self.printHeader(f)
1038 f.write('<h1>Tags</h1>')
1039 self.printNav(f)
1041 f.write('<dl>')
1042 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
1043 if len(data.tags) > 0:
1044 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
1045 f.write('</dl>')
1047 f.write('<table class="tags">')
1048 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1049 # sort the tags by date desc
1050 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
1051 for tag in tags_sorted_by_date_desc:
1052 authorinfo = []
1053 self.authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
1054 for i in reversed(self.authors_by_commits):
1055 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
1056 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)))
1057 f.write('</table>')
1059 f.write('</body></html>')
1060 f.close()
1062 self.createGraphs(path)
1064 def createGraphs(self, path):
1065 print 'Generating graphs...'
1067 # hour of day
1068 f = open(path + '/hour_of_day.plot', 'w')
1069 f.write(GNUPLOT_COMMON)
1070 f.write(
1072 set output 'hour_of_day.png'
1073 unset key
1074 set xrange [0.5:24.5]
1075 set xtics 4
1076 set grid y
1077 set ylabel "Commits"
1078 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1079 """)
1080 f.close()
1082 # day of week
1083 f = open(path + '/day_of_week.plot', 'w')
1084 f.write(GNUPLOT_COMMON)
1085 f.write(
1087 set output 'day_of_week.png'
1088 unset key
1089 set xrange [0.5:7.5]
1090 set xtics 1
1091 set grid y
1092 set ylabel "Commits"
1093 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1094 """)
1095 f.close()
1097 # Domains
1098 f = open(path + '/domains.plot', 'w')
1099 f.write(GNUPLOT_COMMON)
1100 f.write(
1102 set output 'domains.png'
1103 unset key
1104 unset xtics
1105 set yrange [0:]
1106 set grid y
1107 set ylabel "Commits"
1108 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1109 """)
1110 f.close()
1112 # Month of Year
1113 f = open(path + '/month_of_year.plot', 'w')
1114 f.write(GNUPLOT_COMMON)
1115 f.write(
1117 set output 'month_of_year.png'
1118 unset key
1119 set xrange [0.5:12.5]
1120 set xtics 1
1121 set grid y
1122 set ylabel "Commits"
1123 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1124 """)
1125 f.close()
1127 # commits_by_year_month
1128 f = open(path + '/commits_by_year_month.plot', 'w')
1129 f.write(GNUPLOT_COMMON)
1130 f.write(
1132 set output 'commits_by_year_month.png'
1133 unset key
1134 set xdata time
1135 set timefmt "%Y-%m"
1136 set format x "%Y-%m"
1137 set xtics rotate
1138 set bmargin 5
1139 set grid y
1140 set ylabel "Commits"
1141 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1142 """)
1143 f.close()
1145 # commits_by_year
1146 f = open(path + '/commits_by_year.plot', 'w')
1147 f.write(GNUPLOT_COMMON)
1148 f.write(
1150 set output 'commits_by_year.png'
1151 unset key
1152 set xtics 1 rotate
1153 set grid y
1154 set ylabel "Commits"
1155 set yrange [0:]
1156 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1157 """)
1158 f.close()
1160 # Files by date
1161 f = open(path + '/files_by_date.plot', 'w')
1162 f.write(GNUPLOT_COMMON)
1163 f.write(
1165 set output 'files_by_date.png'
1166 unset key
1167 set xdata time
1168 set timefmt "%Y-%m-%d"
1169 set format x "%Y-%m-%d"
1170 set grid y
1171 set ylabel "Files"
1172 set xtics rotate
1173 set ytics autofreq
1174 set bmargin 6
1175 plot 'files_by_date.dat' using 1:2 w steps
1176 """)
1177 f.close()
1179 # Lines of Code
1180 f = open(path + '/lines_of_code.plot', 'w')
1181 f.write(GNUPLOT_COMMON)
1182 f.write(
1184 set output 'lines_of_code.png'
1185 unset key
1186 set xdata time
1187 set timefmt "%s"
1188 set format x "%Y-%m-%d"
1189 set grid y
1190 set ylabel "Lines"
1191 set xtics rotate
1192 set bmargin 6
1193 plot 'lines_of_code.dat' using 1:2 w lines
1194 """)
1195 f.close()
1197 # Lines of Code Added per author
1198 f = open(path + '/lines_of_code_by_author.plot', 'w')
1199 f.write(GNUPLOT_COMMON)
1200 f.write(
1202 set terminal png transparent size 640,480
1203 set output 'lines_of_code_by_author.png'
1204 set key left top
1205 set xdata time
1206 set timefmt "%s"
1207 set format x "%Y-%m-%d"
1208 set grid y
1209 set ylabel "Lines"
1210 set xtics rotate
1211 set bmargin 6
1212 plot """
1214 i = 1
1215 plots = []
1216 for a in self.authors_to_plot:
1217 i = i + 1
1218 plots.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1219 f.write(", ".join(plots))
1220 f.write('\n')
1222 f.close()
1224 # Commits per author
1225 f = open(path + '/commits_by_author.plot', 'w')
1226 f.write(GNUPLOT_COMMON)
1227 f.write(
1229 set terminal png transparent size 640,480
1230 set output 'commits_by_author.png'
1231 set key left top
1232 set xdata time
1233 set timefmt "%s"
1234 set format x "%Y-%m-%d"
1235 set grid y
1236 set ylabel "Commits"
1237 set xtics rotate
1238 set bmargin 6
1239 plot """
1241 i = 1
1242 plots = []
1243 for a in self.authors_to_plot:
1244 i = i + 1
1245 plots.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1246 f.write(", ".join(plots))
1247 f.write('\n')
1249 f.close()
1251 os.chdir(path)
1252 files = glob.glob(path + '/*.plot')
1253 for f in files:
1254 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1255 if len(out) > 0:
1256 print out
1258 def printHeader(self, f, title = ''):
1259 f.write(
1260 """<?xml version="1.0" encoding="UTF-8"?>
1261 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1262 <html xmlns="http://www.w3.org/1999/xhtml">
1263 <head>
1264 <title>GitStats - %s</title>
1265 <link rel="stylesheet" href="%s" type="text/css" />
1266 <meta name="generator" content="GitStats %s" />
1267 <script type="text/javascript" src="sortable.js"></script>
1268 </head>
1269 <body>
1270 """ % (self.title, conf['style'], getversion()))
1272 def printNav(self, f):
1273 f.write("""
1274 <div class="nav">
1275 <ul>
1276 <li><a href="index.html">General</a></li>
1277 <li><a href="activity.html">Activity</a></li>
1278 <li><a href="authors.html">Authors</a></li>
1279 <li><a href="files.html">Files</a></li>
1280 <li><a href="lines.html">Lines</a></li>
1281 <li><a href="tags.html">Tags</a></li>
1282 </ul>
1283 </div>
1284 """)
1287 class GitStats:
1288 def run(self, args_orig):
1289 optlist, args = getopt.getopt(args_orig, 'c:')
1290 for o,v in optlist:
1291 if o == '-c':
1292 key, value = v.split('=', 1)
1293 if key not in conf:
1294 raise KeyError('no such key "%s" in config' % key)
1295 if isinstance(conf[key], int):
1296 conf[key] = int(value)
1297 else:
1298 conf[key] = value
1300 if len(args) < 2:
1301 print """
1302 Usage: gitstats [options] <gitpath..> <outputpath>
1304 Options:
1305 -c key=value Override configuration value
1307 Default config values:
1309 """ % conf
1310 sys.exit(0)
1312 outputpath = os.path.abspath(args[-1])
1313 rundir = os.getcwd()
1315 try:
1316 os.makedirs(outputpath)
1317 except OSError:
1318 pass
1319 if not os.path.isdir(outputpath):
1320 print 'FATAL: Output path is not a directory or does not exist'
1321 sys.exit(1)
1323 print 'Output path: %s' % outputpath
1324 cachefile = os.path.join(outputpath, 'gitstats.cache')
1326 data = GitDataCollector()
1327 data.loadCache(cachefile)
1329 for gitpath in args[0:-1]:
1330 print 'Git path: %s' % gitpath
1332 os.chdir(gitpath)
1334 print 'Collecting data...'
1335 data.collect(gitpath)
1337 print 'Refining data...'
1338 data.saveCache(cachefile)
1339 data.refine()
1341 os.chdir(rundir)
1343 print 'Generating report...'
1344 report = HTMLReportCreator()
1345 report.create(data, outputpath)
1347 time_end = time.time()
1348 exectime_internal = time_end - time_start
1349 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1351 if __name__=='__main__':
1352 g = GitStats()
1353 g.run(sys.argv[1:])