Parse git's diff stat summary more flexibly.
[gitstats.git] / gitstats
blob51fe8a9acb304acdf8e29b8106a40724b990ff70
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2011 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
3 # GPLv2 / GPLv3
4 import datetime
5 import getopt
6 import glob
7 import os
8 import pickle
9 import platform
10 import re
11 import shutil
12 import subprocess
13 import sys
14 import time
15 import zlib
17 GNUPLOT_COMMON = 'set terminal png transparent size 640,240\nset size 1.0,1.0\n'
18 ON_LINUX = (platform.system() == 'Linux')
19 WEEKDAYS = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
21 exectime_internal = 0.0
22 exectime_external = 0.0
23 time_start = time.time()
25 # By default, gnuplot is searched from path, but can be overridden with the
26 # environment variable "GNUPLOT"
27 gnuplot_cmd = 'gnuplot'
28 if 'GNUPLOT' in os.environ:
29 gnuplot_cmd = os.environ['GNUPLOT']
31 conf = {
32 'max_domains': 10,
33 'max_ext_length': 10,
34 'style': 'gitstats.css',
35 'max_authors': 20,
36 'authors_top': 5,
37 'commit_begin': '',
38 'commit_end': 'HEAD',
39 'linear_linestats': 1,
40 'project_name': '',
43 def getpipeoutput(cmds, quiet = False):
44 global exectime_external
45 start = time.time()
46 if not quiet and ON_LINUX and os.isatty(1):
47 print '>> ' + ' | '.join(cmds),
48 sys.stdout.flush()
49 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
50 p = p0
51 for x in cmds[1:]:
52 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
53 p0 = p
54 output = p.communicate()[0]
55 end = time.time()
56 if not quiet:
57 if ON_LINUX and os.isatty(1):
58 print '\r',
59 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
60 exectime_external += (end - start)
61 return output.rstrip('\n')
63 def getcommitrange(defaultrange = 'HEAD', end_only = False):
64 if len(conf['commit_end']) > 0:
65 if end_only or len(conf['commit_begin']) == 0:
66 return conf['commit_end']
67 return '%s..%s' % (conf['commit_begin'], conf['commit_end'])
68 return defaultrange
70 def getkeyssortedbyvalues(dict):
71 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
73 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
74 def getkeyssortedbyvaluekey(d, key):
75 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
77 def getstatsummarycounts(line):
78 numbers = re.findall('\d+', line)
79 if len(numbers) == 1:
80 # neither insertions nor deletions: may probably only happen for "0 files changed"
81 numbers.append(0);
82 numbers.append(0);
83 elif len(numbers) == 2 and line.find('(+)') != -1:
84 numbers.append(0); # only insertions were printed on line
85 elif len(numbers) == 2 and line.find('(-)') != -1:
86 numbers.insert(1, 0); # only deletions were printed on line
87 return numbers
89 VERSION = 0
90 def getversion():
91 global VERSION
92 if VERSION == 0:
93 VERSION = getpipeoutput(["git rev-parse --short %s" % getcommitrange('HEAD')]).split('\n')[0]
94 return VERSION
96 def getgitversion():
97 return getpipeoutput(['git --version']).split('\n')[0]
99 def getgnuplotversion():
100 return getpipeoutput(['gnuplot --version']).split('\n')[0]
102 class DataCollector:
103 """Manages data collection from a revision control repository."""
104 def __init__(self):
105 self.stamp_created = time.time()
106 self.cache = {}
107 self.total_authors = 0
108 self.activity_by_hour_of_day = {} # hour -> commits
109 self.activity_by_day_of_week = {} # day -> commits
110 self.activity_by_month_of_year = {} # month [1-12] -> commits
111 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
112 self.activity_by_hour_of_day_busiest = 0
113 self.activity_by_hour_of_week_busiest = 0
114 self.activity_by_year_week = {} # yy_wNN -> commits
115 self.activity_by_year_week_peak = 0
117 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
119 self.total_commits = 0
120 self.total_files = 0
121 self.authors_by_commits = 0
123 # domains
124 self.domains = {} # domain -> commits
126 # author of the month
127 self.author_of_month = {} # month -> author -> commits
128 self.author_of_year = {} # year -> author -> commits
129 self.commits_by_month = {} # month -> commits
130 self.commits_by_year = {} # year -> commits
131 self.lines_added_by_month = {} # month -> lines added
132 self.lines_added_by_year = {} # year -> lines added
133 self.lines_removed_by_month = {} # month -> lines removed
134 self.lines_removed_by_year = {} # year -> lines removed
135 self.first_commit_stamp = 0
136 self.last_commit_stamp = 0
137 self.last_active_day = None
138 self.active_days = set()
140 # lines
141 self.total_lines = 0
142 self.total_lines_added = 0
143 self.total_lines_removed = 0
145 # size
146 self.total_size = 0
148 # timezone
149 self.commits_by_timezone = {} # timezone -> commits
151 # tags
152 self.tags = {}
154 self.files_by_stamp = {} # stamp -> files
156 # extensions
157 self.extensions = {} # extension -> files, lines
159 # line statistics
160 self.changes_by_date = {} # stamp -> { files, ins, del }
163 # This should be the main function to extract data from the repository.
164 def collect(self, dir):
165 self.dir = dir
166 if len(conf['project_name']) == 0:
167 self.projectname = os.path.basename(os.path.abspath(dir))
168 else:
169 self.projectname = conf['project_name']
172 # Load cacheable data
173 def loadCache(self, cachefile):
174 if not os.path.exists(cachefile):
175 return
176 print 'Loading cache...'
177 f = open(cachefile, 'rb')
178 try:
179 self.cache = pickle.loads(zlib.decompress(f.read()))
180 except:
181 # temporary hack to upgrade non-compressed caches
182 f.seek(0)
183 self.cache = pickle.load(f)
184 f.close()
187 # Produce any additional statistics from the extracted data.
188 def refine(self):
189 pass
192 # : get a dictionary of author
193 def getAuthorInfo(self, author):
194 return None
196 def getActivityByDayOfWeek(self):
197 return {}
199 def getActivityByHourOfDay(self):
200 return {}
202 # : get a dictionary of domains
203 def getDomainInfo(self, domain):
204 return None
207 # Get a list of authors
208 def getAuthors(self):
209 return []
211 def getFirstCommitDate(self):
212 return datetime.datetime.now()
214 def getLastCommitDate(self):
215 return datetime.datetime.now()
217 def getStampCreated(self):
218 return self.stamp_created
220 def getTags(self):
221 return []
223 def getTotalAuthors(self):
224 return -1
226 def getTotalCommits(self):
227 return -1
229 def getTotalFiles(self):
230 return -1
232 def getTotalLOC(self):
233 return -1
236 # Save cacheable data
237 def saveCache(self, cachefile):
238 print 'Saving cache...'
239 f = open(cachefile, 'wb')
240 #pickle.dump(self.cache, f)
241 data = zlib.compress(pickle.dumps(self.cache))
242 f.write(data)
243 f.close()
245 class GitDataCollector(DataCollector):
246 def collect(self, dir):
247 DataCollector.collect(self, dir)
249 try:
250 self.total_authors += int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
251 except:
252 self.total_authors = 0
253 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
255 # tags
256 lines = getpipeoutput(['git show-ref --tags']).split('\n')
257 for line in lines:
258 if len(line) == 0:
259 continue
260 (hash, tag) = line.split(' ')
262 tag = tag.replace('refs/tags/', '')
263 output = getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
264 if len(output) > 0:
265 parts = output.split(' ')
266 stamp = 0
267 try:
268 stamp = int(parts[0])
269 except ValueError:
270 stamp = 0
271 self.tags[tag] = { 'stamp': stamp, 'hash' : hash, 'date' : datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
273 # collect info on tags, starting from latest
274 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), self.tags.items()))))
275 prev = None
276 for tag in reversed(tags_sorted_by_date_desc):
277 cmd = 'git shortlog -s "%s"' % tag
278 if prev != None:
279 cmd += ' "^%s"' % prev
280 output = getpipeoutput([cmd])
281 if len(output) == 0:
282 continue
283 prev = tag
284 for line in output.split('\n'):
285 parts = re.split('\s+', line, 2)
286 commits = int(parts[1])
287 author = parts[2]
288 self.tags[tag]['commits'] += commits
289 self.tags[tag]['authors'][author] = commits
291 # Collect revision statistics
292 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
293 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
294 for line in lines:
295 parts = line.split(' ', 4)
296 author = ''
297 try:
298 stamp = int(parts[0])
299 except ValueError:
300 stamp = 0
301 timezone = parts[3]
302 author, mail = parts[4].split('<', 1)
303 author = author.rstrip()
304 mail = mail.rstrip('>')
305 domain = '?'
306 if mail.find('@') != -1:
307 domain = mail.rsplit('@', 1)[1]
308 date = datetime.datetime.fromtimestamp(float(stamp))
310 # First and last commit stamp (may be in any order because of cherry-picking and patches)
311 if stamp > self.last_commit_stamp:
312 self.last_commit_stamp = stamp
313 if self.first_commit_stamp == 0 or stamp < self.first_commit_stamp:
314 self.first_commit_stamp = stamp
316 # activity
317 # hour
318 hour = date.hour
319 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
320 # most active hour?
321 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
322 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
324 # day of week
325 day = date.weekday()
326 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
328 # domain stats
329 if domain not in self.domains:
330 self.domains[domain] = {}
331 # commits
332 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
334 # hour of week
335 if day not in self.activity_by_hour_of_week:
336 self.activity_by_hour_of_week[day] = {}
337 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
338 # most active hour?
339 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
340 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
342 # month of year
343 month = date.month
344 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
346 # yearly/weekly activity
347 yyw = date.strftime('%Y-%W')
348 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
349 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
350 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
352 # author stats
353 if author not in self.authors:
354 self.authors[author] = {}
355 # commits, note again that commits may be in any date order because of cherry-picking and patches
356 if 'last_commit_stamp' not in self.authors[author]:
357 self.authors[author]['last_commit_stamp'] = stamp
358 if stamp > self.authors[author]['last_commit_stamp']:
359 self.authors[author]['last_commit_stamp'] = stamp
360 if 'first_commit_stamp' not in self.authors[author]:
361 self.authors[author]['first_commit_stamp'] = stamp
362 if stamp < self.authors[author]['first_commit_stamp']:
363 self.authors[author]['first_commit_stamp'] = stamp
365 # author of the month/year
366 yymm = date.strftime('%Y-%m')
367 if yymm in self.author_of_month:
368 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
369 else:
370 self.author_of_month[yymm] = {}
371 self.author_of_month[yymm][author] = 1
372 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
374 yy = date.year
375 if yy in self.author_of_year:
376 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
377 else:
378 self.author_of_year[yy] = {}
379 self.author_of_year[yy][author] = 1
380 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
382 # authors: active days
383 yymmdd = date.strftime('%Y-%m-%d')
384 if 'last_active_day' not in self.authors[author]:
385 self.authors[author]['last_active_day'] = yymmdd
386 self.authors[author]['active_days'] = set([yymmdd])
387 elif yymmdd != self.authors[author]['last_active_day']:
388 self.authors[author]['last_active_day'] = yymmdd
389 self.authors[author]['active_days'].add(yymmdd)
391 # project: active days
392 if yymmdd != self.last_active_day:
393 self.last_active_day = yymmdd
394 self.active_days.add(yymmdd)
396 # timezone
397 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
399 # TODO Optimize this, it's the worst bottleneck
400 # outputs "<stamp> <files>" for each revision
401 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
402 lines = []
403 for revline in revlines:
404 time, rev = revline.split(' ')
405 linecount = self.getFilesInCommit(rev)
406 lines.append('%d %d' % (int(time), linecount))
408 self.total_commits += len(lines)
409 for line in lines:
410 parts = line.split(' ')
411 if len(parts) != 2:
412 continue
413 (stamp, files) = parts[0:2]
414 try:
415 self.files_by_stamp[int(stamp)] = int(files)
416 except ValueError:
417 print 'Warning: failed to parse line "%s"' % line
419 # extensions and size of files
420 lines = getpipeoutput(['git ls-tree -r -l -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
421 for line in lines:
422 if len(line) == 0:
423 continue
424 parts = re.split('\s+', line, 5)
425 if parts[0] == '160000' and parts[3] == '-':
426 # skip submodules
427 continue
428 sha1 = parts[2]
429 size = int(parts[3])
430 fullpath = parts[4]
432 self.total_size += size
433 self.total_files += 1
435 filename = fullpath.split('/')[-1] # strip directories
436 if filename.find('.') == -1 or filename.rfind('.') == 0:
437 ext = ''
438 else:
439 ext = filename[(filename.rfind('.') + 1):]
440 if len(ext) > conf['max_ext_length']:
441 ext = ''
443 if ext not in self.extensions:
444 self.extensions[ext] = {'files': 0, 'lines': 0}
446 self.extensions[ext]['files'] += 1
447 try:
448 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
449 except:
450 print 'Warning: Could not count lines for file "%s"' % line
452 # line statistics
453 # outputs:
454 # N files changed, N insertions (+), N deletions(-)
455 # <stamp> <author>
456 self.changes_by_date = {} # stamp -> { files, ins, del }
457 # computation of lines of code by date is better done
458 # on a linear history.
459 extra = ''
460 if conf['linear_linestats']:
461 extra = '--first-parent -m'
462 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
463 lines.reverse()
464 files = 0; inserted = 0; deleted = 0; total_lines = 0
465 author = None
466 for line in lines:
467 if len(line) == 0:
468 continue
470 # <stamp> <author>
471 if re.search('files? changed', line) == None:
472 pos = line.find(' ')
473 if pos != -1:
474 try:
475 (stamp, author) = (int(line[:pos]), line[pos+1:])
476 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
478 date = datetime.datetime.fromtimestamp(stamp)
479 yymm = date.strftime('%Y-%m')
480 self.lines_added_by_month[yymm] = self.lines_added_by_month.get(yymm, 0) + inserted
481 self.lines_removed_by_month[yymm] = self.lines_removed_by_month.get(yymm, 0) + deleted
483 yy = date.year
484 self.lines_added_by_year[yy] = self.lines_added_by_year.get(yy,0) + inserted
485 self.lines_removed_by_year[yy] = self.lines_removed_by_year.get(yy, 0) + deleted
487 files, inserted, deleted = 0, 0, 0
488 except ValueError:
489 print 'Warning: unexpected line "%s"' % line
490 else:
491 print 'Warning: unexpected line "%s"' % line
492 else:
493 numbers = getstatsummarycounts(line)
495 if len(numbers) == 3:
496 (files, inserted, deleted) = map(lambda el : int(el), numbers)
497 total_lines += inserted
498 total_lines -= deleted
499 self.total_lines_added += inserted
500 self.total_lines_removed += deleted
502 else:
503 print 'Warning: failed to handle line "%s"' % line
504 (files, inserted, deleted) = (0, 0, 0)
505 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
506 self.total_lines = total_lines
508 # Per-author statistics
510 # defined for stamp, author only if author commited at this timestamp.
511 self.changes_by_date_by_author = {} # stamp -> author -> lines_added
513 # Similar to the above, but never use --first-parent
514 # (we need to walk through every commit to know who
515 # committed what, not just through mainline)
516 lines = getpipeoutput(['git log --shortstat --date-order --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
517 lines.reverse()
518 files = 0; inserted = 0; deleted = 0
519 author = None
520 stamp = 0
521 for line in lines:
522 if len(line) == 0:
523 continue
525 # <stamp> <author>
526 if re.search('files? changed', line) == None:
527 pos = line.find(' ')
528 if pos != -1:
529 try:
530 oldstamp = stamp
531 (stamp, author) = (int(line[:pos]), line[pos+1:])
532 if oldstamp > stamp:
533 # clock skew, keep old timestamp to avoid having ugly graph
534 stamp = oldstamp
535 if author not in self.authors:
536 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
537 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
538 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
539 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
540 if stamp not in self.changes_by_date_by_author:
541 self.changes_by_date_by_author[stamp] = {}
542 if author not in self.changes_by_date_by_author[stamp]:
543 self.changes_by_date_by_author[stamp][author] = {}
544 self.changes_by_date_by_author[stamp][author]['lines_added'] = self.authors[author]['lines_added']
545 self.changes_by_date_by_author[stamp][author]['commits'] = self.authors[author]['commits']
546 files, inserted, deleted = 0, 0, 0
547 except ValueError:
548 print 'Warning: unexpected line "%s"' % line
549 else:
550 print 'Warning: unexpected line "%s"' % line
551 else:
552 numbers = getstatsummarycounts(line);
554 if len(numbers) == 3:
555 (files, inserted, deleted) = map(lambda el : int(el), numbers)
556 else:
557 print 'Warning: failed to handle line "%s"' % line
558 (files, inserted, deleted) = (0, 0, 0)
560 def refine(self):
561 # authors
562 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
563 self.authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
564 self.authors_by_commits.reverse() # most first
565 for i, name in enumerate(self.authors_by_commits):
566 self.authors[name]['place_by_commits'] = i + 1
568 for name in self.authors.keys():
569 a = self.authors[name]
570 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
571 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
572 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
573 delta = date_last - date_first
574 a['date_first'] = date_first.strftime('%Y-%m-%d')
575 a['date_last'] = date_last.strftime('%Y-%m-%d')
576 a['timedelta'] = delta
577 if 'lines_added' not in a: a['lines_added'] = 0
578 if 'lines_removed' not in a: a['lines_removed'] = 0
580 def getActiveDays(self):
581 return self.active_days
583 def getActivityByDayOfWeek(self):
584 return self.activity_by_day_of_week
586 def getActivityByHourOfDay(self):
587 return self.activity_by_hour_of_day
589 def getAuthorInfo(self, author):
590 return self.authors[author]
592 def getAuthors(self, limit = None):
593 res = getkeyssortedbyvaluekey(self.authors, 'commits')
594 res.reverse()
595 return res[:limit]
597 def getCommitDeltaDays(self):
598 return (self.last_commit_stamp / 86400 - self.first_commit_stamp / 86400) + 1
600 def getDomainInfo(self, domain):
601 return self.domains[domain]
603 def getDomains(self):
604 return self.domains.keys()
606 def getFilesInCommit(self, rev):
607 try:
608 res = self.cache['files_in_tree'][rev]
609 except:
610 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
611 if 'files_in_tree' not in self.cache:
612 self.cache['files_in_tree'] = {}
613 self.cache['files_in_tree'][rev] = res
615 return res
617 def getFirstCommitDate(self):
618 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
620 def getLastCommitDate(self):
621 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
623 def getLinesInBlob(self, sha1):
624 try:
625 res = self.cache['lines_in_blob'][sha1]
626 except:
627 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
628 if 'lines_in_blob' not in self.cache:
629 self.cache['lines_in_blob'] = {}
630 self.cache['lines_in_blob'][sha1] = res
631 return res
633 def getTags(self):
634 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
635 return lines.split('\n')
637 def getTagDate(self, tag):
638 return self.revToDate('tags/' + tag)
640 def getTotalAuthors(self):
641 return self.total_authors
643 def getTotalCommits(self):
644 return self.total_commits
646 def getTotalFiles(self):
647 return self.total_files
649 def getTotalLOC(self):
650 return self.total_lines
652 def getTotalSize(self):
653 return self.total_size
655 def revToDate(self, rev):
656 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
657 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
659 class ReportCreator:
660 """Creates the actual report based on given data."""
661 def __init__(self):
662 pass
664 def create(self, data, path):
665 self.data = data
666 self.path = path
668 def html_linkify(text):
669 return text.lower().replace(' ', '_')
671 def html_header(level, text):
672 name = html_linkify(text)
673 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
675 class HTMLReportCreator(ReportCreator):
676 def create(self, data, path):
677 ReportCreator.create(self, data, path)
678 self.title = data.projectname
680 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
681 binarypath = os.path.dirname(os.path.abspath(__file__))
682 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
683 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
684 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
685 for base in basedirs:
686 src = base + '/' + file
687 if os.path.exists(src):
688 shutil.copyfile(src, path + '/' + file)
689 break
690 else:
691 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
693 f = open(path + "/index.html", 'w')
694 format = '%Y-%m-%d %H:%M:%S'
695 self.printHeader(f)
697 f.write('<h1>GitStats - %s</h1>' % data.projectname)
699 self.printNav(f)
701 f.write('<dl>')
702 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
703 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
704 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
705 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
706 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())))
707 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
708 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))
709 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()))
710 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
711 f.write('</dl>')
713 f.write('</body>\n</html>')
714 f.close()
717 # Activity
718 f = open(path + '/activity.html', 'w')
719 self.printHeader(f)
720 f.write('<h1>Activity</h1>')
721 self.printNav(f)
723 #f.write('<h2>Last 30 days</h2>')
725 #f.write('<h2>Last 12 months</h2>')
727 # Weekly activity
728 WEEKS = 32
729 f.write(html_header(2, 'Weekly activity'))
730 f.write('<p>Last %d weeks</p>' % WEEKS)
732 # generate weeks to show (previous N weeks from now)
733 now = datetime.datetime.now()
734 deltaweek = datetime.timedelta(7)
735 weeks = []
736 stampcur = now
737 for i in range(0, WEEKS):
738 weeks.insert(0, stampcur.strftime('%Y-%W'))
739 stampcur -= deltaweek
741 # top row: commits & bar
742 f.write('<table class="noborders"><tr>')
743 for i in range(0, WEEKS):
744 commits = 0
745 if weeks[i] in data.activity_by_year_week:
746 commits = data.activity_by_year_week[weeks[i]]
748 percentage = 0
749 if weeks[i] in data.activity_by_year_week:
750 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
751 height = max(1, int(200 * percentage))
752 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))
754 # bottom row: year/week
755 f.write('</tr><tr>')
756 for i in range(0, WEEKS):
757 f.write('<td>%s</td>' % (WEEKS - i))
758 f.write('</tr></table>')
760 # Hour of Day
761 f.write(html_header(2, 'Hour of Day'))
762 hour_of_day = data.getActivityByHourOfDay()
763 f.write('<table><tr><th>Hour</th>')
764 for i in range(0, 24):
765 f.write('<th>%d</th>' % i)
766 f.write('</tr>\n<tr><th>Commits</th>')
767 fp = open(path + '/hour_of_day.dat', 'w')
768 for i in range(0, 24):
769 if i in hour_of_day:
770 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
771 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
772 fp.write('%d %d\n' % (i, hour_of_day[i]))
773 else:
774 f.write('<td>0</td>')
775 fp.write('%d 0\n' % i)
776 fp.close()
777 f.write('</tr>\n<tr><th>%</th>')
778 totalcommits = data.getTotalCommits()
779 for i in range(0, 24):
780 if i in hour_of_day:
781 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
782 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
783 else:
784 f.write('<td>0.00</td>')
785 f.write('</tr></table>')
786 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
787 fg = open(path + '/hour_of_day.dat', 'w')
788 for i in range(0, 24):
789 if i in hour_of_day:
790 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
791 else:
792 fg.write('%d 0\n' % (i + 1))
793 fg.close()
795 # Day of Week
796 f.write(html_header(2, 'Day of Week'))
797 day_of_week = data.getActivityByDayOfWeek()
798 f.write('<div class="vtable"><table>')
799 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
800 fp = open(path + '/day_of_week.dat', 'w')
801 for d in range(0, 7):
802 commits = 0
803 if d in day_of_week:
804 commits = day_of_week[d]
805 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
806 f.write('<tr>')
807 f.write('<th>%s</th>' % (WEEKDAYS[d]))
808 if d in day_of_week:
809 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
810 else:
811 f.write('<td>0</td>')
812 f.write('</tr>')
813 f.write('</table></div>')
814 f.write('<img src="day_of_week.png" alt="Day of Week" />')
815 fp.close()
817 # Hour of Week
818 f.write(html_header(2, 'Hour of Week'))
819 f.write('<table>')
821 f.write('<tr><th>Weekday</th>')
822 for hour in range(0, 24):
823 f.write('<th>%d</th>' % (hour))
824 f.write('</tr>')
826 for weekday in range(0, 7):
827 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
828 for hour in range(0, 24):
829 try:
830 commits = data.activity_by_hour_of_week[weekday][hour]
831 except KeyError:
832 commits = 0
833 if commits != 0:
834 f.write('<td')
835 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
836 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
837 f.write('>%d</td>' % commits)
838 else:
839 f.write('<td></td>')
840 f.write('</tr>')
842 f.write('</table>')
844 # Month of Year
845 f.write(html_header(2, 'Month of Year'))
846 f.write('<div class="vtable"><table>')
847 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
848 fp = open (path + '/month_of_year.dat', 'w')
849 for mm in range(1, 13):
850 commits = 0
851 if mm in data.activity_by_month_of_year:
852 commits = data.activity_by_month_of_year[mm]
853 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
854 fp.write('%d %d\n' % (mm, commits))
855 fp.close()
856 f.write('</table></div>')
857 f.write('<img src="month_of_year.png" alt="Month of Year" />')
859 # Commits by year/month
860 f.write(html_header(2, 'Commits by year/month'))
861 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th><th>Lines added</th><th>Lines removed</th></tr>')
862 for yymm in reversed(sorted(data.commits_by_month.keys())):
863 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)))
864 f.write('</table></div>')
865 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
866 fg = open(path + '/commits_by_year_month.dat', 'w')
867 for yymm in sorted(data.commits_by_month.keys()):
868 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
869 fg.close()
871 # Commits by year
872 f.write(html_header(2, 'Commits by Year'))
873 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th><th>Lines added</th><th>Lines removed</th></tr>')
874 for yy in reversed(sorted(data.commits_by_year.keys())):
875 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)))
876 f.write('</table></div>')
877 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
878 fg = open(path + '/commits_by_year.dat', 'w')
879 for yy in sorted(data.commits_by_year.keys()):
880 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
881 fg.close()
883 # Commits by timezone
884 f.write(html_header(2, 'Commits by Timezone'))
885 f.write('<table><tr>')
886 f.write('<th>Timezone</th><th>Commits</th>')
887 max_commits_on_tz = max(data.commits_by_timezone.values())
888 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
889 commits = data.commits_by_timezone[i]
890 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
891 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
892 f.write('</tr></table>')
894 f.write('</body></html>')
895 f.close()
898 # Authors
899 f = open(path + '/authors.html', 'w')
900 self.printHeader(f)
902 f.write('<h1>Authors</h1>')
903 self.printNav(f)
905 # Authors :: List of authors
906 f.write(html_header(2, 'List of Authors'))
908 f.write('<table class="authors sortable" id="authors">')
909 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>')
910 for author in data.getAuthors(conf['max_authors']):
911 info = data.getAuthorInfo(author)
912 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']))
913 f.write('</table>')
915 allauthors = data.getAuthors()
916 if len(allauthors) > conf['max_authors']:
917 rest = allauthors[conf['max_authors']:]
918 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
920 f.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
921 f.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
922 if len(allauthors) > conf['max_authors']:
923 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
925 f.write(html_header(2, 'Commits per Author'))
926 f.write('<img src="commits_by_author.png" alt="Commits per Author" />')
927 if len(allauthors) > conf['max_authors']:
928 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
930 fgl = open(path + '/lines_of_code_by_author.dat', 'w')
931 fgc = open(path + '/commits_by_author.dat', 'w')
933 lines_by_authors = {} # cumulated added lines by
934 # author. to save memory,
935 # changes_by_date_by_author[stamp][author] is defined
936 # only at points where author commits.
937 # lines_by_authors allows us to generate all the
938 # points in the .dat file.
940 # Don't rely on getAuthors to give the same order each
941 # time. Be robust and keep the list in a variable.
942 commits_by_authors = {} # cumulated added lines by
944 self.authors_to_plot = data.getAuthors(conf['max_authors'])
945 for author in self.authors_to_plot:
946 lines_by_authors[author] = 0
947 commits_by_authors[author] = 0
948 for stamp in sorted(data.changes_by_date_by_author.keys()):
949 fgl.write('%d' % stamp)
950 fgc.write('%d' % stamp)
951 for author in self.authors_to_plot:
952 if author in data.changes_by_date_by_author[stamp].keys():
953 lines_by_authors[author] = data.changes_by_date_by_author[stamp][author]['lines_added']
954 commits_by_authors[author] = data.changes_by_date_by_author[stamp][author]['commits']
955 fgl.write(' %d' % lines_by_authors[author])
956 fgc.write(' %d' % commits_by_authors[author])
957 fgl.write('\n')
958 fgc.write('\n')
959 fgl.close()
960 fgc.close()
962 # Authors :: Author of Month
963 f.write(html_header(2, 'Author of Month'))
964 f.write('<table class="sortable" id="aom">')
965 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'])
966 for yymm in reversed(sorted(data.author_of_month.keys())):
967 authordict = data.author_of_month[yymm]
968 authors = getkeyssortedbyvalues(authordict)
969 authors.reverse()
970 commits = data.author_of_month[yymm][authors[0]]
971 next = ', '.join(authors[1:conf['authors_top']+1])
972 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)))
974 f.write('</table>')
976 f.write(html_header(2, 'Author of Year'))
977 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'])
978 for yy in reversed(sorted(data.author_of_year.keys())):
979 authordict = data.author_of_year[yy]
980 authors = getkeyssortedbyvalues(authordict)
981 authors.reverse()
982 commits = data.author_of_year[yy][authors[0]]
983 next = ', '.join(authors[1:conf['authors_top']+1])
984 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)))
985 f.write('</table>')
987 # Domains
988 f.write(html_header(2, 'Commits by Domains'))
989 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
990 domains_by_commits.reverse() # most first
991 f.write('<div class="vtable"><table>')
992 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
993 fp = open(path + '/domains.dat', 'w')
994 n = 0
995 for domain in domains_by_commits:
996 if n == conf['max_domains']:
997 break
998 commits = 0
999 n += 1
1000 info = data.getDomainInfo(domain)
1001 fp.write('%s %d %d\n' % (domain, n , info['commits']))
1002 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
1003 f.write('</table></div>')
1004 f.write('<img src="domains.png" alt="Commits by Domains" />')
1005 fp.close()
1007 f.write('</body></html>')
1008 f.close()
1011 # Files
1012 f = open(path + '/files.html', 'w')
1013 self.printHeader(f)
1014 f.write('<h1>Files</h1>')
1015 self.printNav(f)
1017 f.write('<dl>\n')
1018 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
1019 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1020 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % (float(data.getTotalSize()) / data.getTotalFiles()))
1021 f.write('</dl>\n')
1023 # Files :: File count by date
1024 f.write(html_header(2, 'File count by date'))
1026 # use set to get rid of duplicate/unnecessary entries
1027 files_by_date = set()
1028 for stamp in sorted(data.files_by_stamp.keys()):
1029 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1031 fg = open(path + '/files_by_date.dat', 'w')
1032 for line in sorted(list(files_by_date)):
1033 fg.write('%s\n' % line)
1034 #for stamp in sorted(data.files_by_stamp.keys()):
1035 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1036 fg.close()
1038 f.write('<img src="files_by_date.png" alt="Files by Date" />')
1040 #f.write('<h2>Average file size by date</h2>')
1042 # Files :: Extensions
1043 f.write(html_header(2, 'Extensions'))
1044 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
1045 for ext in sorted(data.extensions.keys()):
1046 files = data.extensions[ext]['files']
1047 lines = data.extensions[ext]['lines']
1048 f.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%d (%.2f%%)</td><td>%d</td></tr>' % (ext, files, (100.0 * files) / data.getTotalFiles(), lines, (100.0 * lines) / data.getTotalLOC(), lines / files))
1049 f.write('</table>')
1051 f.write('</body></html>')
1052 f.close()
1055 # Lines
1056 f = open(path + '/lines.html', 'w')
1057 self.printHeader(f)
1058 f.write('<h1>Lines</h1>')
1059 self.printNav(f)
1061 f.write('<dl>\n')
1062 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1063 f.write('</dl>\n')
1065 f.write(html_header(2, 'Lines of Code'))
1066 f.write('<img src="lines_of_code.png" />')
1068 fg = open(path + '/lines_of_code.dat', 'w')
1069 for stamp in sorted(data.changes_by_date.keys()):
1070 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
1071 fg.close()
1073 f.write('</body></html>')
1074 f.close()
1077 # tags.html
1078 f = open(path + '/tags.html', 'w')
1079 self.printHeader(f)
1080 f.write('<h1>Tags</h1>')
1081 self.printNav(f)
1083 f.write('<dl>')
1084 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
1085 if len(data.tags) > 0:
1086 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
1087 f.write('</dl>')
1089 f.write('<table class="tags">')
1090 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1091 # sort the tags by date desc
1092 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
1093 for tag in tags_sorted_by_date_desc:
1094 authorinfo = []
1095 self.authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
1096 for i in reversed(self.authors_by_commits):
1097 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
1098 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)))
1099 f.write('</table>')
1101 f.write('</body></html>')
1102 f.close()
1104 self.createGraphs(path)
1106 def createGraphs(self, path):
1107 print 'Generating graphs...'
1109 # hour of day
1110 f = open(path + '/hour_of_day.plot', 'w')
1111 f.write(GNUPLOT_COMMON)
1112 f.write(
1114 set output 'hour_of_day.png'
1115 unset key
1116 set xrange [0.5:24.5]
1117 set xtics 4
1118 set grid y
1119 set ylabel "Commits"
1120 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1121 """)
1122 f.close()
1124 # day of week
1125 f = open(path + '/day_of_week.plot', 'w')
1126 f.write(GNUPLOT_COMMON)
1127 f.write(
1129 set output 'day_of_week.png'
1130 unset key
1131 set xrange [0.5:7.5]
1132 set xtics 1
1133 set grid y
1134 set ylabel "Commits"
1135 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1136 """)
1137 f.close()
1139 # Domains
1140 f = open(path + '/domains.plot', 'w')
1141 f.write(GNUPLOT_COMMON)
1142 f.write(
1144 set output 'domains.png'
1145 unset key
1146 unset xtics
1147 set yrange [0:]
1148 set grid y
1149 set ylabel "Commits"
1150 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1151 """)
1152 f.close()
1154 # Month of Year
1155 f = open(path + '/month_of_year.plot', 'w')
1156 f.write(GNUPLOT_COMMON)
1157 f.write(
1159 set output 'month_of_year.png'
1160 unset key
1161 set xrange [0.5:12.5]
1162 set xtics 1
1163 set grid y
1164 set ylabel "Commits"
1165 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1166 """)
1167 f.close()
1169 # commits_by_year_month
1170 f = open(path + '/commits_by_year_month.plot', 'w')
1171 f.write(GNUPLOT_COMMON)
1172 f.write(
1174 set output 'commits_by_year_month.png'
1175 unset key
1176 set xdata time
1177 set timefmt "%Y-%m"
1178 set format x "%Y-%m"
1179 set xtics rotate
1180 set bmargin 5
1181 set grid y
1182 set ylabel "Commits"
1183 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1184 """)
1185 f.close()
1187 # commits_by_year
1188 f = open(path + '/commits_by_year.plot', 'w')
1189 f.write(GNUPLOT_COMMON)
1190 f.write(
1192 set output 'commits_by_year.png'
1193 unset key
1194 set xtics 1 rotate
1195 set grid y
1196 set ylabel "Commits"
1197 set yrange [0:]
1198 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1199 """)
1200 f.close()
1202 # Files by date
1203 f = open(path + '/files_by_date.plot', 'w')
1204 f.write(GNUPLOT_COMMON)
1205 f.write(
1207 set output 'files_by_date.png'
1208 unset key
1209 set xdata time
1210 set timefmt "%Y-%m-%d"
1211 set format x "%Y-%m-%d"
1212 set grid y
1213 set ylabel "Files"
1214 set xtics rotate
1215 set ytics autofreq
1216 set bmargin 6
1217 plot 'files_by_date.dat' using 1:2 w steps
1218 """)
1219 f.close()
1221 # Lines of Code
1222 f = open(path + '/lines_of_code.plot', 'w')
1223 f.write(GNUPLOT_COMMON)
1224 f.write(
1226 set output 'lines_of_code.png'
1227 unset key
1228 set xdata time
1229 set timefmt "%s"
1230 set format x "%Y-%m-%d"
1231 set grid y
1232 set ylabel "Lines"
1233 set xtics rotate
1234 set bmargin 6
1235 plot 'lines_of_code.dat' using 1:2 w lines
1236 """)
1237 f.close()
1239 # Lines of Code Added per author
1240 f = open(path + '/lines_of_code_by_author.plot', 'w')
1241 f.write(GNUPLOT_COMMON)
1242 f.write(
1244 set terminal png transparent size 640,480
1245 set output 'lines_of_code_by_author.png'
1246 set key left top
1247 set xdata time
1248 set timefmt "%s"
1249 set format x "%Y-%m-%d"
1250 set grid y
1251 set ylabel "Lines"
1252 set xtics rotate
1253 set bmargin 6
1254 plot """
1256 i = 1
1257 plots = []
1258 for a in self.authors_to_plot:
1259 i = i + 1
1260 plots.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1261 f.write(", ".join(plots))
1262 f.write('\n')
1264 f.close()
1266 # Commits per author
1267 f = open(path + '/commits_by_author.plot', 'w')
1268 f.write(GNUPLOT_COMMON)
1269 f.write(
1271 set terminal png transparent size 640,480
1272 set output 'commits_by_author.png'
1273 set key left top
1274 set xdata time
1275 set timefmt "%s"
1276 set format x "%Y-%m-%d"
1277 set grid y
1278 set ylabel "Commits"
1279 set xtics rotate
1280 set bmargin 6
1281 plot """
1283 i = 1
1284 plots = []
1285 for a in self.authors_to_plot:
1286 i = i + 1
1287 plots.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1288 f.write(", ".join(plots))
1289 f.write('\n')
1291 f.close()
1293 os.chdir(path)
1294 files = glob.glob(path + '/*.plot')
1295 for f in files:
1296 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1297 if len(out) > 0:
1298 print out
1300 def printHeader(self, f, title = ''):
1301 f.write(
1302 """<?xml version="1.0" encoding="UTF-8"?>
1303 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1304 <html xmlns="http://www.w3.org/1999/xhtml">
1305 <head>
1306 <title>GitStats - %s</title>
1307 <link rel="stylesheet" href="%s" type="text/css" />
1308 <meta name="generator" content="GitStats %s" />
1309 <script type="text/javascript" src="sortable.js"></script>
1310 </head>
1311 <body>
1312 """ % (self.title, conf['style'], getversion()))
1314 def printNav(self, f):
1315 f.write("""
1316 <div class="nav">
1317 <ul>
1318 <li><a href="index.html">General</a></li>
1319 <li><a href="activity.html">Activity</a></li>
1320 <li><a href="authors.html">Authors</a></li>
1321 <li><a href="files.html">Files</a></li>
1322 <li><a href="lines.html">Lines</a></li>
1323 <li><a href="tags.html">Tags</a></li>
1324 </ul>
1325 </div>
1326 """)
1329 class GitStats:
1330 def run(self, args_orig):
1331 optlist, args = getopt.getopt(args_orig, 'c:')
1332 for o,v in optlist:
1333 if o == '-c':
1334 key, value = v.split('=', 1)
1335 if key not in conf:
1336 raise KeyError('no such key "%s" in config' % key)
1337 if isinstance(conf[key], int):
1338 conf[key] = int(value)
1339 else:
1340 conf[key] = value
1342 if len(args) < 2:
1343 print """
1344 Usage: gitstats [options] <gitpath..> <outputpath>
1346 Options:
1347 -c key=value Override configuration value
1349 Default config values:
1351 """ % conf
1352 sys.exit(0)
1354 outputpath = os.path.abspath(args[-1])
1355 rundir = os.getcwd()
1357 try:
1358 os.makedirs(outputpath)
1359 except OSError:
1360 pass
1361 if not os.path.isdir(outputpath):
1362 print 'FATAL: Output path is not a directory or does not exist'
1363 sys.exit(1)
1365 print 'Output path: %s' % outputpath
1366 cachefile = os.path.join(outputpath, 'gitstats.cache')
1368 data = GitDataCollector()
1369 data.loadCache(cachefile)
1371 for gitpath in args[0:-1]:
1372 print 'Git path: %s' % gitpath
1374 os.chdir(gitpath)
1376 print 'Collecting data...'
1377 data.collect(gitpath)
1379 print 'Refining data...'
1380 data.saveCache(cachefile)
1381 data.refine()
1383 os.chdir(rundir)
1385 print 'Generating report...'
1386 report = HTMLReportCreator()
1387 report.create(data, outputpath)
1389 time_end = time.time()
1390 exectime_internal = time_end - time_start
1391 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1392 if sys.stdin.isatty():
1393 print 'You may now run:'
1394 print
1395 print ' sensible-browser \'%s\'' % os.path.join(outputpath, 'index.html').replace("'", "'\\''")
1396 print
1398 if __name__=='__main__':
1399 g = GitStats()
1400 g.run(sys.argv[1:])