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