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