Fix performance issue for huge repositories
[gitstats.git] / gitstats
blobed3a24d6421687d9531074c2865ecc4a48011911
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2013 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 if sys.version_info < (2, 6):
18 print >> sys.stderr, "Python 2.6 or higher is required for gitstats"
19 sys.exit(1)
21 from multiprocessing import Pool
23 os.environ['LC_ALL'] = 'C'
25 GNUPLOT_COMMON = 'set terminal png transparent size 640,240\nset size 1.0,1.0\n'
26 ON_LINUX = (platform.system() == 'Linux')
27 WEEKDAYS = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
29 exectime_internal = 0.0
30 exectime_external = 0.0
31 time_start = time.time()
33 # By default, gnuplot is searched from path, but can be overridden with the
34 # environment variable "GNUPLOT"
35 gnuplot_cmd = 'gnuplot'
36 if 'GNUPLOT' in os.environ:
37 gnuplot_cmd = os.environ['GNUPLOT']
39 conf = {
40 'max_domains': 10,
41 'max_ext_length': 10,
42 'style': 'gitstats.css',
43 'max_authors': 20,
44 'authors_top': 5,
45 'commit_begin': '',
46 'commit_end': 'HEAD',
47 'linear_linestats': 1,
48 'project_name': '',
49 'merge_authors': {}
52 def getpipeoutput(cmds, quiet = False):
53 global exectime_external
54 start = time.time()
55 if not quiet and ON_LINUX and os.isatty(1):
56 print '>> ' + ' | '.join(cmds),
57 sys.stdout.flush()
58 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
59 p = p0
60 for x in cmds[1:]:
61 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
62 p0 = p
63 output = p.communicate()[0]
64 end = time.time()
65 if not quiet:
66 if ON_LINUX and os.isatty(1):
67 print '\r',
68 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
69 exectime_external += (end - start)
70 return output.rstrip('\n')
72 def getcommitrange(defaultrange = 'HEAD', end_only = False):
73 if len(conf['commit_end']) > 0:
74 if end_only or len(conf['commit_begin']) == 0:
75 return conf['commit_end']
76 return '%s..%s' % (conf['commit_begin'], conf['commit_end'])
77 return defaultrange
79 def getkeyssortedbyvalues(dict):
80 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
82 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
83 def getkeyssortedbyvaluekey(d, key):
84 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
86 def getstatsummarycounts(line):
87 numbers = re.findall('\d+', line)
88 if len(numbers) == 1:
89 # neither insertions nor deletions: may probably only happen for "0 files changed"
90 numbers.append(0);
91 numbers.append(0);
92 elif len(numbers) == 2 and line.find('(+)') != -1:
93 numbers.append(0); # only insertions were printed on line
94 elif len(numbers) == 2 and line.find('(-)') != -1:
95 numbers.insert(1, 0); # only deletions were printed on line
96 return numbers
98 VERSION = 0
99 def getversion():
100 global VERSION
101 if VERSION == 0:
102 gitstats_repo = os.path.dirname(os.path.abspath(__file__))
103 VERSION = getpipeoutput(["git --git-dir=%s/.git --work-tree=%s rev-parse --short %s" %
104 (gitstats_repo, gitstats_repo, getcommitrange('HEAD').split('\n')[0])])
105 return VERSION
107 def getgitversion():
108 return getpipeoutput(['git --version']).split('\n')[0]
110 def getgnuplotversion():
111 return getpipeoutput(['%s --version' % gnuplot_cmd]).split('\n')[0]
113 def getnumoffilesfromrev(time_rev):
115 Get number of files changed in commit
117 time, rev = time_rev
118 return (int(time), rev, int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0]))
120 def getnumoflinesinblob(ext_blob):
122 Get number of lines in blob
124 ext, blob_id = ext_blob
125 return (ext, blob_id, int(getpipeoutput(['git cat-file blob %s' % blob_id, 'wc -l']).split()[0]))
127 class DataCollector:
128 """Manages data collection from a revision control repository."""
129 def __init__(self):
130 self.stamp_created = time.time()
131 self.cache = {}
132 self.total_authors = 0
133 self.activity_by_hour_of_day = {} # hour -> commits
134 self.activity_by_day_of_week = {} # day -> commits
135 self.activity_by_month_of_year = {} # month [1-12] -> commits
136 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
137 self.activity_by_hour_of_day_busiest = 0
138 self.activity_by_hour_of_week_busiest = 0
139 self.activity_by_year_week = {} # yy_wNN -> commits
140 self.activity_by_year_week_peak = 0
142 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
144 self.total_commits = 0
145 self.total_files = 0
146 self.authors_by_commits = 0
148 # domains
149 self.domains = {} # domain -> commits
151 # author of the month
152 self.author_of_month = {} # month -> author -> commits
153 self.author_of_year = {} # year -> author -> commits
154 self.commits_by_month = {} # month -> commits
155 self.commits_by_year = {} # year -> commits
156 self.lines_added_by_month = {} # month -> lines added
157 self.lines_added_by_year = {} # year -> lines added
158 self.lines_removed_by_month = {} # month -> lines removed
159 self.lines_removed_by_year = {} # year -> lines removed
160 self.first_commit_stamp = 0
161 self.last_commit_stamp = 0
162 self.last_active_day = None
163 self.active_days = set()
165 # lines
166 self.total_lines = 0
167 self.total_lines_added = 0
168 self.total_lines_removed = 0
170 # size
171 self.total_size = 0
173 # timezone
174 self.commits_by_timezone = {} # timezone -> commits
176 # tags
177 self.tags = {}
179 self.files_by_stamp = {} # stamp -> files
181 # extensions
182 self.extensions = {} # extension -> files, lines
184 # line statistics
185 self.changes_by_date = {} # stamp -> { files, ins, del }
188 # This should be the main function to extract data from the repository.
189 def collect(self, dir):
190 self.dir = dir
191 if len(conf['project_name']) == 0:
192 self.projectname = os.path.basename(os.path.abspath(dir))
193 else:
194 self.projectname = conf['project_name']
197 # Load cacheable data
198 def loadCache(self, cachefile):
199 if not os.path.exists(cachefile):
200 return
201 print 'Loading cache...'
202 f = open(cachefile, 'rb')
203 try:
204 self.cache = pickle.loads(zlib.decompress(f.read()))
205 except:
206 # temporary hack to upgrade non-compressed caches
207 f.seek(0)
208 self.cache = pickle.load(f)
209 f.close()
212 # Produce any additional statistics from the extracted data.
213 def refine(self):
214 pass
217 # : get a dictionary of author
218 def getAuthorInfo(self, author):
219 return None
221 def getActivityByDayOfWeek(self):
222 return {}
224 def getActivityByHourOfDay(self):
225 return {}
227 # : get a dictionary of domains
228 def getDomainInfo(self, domain):
229 return None
232 # Get a list of authors
233 def getAuthors(self):
234 return []
236 def getFirstCommitDate(self):
237 return datetime.datetime.now()
239 def getLastCommitDate(self):
240 return datetime.datetime.now()
242 def getStampCreated(self):
243 return self.stamp_created
245 def getTags(self):
246 return []
248 def getTotalAuthors(self):
249 return -1
251 def getTotalCommits(self):
252 return -1
254 def getTotalFiles(self):
255 return -1
257 def getTotalLOC(self):
258 return -1
261 # Save cacheable data
262 def saveCache(self, cachefile):
263 print 'Saving cache...'
264 tempfile = cachefile + '.tmp'
265 f = open(tempfile, 'wb')
266 #pickle.dump(self.cache, f)
267 data = zlib.compress(pickle.dumps(self.cache))
268 f.write(data)
269 f.close()
270 try:
271 os.remove(cachefile)
272 except OSError:
273 pass
274 os.rename(tempfile, cachefile)
276 class GitDataCollector(DataCollector):
277 def collect(self, dir):
278 DataCollector.collect(self, dir)
280 self.total_authors += int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
281 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
283 # tags
284 lines = getpipeoutput(['git show-ref --tags']).split('\n')
285 for line in lines:
286 if len(line) == 0:
287 continue
288 (hash, tag) = line.split(' ')
290 tag = tag.replace('refs/tags/', '')
291 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
292 if len(output) > 0:
293 parts = output.split(' ')
294 stamp = 0
295 try:
296 stamp = int(parts[0])
297 except ValueError:
298 stamp = 0
299 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
301 # collect info on tags, starting from latest
302 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
303 prev = None
304 for tag in reversed(tags_sorted_by_date_desc):
305 cmd = 'git shortlog -s "%s"' % tag
306 if prev != None:
307 cmd += ' "^%s"' % prev
308 output = getpipeoutput([cmd])
309 if len(output) == 0:
310 continue
311 prev = tag
312 for line in output.split('\n'):
313 parts = re.split('\s+', line, 2)
314 commits = int(parts[1])
315 author = parts[2]
316 if author in conf['merge_authors']:
317 author = conf['merge_authors'][author]
318 self.tags[tag]['commits'] += commits
319 self.tags[tag]['authors'][author] = commits
321 # Collect revision statistics
322 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
323 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
324 for line in lines:
325 parts = line.split(' ', 4)
326 author = ''
327 try:
328 stamp = int(parts[0])
329 except ValueError:
330 stamp = 0
331 timezone = parts[3]
332 author, mail = parts[4].split('<', 1)
333 author = author.rstrip()
334 if author in conf['merge_authors']:
335 author = conf['merge_authors'][author]
336 mail = mail.rstrip('>')
337 domain = '?'
338 if mail.find('@') != -1:
339 domain = mail.rsplit('@', 1)[1]
340 date = datetime.datetime.fromtimestamp(float(stamp))
342 # First and last commit stamp (may be in any order because of cherry-picking and patches)
343 if stamp > self.last_commit_stamp:
344 self.last_commit_stamp = stamp
345 if self.first_commit_stamp == 0 or stamp < self.first_commit_stamp:
346 self.first_commit_stamp = stamp
348 # activity
349 # hour
350 hour = date.hour
351 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
352 # most active hour?
353 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
354 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
356 # day of week
357 day = date.weekday()
358 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
360 # domain stats
361 if domain not in self.domains:
362 self.domains[domain] = {}
363 # commits
364 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
366 # hour of week
367 if day not in self.activity_by_hour_of_week:
368 self.activity_by_hour_of_week[day] = {}
369 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
370 # most active hour?
371 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
372 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
374 # month of year
375 month = date.month
376 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
378 # yearly/weekly activity
379 yyw = date.strftime('%Y-%W')
380 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
381 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
382 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
384 # author stats
385 if author not in self.authors:
386 self.authors[author] = {}
387 # commits, note again that commits may be in any date order because of cherry-picking and patches
388 if 'last_commit_stamp' not in self.authors[author]:
389 self.authors[author]['last_commit_stamp'] = stamp
390 if stamp > self.authors[author]['last_commit_stamp']:
391 self.authors[author]['last_commit_stamp'] = stamp
392 if 'first_commit_stamp' not in self.authors[author]:
393 self.authors[author]['first_commit_stamp'] = stamp
394 if stamp < self.authors[author]['first_commit_stamp']:
395 self.authors[author]['first_commit_stamp'] = stamp
397 # author of the month/year
398 yymm = date.strftime('%Y-%m')
399 if yymm in self.author_of_month:
400 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
401 else:
402 self.author_of_month[yymm] = {}
403 self.author_of_month[yymm][author] = 1
404 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
406 yy = date.year
407 if yy in self.author_of_year:
408 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
409 else:
410 self.author_of_year[yy] = {}
411 self.author_of_year[yy][author] = 1
412 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
414 # authors: active days
415 yymmdd = date.strftime('%Y-%m-%d')
416 if 'last_active_day' not in self.authors[author]:
417 self.authors[author]['last_active_day'] = yymmdd
418 self.authors[author]['active_days'] = set([yymmdd])
419 elif yymmdd != self.authors[author]['last_active_day']:
420 self.authors[author]['last_active_day'] = yymmdd
421 self.authors[author]['active_days'].add(yymmdd)
423 # project: active days
424 if yymmdd != self.last_active_day:
425 self.last_active_day = yymmdd
426 self.active_days.add(yymmdd)
428 # timezone
429 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
431 # outputs "<stamp> <files>" for each revision
432 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
433 lines = []
434 revs_to_read = []
435 time_rev_count = []
436 #Look up rev in cache and take info from cache if found
437 #If not append rev to list of rev to read from repo
438 for revline in revlines:
439 time, rev = revline.split(' ')
440 #if cache empty then add time and rev to list of new rev's
441 #otherwise try to read needed info from cache
442 if 'files_in_tree' not in self.cache.keys():
443 revs_to_read.append((time,rev))
444 continue
445 if rev in self.cache['files_in_tree'].keys():
446 lines.append('%d %d' % (int(time), self.cache['files_in_tree'][rev]))
447 else:
448 revs_to_read.append((time,rev))
450 #Read revisions from repo
451 time_rev_count = Pool(processes=24).map(getnumoffilesfromrev, revs_to_read)
453 #Update cache with new revisions and append then to general list
454 for (time, rev, count) in time_rev_count:
455 if 'files_in_tree' not in self.cache:
456 self.cache['files_in_tree'] = {}
457 self.cache['files_in_tree'][rev] = count
458 lines.append('%d %d' % (int(time), count))
460 self.total_commits += len(lines)
461 for line in lines:
462 parts = line.split(' ')
463 if len(parts) != 2:
464 continue
465 (stamp, files) = parts[0:2]
466 try:
467 self.files_by_stamp[int(stamp)] = int(files)
468 except ValueError:
469 print 'Warning: failed to parse line "%s"' % line
471 # extensions and size of files
472 lines = getpipeoutput(['git ls-tree -r -l -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
473 blobs_to_read = []
474 for line in lines:
475 if len(line) == 0:
476 continue
477 parts = re.split('\s+', line, 5)
478 if parts[0] == '160000' and parts[3] == '-':
479 # skip submodules
480 continue
481 blob_id = parts[2]
482 size = int(parts[3])
483 fullpath = parts[4]
485 self.total_size += size
486 self.total_files += 1
488 filename = fullpath.split('/')[-1] # strip directories
489 if filename.find('.') == -1 or filename.rfind('.') == 0:
490 ext = ''
491 else:
492 ext = filename[(filename.rfind('.') + 1):]
493 if len(ext) > conf['max_ext_length']:
494 ext = ''
495 if ext not in self.extensions:
496 self.extensions[ext] = {'files': 0, 'lines': 0}
497 self.extensions[ext]['files'] += 1
498 #if cache empty then add ext and blob id to list of new blob's
499 #otherwise try to read needed info from cache
500 if 'lines_in_blob' not in self.cache.keys():
501 blobs_to_read.append((ext,blob_id))
502 continue
503 if blob_id in self.cache['lines_in_blob'].keys():
504 self.extensions[ext]['lines'] += self.cache['lines_in_blob'][blob_id]
505 else:
506 blobs_to_read.append((ext,blob_id))
508 #Get info abount line count for new blob's that wasn't found in cache
509 ext_blob_linecount = Pool(processes=24).map(getnumoflinesinblob, blobs_to_read)
511 #Update cache and write down info about number of number of lines
512 for (ext, blob_id, linecount) in ext_blob_linecount:
513 if 'lines_in_blob' not in self.cache:
514 self.cache['lines_in_blob'] = {}
515 self.cache['lines_in_blob'][blob_id] = linecount
516 self.extensions[ext]['lines'] += self.cache['lines_in_blob'][blob_id]
518 # line statistics
519 # outputs:
520 # N files changed, N insertions (+), N deletions(-)
521 # <stamp> <author>
522 self.changes_by_date = {} # stamp -> { files, ins, del }
523 # computation of lines of code by date is better done
524 # on a linear history.
525 extra = ''
526 if conf['linear_linestats']:
527 extra = '--first-parent -m'
528 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
529 lines.reverse()
530 files = 0; inserted = 0; deleted = 0; total_lines = 0
531 author = None
532 for line in lines:
533 if len(line) == 0:
534 continue
536 # <stamp> <author>
537 if re.search('files? changed', line) == None:
538 pos = line.find(' ')
539 if pos != -1:
540 try:
541 (stamp, author) = (int(line[:pos]), line[pos+1:])
542 if author in conf['merge_authors']:
543 author = conf['merge_authors'][author]
544 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
546 date = datetime.datetime.fromtimestamp(stamp)
547 yymm = date.strftime('%Y-%m')
548 self.lines_added_by_month[yymm] = self.lines_added_by_month.get(yymm, 0) + inserted
549 self.lines_removed_by_month[yymm] = self.lines_removed_by_month.get(yymm, 0) + deleted
551 yy = date.year
552 self.lines_added_by_year[yy] = self.lines_added_by_year.get(yy,0) + inserted
553 self.lines_removed_by_year[yy] = self.lines_removed_by_year.get(yy, 0) + deleted
555 files, inserted, deleted = 0, 0, 0
556 except ValueError:
557 print 'Warning: unexpected line "%s"' % line
558 else:
559 print 'Warning: unexpected line "%s"' % line
560 else:
561 numbers = getstatsummarycounts(line)
563 if len(numbers) == 3:
564 (files, inserted, deleted) = map(lambda el : int(el), numbers)
565 total_lines += inserted
566 total_lines -= deleted
567 self.total_lines_added += inserted
568 self.total_lines_removed += deleted
570 else:
571 print 'Warning: failed to handle line "%s"' % line
572 (files, inserted, deleted) = (0, 0, 0)
573 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
574 self.total_lines += total_lines
576 # Per-author statistics
578 # defined for stamp, author only if author commited at this timestamp.
579 self.changes_by_date_by_author = {} # stamp -> author -> lines_added
581 # Similar to the above, but never use --first-parent
582 # (we need to walk through every commit to know who
583 # committed what, not just through mainline)
584 lines = getpipeoutput(['git log --shortstat --date-order --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
585 lines.reverse()
586 files = 0; inserted = 0; deleted = 0
587 author = None
588 stamp = 0
589 for line in lines:
590 if len(line) == 0:
591 continue
593 # <stamp> <author>
594 if re.search('files? changed', line) == None:
595 pos = line.find(' ')
596 if pos != -1:
597 try:
598 oldstamp = stamp
599 (stamp, author) = (int(line[:pos]), line[pos+1:])
600 if author in conf['merge_authors']:
601 author = conf['merge_authors'][author]
602 if oldstamp > stamp:
603 # clock skew, keep old timestamp to avoid having ugly graph
604 stamp = oldstamp
605 if author not in self.authors:
606 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
607 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
608 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
609 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
610 if stamp not in self.changes_by_date_by_author:
611 self.changes_by_date_by_author[stamp] = {}
612 if author not in self.changes_by_date_by_author[stamp]:
613 self.changes_by_date_by_author[stamp][author] = {}
614 self.changes_by_date_by_author[stamp][author]['lines_added'] = self.authors[author]['lines_added']
615 self.changes_by_date_by_author[stamp][author]['commits'] = self.authors[author]['commits']
616 files, inserted, deleted = 0, 0, 0
617 except ValueError:
618 print 'Warning: unexpected line "%s"' % line
619 else:
620 print 'Warning: unexpected line "%s"' % line
621 else:
622 numbers = getstatsummarycounts(line);
624 if len(numbers) == 3:
625 (files, inserted, deleted) = map(lambda el : int(el), numbers)
626 else:
627 print 'Warning: failed to handle line "%s"' % line
628 (files, inserted, deleted) = (0, 0, 0)
630 def refine(self):
631 # authors
632 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
633 self.authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
634 self.authors_by_commits.reverse() # most first
635 for i, name in enumerate(self.authors_by_commits):
636 self.authors[name]['place_by_commits'] = i + 1
638 for name in self.authors.keys():
639 a = self.authors[name]
640 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
641 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
642 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
643 delta = date_last - date_first
644 a['date_first'] = date_first.strftime('%Y-%m-%d')
645 a['date_last'] = date_last.strftime('%Y-%m-%d')
646 a['timedelta'] = delta
647 if 'lines_added' not in a: a['lines_added'] = 0
648 if 'lines_removed' not in a: a['lines_removed'] = 0
650 def getActiveDays(self):
651 return self.active_days
653 def getActivityByDayOfWeek(self):
654 return self.activity_by_day_of_week
656 def getActivityByHourOfDay(self):
657 return self.activity_by_hour_of_day
659 def getAuthorInfo(self, author):
660 return self.authors[author]
662 def getAuthors(self, limit = None):
663 res = getkeyssortedbyvaluekey(self.authors, 'commits')
664 res.reverse()
665 return res[:limit]
667 def getCommitDeltaDays(self):
668 return (self.last_commit_stamp / 86400 - self.first_commit_stamp / 86400) + 1
670 def getDomainInfo(self, domain):
671 return self.domains[domain]
673 def getDomains(self):
674 return self.domains.keys()
676 def getFirstCommitDate(self):
677 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
679 def getLastCommitDate(self):
680 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
682 def getTags(self):
683 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
684 return lines.split('\n')
686 def getTagDate(self, tag):
687 return self.revToDate('tags/' + tag)
689 def getTotalAuthors(self):
690 return self.total_authors
692 def getTotalCommits(self):
693 return self.total_commits
695 def getTotalFiles(self):
696 return self.total_files
698 def getTotalLOC(self):
699 return self.total_lines
701 def getTotalSize(self):
702 return self.total_size
704 def revToDate(self, rev):
705 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
706 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
708 class ReportCreator:
709 """Creates the actual report based on given data."""
710 def __init__(self):
711 pass
713 def create(self, data, path):
714 self.data = data
715 self.path = path
717 def html_linkify(text):
718 return text.lower().replace(' ', '_')
720 def html_header(level, text):
721 name = html_linkify(text)
722 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
724 class HTMLReportCreator(ReportCreator):
725 def create(self, data, path):
726 ReportCreator.create(self, data, path)
727 self.title = data.projectname
729 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
730 binarypath = os.path.dirname(os.path.abspath(__file__))
731 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
732 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
733 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
734 for base in basedirs:
735 src = base + '/' + file
736 if os.path.exists(src):
737 shutil.copyfile(src, path + '/' + file)
738 break
739 else:
740 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
742 f = open(path + "/index.html", 'w')
743 format = '%Y-%m-%d %H:%M:%S'
744 self.printHeader(f)
746 f.write('<h1>GitStats - %s</h1>' % data.projectname)
748 self.printNav(f)
750 f.write('<dl>')
751 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
752 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
753 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
754 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
755 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())))
756 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
757 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))
758 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()))
759 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
760 f.write('</dl>')
762 f.write('</body>\n</html>')
763 f.close()
766 # Activity
767 f = open(path + '/activity.html', 'w')
768 self.printHeader(f)
769 f.write('<h1>Activity</h1>')
770 self.printNav(f)
772 #f.write('<h2>Last 30 days</h2>')
774 #f.write('<h2>Last 12 months</h2>')
776 # Weekly activity
777 WEEKS = 32
778 f.write(html_header(2, 'Weekly activity'))
779 f.write('<p>Last %d weeks</p>' % WEEKS)
781 # generate weeks to show (previous N weeks from now)
782 now = datetime.datetime.now()
783 deltaweek = datetime.timedelta(7)
784 weeks = []
785 stampcur = now
786 for i in range(0, WEEKS):
787 weeks.insert(0, stampcur.strftime('%Y-%W'))
788 stampcur -= deltaweek
790 # top row: commits & bar
791 f.write('<table class="noborders"><tr>')
792 for i in range(0, WEEKS):
793 commits = 0
794 if weeks[i] in data.activity_by_year_week:
795 commits = data.activity_by_year_week[weeks[i]]
797 percentage = 0
798 if weeks[i] in data.activity_by_year_week:
799 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
800 height = max(1, int(200 * percentage))
801 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))
803 # bottom row: year/week
804 f.write('</tr><tr>')
805 for i in range(0, WEEKS):
806 f.write('<td>%s</td>' % (WEEKS - i))
807 f.write('</tr></table>')
809 # Hour of Day
810 f.write(html_header(2, 'Hour of Day'))
811 hour_of_day = data.getActivityByHourOfDay()
812 f.write('<table><tr><th>Hour</th>')
813 for i in range(0, 24):
814 f.write('<th>%d</th>' % i)
815 f.write('</tr>\n<tr><th>Commits</th>')
816 fp = open(path + '/hour_of_day.dat', 'w')
817 for i in range(0, 24):
818 if i in hour_of_day:
819 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
820 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
821 fp.write('%d %d\n' % (i, hour_of_day[i]))
822 else:
823 f.write('<td>0</td>')
824 fp.write('%d 0\n' % i)
825 fp.close()
826 f.write('</tr>\n<tr><th>%</th>')
827 totalcommits = data.getTotalCommits()
828 for i in range(0, 24):
829 if i in hour_of_day:
830 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
831 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
832 else:
833 f.write('<td>0.00</td>')
834 f.write('</tr></table>')
835 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
836 fg = open(path + '/hour_of_day.dat', 'w')
837 for i in range(0, 24):
838 if i in hour_of_day:
839 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
840 else:
841 fg.write('%d 0\n' % (i + 1))
842 fg.close()
844 # Day of Week
845 f.write(html_header(2, 'Day of Week'))
846 day_of_week = data.getActivityByDayOfWeek()
847 f.write('<div class="vtable"><table>')
848 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
849 fp = open(path + '/day_of_week.dat', 'w')
850 for d in range(0, 7):
851 commits = 0
852 if d in day_of_week:
853 commits = day_of_week[d]
854 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
855 f.write('<tr>')
856 f.write('<th>%s</th>' % (WEEKDAYS[d]))
857 if d in day_of_week:
858 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
859 else:
860 f.write('<td>0</td>')
861 f.write('</tr>')
862 f.write('</table></div>')
863 f.write('<img src="day_of_week.png" alt="Day of Week" />')
864 fp.close()
866 # Hour of Week
867 f.write(html_header(2, 'Hour of Week'))
868 f.write('<table>')
870 f.write('<tr><th>Weekday</th>')
871 for hour in range(0, 24):
872 f.write('<th>%d</th>' % (hour))
873 f.write('</tr>')
875 for weekday in range(0, 7):
876 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
877 for hour in range(0, 24):
878 try:
879 commits = data.activity_by_hour_of_week[weekday][hour]
880 except KeyError:
881 commits = 0
882 if commits != 0:
883 f.write('<td')
884 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
885 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
886 f.write('>%d</td>' % commits)
887 else:
888 f.write('<td></td>')
889 f.write('</tr>')
891 f.write('</table>')
893 # Month of Year
894 f.write(html_header(2, 'Month of Year'))
895 f.write('<div class="vtable"><table>')
896 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
897 fp = open (path + '/month_of_year.dat', 'w')
898 for mm in range(1, 13):
899 commits = 0
900 if mm in data.activity_by_month_of_year:
901 commits = data.activity_by_month_of_year[mm]
902 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
903 fp.write('%d %d\n' % (mm, commits))
904 fp.close()
905 f.write('</table></div>')
906 f.write('<img src="month_of_year.png" alt="Month of Year" />')
908 # Commits by year/month
909 f.write(html_header(2, 'Commits by year/month'))
910 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th><th>Lines added</th><th>Lines removed</th></tr>')
911 for yymm in reversed(sorted(data.commits_by_month.keys())):
912 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)))
913 f.write('</table></div>')
914 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
915 fg = open(path + '/commits_by_year_month.dat', 'w')
916 for yymm in sorted(data.commits_by_month.keys()):
917 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
918 fg.close()
920 # Commits by year
921 f.write(html_header(2, 'Commits by Year'))
922 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th><th>Lines added</th><th>Lines removed</th></tr>')
923 for yy in reversed(sorted(data.commits_by_year.keys())):
924 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)))
925 f.write('</table></div>')
926 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
927 fg = open(path + '/commits_by_year.dat', 'w')
928 for yy in sorted(data.commits_by_year.keys()):
929 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
930 fg.close()
932 # Commits by timezone
933 f.write(html_header(2, 'Commits by Timezone'))
934 f.write('<table><tr>')
935 f.write('<th>Timezone</th><th>Commits</th>')
936 max_commits_on_tz = max(data.commits_by_timezone.values())
937 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
938 commits = data.commits_by_timezone[i]
939 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
940 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
941 f.write('</tr></table>')
943 f.write('</body></html>')
944 f.close()
947 # Authors
948 f = open(path + '/authors.html', 'w')
949 self.printHeader(f)
951 f.write('<h1>Authors</h1>')
952 self.printNav(f)
954 # Authors :: List of authors
955 f.write(html_header(2, 'List of Authors'))
957 f.write('<table class="authors sortable" id="authors">')
958 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>')
959 for author in data.getAuthors(conf['max_authors']):
960 info = data.getAuthorInfo(author)
961 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']))
962 f.write('</table>')
964 allauthors = data.getAuthors()
965 if len(allauthors) > conf['max_authors']:
966 rest = allauthors[conf['max_authors']:]
967 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
969 f.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
970 f.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
971 if len(allauthors) > conf['max_authors']:
972 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
974 f.write(html_header(2, 'Commits per Author'))
975 f.write('<img src="commits_by_author.png" alt="Commits per Author" />')
976 if len(allauthors) > conf['max_authors']:
977 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
979 fgl = open(path + '/lines_of_code_by_author.dat', 'w')
980 fgc = open(path + '/commits_by_author.dat', 'w')
982 lines_by_authors = {} # cumulated added lines by
983 # author. to save memory,
984 # changes_by_date_by_author[stamp][author] is defined
985 # only at points where author commits.
986 # lines_by_authors allows us to generate all the
987 # points in the .dat file.
989 # Don't rely on getAuthors to give the same order each
990 # time. Be robust and keep the list in a variable.
991 commits_by_authors = {} # cumulated added lines by
993 self.authors_to_plot = data.getAuthors(conf['max_authors'])
994 for author in self.authors_to_plot:
995 lines_by_authors[author] = 0
996 commits_by_authors[author] = 0
997 for stamp in sorted(data.changes_by_date_by_author.keys()):
998 fgl.write('%d' % stamp)
999 fgc.write('%d' % stamp)
1000 for author in self.authors_to_plot:
1001 if author in data.changes_by_date_by_author[stamp].keys():
1002 lines_by_authors[author] = data.changes_by_date_by_author[stamp][author]['lines_added']
1003 commits_by_authors[author] = data.changes_by_date_by_author[stamp][author]['commits']
1004 fgl.write(' %d' % lines_by_authors[author])
1005 fgc.write(' %d' % commits_by_authors[author])
1006 fgl.write('\n')
1007 fgc.write('\n')
1008 fgl.close()
1009 fgc.close()
1011 # Authors :: Author of Month
1012 f.write(html_header(2, 'Author of Month'))
1013 f.write('<table class="sortable" id="aom">')
1014 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'])
1015 for yymm in reversed(sorted(data.author_of_month.keys())):
1016 authordict = data.author_of_month[yymm]
1017 authors = getkeyssortedbyvalues(authordict)
1018 authors.reverse()
1019 commits = data.author_of_month[yymm][authors[0]]
1020 next = ', '.join(authors[1:conf['authors_top']+1])
1021 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)))
1023 f.write('</table>')
1025 f.write(html_header(2, 'Author of Year'))
1026 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'])
1027 for yy in reversed(sorted(data.author_of_year.keys())):
1028 authordict = data.author_of_year[yy]
1029 authors = getkeyssortedbyvalues(authordict)
1030 authors.reverse()
1031 commits = data.author_of_year[yy][authors[0]]
1032 next = ', '.join(authors[1:conf['authors_top']+1])
1033 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)))
1034 f.write('</table>')
1036 # Domains
1037 f.write(html_header(2, 'Commits by Domains'))
1038 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
1039 domains_by_commits.reverse() # most first
1040 f.write('<div class="vtable"><table>')
1041 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
1042 fp = open(path + '/domains.dat', 'w')
1043 n = 0
1044 for domain in domains_by_commits:
1045 if n == conf['max_domains']:
1046 break
1047 commits = 0
1048 n += 1
1049 info = data.getDomainInfo(domain)
1050 fp.write('%s %d %d\n' % (domain, n , info['commits']))
1051 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
1052 f.write('</table></div>')
1053 f.write('<img src="domains.png" alt="Commits by Domains" />')
1054 fp.close()
1056 f.write('</body></html>')
1057 f.close()
1060 # Files
1061 f = open(path + '/files.html', 'w')
1062 self.printHeader(f)
1063 f.write('<h1>Files</h1>')
1064 self.printNav(f)
1066 f.write('<dl>\n')
1067 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
1068 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1069 try:
1070 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % (float(data.getTotalSize()) / data.getTotalFiles()))
1071 except ZeroDivisionError:
1072 pass
1073 f.write('</dl>\n')
1075 # Files :: File count by date
1076 f.write(html_header(2, 'File count by date'))
1078 # use set to get rid of duplicate/unnecessary entries
1079 files_by_date = set()
1080 for stamp in sorted(data.files_by_stamp.keys()):
1081 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1083 fg = open(path + '/files_by_date.dat', 'w')
1084 for line in sorted(list(files_by_date)):
1085 fg.write('%s\n' % line)
1086 #for stamp in sorted(data.files_by_stamp.keys()):
1087 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1088 fg.close()
1090 f.write('<img src="files_by_date.png" alt="Files by Date" />')
1092 #f.write('<h2>Average file size by date</h2>')
1094 # Files :: Extensions
1095 f.write(html_header(2, 'Extensions'))
1096 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
1097 for ext in sorted(data.extensions.keys()):
1098 files = data.extensions[ext]['files']
1099 lines = data.extensions[ext]['lines']
1100 try:
1101 loc_percentage = (100.0 * lines) / data.getTotalLOC()
1102 except ZeroDivisionError:
1103 loc_percentage = 0
1104 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))
1105 f.write('</table>')
1107 f.write('</body></html>')
1108 f.close()
1111 # Lines
1112 f = open(path + '/lines.html', 'w')
1113 self.printHeader(f)
1114 f.write('<h1>Lines</h1>')
1115 self.printNav(f)
1117 f.write('<dl>\n')
1118 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1119 f.write('</dl>\n')
1121 f.write(html_header(2, 'Lines of Code'))
1122 f.write('<img src="lines_of_code.png" />')
1124 fg = open(path + '/lines_of_code.dat', 'w')
1125 for stamp in sorted(data.changes_by_date.keys()):
1126 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
1127 fg.close()
1129 f.write('</body></html>')
1130 f.close()
1133 # tags.html
1134 f = open(path + '/tags.html', 'w')
1135 self.printHeader(f)
1136 f.write('<h1>Tags</h1>')
1137 self.printNav(f)
1139 f.write('<dl>')
1140 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
1141 if len(data.tags) > 0:
1142 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
1143 f.write('</dl>')
1145 f.write('<table class="tags">')
1146 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1147 # sort the tags by date desc
1148 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
1149 for tag in tags_sorted_by_date_desc:
1150 authorinfo = []
1151 self.authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
1152 for i in reversed(self.authors_by_commits):
1153 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
1154 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)))
1155 f.write('</table>')
1157 f.write('</body></html>')
1158 f.close()
1160 self.createGraphs(path)
1162 def createGraphs(self, path):
1163 print 'Generating graphs...'
1165 # hour of day
1166 f = open(path + '/hour_of_day.plot', 'w')
1167 f.write(GNUPLOT_COMMON)
1168 f.write(
1170 set output 'hour_of_day.png'
1171 unset key
1172 set xrange [0.5:24.5]
1173 set xtics 4
1174 set grid y
1175 set ylabel "Commits"
1176 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1177 """)
1178 f.close()
1180 # day of week
1181 f = open(path + '/day_of_week.plot', 'w')
1182 f.write(GNUPLOT_COMMON)
1183 f.write(
1185 set output 'day_of_week.png'
1186 unset key
1187 set xrange [0.5:7.5]
1188 set xtics 1
1189 set grid y
1190 set ylabel "Commits"
1191 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1192 """)
1193 f.close()
1195 # Domains
1196 f = open(path + '/domains.plot', 'w')
1197 f.write(GNUPLOT_COMMON)
1198 f.write(
1200 set output 'domains.png'
1201 unset key
1202 unset xtics
1203 set yrange [0:]
1204 set grid y
1205 set ylabel "Commits"
1206 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1207 """)
1208 f.close()
1210 # Month of Year
1211 f = open(path + '/month_of_year.plot', 'w')
1212 f.write(GNUPLOT_COMMON)
1213 f.write(
1215 set output 'month_of_year.png'
1216 unset key
1217 set xrange [0.5:12.5]
1218 set xtics 1
1219 set grid y
1220 set ylabel "Commits"
1221 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1222 """)
1223 f.close()
1225 # commits_by_year_month
1226 f = open(path + '/commits_by_year_month.plot', 'w')
1227 f.write(GNUPLOT_COMMON)
1228 f.write(
1230 set output 'commits_by_year_month.png'
1231 unset key
1232 set xdata time
1233 set timefmt "%Y-%m"
1234 set format x "%Y-%m"
1235 set xtics rotate
1236 set bmargin 5
1237 set grid y
1238 set ylabel "Commits"
1239 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1240 """)
1241 f.close()
1243 # commits_by_year
1244 f = open(path + '/commits_by_year.plot', 'w')
1245 f.write(GNUPLOT_COMMON)
1246 f.write(
1248 set output 'commits_by_year.png'
1249 unset key
1250 set xtics 1 rotate
1251 set grid y
1252 set ylabel "Commits"
1253 set yrange [0:]
1254 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1255 """)
1256 f.close()
1258 # Files by date
1259 f = open(path + '/files_by_date.plot', 'w')
1260 f.write(GNUPLOT_COMMON)
1261 f.write(
1263 set output 'files_by_date.png'
1264 unset key
1265 set xdata time
1266 set timefmt "%Y-%m-%d"
1267 set format x "%Y-%m-%d"
1268 set grid y
1269 set ylabel "Files"
1270 set xtics rotate
1271 set ytics autofreq
1272 set bmargin 6
1273 plot 'files_by_date.dat' using 1:2 w steps
1274 """)
1275 f.close()
1277 # Lines of Code
1278 f = open(path + '/lines_of_code.plot', 'w')
1279 f.write(GNUPLOT_COMMON)
1280 f.write(
1282 set output 'lines_of_code.png'
1283 unset key
1284 set xdata time
1285 set timefmt "%s"
1286 set format x "%Y-%m-%d"
1287 set grid y
1288 set ylabel "Lines"
1289 set xtics rotate
1290 set bmargin 6
1291 plot 'lines_of_code.dat' using 1:2 w lines
1292 """)
1293 f.close()
1295 # Lines of Code Added per author
1296 f = open(path + '/lines_of_code_by_author.plot', 'w')
1297 f.write(GNUPLOT_COMMON)
1298 f.write(
1300 set terminal png transparent size 640,480
1301 set output 'lines_of_code_by_author.png'
1302 set key left top
1303 set xdata time
1304 set timefmt "%s"
1305 set format x "%Y-%m-%d"
1306 set grid y
1307 set ylabel "Lines"
1308 set xtics rotate
1309 set bmargin 6
1310 plot """
1312 i = 1
1313 plots = []
1314 for a in self.authors_to_plot:
1315 i = i + 1
1316 plots.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1317 f.write(", ".join(plots))
1318 f.write('\n')
1320 f.close()
1322 # Commits per author
1323 f = open(path + '/commits_by_author.plot', 'w')
1324 f.write(GNUPLOT_COMMON)
1325 f.write(
1327 set terminal png transparent size 640,480
1328 set output 'commits_by_author.png'
1329 set key left top
1330 set xdata time
1331 set timefmt "%s"
1332 set format x "%Y-%m-%d"
1333 set grid y
1334 set ylabel "Commits"
1335 set xtics rotate
1336 set bmargin 6
1337 plot """
1339 i = 1
1340 plots = []
1341 for a in self.authors_to_plot:
1342 i = i + 1
1343 plots.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1344 f.write(", ".join(plots))
1345 f.write('\n')
1347 f.close()
1349 os.chdir(path)
1350 files = glob.glob(path + '/*.plot')
1351 for f in files:
1352 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1353 if len(out) > 0:
1354 print out
1356 def printHeader(self, f, title = ''):
1357 f.write(
1358 """<?xml version="1.0" encoding="UTF-8"?>
1359 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1360 <html xmlns="http://www.w3.org/1999/xhtml">
1361 <head>
1362 <title>GitStats - %s</title>
1363 <link rel="stylesheet" href="%s" type="text/css" />
1364 <meta name="generator" content="GitStats %s" />
1365 <script type="text/javascript" src="sortable.js"></script>
1366 </head>
1367 <body>
1368 """ % (self.title, conf['style'], getversion()))
1370 def printNav(self, f):
1371 f.write("""
1372 <div class="nav">
1373 <ul>
1374 <li><a href="index.html">General</a></li>
1375 <li><a href="activity.html">Activity</a></li>
1376 <li><a href="authors.html">Authors</a></li>
1377 <li><a href="files.html">Files</a></li>
1378 <li><a href="lines.html">Lines</a></li>
1379 <li><a href="tags.html">Tags</a></li>
1380 </ul>
1381 </div>
1382 """)
1384 def usage():
1385 print """
1386 Usage: gitstats [options] <gitpath..> <outputpath>
1388 Options:
1389 -c key=value Override configuration value
1391 Default config values:
1394 Please see the manual page for more details.
1395 """ % conf
1398 class GitStats:
1399 def run(self, args_orig):
1400 optlist, args = getopt.getopt(args_orig, 'hc:', ["help"])
1401 for o,v in optlist:
1402 if o == '-c':
1403 key, value = v.split('=', 1)
1404 if key not in conf:
1405 raise KeyError('no such key "%s" in config' % key)
1406 if isinstance(conf[key], int):
1407 conf[key] = int(value)
1408 elif isinstance(conf[key], dict):
1409 kk,vv = value.split(',', 1)
1410 conf[key][kk] = vv
1411 else:
1412 conf[key] = value
1413 elif o in ('-h', '--help'):
1414 usage()
1415 sys.exit()
1417 if len(args) < 2:
1418 usage()
1419 sys.exit(0)
1421 outputpath = os.path.abspath(args[-1])
1422 rundir = os.getcwd()
1424 try:
1425 os.makedirs(outputpath)
1426 except OSError:
1427 pass
1428 if not os.path.isdir(outputpath):
1429 print 'FATAL: Output path is not a directory or does not exist'
1430 sys.exit(1)
1432 if not getgnuplotversion():
1433 print 'gnuplot not found'
1434 sys.exit(1)
1436 print 'Output path: %s' % outputpath
1437 cachefile = os.path.join(outputpath, 'gitstats.cache')
1439 data = GitDataCollector()
1440 data.loadCache(cachefile)
1442 for gitpath in args[0:-1]:
1443 print 'Git path: %s' % gitpath
1445 os.chdir(gitpath)
1447 print 'Collecting data...'
1448 data.collect(gitpath)
1450 print 'Refining data...'
1451 data.saveCache(cachefile)
1452 data.refine()
1454 os.chdir(rundir)
1456 print 'Generating report...'
1457 report = HTMLReportCreator()
1458 report.create(data, outputpath)
1460 time_end = time.time()
1461 exectime_internal = time_end - time_start
1462 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1463 if sys.stdin.isatty():
1464 print 'You may now run:'
1465 print
1466 print ' sensible-browser \'%s\'' % os.path.join(outputpath, 'index.html').replace("'", "'\\''")
1467 print
1469 if __name__=='__main__':
1470 g = GitStats()
1471 g.run(sys.argv[1:])