Added ability to merge/rename authors
[gitstats.git] / gitstats
blobeac9d02e4570157506540aad9a839d9104f3bb8a
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': '',
43 'merge_authors': {}
46 def getpipeoutput(cmds, quiet = False):
47 global exectime_external
48 start = time.time()
49 if not quiet and ON_LINUX and os.isatty(1):
50 print '>> ' + ' | '.join(cmds),
51 sys.stdout.flush()
52 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
53 p = p0
54 for x in cmds[1:]:
55 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
56 p0 = p
57 output = p.communicate()[0]
58 end = time.time()
59 if not quiet:
60 if ON_LINUX and os.isatty(1):
61 print '\r',
62 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
63 exectime_external += (end - start)
64 return output.rstrip('\n')
66 def getcommitrange(defaultrange = 'HEAD', end_only = False):
67 if len(conf['commit_end']) > 0:
68 if end_only or len(conf['commit_begin']) == 0:
69 return conf['commit_end']
70 return '%s..%s' % (conf['commit_begin'], conf['commit_end'])
71 return defaultrange
73 def getkeyssortedbyvalues(dict):
74 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
76 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
77 def getkeyssortedbyvaluekey(d, key):
78 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
80 def getstatsummarycounts(line):
81 numbers = re.findall('\d+', line)
82 if len(numbers) == 1:
83 # neither insertions nor deletions: may probably only happen for "0 files changed"
84 numbers.append(0);
85 numbers.append(0);
86 elif len(numbers) == 2 and line.find('(+)') != -1:
87 numbers.append(0); # only insertions were printed on line
88 elif len(numbers) == 2 and line.find('(-)') != -1:
89 numbers.insert(1, 0); # only deletions were printed on line
90 return numbers
92 VERSION = 0
93 def getversion():
94 global VERSION
95 if VERSION == 0:
96 gitstats_repo = os.path.dirname(os.path.abspath(__file__))
97 VERSION = getpipeoutput(["git --git-dir=%s/.git --work-tree=%s rev-parse --short %s" %
98 (gitstats_repo, gitstats_repo, getcommitrange('HEAD').split('\n')[0])])
99 return VERSION
101 def getgitversion():
102 return getpipeoutput(['git --version']).split('\n')[0]
104 def getgnuplotversion():
105 return getpipeoutput(['%s --version' % gnuplot_cmd]).split('\n')[0]
107 class DataCollector:
108 """Manages data collection from a revision control repository."""
109 def __init__(self):
110 self.stamp_created = time.time()
111 self.cache = {}
112 self.total_authors = 0
113 self.activity_by_hour_of_day = {} # hour -> commits
114 self.activity_by_day_of_week = {} # day -> commits
115 self.activity_by_month_of_year = {} # month [1-12] -> commits
116 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
117 self.activity_by_hour_of_day_busiest = 0
118 self.activity_by_hour_of_week_busiest = 0
119 self.activity_by_year_week = {} # yy_wNN -> commits
120 self.activity_by_year_week_peak = 0
122 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
124 self.total_commits = 0
125 self.total_files = 0
126 self.authors_by_commits = 0
128 # domains
129 self.domains = {} # domain -> commits
131 # author of the month
132 self.author_of_month = {} # month -> author -> commits
133 self.author_of_year = {} # year -> author -> commits
134 self.commits_by_month = {} # month -> commits
135 self.commits_by_year = {} # year -> commits
136 self.lines_added_by_month = {} # month -> lines added
137 self.lines_added_by_year = {} # year -> lines added
138 self.lines_removed_by_month = {} # month -> lines removed
139 self.lines_removed_by_year = {} # year -> lines removed
140 self.first_commit_stamp = 0
141 self.last_commit_stamp = 0
142 self.last_active_day = None
143 self.active_days = set()
145 # lines
146 self.total_lines = 0
147 self.total_lines_added = 0
148 self.total_lines_removed = 0
150 # size
151 self.total_size = 0
153 # timezone
154 self.commits_by_timezone = {} # timezone -> commits
156 # tags
157 self.tags = {}
159 self.files_by_stamp = {} # stamp -> files
161 # extensions
162 self.extensions = {} # extension -> files, lines
164 # line statistics
165 self.changes_by_date = {} # stamp -> { files, ins, del }
168 # This should be the main function to extract data from the repository.
169 def collect(self, dir):
170 self.dir = dir
171 if len(conf['project_name']) == 0:
172 self.projectname = os.path.basename(os.path.abspath(dir))
173 else:
174 self.projectname = conf['project_name']
177 # Load cacheable data
178 def loadCache(self, cachefile):
179 if not os.path.exists(cachefile):
180 return
181 print 'Loading cache...'
182 f = open(cachefile, 'rb')
183 try:
184 self.cache = pickle.loads(zlib.decompress(f.read()))
185 except:
186 # temporary hack to upgrade non-compressed caches
187 f.seek(0)
188 self.cache = pickle.load(f)
189 f.close()
192 # Produce any additional statistics from the extracted data.
193 def refine(self):
194 pass
197 # : get a dictionary of author
198 def getAuthorInfo(self, author):
199 return None
201 def getActivityByDayOfWeek(self):
202 return {}
204 def getActivityByHourOfDay(self):
205 return {}
207 # : get a dictionary of domains
208 def getDomainInfo(self, domain):
209 return None
212 # Get a list of authors
213 def getAuthors(self):
214 return []
216 def getFirstCommitDate(self):
217 return datetime.datetime.now()
219 def getLastCommitDate(self):
220 return datetime.datetime.now()
222 def getStampCreated(self):
223 return self.stamp_created
225 def getTags(self):
226 return []
228 def getTotalAuthors(self):
229 return -1
231 def getTotalCommits(self):
232 return -1
234 def getTotalFiles(self):
235 return -1
237 def getTotalLOC(self):
238 return -1
241 # Save cacheable data
242 def saveCache(self, cachefile):
243 print 'Saving cache...'
244 f = open(cachefile, 'wb')
245 #pickle.dump(self.cache, f)
246 data = zlib.compress(pickle.dumps(self.cache))
247 f.write(data)
248 f.close()
250 class GitDataCollector(DataCollector):
251 def collect(self, dir):
252 DataCollector.collect(self, dir)
254 self.total_authors += int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
255 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
257 # tags
258 lines = getpipeoutput(['git show-ref --tags']).split('\n')
259 for line in lines:
260 if len(line) == 0:
261 continue
262 (hash, tag) = line.split(' ')
264 tag = tag.replace('refs/tags/', '')
265 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
266 if len(output) > 0:
267 parts = output.split(' ')
268 stamp = 0
269 try:
270 stamp = int(parts[0])
271 except ValueError:
272 stamp = 0
273 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
275 # collect info on tags, starting from latest
276 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
277 prev = None
278 for tag in reversed(tags_sorted_by_date_desc):
279 cmd = 'git shortlog -s "%s"' % tag
280 if prev != None:
281 cmd += ' "^%s"' % prev
282 output = getpipeoutput([cmd])
283 if len(output) == 0:
284 continue
285 prev = tag
286 for line in output.split('\n'):
287 parts = re.split('\s+', line, 2)
288 commits = int(parts[1])
289 author = parts[2]
290 if author in conf['merge_authors']:
291 author = conf['merge_authors'][author]
292 self.tags[tag]['commits'] += commits
293 self.tags[tag]['authors'][author] = commits
295 # Collect revision statistics
296 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
297 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
298 for line in lines:
299 parts = line.split(' ', 4)
300 author = ''
301 try:
302 stamp = int(parts[0])
303 except ValueError:
304 stamp = 0
305 timezone = parts[3]
306 author, mail = parts[4].split('<', 1)
307 author = author.rstrip()
308 if author in conf['merge_authors']:
309 author = conf['merge_authors'][author]
310 mail = mail.rstrip('>')
311 domain = '?'
312 if mail.find('@') != -1:
313 domain = mail.rsplit('@', 1)[1]
314 date = datetime.datetime.fromtimestamp(float(stamp))
316 # First and last commit stamp (may be in any order because of cherry-picking and patches)
317 if stamp > self.last_commit_stamp:
318 self.last_commit_stamp = stamp
319 if self.first_commit_stamp == 0 or stamp < self.first_commit_stamp:
320 self.first_commit_stamp = stamp
322 # activity
323 # hour
324 hour = date.hour
325 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
326 # most active hour?
327 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
328 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
330 # day of week
331 day = date.weekday()
332 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
334 # domain stats
335 if domain not in self.domains:
336 self.domains[domain] = {}
337 # commits
338 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
340 # hour of week
341 if day not in self.activity_by_hour_of_week:
342 self.activity_by_hour_of_week[day] = {}
343 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
344 # most active hour?
345 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
346 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
348 # month of year
349 month = date.month
350 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
352 # yearly/weekly activity
353 yyw = date.strftime('%Y-%W')
354 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
355 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
356 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
358 # author stats
359 if author not in self.authors:
360 self.authors[author] = {}
361 # commits, note again that commits may be in any date order because of cherry-picking and patches
362 if 'last_commit_stamp' not in self.authors[author]:
363 self.authors[author]['last_commit_stamp'] = stamp
364 if stamp > self.authors[author]['last_commit_stamp']:
365 self.authors[author]['last_commit_stamp'] = stamp
366 if 'first_commit_stamp' not in self.authors[author]:
367 self.authors[author]['first_commit_stamp'] = stamp
368 if stamp < self.authors[author]['first_commit_stamp']:
369 self.authors[author]['first_commit_stamp'] = stamp
371 # author of the month/year
372 yymm = date.strftime('%Y-%m')
373 if yymm in self.author_of_month:
374 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
375 else:
376 self.author_of_month[yymm] = {}
377 self.author_of_month[yymm][author] = 1
378 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
380 yy = date.year
381 if yy in self.author_of_year:
382 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
383 else:
384 self.author_of_year[yy] = {}
385 self.author_of_year[yy][author] = 1
386 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
388 # authors: active days
389 yymmdd = date.strftime('%Y-%m-%d')
390 if 'last_active_day' not in self.authors[author]:
391 self.authors[author]['last_active_day'] = yymmdd
392 self.authors[author]['active_days'] = set([yymmdd])
393 elif yymmdd != self.authors[author]['last_active_day']:
394 self.authors[author]['last_active_day'] = yymmdd
395 self.authors[author]['active_days'].add(yymmdd)
397 # project: active days
398 if yymmdd != self.last_active_day:
399 self.last_active_day = yymmdd
400 self.active_days.add(yymmdd)
402 # timezone
403 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
405 # TODO Optimize this, it's the worst bottleneck
406 # outputs "<stamp> <files>" for each revision
407 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
408 lines = []
409 for revline in revlines:
410 time, rev = revline.split(' ')
411 linecount = self.getFilesInCommit(rev)
412 lines.append('%d %d' % (int(time), linecount))
414 self.total_commits += len(lines)
415 for line in lines:
416 parts = line.split(' ')
417 if len(parts) != 2:
418 continue
419 (stamp, files) = parts[0:2]
420 try:
421 self.files_by_stamp[int(stamp)] = int(files)
422 except ValueError:
423 print 'Warning: failed to parse line "%s"' % line
425 # extensions and size of files
426 lines = getpipeoutput(['git ls-tree -r -l -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
427 for line in lines:
428 if len(line) == 0:
429 continue
430 parts = re.split('\s+', line, 5)
431 if parts[0] == '160000' and parts[3] == '-':
432 # skip submodules
433 continue
434 sha1 = parts[2]
435 size = int(parts[3])
436 fullpath = parts[4]
438 self.total_size += size
439 self.total_files += 1
441 filename = fullpath.split('/')[-1] # strip directories
442 if filename.find('.') == -1 or filename.rfind('.') == 0:
443 ext = ''
444 else:
445 ext = filename[(filename.rfind('.') + 1):]
446 if len(ext) > conf['max_ext_length']:
447 ext = ''
449 if ext not in self.extensions:
450 self.extensions[ext] = {'files': 0, 'lines': 0}
452 self.extensions[ext]['files'] += 1
453 try:
454 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
455 except:
456 print 'Warning: Could not count lines for file "%s"' % line
458 # line statistics
459 # outputs:
460 # N files changed, N insertions (+), N deletions(-)
461 # <stamp> <author>
462 self.changes_by_date = {} # stamp -> { files, ins, del }
463 # computation of lines of code by date is better done
464 # on a linear history.
465 extra = ''
466 if conf['linear_linestats']:
467 extra = '--first-parent -m'
468 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
469 lines.reverse()
470 files = 0; inserted = 0; deleted = 0; total_lines = 0
471 author = None
472 for line in lines:
473 if len(line) == 0:
474 continue
476 # <stamp> <author>
477 if re.search('files? changed', line) == None:
478 pos = line.find(' ')
479 if pos != -1:
480 try:
481 (stamp, author) = (int(line[:pos]), line[pos+1:])
482 if author in conf['merge_authors']:
483 author = conf['merge_authors'][author]
484 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
486 date = datetime.datetime.fromtimestamp(stamp)
487 yymm = date.strftime('%Y-%m')
488 self.lines_added_by_month[yymm] = self.lines_added_by_month.get(yymm, 0) + inserted
489 self.lines_removed_by_month[yymm] = self.lines_removed_by_month.get(yymm, 0) + deleted
491 yy = date.year
492 self.lines_added_by_year[yy] = self.lines_added_by_year.get(yy,0) + inserted
493 self.lines_removed_by_year[yy] = self.lines_removed_by_year.get(yy, 0) + deleted
495 files, inserted, deleted = 0, 0, 0
496 except ValueError:
497 print 'Warning: unexpected line "%s"' % line
498 else:
499 print 'Warning: unexpected line "%s"' % line
500 else:
501 numbers = getstatsummarycounts(line)
503 if len(numbers) == 3:
504 (files, inserted, deleted) = map(lambda el : int(el), numbers)
505 total_lines += inserted
506 total_lines -= deleted
507 self.total_lines_added += inserted
508 self.total_lines_removed += deleted
510 else:
511 print 'Warning: failed to handle line "%s"' % line
512 (files, inserted, deleted) = (0, 0, 0)
513 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
514 self.total_lines = total_lines
516 # Per-author statistics
518 # defined for stamp, author only if author commited at this timestamp.
519 self.changes_by_date_by_author = {} # stamp -> author -> lines_added
521 # Similar to the above, but never use --first-parent
522 # (we need to walk through every commit to know who
523 # committed what, not just through mainline)
524 lines = getpipeoutput(['git log --shortstat --date-order --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
525 lines.reverse()
526 files = 0; inserted = 0; deleted = 0
527 author = None
528 stamp = 0
529 for line in lines:
530 if len(line) == 0:
531 continue
533 # <stamp> <author>
534 if re.search('files? changed', line) == None:
535 pos = line.find(' ')
536 if pos != -1:
537 try:
538 oldstamp = stamp
539 (stamp, author) = (int(line[:pos]), line[pos+1:])
540 if author in conf['merge_authors']:
541 author = conf['merge_authors'][author]
542 if oldstamp > stamp:
543 # clock skew, keep old timestamp to avoid having ugly graph
544 stamp = oldstamp
545 if author not in self.authors:
546 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
547 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
548 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
549 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
550 if stamp not in self.changes_by_date_by_author:
551 self.changes_by_date_by_author[stamp] = {}
552 if author not in self.changes_by_date_by_author[stamp]:
553 self.changes_by_date_by_author[stamp][author] = {}
554 self.changes_by_date_by_author[stamp][author]['lines_added'] = self.authors[author]['lines_added']
555 self.changes_by_date_by_author[stamp][author]['commits'] = self.authors[author]['commits']
556 files, inserted, deleted = 0, 0, 0
557 except ValueError:
558 print 'Warning: unexpected line "%s"' % line
559 else:
560 print 'Warning: unexpected line "%s"' % line
561 else:
562 numbers = getstatsummarycounts(line);
564 if len(numbers) == 3:
565 (files, inserted, deleted) = map(lambda el : int(el), numbers)
566 else:
567 print 'Warning: failed to handle line "%s"' % line
568 (files, inserted, deleted) = (0, 0, 0)
570 def refine(self):
571 # authors
572 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
573 self.authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
574 self.authors_by_commits.reverse() # most first
575 for i, name in enumerate(self.authors_by_commits):
576 self.authors[name]['place_by_commits'] = i + 1
578 for name in self.authors.keys():
579 a = self.authors[name]
580 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
581 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
582 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
583 delta = date_last - date_first
584 a['date_first'] = date_first.strftime('%Y-%m-%d')
585 a['date_last'] = date_last.strftime('%Y-%m-%d')
586 a['timedelta'] = delta
587 if 'lines_added' not in a: a['lines_added'] = 0
588 if 'lines_removed' not in a: a['lines_removed'] = 0
590 def getActiveDays(self):
591 return self.active_days
593 def getActivityByDayOfWeek(self):
594 return self.activity_by_day_of_week
596 def getActivityByHourOfDay(self):
597 return self.activity_by_hour_of_day
599 def getAuthorInfo(self, author):
600 return self.authors[author]
602 def getAuthors(self, limit = None):
603 res = getkeyssortedbyvaluekey(self.authors, 'commits')
604 res.reverse()
605 return res[:limit]
607 def getCommitDeltaDays(self):
608 return (self.last_commit_stamp / 86400 - self.first_commit_stamp / 86400) + 1
610 def getDomainInfo(self, domain):
611 return self.domains[domain]
613 def getDomains(self):
614 return self.domains.keys()
616 def getFilesInCommit(self, rev):
617 try:
618 res = self.cache['files_in_tree'][rev]
619 except:
620 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
621 if 'files_in_tree' not in self.cache:
622 self.cache['files_in_tree'] = {}
623 self.cache['files_in_tree'][rev] = res
625 return res
627 def getFirstCommitDate(self):
628 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
630 def getLastCommitDate(self):
631 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
633 def getLinesInBlob(self, sha1):
634 try:
635 res = self.cache['lines_in_blob'][sha1]
636 except:
637 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
638 if 'lines_in_blob' not in self.cache:
639 self.cache['lines_in_blob'] = {}
640 self.cache['lines_in_blob'][sha1] = res
641 return res
643 def getTags(self):
644 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
645 return lines.split('\n')
647 def getTagDate(self, tag):
648 return self.revToDate('tags/' + tag)
650 def getTotalAuthors(self):
651 return self.total_authors
653 def getTotalCommits(self):
654 return self.total_commits
656 def getTotalFiles(self):
657 return self.total_files
659 def getTotalLOC(self):
660 return self.total_lines
662 def getTotalSize(self):
663 return self.total_size
665 def revToDate(self, rev):
666 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
667 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
669 class ReportCreator:
670 """Creates the actual report based on given data."""
671 def __init__(self):
672 pass
674 def create(self, data, path):
675 self.data = data
676 self.path = path
678 def html_linkify(text):
679 return text.lower().replace(' ', '_')
681 def html_header(level, text):
682 name = html_linkify(text)
683 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
685 class HTMLReportCreator(ReportCreator):
686 def create(self, data, path):
687 ReportCreator.create(self, data, path)
688 self.title = data.projectname
690 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
691 binarypath = os.path.dirname(os.path.abspath(__file__))
692 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
693 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
694 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
695 for base in basedirs:
696 src = base + '/' + file
697 if os.path.exists(src):
698 shutil.copyfile(src, path + '/' + file)
699 break
700 else:
701 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
703 f = open(path + "/index.html", 'w')
704 format = '%Y-%m-%d %H:%M:%S'
705 self.printHeader(f)
707 f.write('<h1>GitStats - %s</h1>' % data.projectname)
709 self.printNav(f)
711 f.write('<dl>')
712 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
713 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
714 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
715 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
716 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())))
717 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
718 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))
719 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()))
720 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
721 f.write('</dl>')
723 f.write('</body>\n</html>')
724 f.close()
727 # Activity
728 f = open(path + '/activity.html', 'w')
729 self.printHeader(f)
730 f.write('<h1>Activity</h1>')
731 self.printNav(f)
733 #f.write('<h2>Last 30 days</h2>')
735 #f.write('<h2>Last 12 months</h2>')
737 # Weekly activity
738 WEEKS = 32
739 f.write(html_header(2, 'Weekly activity'))
740 f.write('<p>Last %d weeks</p>' % WEEKS)
742 # generate weeks to show (previous N weeks from now)
743 now = datetime.datetime.now()
744 deltaweek = datetime.timedelta(7)
745 weeks = []
746 stampcur = now
747 for i in range(0, WEEKS):
748 weeks.insert(0, stampcur.strftime('%Y-%W'))
749 stampcur -= deltaweek
751 # top row: commits & bar
752 f.write('<table class="noborders"><tr>')
753 for i in range(0, WEEKS):
754 commits = 0
755 if weeks[i] in data.activity_by_year_week:
756 commits = data.activity_by_year_week[weeks[i]]
758 percentage = 0
759 if weeks[i] in data.activity_by_year_week:
760 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
761 height = max(1, int(200 * percentage))
762 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))
764 # bottom row: year/week
765 f.write('</tr><tr>')
766 for i in range(0, WEEKS):
767 f.write('<td>%s</td>' % (WEEKS - i))
768 f.write('</tr></table>')
770 # Hour of Day
771 f.write(html_header(2, 'Hour of Day'))
772 hour_of_day = data.getActivityByHourOfDay()
773 f.write('<table><tr><th>Hour</th>')
774 for i in range(0, 24):
775 f.write('<th>%d</th>' % i)
776 f.write('</tr>\n<tr><th>Commits</th>')
777 fp = open(path + '/hour_of_day.dat', 'w')
778 for i in range(0, 24):
779 if i in hour_of_day:
780 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
781 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
782 fp.write('%d %d\n' % (i, hour_of_day[i]))
783 else:
784 f.write('<td>0</td>')
785 fp.write('%d 0\n' % i)
786 fp.close()
787 f.write('</tr>\n<tr><th>%</th>')
788 totalcommits = data.getTotalCommits()
789 for i in range(0, 24):
790 if i in hour_of_day:
791 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
792 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
793 else:
794 f.write('<td>0.00</td>')
795 f.write('</tr></table>')
796 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
797 fg = open(path + '/hour_of_day.dat', 'w')
798 for i in range(0, 24):
799 if i in hour_of_day:
800 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
801 else:
802 fg.write('%d 0\n' % (i + 1))
803 fg.close()
805 # Day of Week
806 f.write(html_header(2, 'Day of Week'))
807 day_of_week = data.getActivityByDayOfWeek()
808 f.write('<div class="vtable"><table>')
809 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
810 fp = open(path + '/day_of_week.dat', 'w')
811 for d in range(0, 7):
812 commits = 0
813 if d in day_of_week:
814 commits = day_of_week[d]
815 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
816 f.write('<tr>')
817 f.write('<th>%s</th>' % (WEEKDAYS[d]))
818 if d in day_of_week:
819 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
820 else:
821 f.write('<td>0</td>')
822 f.write('</tr>')
823 f.write('</table></div>')
824 f.write('<img src="day_of_week.png" alt="Day of Week" />')
825 fp.close()
827 # Hour of Week
828 f.write(html_header(2, 'Hour of Week'))
829 f.write('<table>')
831 f.write('<tr><th>Weekday</th>')
832 for hour in range(0, 24):
833 f.write('<th>%d</th>' % (hour))
834 f.write('</tr>')
836 for weekday in range(0, 7):
837 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
838 for hour in range(0, 24):
839 try:
840 commits = data.activity_by_hour_of_week[weekday][hour]
841 except KeyError:
842 commits = 0
843 if commits != 0:
844 f.write('<td')
845 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
846 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
847 f.write('>%d</td>' % commits)
848 else:
849 f.write('<td></td>')
850 f.write('</tr>')
852 f.write('</table>')
854 # Month of Year
855 f.write(html_header(2, 'Month of Year'))
856 f.write('<div class="vtable"><table>')
857 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
858 fp = open (path + '/month_of_year.dat', 'w')
859 for mm in range(1, 13):
860 commits = 0
861 if mm in data.activity_by_month_of_year:
862 commits = data.activity_by_month_of_year[mm]
863 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
864 fp.write('%d %d\n' % (mm, commits))
865 fp.close()
866 f.write('</table></div>')
867 f.write('<img src="month_of_year.png" alt="Month of Year" />')
869 # Commits by year/month
870 f.write(html_header(2, 'Commits by year/month'))
871 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th><th>Lines added</th><th>Lines removed</th></tr>')
872 for yymm in reversed(sorted(data.commits_by_month.keys())):
873 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)))
874 f.write('</table></div>')
875 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
876 fg = open(path + '/commits_by_year_month.dat', 'w')
877 for yymm in sorted(data.commits_by_month.keys()):
878 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
879 fg.close()
881 # Commits by year
882 f.write(html_header(2, 'Commits by Year'))
883 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th><th>Lines added</th><th>Lines removed</th></tr>')
884 for yy in reversed(sorted(data.commits_by_year.keys())):
885 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)))
886 f.write('</table></div>')
887 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
888 fg = open(path + '/commits_by_year.dat', 'w')
889 for yy in sorted(data.commits_by_year.keys()):
890 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
891 fg.close()
893 # Commits by timezone
894 f.write(html_header(2, 'Commits by Timezone'))
895 f.write('<table><tr>')
896 f.write('<th>Timezone</th><th>Commits</th>')
897 max_commits_on_tz = max(data.commits_by_timezone.values())
898 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
899 commits = data.commits_by_timezone[i]
900 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
901 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
902 f.write('</tr></table>')
904 f.write('</body></html>')
905 f.close()
908 # Authors
909 f = open(path + '/authors.html', 'w')
910 self.printHeader(f)
912 f.write('<h1>Authors</h1>')
913 self.printNav(f)
915 # Authors :: List of authors
916 f.write(html_header(2, 'List of Authors'))
918 f.write('<table class="authors sortable" id="authors">')
919 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>')
920 for author in data.getAuthors(conf['max_authors']):
921 info = data.getAuthorInfo(author)
922 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']))
923 f.write('</table>')
925 allauthors = data.getAuthors()
926 if len(allauthors) > conf['max_authors']:
927 rest = allauthors[conf['max_authors']:]
928 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
930 f.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
931 f.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
932 if len(allauthors) > conf['max_authors']:
933 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
935 f.write(html_header(2, 'Commits per Author'))
936 f.write('<img src="commits_by_author.png" alt="Commits per Author" />')
937 if len(allauthors) > conf['max_authors']:
938 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
940 fgl = open(path + '/lines_of_code_by_author.dat', 'w')
941 fgc = open(path + '/commits_by_author.dat', 'w')
943 lines_by_authors = {} # cumulated added lines by
944 # author. to save memory,
945 # changes_by_date_by_author[stamp][author] is defined
946 # only at points where author commits.
947 # lines_by_authors allows us to generate all the
948 # points in the .dat file.
950 # Don't rely on getAuthors to give the same order each
951 # time. Be robust and keep the list in a variable.
952 commits_by_authors = {} # cumulated added lines by
954 self.authors_to_plot = data.getAuthors(conf['max_authors'])
955 for author in self.authors_to_plot:
956 lines_by_authors[author] = 0
957 commits_by_authors[author] = 0
958 for stamp in sorted(data.changes_by_date_by_author.keys()):
959 fgl.write('%d' % stamp)
960 fgc.write('%d' % stamp)
961 for author in self.authors_to_plot:
962 if author in data.changes_by_date_by_author[stamp].keys():
963 lines_by_authors[author] = data.changes_by_date_by_author[stamp][author]['lines_added']
964 commits_by_authors[author] = data.changes_by_date_by_author[stamp][author]['commits']
965 fgl.write(' %d' % lines_by_authors[author])
966 fgc.write(' %d' % commits_by_authors[author])
967 fgl.write('\n')
968 fgc.write('\n')
969 fgl.close()
970 fgc.close()
972 # Authors :: Author of Month
973 f.write(html_header(2, 'Author of Month'))
974 f.write('<table class="sortable" id="aom">')
975 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'])
976 for yymm in reversed(sorted(data.author_of_month.keys())):
977 authordict = data.author_of_month[yymm]
978 authors = getkeyssortedbyvalues(authordict)
979 authors.reverse()
980 commits = data.author_of_month[yymm][authors[0]]
981 next = ', '.join(authors[1:conf['authors_top']+1])
982 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)))
984 f.write('</table>')
986 f.write(html_header(2, 'Author of Year'))
987 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'])
988 for yy in reversed(sorted(data.author_of_year.keys())):
989 authordict = data.author_of_year[yy]
990 authors = getkeyssortedbyvalues(authordict)
991 authors.reverse()
992 commits = data.author_of_year[yy][authors[0]]
993 next = ', '.join(authors[1:conf['authors_top']+1])
994 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)))
995 f.write('</table>')
997 # Domains
998 f.write(html_header(2, 'Commits by Domains'))
999 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
1000 domains_by_commits.reverse() # most first
1001 f.write('<div class="vtable"><table>')
1002 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
1003 fp = open(path + '/domains.dat', 'w')
1004 n = 0
1005 for domain in domains_by_commits:
1006 if n == conf['max_domains']:
1007 break
1008 commits = 0
1009 n += 1
1010 info = data.getDomainInfo(domain)
1011 fp.write('%s %d %d\n' % (domain, n , info['commits']))
1012 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
1013 f.write('</table></div>')
1014 f.write('<img src="domains.png" alt="Commits by Domains" />')
1015 fp.close()
1017 f.write('</body></html>')
1018 f.close()
1021 # Files
1022 f = open(path + '/files.html', 'w')
1023 self.printHeader(f)
1024 f.write('<h1>Files</h1>')
1025 self.printNav(f)
1027 f.write('<dl>\n')
1028 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
1029 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1030 try:
1031 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % (float(data.getTotalSize()) / data.getTotalFiles()))
1032 except ZeroDivisionError:
1033 pass
1034 f.write('</dl>\n')
1036 # Files :: File count by date
1037 f.write(html_header(2, 'File count by date'))
1039 # use set to get rid of duplicate/unnecessary entries
1040 files_by_date = set()
1041 for stamp in sorted(data.files_by_stamp.keys()):
1042 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1044 fg = open(path + '/files_by_date.dat', 'w')
1045 for line in sorted(list(files_by_date)):
1046 fg.write('%s\n' % line)
1047 #for stamp in sorted(data.files_by_stamp.keys()):
1048 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1049 fg.close()
1051 f.write('<img src="files_by_date.png" alt="Files by Date" />')
1053 #f.write('<h2>Average file size by date</h2>')
1055 # Files :: Extensions
1056 f.write(html_header(2, 'Extensions'))
1057 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
1058 for ext in sorted(data.extensions.keys()):
1059 files = data.extensions[ext]['files']
1060 lines = data.extensions[ext]['lines']
1061 try:
1062 loc_percentage = (100.0 * lines) / data.getTotalLOC()
1063 except ZeroDivisionError:
1064 loc_percentage = 0
1065 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))
1066 f.write('</table>')
1068 f.write('</body></html>')
1069 f.close()
1072 # Lines
1073 f = open(path + '/lines.html', 'w')
1074 self.printHeader(f)
1075 f.write('<h1>Lines</h1>')
1076 self.printNav(f)
1078 f.write('<dl>\n')
1079 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1080 f.write('</dl>\n')
1082 f.write(html_header(2, 'Lines of Code'))
1083 f.write('<img src="lines_of_code.png" />')
1085 fg = open(path + '/lines_of_code.dat', 'w')
1086 for stamp in sorted(data.changes_by_date.keys()):
1087 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
1088 fg.close()
1090 f.write('</body></html>')
1091 f.close()
1094 # tags.html
1095 f = open(path + '/tags.html', 'w')
1096 self.printHeader(f)
1097 f.write('<h1>Tags</h1>')
1098 self.printNav(f)
1100 f.write('<dl>')
1101 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
1102 if len(data.tags) > 0:
1103 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
1104 f.write('</dl>')
1106 f.write('<table class="tags">')
1107 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1108 # sort the tags by date desc
1109 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
1110 for tag in tags_sorted_by_date_desc:
1111 authorinfo = []
1112 self.authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
1113 for i in reversed(self.authors_by_commits):
1114 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
1115 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)))
1116 f.write('</table>')
1118 f.write('</body></html>')
1119 f.close()
1121 self.createGraphs(path)
1123 def createGraphs(self, path):
1124 print 'Generating graphs...'
1126 # hour of day
1127 f = open(path + '/hour_of_day.plot', 'w')
1128 f.write(GNUPLOT_COMMON)
1129 f.write(
1131 set output 'hour_of_day.png'
1132 unset key
1133 set xrange [0.5:24.5]
1134 set xtics 4
1135 set grid y
1136 set ylabel "Commits"
1137 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1138 """)
1139 f.close()
1141 # day of week
1142 f = open(path + '/day_of_week.plot', 'w')
1143 f.write(GNUPLOT_COMMON)
1144 f.write(
1146 set output 'day_of_week.png'
1147 unset key
1148 set xrange [0.5:7.5]
1149 set xtics 1
1150 set grid y
1151 set ylabel "Commits"
1152 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1153 """)
1154 f.close()
1156 # Domains
1157 f = open(path + '/domains.plot', 'w')
1158 f.write(GNUPLOT_COMMON)
1159 f.write(
1161 set output 'domains.png'
1162 unset key
1163 unset xtics
1164 set yrange [0:]
1165 set grid y
1166 set ylabel "Commits"
1167 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1168 """)
1169 f.close()
1171 # Month of Year
1172 f = open(path + '/month_of_year.plot', 'w')
1173 f.write(GNUPLOT_COMMON)
1174 f.write(
1176 set output 'month_of_year.png'
1177 unset key
1178 set xrange [0.5:12.5]
1179 set xtics 1
1180 set grid y
1181 set ylabel "Commits"
1182 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1183 """)
1184 f.close()
1186 # commits_by_year_month
1187 f = open(path + '/commits_by_year_month.plot', 'w')
1188 f.write(GNUPLOT_COMMON)
1189 f.write(
1191 set output 'commits_by_year_month.png'
1192 unset key
1193 set xdata time
1194 set timefmt "%Y-%m"
1195 set format x "%Y-%m"
1196 set xtics rotate
1197 set bmargin 5
1198 set grid y
1199 set ylabel "Commits"
1200 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1201 """)
1202 f.close()
1204 # commits_by_year
1205 f = open(path + '/commits_by_year.plot', 'w')
1206 f.write(GNUPLOT_COMMON)
1207 f.write(
1209 set output 'commits_by_year.png'
1210 unset key
1211 set xtics 1 rotate
1212 set grid y
1213 set ylabel "Commits"
1214 set yrange [0:]
1215 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1216 """)
1217 f.close()
1219 # Files by date
1220 f = open(path + '/files_by_date.plot', 'w')
1221 f.write(GNUPLOT_COMMON)
1222 f.write(
1224 set output 'files_by_date.png'
1225 unset key
1226 set xdata time
1227 set timefmt "%Y-%m-%d"
1228 set format x "%Y-%m-%d"
1229 set grid y
1230 set ylabel "Files"
1231 set xtics rotate
1232 set ytics autofreq
1233 set bmargin 6
1234 plot 'files_by_date.dat' using 1:2 w steps
1235 """)
1236 f.close()
1238 # Lines of Code
1239 f = open(path + '/lines_of_code.plot', 'w')
1240 f.write(GNUPLOT_COMMON)
1241 f.write(
1243 set output 'lines_of_code.png'
1244 unset key
1245 set xdata time
1246 set timefmt "%s"
1247 set format x "%Y-%m-%d"
1248 set grid y
1249 set ylabel "Lines"
1250 set xtics rotate
1251 set bmargin 6
1252 plot 'lines_of_code.dat' using 1:2 w lines
1253 """)
1254 f.close()
1256 # Lines of Code Added per author
1257 f = open(path + '/lines_of_code_by_author.plot', 'w')
1258 f.write(GNUPLOT_COMMON)
1259 f.write(
1261 set terminal png transparent size 640,480
1262 set output 'lines_of_code_by_author.png'
1263 set key left top
1264 set xdata time
1265 set timefmt "%s"
1266 set format x "%Y-%m-%d"
1267 set grid y
1268 set ylabel "Lines"
1269 set xtics rotate
1270 set bmargin 6
1271 plot """
1273 i = 1
1274 plots = []
1275 for a in self.authors_to_plot:
1276 i = i + 1
1277 plots.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1278 f.write(", ".join(plots))
1279 f.write('\n')
1281 f.close()
1283 # Commits per author
1284 f = open(path + '/commits_by_author.plot', 'w')
1285 f.write(GNUPLOT_COMMON)
1286 f.write(
1288 set terminal png transparent size 640,480
1289 set output 'commits_by_author.png'
1290 set key left top
1291 set xdata time
1292 set timefmt "%s"
1293 set format x "%Y-%m-%d"
1294 set grid y
1295 set ylabel "Commits"
1296 set xtics rotate
1297 set bmargin 6
1298 plot """
1300 i = 1
1301 plots = []
1302 for a in self.authors_to_plot:
1303 i = i + 1
1304 plots.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1305 f.write(", ".join(plots))
1306 f.write('\n')
1308 f.close()
1310 os.chdir(path)
1311 files = glob.glob(path + '/*.plot')
1312 for f in files:
1313 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1314 if len(out) > 0:
1315 print out
1317 def printHeader(self, f, title = ''):
1318 f.write(
1319 """<?xml version="1.0" encoding="UTF-8"?>
1320 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1321 <html xmlns="http://www.w3.org/1999/xhtml">
1322 <head>
1323 <title>GitStats - %s</title>
1324 <link rel="stylesheet" href="%s" type="text/css" />
1325 <meta name="generator" content="GitStats %s" />
1326 <script type="text/javascript" src="sortable.js"></script>
1327 </head>
1328 <body>
1329 """ % (self.title, conf['style'], getversion()))
1331 def printNav(self, f):
1332 f.write("""
1333 <div class="nav">
1334 <ul>
1335 <li><a href="index.html">General</a></li>
1336 <li><a href="activity.html">Activity</a></li>
1337 <li><a href="authors.html">Authors</a></li>
1338 <li><a href="files.html">Files</a></li>
1339 <li><a href="lines.html">Lines</a></li>
1340 <li><a href="tags.html">Tags</a></li>
1341 </ul>
1342 </div>
1343 """)
1346 class GitStats:
1347 def run(self, args_orig):
1348 optlist, args = getopt.getopt(args_orig, 'c:')
1349 for o,v in optlist:
1350 if o == '-c':
1351 key, value = v.split('=', 1)
1352 if key not in conf:
1353 raise KeyError('no such key "%s" in config' % key)
1354 if isinstance(conf[key], int):
1355 conf[key] = int(value)
1356 elif isinstance(conf[key], dict):
1357 kk,vv = value.split(',', 1)
1358 conf[key][kk] = vv
1359 else:
1360 conf[key] = value
1362 if len(args) < 2:
1363 print """
1364 Usage: gitstats [options] <gitpath..> <outputpath>
1366 Options:
1367 -c key=value Override configuration value
1369 Default config values:
1371 """ % conf
1372 sys.exit(0)
1374 outputpath = os.path.abspath(args[-1])
1375 rundir = os.getcwd()
1377 try:
1378 os.makedirs(outputpath)
1379 except OSError:
1380 pass
1381 if not os.path.isdir(outputpath):
1382 print 'FATAL: Output path is not a directory or does not exist'
1383 sys.exit(1)
1385 if not getgnuplotversion():
1386 print 'gnuplot not found'
1387 sys.exit(1)
1389 print 'Output path: %s' % outputpath
1390 cachefile = os.path.join(outputpath, 'gitstats.cache')
1392 data = GitDataCollector()
1393 data.loadCache(cachefile)
1395 for gitpath in args[0:-1]:
1396 print 'Git path: %s' % gitpath
1398 os.chdir(gitpath)
1400 print 'Collecting data...'
1401 data.collect(gitpath)
1403 print 'Refining data...'
1404 data.saveCache(cachefile)
1405 data.refine()
1407 os.chdir(rundir)
1409 print 'Generating report...'
1410 report = HTMLReportCreator()
1411 report.create(data, outputpath)
1413 time_end = time.time()
1414 exectime_internal = time_end - time_start
1415 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1416 if sys.stdin.isatty():
1417 print 'You may now run:'
1418 print
1419 print ' sensible-browser \'%s\'' % os.path.join(outputpath, 'index.html').replace("'", "'\\''")
1420 print
1422 if __name__=='__main__':
1423 g = GitStats()
1424 g.run(sys.argv[1:])