Trivial change to Wulf's patch.
[gitstats.git] / gitstats
blob2ec7861f942fc77d03930ce3a0e5f2162d16f552
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
292 if self.last_commit_stamp == 0:
293 self.last_commit_stamp = stamp
294 self.first_commit_stamp = stamp
296 # activity
297 # hour
298 hour = date.hour
299 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
300 # most active hour?
301 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
302 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
304 # day of week
305 day = date.weekday()
306 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
308 # domain stats
309 if domain not in self.domains:
310 self.domains[domain] = {}
311 # commits
312 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
314 # hour of week
315 if day not in self.activity_by_hour_of_week:
316 self.activity_by_hour_of_week[day] = {}
317 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
318 # most active hour?
319 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
320 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
322 # month of year
323 month = date.month
324 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
326 # yearly/weekly activity
327 yyw = date.strftime('%Y-%W')
328 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
329 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
330 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
332 # author stats
333 if author not in self.authors:
334 self.authors[author] = {}
335 # commits
336 if 'last_commit_stamp' not in self.authors[author]:
337 self.authors[author]['last_commit_stamp'] = stamp
338 self.authors[author]['first_commit_stamp'] = stamp
340 # author of the month/year
341 yymm = date.strftime('%Y-%m')
342 if yymm in self.author_of_month:
343 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
344 else:
345 self.author_of_month[yymm] = {}
346 self.author_of_month[yymm][author] = 1
347 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
349 yy = date.year
350 if yy in self.author_of_year:
351 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
352 else:
353 self.author_of_year[yy] = {}
354 self.author_of_year[yy][author] = 1
355 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
357 # authors: active days
358 yymmdd = date.strftime('%Y-%m-%d')
359 if 'last_active_day' not in self.authors[author]:
360 self.authors[author]['last_active_day'] = yymmdd
361 self.authors[author]['active_days'] = 1
362 elif yymmdd != self.authors[author]['last_active_day']:
363 self.authors[author]['last_active_day'] = yymmdd
364 self.authors[author]['active_days'] += 1
366 # project: active days
367 if yymmdd != self.last_active_day:
368 self.last_active_day = yymmdd
369 self.active_days.add(yymmdd)
371 # timezone
372 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
374 # TODO Optimize this, it's the worst bottleneck
375 # outputs "<stamp> <files>" for each revision
376 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
377 lines = []
378 for revline in revlines:
379 time, rev = revline.split(' ')
380 linecount = self.getFilesInCommit(rev)
381 lines.append('%d %d' % (int(time), linecount))
383 self.total_commits += len(lines)
384 for line in lines:
385 parts = line.split(' ')
386 if len(parts) != 2:
387 continue
388 (stamp, files) = parts[0:2]
389 try:
390 self.files_by_stamp[int(stamp)] = int(files)
391 except ValueError:
392 print 'Warning: failed to parse line "%s"' % line
394 # extensions
395 lines = getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
396 self.total_files += len(lines)
397 for line in lines:
398 if len(line) == 0:
399 continue
400 parts = re.split('\s+', line, 4)
401 sha1 = parts[2]
402 filename = parts[3]
404 if filename.find('.') == -1 or filename.rfind('.') == 0:
405 ext = ''
406 else:
407 ext = filename[(filename.rfind('.') + 1):]
408 if len(ext) > conf['max_ext_length']:
409 ext = ''
411 if ext not in self.extensions:
412 self.extensions[ext] = {'files': 0, 'lines': 0}
414 self.extensions[ext]['files'] += 1
415 try:
416 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
417 except:
418 print 'Warning: Could not count lines for file "%s"' % line
420 # line statistics
421 # outputs:
422 # N files changed, N insertions (+), N deletions(-)
423 # <stamp> <author>
424 self.changes_by_date = {} # stamp -> { files, ins, del }
425 # computation of lines of code by date is better done
426 # on a linear history.
427 extra = ''
428 if conf['linear_linestats']:
429 extra = '--first-parent -m'
430 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
431 lines.reverse()
432 files = 0; inserted = 0; deleted = 0; total_lines = 0
433 author = None
434 for line in lines:
435 if len(line) == 0:
436 continue
438 # <stamp> <author>
439 if line.find('files changed,') == -1:
440 pos = line.find(' ')
441 if pos != -1:
442 try:
443 (stamp, author) = (int(line[:pos]), line[pos+1:])
444 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
445 files, inserted, deleted = 0, 0, 0
446 except ValueError:
447 print 'Warning: unexpected line "%s"' % line
448 else:
449 print 'Warning: unexpected line "%s"' % line
450 else:
451 numbers = re.findall('\d+', line)
452 if len(numbers) == 3:
453 (files, inserted, deleted) = map(lambda el : int(el), numbers)
454 total_lines += inserted
455 total_lines -= deleted
456 self.total_lines_added += inserted
457 self.total_lines_removed += deleted
458 else:
459 print 'Warning: failed to handle line "%s"' % line
460 (files, inserted, deleted) = (0, 0, 0)
461 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
462 self.total_lines = total_lines
464 # Per-author statistics
466 # defined for stamp, author only if author commited at this timestamp.
467 self.changes_by_date_by_author = {} # stamp -> author -> lines_added
469 # Similar to the above, but never use --first-parent
470 # (we need to walk through every commit to know who
471 # committed what, not just through mainline)
472 lines = getpipeoutput(['git log --shortstat --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
473 lines.reverse()
474 files = 0; inserted = 0; deleted = 0
475 author = None
476 for line in lines:
477 if len(line) == 0:
478 continue
480 # <stamp> <author>
481 if line.find('files changed,') == -1:
482 pos = line.find(' ')
483 if pos != -1:
484 try:
485 (stamp, author) = (int(line[:pos]), line[pos+1:])
486 if author not in self.authors:
487 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
488 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
489 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
490 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
491 if stamp not in self.changes_by_date_by_author:
492 self.changes_by_date_by_author[stamp] = {}
493 if author not in self.changes_by_date_by_author[stamp]:
494 self.changes_by_date_by_author[stamp][author] = {}
495 self.changes_by_date_by_author[stamp][author]['lines_added'] = self.authors[author]['lines_added']
496 self.changes_by_date_by_author[stamp][author]['commits'] = self.authors[author]['commits']
497 files, inserted, deleted = 0, 0, 0
498 except ValueError:
499 print 'Warning: unexpected line "%s"' % line
500 else:
501 print 'Warning: unexpected line "%s"' % line
502 else:
503 numbers = re.findall('\d+', line)
504 if len(numbers) == 3:
505 (files, inserted, deleted) = map(lambda el : int(el), numbers)
506 else:
507 print 'Warning: failed to handle line "%s"' % line
508 (files, inserted, deleted) = (0, 0, 0)
510 def refine(self):
511 # authors
512 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
513 self.authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
514 self.authors_by_commits.reverse() # most first
515 for i, name in enumerate(self.authors_by_commits):
516 self.authors[name]['place_by_commits'] = i + 1
518 for name in self.authors.keys():
519 a = self.authors[name]
520 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
521 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
522 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
523 delta = date_last - date_first
524 a['date_first'] = date_first.strftime('%Y-%m-%d')
525 a['date_last'] = date_last.strftime('%Y-%m-%d')
526 a['timedelta'] = delta
527 if 'lines_added' not in a: a['lines_added'] = 0
528 if 'lines_removed' not in a: a['lines_removed'] = 0
530 def getActiveDays(self):
531 return self.active_days
533 def getActivityByDayOfWeek(self):
534 return self.activity_by_day_of_week
536 def getActivityByHourOfDay(self):
537 return self.activity_by_hour_of_day
539 def getAuthorInfo(self, author):
540 return self.authors[author]
542 def getAuthors(self, limit = None):
543 res = getkeyssortedbyvaluekey(self.authors, 'commits')
544 res.reverse()
545 return res[:limit]
547 def getCommitDeltaDays(self):
548 return (self.last_commit_stamp - self.first_commit_stamp) / 86400 + 1
550 def getDomainInfo(self, domain):
551 return self.domains[domain]
553 def getDomains(self):
554 return self.domains.keys()
556 def getFilesInCommit(self, rev):
557 try:
558 res = self.cache['files_in_tree'][rev]
559 except:
560 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
561 if 'files_in_tree' not in self.cache:
562 self.cache['files_in_tree'] = {}
563 self.cache['files_in_tree'][rev] = res
565 return res
567 def getFirstCommitDate(self):
568 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
570 def getLastCommitDate(self):
571 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
573 def getLinesInBlob(self, sha1):
574 try:
575 res = self.cache['lines_in_blob'][sha1]
576 except:
577 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
578 if 'lines_in_blob' not in self.cache:
579 self.cache['lines_in_blob'] = {}
580 self.cache['lines_in_blob'][sha1] = res
581 return res
583 def getTags(self):
584 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
585 return lines.split('\n')
587 def getTagDate(self, tag):
588 return self.revToDate('tags/' + tag)
590 def getTotalAuthors(self):
591 return self.total_authors
593 def getTotalCommits(self):
594 return self.total_commits
596 def getTotalFiles(self):
597 return self.total_files
599 def getTotalLOC(self):
600 return self.total_lines
602 def revToDate(self, rev):
603 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
604 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
606 class ReportCreator:
607 """Creates the actual report based on given data."""
608 def __init__(self):
609 pass
611 def create(self, data, path):
612 self.data = data
613 self.path = path
615 def html_linkify(text):
616 return text.lower().replace(' ', '_')
618 def html_header(level, text):
619 name = html_linkify(text)
620 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
622 class HTMLReportCreator(ReportCreator):
623 def create(self, data, path):
624 ReportCreator.create(self, data, path)
625 self.title = data.projectname
627 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
628 binarypath = os.path.dirname(os.path.abspath(__file__))
629 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
630 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
631 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
632 for base in basedirs:
633 src = base + '/' + file
634 if os.path.exists(src):
635 shutil.copyfile(src, path + '/' + file)
636 break
637 else:
638 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
640 f = open(path + "/index.html", 'w')
641 format = '%Y-%m-%d %H:%M:%S'
642 self.printHeader(f)
644 f.write('<h1>GitStats - %s</h1>' % data.projectname)
646 self.printNav(f)
648 f.write('<dl>')
649 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
650 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
651 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
652 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
653 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())))
654 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
655 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))
656 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()))
657 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
658 f.write('</dl>')
660 f.write('</body>\n</html>')
661 f.close()
664 # Activity
665 f = open(path + '/activity.html', 'w')
666 self.printHeader(f)
667 f.write('<h1>Activity</h1>')
668 self.printNav(f)
670 #f.write('<h2>Last 30 days</h2>')
672 #f.write('<h2>Last 12 months</h2>')
674 # Weekly activity
675 WEEKS = 32
676 f.write(html_header(2, 'Weekly activity'))
677 f.write('<p>Last %d weeks</p>' % WEEKS)
679 # generate weeks to show (previous N weeks from now)
680 now = datetime.datetime.now()
681 deltaweek = datetime.timedelta(7)
682 weeks = []
683 stampcur = now
684 for i in range(0, WEEKS):
685 weeks.insert(0, stampcur.strftime('%Y-%W'))
686 stampcur -= deltaweek
688 # top row: commits & bar
689 f.write('<table class="noborders"><tr>')
690 for i in range(0, WEEKS):
691 commits = 0
692 if weeks[i] in data.activity_by_year_week:
693 commits = data.activity_by_year_week[weeks[i]]
695 percentage = 0
696 if weeks[i] in data.activity_by_year_week:
697 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
698 height = max(1, int(200 * percentage))
699 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))
701 # bottom row: year/week
702 f.write('</tr><tr>')
703 for i in range(0, WEEKS):
704 f.write('<td>%s</td>' % (WEEKS - i))
705 f.write('</tr></table>')
707 # Hour of Day
708 f.write(html_header(2, 'Hour of Day'))
709 hour_of_day = data.getActivityByHourOfDay()
710 f.write('<table><tr><th>Hour</th>')
711 for i in range(0, 24):
712 f.write('<th>%d</th>' % i)
713 f.write('</tr>\n<tr><th>Commits</th>')
714 fp = open(path + '/hour_of_day.dat', 'w')
715 for i in range(0, 24):
716 if i in hour_of_day:
717 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
718 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
719 fp.write('%d %d\n' % (i, hour_of_day[i]))
720 else:
721 f.write('<td>0</td>')
722 fp.write('%d 0\n' % i)
723 fp.close()
724 f.write('</tr>\n<tr><th>%</th>')
725 totalcommits = data.getTotalCommits()
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)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
730 else:
731 f.write('<td>0.00</td>')
732 f.write('</tr></table>')
733 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
734 fg = open(path + '/hour_of_day.dat', 'w')
735 for i in range(0, 24):
736 if i in hour_of_day:
737 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
738 else:
739 fg.write('%d 0\n' % (i + 1))
740 fg.close()
742 # Day of Week
743 f.write(html_header(2, 'Day of Week'))
744 day_of_week = data.getActivityByDayOfWeek()
745 f.write('<div class="vtable"><table>')
746 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
747 fp = open(path + '/day_of_week.dat', 'w')
748 for d in range(0, 7):
749 commits = 0
750 if d in day_of_week:
751 commits = day_of_week[d]
752 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
753 f.write('<tr>')
754 f.write('<th>%s</th>' % (WEEKDAYS[d]))
755 if d in day_of_week:
756 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
757 else:
758 f.write('<td>0</td>')
759 f.write('</tr>')
760 f.write('</table></div>')
761 f.write('<img src="day_of_week.png" alt="Day of Week" />')
762 fp.close()
764 # Hour of Week
765 f.write(html_header(2, 'Hour of Week'))
766 f.write('<table>')
768 f.write('<tr><th>Weekday</th>')
769 for hour in range(0, 24):
770 f.write('<th>%d</th>' % (hour))
771 f.write('</tr>')
773 for weekday in range(0, 7):
774 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
775 for hour in range(0, 24):
776 try:
777 commits = data.activity_by_hour_of_week[weekday][hour]
778 except KeyError:
779 commits = 0
780 if commits != 0:
781 f.write('<td')
782 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
783 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
784 f.write('>%d</td>' % commits)
785 else:
786 f.write('<td></td>')
787 f.write('</tr>')
789 f.write('</table>')
791 # Month of Year
792 f.write(html_header(2, 'Month of Year'))
793 f.write('<div class="vtable"><table>')
794 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
795 fp = open (path + '/month_of_year.dat', 'w')
796 for mm in range(1, 13):
797 commits = 0
798 if mm in data.activity_by_month_of_year:
799 commits = data.activity_by_month_of_year[mm]
800 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
801 fp.write('%d %d\n' % (mm, commits))
802 fp.close()
803 f.write('</table></div>')
804 f.write('<img src="month_of_year.png" alt="Month of Year" />')
806 # Commits by year/month
807 f.write(html_header(2, 'Commits by year/month'))
808 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
809 for yymm in reversed(sorted(data.commits_by_month.keys())):
810 f.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm, data.commits_by_month[yymm]))
811 f.write('</table></div>')
812 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
813 fg = open(path + '/commits_by_year_month.dat', 'w')
814 for yymm in sorted(data.commits_by_month.keys()):
815 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
816 fg.close()
818 # Commits by year
819 f.write(html_header(2, 'Commits by Year'))
820 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
821 for yy in reversed(sorted(data.commits_by_year.keys())):
822 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()))
823 f.write('</table></div>')
824 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
825 fg = open(path + '/commits_by_year.dat', 'w')
826 for yy in sorted(data.commits_by_year.keys()):
827 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
828 fg.close()
830 # Commits by timezone
831 f.write(html_header(2, 'Commits by Timezone'))
832 f.write('<table><tr>')
833 f.write('<th>Timezone</th><th>Commits</th>')
834 max_commits_on_tz = max(data.commits_by_timezone.values())
835 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
836 commits = data.commits_by_timezone[i]
837 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
838 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
839 f.write('</tr></table>')
841 f.write('</body></html>')
842 f.close()
845 # Authors
846 f = open(path + '/authors.html', 'w')
847 self.printHeader(f)
849 f.write('<h1>Authors</h1>')
850 self.printNav(f)
852 # Authors :: List of authors
853 f.write(html_header(2, 'List of Authors'))
855 f.write('<table class="authors sortable" id="authors">')
856 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>')
857 for author in data.getAuthors(conf['max_authors']):
858 info = data.getAuthorInfo(author)
859 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']))
860 f.write('</table>')
862 allauthors = data.getAuthors()
863 if len(allauthors) > conf['max_authors']:
864 rest = allauthors[conf['max_authors']:]
865 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
867 f.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
868 f.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
869 if len(allauthors) > conf['max_authors']:
870 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
872 f.write(html_header(2, 'Commits per Author'))
873 f.write('<img src="commits_by_author.png" alt="Commits per Author" />')
874 if len(allauthors) > conf['max_authors']:
875 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
877 fgl = open(path + '/lines_of_code_by_author.dat', 'w')
878 fgc = open(path + '/commits_by_author.dat', 'w')
880 lines_by_authors = {} # cumulated added lines by
881 # author. to save memory,
882 # changes_by_date_by_author[stamp][author] is defined
883 # only at points where author commits.
884 # lines_by_authors allows us to generate all the
885 # points in the .dat file.
887 # Don't rely on getAuthors to give the same order each
888 # time. Be robust and keep the list in a variable.
889 commits_by_authors = {} # cumulated added lines by
891 self.authors_to_plot = data.getAuthors(conf['max_authors'])
892 for author in self.authors_to_plot:
893 lines_by_authors[author] = 0
894 commits_by_authors[author] = 0
895 for stamp in sorted(data.changes_by_date_by_author.keys()):
896 fgl.write('%d' % stamp)
897 fgc.write('%d' % stamp)
898 for author in self.authors_to_plot:
899 if author in data.changes_by_date_by_author[stamp].keys():
900 lines_by_authors[author] = data.changes_by_date_by_author[stamp][author]['lines_added']
901 commits_by_authors[author] = data.changes_by_date_by_author[stamp][author]['commits']
902 fgl.write(' %d' % lines_by_authors[author])
903 fgc.write(' %d' % commits_by_authors[author])
904 fgl.write('\n')
905 fgc.write('\n')
906 fgl.close()
907 fgc.close()
909 # Authors :: Author of Month
910 f.write(html_header(2, 'Author of Month'))
911 f.write('<table class="sortable" id="aom">')
912 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'])
913 for yymm in reversed(sorted(data.author_of_month.keys())):
914 authordict = data.author_of_month[yymm]
915 authors = getkeyssortedbyvalues(authordict)
916 authors.reverse()
917 commits = data.author_of_month[yymm][authors[0]]
918 next = ', '.join(authors[1:conf['authors_top']+1])
919 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)))
921 f.write('</table>')
923 f.write(html_header(2, 'Author of Year'))
924 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'])
925 for yy in reversed(sorted(data.author_of_year.keys())):
926 authordict = data.author_of_year[yy]
927 authors = getkeyssortedbyvalues(authordict)
928 authors.reverse()
929 commits = data.author_of_year[yy][authors[0]]
930 next = ', '.join(authors[1:conf['authors_top']+1])
931 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)))
932 f.write('</table>')
934 # Domains
935 f.write(html_header(2, 'Commits by Domains'))
936 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
937 domains_by_commits.reverse() # most first
938 f.write('<div class="vtable"><table>')
939 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
940 fp = open(path + '/domains.dat', 'w')
941 n = 0
942 for domain in domains_by_commits:
943 if n == conf['max_domains']:
944 break
945 commits = 0
946 n += 1
947 info = data.getDomainInfo(domain)
948 fp.write('%s %d %d\n' % (domain, n , info['commits']))
949 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
950 f.write('</table></div>')
951 f.write('<img src="domains.png" alt="Commits by Domains" />')
952 fp.close()
954 f.write('</body></html>')
955 f.close()
958 # Files
959 f = open(path + '/files.html', 'w')
960 self.printHeader(f)
961 f.write('<h1>Files</h1>')
962 self.printNav(f)
964 f.write('<dl>\n')
965 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
966 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
967 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data.getTotalLOC()) / data.getTotalFiles()))
968 f.write('</dl>\n')
970 # Files :: File count by date
971 f.write(html_header(2, 'File count by date'))
973 # use set to get rid of duplicate/unnecessary entries
974 files_by_date = set()
975 for stamp in sorted(data.files_by_stamp.keys()):
976 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
978 fg = open(path + '/files_by_date.dat', 'w')
979 for line in sorted(list(files_by_date)):
980 fg.write('%s\n' % line)
981 #for stamp in sorted(data.files_by_stamp.keys()):
982 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
983 fg.close()
985 f.write('<img src="files_by_date.png" alt="Files by Date" />')
987 #f.write('<h2>Average file size by date</h2>')
989 # Files :: Extensions
990 f.write(html_header(2, 'Extensions'))
991 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
992 for ext in sorted(data.extensions.keys()):
993 files = data.extensions[ext]['files']
994 lines = data.extensions[ext]['lines']
995 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))
996 f.write('</table>')
998 f.write('</body></html>')
999 f.close()
1002 # Lines
1003 f = open(path + '/lines.html', 'w')
1004 self.printHeader(f)
1005 f.write('<h1>Lines</h1>')
1006 self.printNav(f)
1008 f.write('<dl>\n')
1009 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1010 f.write('</dl>\n')
1012 f.write(html_header(2, 'Lines of Code'))
1013 f.write('<img src="lines_of_code.png" />')
1015 fg = open(path + '/lines_of_code.dat', 'w')
1016 for stamp in sorted(data.changes_by_date.keys()):
1017 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
1018 fg.close()
1020 f.write('</body></html>')
1021 f.close()
1024 # tags.html
1025 f = open(path + '/tags.html', 'w')
1026 self.printHeader(f)
1027 f.write('<h1>Tags</h1>')
1028 self.printNav(f)
1030 f.write('<dl>')
1031 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
1032 if len(data.tags) > 0:
1033 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
1034 f.write('</dl>')
1036 f.write('<table class="tags">')
1037 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1038 # sort the tags by date desc
1039 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
1040 for tag in tags_sorted_by_date_desc:
1041 authorinfo = []
1042 self.authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
1043 for i in reversed(self.authors_by_commits):
1044 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
1045 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)))
1046 f.write('</table>')
1048 f.write('</body></html>')
1049 f.close()
1051 self.createGraphs(path)
1053 def createGraphs(self, path):
1054 print 'Generating graphs...'
1056 # hour of day
1057 f = open(path + '/hour_of_day.plot', 'w')
1058 f.write(GNUPLOT_COMMON)
1059 f.write(
1061 set output 'hour_of_day.png'
1062 unset key
1063 set xrange [0.5:24.5]
1064 set xtics 4
1065 set grid y
1066 set ylabel "Commits"
1067 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1068 """)
1069 f.close()
1071 # day of week
1072 f = open(path + '/day_of_week.plot', 'w')
1073 f.write(GNUPLOT_COMMON)
1074 f.write(
1076 set output 'day_of_week.png'
1077 unset key
1078 set xrange [0.5:7.5]
1079 set xtics 1
1080 set grid y
1081 set ylabel "Commits"
1082 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1083 """)
1084 f.close()
1086 # Domains
1087 f = open(path + '/domains.plot', 'w')
1088 f.write(GNUPLOT_COMMON)
1089 f.write(
1091 set output 'domains.png'
1092 unset key
1093 unset xtics
1094 set yrange [0:]
1095 set grid y
1096 set ylabel "Commits"
1097 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1098 """)
1099 f.close()
1101 # Month of Year
1102 f = open(path + '/month_of_year.plot', 'w')
1103 f.write(GNUPLOT_COMMON)
1104 f.write(
1106 set output 'month_of_year.png'
1107 unset key
1108 set xrange [0.5:12.5]
1109 set xtics 1
1110 set grid y
1111 set ylabel "Commits"
1112 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1113 """)
1114 f.close()
1116 # commits_by_year_month
1117 f = open(path + '/commits_by_year_month.plot', 'w')
1118 f.write(GNUPLOT_COMMON)
1119 f.write(
1121 set output 'commits_by_year_month.png'
1122 unset key
1123 set xdata time
1124 set timefmt "%Y-%m"
1125 set format x "%Y-%m"
1126 set xtics rotate
1127 set bmargin 5
1128 set grid y
1129 set ylabel "Commits"
1130 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1131 """)
1132 f.close()
1134 # commits_by_year
1135 f = open(path + '/commits_by_year.plot', 'w')
1136 f.write(GNUPLOT_COMMON)
1137 f.write(
1139 set output 'commits_by_year.png'
1140 unset key
1141 set xtics 1 rotate
1142 set grid y
1143 set ylabel "Commits"
1144 set yrange [0:]
1145 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1146 """)
1147 f.close()
1149 # Files by date
1150 f = open(path + '/files_by_date.plot', 'w')
1151 f.write(GNUPLOT_COMMON)
1152 f.write(
1154 set output 'files_by_date.png'
1155 unset key
1156 set xdata time
1157 set timefmt "%Y-%m-%d"
1158 set format x "%Y-%m-%d"
1159 set grid y
1160 set ylabel "Files"
1161 set xtics rotate
1162 set ytics autofreq
1163 set bmargin 6
1164 plot 'files_by_date.dat' using 1:2 w steps
1165 """)
1166 f.close()
1168 # Lines of Code
1169 f = open(path + '/lines_of_code.plot', 'w')
1170 f.write(GNUPLOT_COMMON)
1171 f.write(
1173 set output 'lines_of_code.png'
1174 unset key
1175 set xdata time
1176 set timefmt "%s"
1177 set format x "%Y-%m-%d"
1178 set grid y
1179 set ylabel "Lines"
1180 set xtics rotate
1181 set bmargin 6
1182 plot 'lines_of_code.dat' using 1:2 w lines
1183 """)
1184 f.close()
1186 # Lines of Code Added per author
1187 f = open(path + '/lines_of_code_by_author.plot', 'w')
1188 f.write(GNUPLOT_COMMON)
1189 f.write(
1191 set terminal png transparent size 640,480
1192 set output 'lines_of_code_by_author.png'
1193 set key left top
1194 set xdata time
1195 set timefmt "%s"
1196 set format x "%Y-%m-%d"
1197 set grid y
1198 set ylabel "Lines"
1199 set xtics rotate
1200 set bmargin 6
1201 plot """
1203 i = 1
1204 plots = []
1205 for a in self.authors_to_plot:
1206 i = i + 1
1207 plots.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1208 f.write(", ".join(plots))
1209 f.write('\n')
1211 f.close()
1213 # Commits per author
1214 f = open(path + '/commits_by_author.plot', 'w')
1215 f.write(GNUPLOT_COMMON)
1216 f.write(
1218 set terminal png transparent size 640,480
1219 set output 'commits_by_author.png'
1220 set key left top
1221 set xdata time
1222 set timefmt "%s"
1223 set format x "%Y-%m-%d"
1224 set grid y
1225 set ylabel "Commits"
1226 set xtics rotate
1227 set bmargin 6
1228 plot """
1230 i = 1
1231 plots = []
1232 for a in self.authors_to_plot:
1233 i = i + 1
1234 plots.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1235 f.write(", ".join(plots))
1236 f.write('\n')
1238 f.close()
1240 os.chdir(path)
1241 files = glob.glob(path + '/*.plot')
1242 for f in files:
1243 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1244 if len(out) > 0:
1245 print out
1247 def printHeader(self, f, title = ''):
1248 f.write(
1249 """<?xml version="1.0" encoding="UTF-8"?>
1250 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1251 <html xmlns="http://www.w3.org/1999/xhtml">
1252 <head>
1253 <title>GitStats - %s</title>
1254 <link rel="stylesheet" href="%s" type="text/css" />
1255 <meta name="generator" content="GitStats %s" />
1256 <script type="text/javascript" src="sortable.js"></script>
1257 </head>
1258 <body>
1259 """ % (self.title, conf['style'], getversion()))
1261 def printNav(self, f):
1262 f.write("""
1263 <div class="nav">
1264 <ul>
1265 <li><a href="index.html">General</a></li>
1266 <li><a href="activity.html">Activity</a></li>
1267 <li><a href="authors.html">Authors</a></li>
1268 <li><a href="files.html">Files</a></li>
1269 <li><a href="lines.html">Lines</a></li>
1270 <li><a href="tags.html">Tags</a></li>
1271 </ul>
1272 </div>
1273 """)
1276 class GitStats:
1277 def run(self, args_orig):
1278 optlist, args = getopt.getopt(args_orig, 'c:')
1279 for o,v in optlist:
1280 if o == '-c':
1281 key, value = v.split('=', 1)
1282 if key not in conf:
1283 raise KeyError('no such key "%s" in config' % key)
1284 if isinstance(conf[key], int):
1285 conf[key] = int(value)
1286 else:
1287 conf[key] = value
1289 if len(args) < 2:
1290 print """
1291 Usage: gitstats [options] <gitpath..> <outputpath>
1293 Options:
1294 -c key=value Override configuration value
1296 Default config values:
1298 """ % conf
1299 sys.exit(0)
1301 outputpath = os.path.abspath(args[-1])
1302 rundir = os.getcwd()
1304 try:
1305 os.makedirs(outputpath)
1306 except OSError:
1307 pass
1308 if not os.path.isdir(outputpath):
1309 print 'FATAL: Output path is not a directory or does not exist'
1310 sys.exit(1)
1312 print 'Output path: %s' % outputpath
1313 cachefile = os.path.join(outputpath, 'gitstats.cache')
1315 data = GitDataCollector()
1316 data.loadCache(cachefile)
1318 for gitpath in args[0:-1]:
1319 print 'Git path: %s' % gitpath
1321 os.chdir(gitpath)
1323 print 'Collecting data...'
1324 data.collect(gitpath)
1326 print 'Refining data...'
1327 data.saveCache(cachefile)
1328 data.refine()
1330 os.chdir(rundir)
1332 print 'Generating report...'
1333 report = HTMLReportCreator()
1334 report.create(data, outputpath)
1336 time_end = time.time()
1337 exectime_internal = time_end - time_start
1338 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1340 if __name__=='__main__':
1341 g = GitStats()
1342 g.run(sys.argv[1:])