Bump copyright year.
[gitstats.git] / gitstats
blobfe782422db4afcd0f7d899637ff3362b7e0030a6
1 #!/usr/bin/env python
2 # Copyright (c) 2007-2012 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
3 # GPLv2 / GPLv3
4 import datetime
5 import getopt
6 import glob
7 import os
8 import pickle
9 import platform
10 import re
11 import shutil
12 import subprocess
13 import sys
14 import time
15 import zlib
17 os.environ['LC_ALL'] = 'C'
19 GNUPLOT_COMMON = 'set terminal png transparent size 640,240\nset size 1.0,1.0\n'
20 ON_LINUX = (platform.system() == 'Linux')
21 WEEKDAYS = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
23 exectime_internal = 0.0
24 exectime_external = 0.0
25 time_start = time.time()
27 # By default, gnuplot is searched from path, but can be overridden with the
28 # environment variable "GNUPLOT"
29 gnuplot_cmd = 'gnuplot'
30 if 'GNUPLOT' in os.environ:
31 gnuplot_cmd = os.environ['GNUPLOT']
33 conf = {
34 'max_domains': 10,
35 'max_ext_length': 10,
36 'style': 'gitstats.css',
37 'max_authors': 20,
38 'authors_top': 5,
39 'commit_begin': '',
40 'commit_end': 'HEAD',
41 'linear_linestats': 1,
42 'project_name': '',
45 def getpipeoutput(cmds, quiet = False):
46 global exectime_external
47 start = time.time()
48 if not quiet and ON_LINUX and os.isatty(1):
49 print '>> ' + ' | '.join(cmds),
50 sys.stdout.flush()
51 p0 = subprocess.Popen(cmds[0], stdout = subprocess.PIPE, shell = True)
52 p = p0
53 for x in cmds[1:]:
54 p = subprocess.Popen(x, stdin = p0.stdout, stdout = subprocess.PIPE, shell = True)
55 p0 = p
56 output = p.communicate()[0]
57 end = time.time()
58 if not quiet:
59 if ON_LINUX and os.isatty(1):
60 print '\r',
61 print '[%.5f] >> %s' % (end - start, ' | '.join(cmds))
62 exectime_external += (end - start)
63 return output.rstrip('\n')
65 def getcommitrange(defaultrange = 'HEAD', end_only = False):
66 if len(conf['commit_end']) > 0:
67 if end_only or len(conf['commit_begin']) == 0:
68 return conf['commit_end']
69 return '%s..%s' % (conf['commit_begin'], conf['commit_end'])
70 return defaultrange
72 def getkeyssortedbyvalues(dict):
73 return map(lambda el : el[1], sorted(map(lambda el : (el[1], el[0]), dict.items())))
75 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
76 def getkeyssortedbyvaluekey(d, key):
77 return map(lambda el : el[1], sorted(map(lambda el : (d[el][key], el), d.keys())))
79 def getstatsummarycounts(line):
80 numbers = re.findall('\d+', line)
81 if len(numbers) == 1:
82 # neither insertions nor deletions: may probably only happen for "0 files changed"
83 numbers.append(0);
84 numbers.append(0);
85 elif len(numbers) == 2 and line.find('(+)') != -1:
86 numbers.append(0); # only insertions were printed on line
87 elif len(numbers) == 2 and line.find('(-)') != -1:
88 numbers.insert(1, 0); # only deletions were printed on line
89 return numbers
91 VERSION = 0
92 def getversion():
93 global VERSION
94 if VERSION == 0:
95 VERSION = getpipeoutput(["git rev-parse --short %s" % getcommitrange('HEAD')]).split('\n')[0]
96 return VERSION
98 def getgitversion():
99 return getpipeoutput(['git --version']).split('\n')[0]
101 def getgnuplotversion():
102 return getpipeoutput(['gnuplot --version']).split('\n')[0]
104 class DataCollector:
105 """Manages data collection from a revision control repository."""
106 def __init__(self):
107 self.stamp_created = time.time()
108 self.cache = {}
109 self.total_authors = 0
110 self.activity_by_hour_of_day = {} # hour -> commits
111 self.activity_by_day_of_week = {} # day -> commits
112 self.activity_by_month_of_year = {} # month [1-12] -> commits
113 self.activity_by_hour_of_week = {} # weekday -> hour -> commits
114 self.activity_by_hour_of_day_busiest = 0
115 self.activity_by_hour_of_week_busiest = 0
116 self.activity_by_year_week = {} # yy_wNN -> commits
117 self.activity_by_year_week_peak = 0
119 self.authors = {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
121 self.total_commits = 0
122 self.total_files = 0
123 self.authors_by_commits = 0
125 # domains
126 self.domains = {} # domain -> commits
128 # author of the month
129 self.author_of_month = {} # month -> author -> commits
130 self.author_of_year = {} # year -> author -> commits
131 self.commits_by_month = {} # month -> commits
132 self.commits_by_year = {} # year -> commits
133 self.lines_added_by_month = {} # month -> lines added
134 self.lines_added_by_year = {} # year -> lines added
135 self.lines_removed_by_month = {} # month -> lines removed
136 self.lines_removed_by_year = {} # year -> lines removed
137 self.first_commit_stamp = 0
138 self.last_commit_stamp = 0
139 self.last_active_day = None
140 self.active_days = set()
142 # lines
143 self.total_lines = 0
144 self.total_lines_added = 0
145 self.total_lines_removed = 0
147 # size
148 self.total_size = 0
150 # timezone
151 self.commits_by_timezone = {} # timezone -> commits
153 # tags
154 self.tags = {}
156 self.files_by_stamp = {} # stamp -> files
158 # extensions
159 self.extensions = {} # extension -> files, lines
161 # line statistics
162 self.changes_by_date = {} # stamp -> { files, ins, del }
165 # This should be the main function to extract data from the repository.
166 def collect(self, dir):
167 self.dir = dir
168 if len(conf['project_name']) == 0:
169 self.projectname = os.path.basename(os.path.abspath(dir))
170 else:
171 self.projectname = conf['project_name']
174 # Load cacheable data
175 def loadCache(self, cachefile):
176 if not os.path.exists(cachefile):
177 return
178 print 'Loading cache...'
179 f = open(cachefile, 'rb')
180 try:
181 self.cache = pickle.loads(zlib.decompress(f.read()))
182 except:
183 # temporary hack to upgrade non-compressed caches
184 f.seek(0)
185 self.cache = pickle.load(f)
186 f.close()
189 # Produce any additional statistics from the extracted data.
190 def refine(self):
191 pass
194 # : get a dictionary of author
195 def getAuthorInfo(self, author):
196 return None
198 def getActivityByDayOfWeek(self):
199 return {}
201 def getActivityByHourOfDay(self):
202 return {}
204 # : get a dictionary of domains
205 def getDomainInfo(self, domain):
206 return None
209 # Get a list of authors
210 def getAuthors(self):
211 return []
213 def getFirstCommitDate(self):
214 return datetime.datetime.now()
216 def getLastCommitDate(self):
217 return datetime.datetime.now()
219 def getStampCreated(self):
220 return self.stamp_created
222 def getTags(self):
223 return []
225 def getTotalAuthors(self):
226 return -1
228 def getTotalCommits(self):
229 return -1
231 def getTotalFiles(self):
232 return -1
234 def getTotalLOC(self):
235 return -1
238 # Save cacheable data
239 def saveCache(self, cachefile):
240 print 'Saving cache...'
241 f = open(cachefile, 'wb')
242 #pickle.dump(self.cache, f)
243 data = zlib.compress(pickle.dumps(self.cache))
244 f.write(data)
245 f.close()
247 class GitDataCollector(DataCollector):
248 def collect(self, dir):
249 DataCollector.collect(self, dir)
251 try:
252 self.total_authors += int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
253 except:
254 self.total_authors = 0
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 self.tags[tag]['commits'] += commits
291 self.tags[tag]['authors'][author] = commits
293 # Collect revision statistics
294 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
295 lines = getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
296 for line in lines:
297 parts = line.split(' ', 4)
298 author = ''
299 try:
300 stamp = int(parts[0])
301 except ValueError:
302 stamp = 0
303 timezone = parts[3]
304 author, mail = parts[4].split('<', 1)
305 author = author.rstrip()
306 mail = mail.rstrip('>')
307 domain = '?'
308 if mail.find('@') != -1:
309 domain = mail.rsplit('@', 1)[1]
310 date = datetime.datetime.fromtimestamp(float(stamp))
312 # First and last commit stamp (may be in any order because of cherry-picking and patches)
313 if stamp > self.last_commit_stamp:
314 self.last_commit_stamp = stamp
315 if self.first_commit_stamp == 0 or stamp < self.first_commit_stamp:
316 self.first_commit_stamp = stamp
318 # activity
319 # hour
320 hour = date.hour
321 self.activity_by_hour_of_day[hour] = self.activity_by_hour_of_day.get(hour, 0) + 1
322 # most active hour?
323 if self.activity_by_hour_of_day[hour] > self.activity_by_hour_of_day_busiest:
324 self.activity_by_hour_of_day_busiest = self.activity_by_hour_of_day[hour]
326 # day of week
327 day = date.weekday()
328 self.activity_by_day_of_week[day] = self.activity_by_day_of_week.get(day, 0) + 1
330 # domain stats
331 if domain not in self.domains:
332 self.domains[domain] = {}
333 # commits
334 self.domains[domain]['commits'] = self.domains[domain].get('commits', 0) + 1
336 # hour of week
337 if day not in self.activity_by_hour_of_week:
338 self.activity_by_hour_of_week[day] = {}
339 self.activity_by_hour_of_week[day][hour] = self.activity_by_hour_of_week[day].get(hour, 0) + 1
340 # most active hour?
341 if self.activity_by_hour_of_week[day][hour] > self.activity_by_hour_of_week_busiest:
342 self.activity_by_hour_of_week_busiest = self.activity_by_hour_of_week[day][hour]
344 # month of year
345 month = date.month
346 self.activity_by_month_of_year[month] = self.activity_by_month_of_year.get(month, 0) + 1
348 # yearly/weekly activity
349 yyw = date.strftime('%Y-%W')
350 self.activity_by_year_week[yyw] = self.activity_by_year_week.get(yyw, 0) + 1
351 if self.activity_by_year_week_peak < self.activity_by_year_week[yyw]:
352 self.activity_by_year_week_peak = self.activity_by_year_week[yyw]
354 # author stats
355 if author not in self.authors:
356 self.authors[author] = {}
357 # commits, note again that commits may be in any date order because of cherry-picking and patches
358 if 'last_commit_stamp' not in self.authors[author]:
359 self.authors[author]['last_commit_stamp'] = stamp
360 if stamp > self.authors[author]['last_commit_stamp']:
361 self.authors[author]['last_commit_stamp'] = stamp
362 if 'first_commit_stamp' not in self.authors[author]:
363 self.authors[author]['first_commit_stamp'] = stamp
364 if stamp < self.authors[author]['first_commit_stamp']:
365 self.authors[author]['first_commit_stamp'] = stamp
367 # author of the month/year
368 yymm = date.strftime('%Y-%m')
369 if yymm in self.author_of_month:
370 self.author_of_month[yymm][author] = self.author_of_month[yymm].get(author, 0) + 1
371 else:
372 self.author_of_month[yymm] = {}
373 self.author_of_month[yymm][author] = 1
374 self.commits_by_month[yymm] = self.commits_by_month.get(yymm, 0) + 1
376 yy = date.year
377 if yy in self.author_of_year:
378 self.author_of_year[yy][author] = self.author_of_year[yy].get(author, 0) + 1
379 else:
380 self.author_of_year[yy] = {}
381 self.author_of_year[yy][author] = 1
382 self.commits_by_year[yy] = self.commits_by_year.get(yy, 0) + 1
384 # authors: active days
385 yymmdd = date.strftime('%Y-%m-%d')
386 if 'last_active_day' not in self.authors[author]:
387 self.authors[author]['last_active_day'] = yymmdd
388 self.authors[author]['active_days'] = set([yymmdd])
389 elif yymmdd != self.authors[author]['last_active_day']:
390 self.authors[author]['last_active_day'] = yymmdd
391 self.authors[author]['active_days'].add(yymmdd)
393 # project: active days
394 if yymmdd != self.last_active_day:
395 self.last_active_day = yymmdd
396 self.active_days.add(yymmdd)
398 # timezone
399 self.commits_by_timezone[timezone] = self.commits_by_timezone.get(timezone, 0) + 1
401 # TODO Optimize this, it's the worst bottleneck
402 # outputs "<stamp> <files>" for each revision
403 revlines = getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
404 lines = []
405 for revline in revlines:
406 time, rev = revline.split(' ')
407 linecount = self.getFilesInCommit(rev)
408 lines.append('%d %d' % (int(time), linecount))
410 self.total_commits += len(lines)
411 for line in lines:
412 parts = line.split(' ')
413 if len(parts) != 2:
414 continue
415 (stamp, files) = parts[0:2]
416 try:
417 self.files_by_stamp[int(stamp)] = int(files)
418 except ValueError:
419 print 'Warning: failed to parse line "%s"' % line
421 # extensions and size of files
422 lines = getpipeoutput(['git ls-tree -r -l -z %s' % getcommitrange('HEAD', end_only = True)]).split('\000')
423 for line in lines:
424 if len(line) == 0:
425 continue
426 parts = re.split('\s+', line, 5)
427 if parts[0] == '160000' and parts[3] == '-':
428 # skip submodules
429 continue
430 sha1 = parts[2]
431 size = int(parts[3])
432 fullpath = parts[4]
434 self.total_size += size
435 self.total_files += 1
437 filename = fullpath.split('/')[-1] # strip directories
438 if filename.find('.') == -1 or filename.rfind('.') == 0:
439 ext = ''
440 else:
441 ext = filename[(filename.rfind('.') + 1):]
442 if len(ext) > conf['max_ext_length']:
443 ext = ''
445 if ext not in self.extensions:
446 self.extensions[ext] = {'files': 0, 'lines': 0}
448 self.extensions[ext]['files'] += 1
449 try:
450 self.extensions[ext]['lines'] += self.getLinesInBlob(sha1)
451 except:
452 print 'Warning: Could not count lines for file "%s"' % line
454 # line statistics
455 # outputs:
456 # N files changed, N insertions (+), N deletions(-)
457 # <stamp> <author>
458 self.changes_by_date = {} # stamp -> { files, ins, del }
459 # computation of lines of code by date is better done
460 # on a linear history.
461 extra = ''
462 if conf['linear_linestats']:
463 extra = '--first-parent -m'
464 lines = getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra, getcommitrange('HEAD'))]).split('\n')
465 lines.reverse()
466 files = 0; inserted = 0; deleted = 0; total_lines = 0
467 author = None
468 for line in lines:
469 if len(line) == 0:
470 continue
472 # <stamp> <author>
473 if re.search('files? changed', line) == None:
474 pos = line.find(' ')
475 if pos != -1:
476 try:
477 (stamp, author) = (int(line[:pos]), line[pos+1:])
478 self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted, 'lines': total_lines }
480 date = datetime.datetime.fromtimestamp(stamp)
481 yymm = date.strftime('%Y-%m')
482 self.lines_added_by_month[yymm] = self.lines_added_by_month.get(yymm, 0) + inserted
483 self.lines_removed_by_month[yymm] = self.lines_removed_by_month.get(yymm, 0) + deleted
485 yy = date.year
486 self.lines_added_by_year[yy] = self.lines_added_by_year.get(yy,0) + inserted
487 self.lines_removed_by_year[yy] = self.lines_removed_by_year.get(yy, 0) + deleted
489 files, inserted, deleted = 0, 0, 0
490 except ValueError:
491 print 'Warning: unexpected line "%s"' % line
492 else:
493 print 'Warning: unexpected line "%s"' % line
494 else:
495 numbers = getstatsummarycounts(line)
497 if len(numbers) == 3:
498 (files, inserted, deleted) = map(lambda el : int(el), numbers)
499 total_lines += inserted
500 total_lines -= deleted
501 self.total_lines_added += inserted
502 self.total_lines_removed += deleted
504 else:
505 print 'Warning: failed to handle line "%s"' % line
506 (files, inserted, deleted) = (0, 0, 0)
507 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
508 self.total_lines = total_lines
510 # Per-author statistics
512 # defined for stamp, author only if author commited at this timestamp.
513 self.changes_by_date_by_author = {} # stamp -> author -> lines_added
515 # Similar to the above, but never use --first-parent
516 # (we need to walk through every commit to know who
517 # committed what, not just through mainline)
518 lines = getpipeoutput(['git log --shortstat --date-order --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
519 lines.reverse()
520 files = 0; inserted = 0; deleted = 0
521 author = None
522 stamp = 0
523 for line in lines:
524 if len(line) == 0:
525 continue
527 # <stamp> <author>
528 if re.search('files? changed', line) == None:
529 pos = line.find(' ')
530 if pos != -1:
531 try:
532 oldstamp = stamp
533 (stamp, author) = (int(line[:pos]), line[pos+1:])
534 if oldstamp > stamp:
535 # clock skew, keep old timestamp to avoid having ugly graph
536 stamp = oldstamp
537 if author not in self.authors:
538 self.authors[author] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
539 self.authors[author]['commits'] = self.authors[author].get('commits', 0) + 1
540 self.authors[author]['lines_added'] = self.authors[author].get('lines_added', 0) + inserted
541 self.authors[author]['lines_removed'] = self.authors[author].get('lines_removed', 0) + deleted
542 if stamp not in self.changes_by_date_by_author:
543 self.changes_by_date_by_author[stamp] = {}
544 if author not in self.changes_by_date_by_author[stamp]:
545 self.changes_by_date_by_author[stamp][author] = {}
546 self.changes_by_date_by_author[stamp][author]['lines_added'] = self.authors[author]['lines_added']
547 self.changes_by_date_by_author[stamp][author]['commits'] = self.authors[author]['commits']
548 files, inserted, deleted = 0, 0, 0
549 except ValueError:
550 print 'Warning: unexpected line "%s"' % line
551 else:
552 print 'Warning: unexpected line "%s"' % line
553 else:
554 numbers = getstatsummarycounts(line);
556 if len(numbers) == 3:
557 (files, inserted, deleted) = map(lambda el : int(el), numbers)
558 else:
559 print 'Warning: failed to handle line "%s"' % line
560 (files, inserted, deleted) = (0, 0, 0)
562 def refine(self):
563 # authors
564 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
565 self.authors_by_commits = getkeyssortedbyvaluekey(self.authors, 'commits')
566 self.authors_by_commits.reverse() # most first
567 for i, name in enumerate(self.authors_by_commits):
568 self.authors[name]['place_by_commits'] = i + 1
570 for name in self.authors.keys():
571 a = self.authors[name]
572 a['commits_frac'] = (100 * float(a['commits'])) / self.getTotalCommits()
573 date_first = datetime.datetime.fromtimestamp(a['first_commit_stamp'])
574 date_last = datetime.datetime.fromtimestamp(a['last_commit_stamp'])
575 delta = date_last - date_first
576 a['date_first'] = date_first.strftime('%Y-%m-%d')
577 a['date_last'] = date_last.strftime('%Y-%m-%d')
578 a['timedelta'] = delta
579 if 'lines_added' not in a: a['lines_added'] = 0
580 if 'lines_removed' not in a: a['lines_removed'] = 0
582 def getActiveDays(self):
583 return self.active_days
585 def getActivityByDayOfWeek(self):
586 return self.activity_by_day_of_week
588 def getActivityByHourOfDay(self):
589 return self.activity_by_hour_of_day
591 def getAuthorInfo(self, author):
592 return self.authors[author]
594 def getAuthors(self, limit = None):
595 res = getkeyssortedbyvaluekey(self.authors, 'commits')
596 res.reverse()
597 return res[:limit]
599 def getCommitDeltaDays(self):
600 return (self.last_commit_stamp / 86400 - self.first_commit_stamp / 86400) + 1
602 def getDomainInfo(self, domain):
603 return self.domains[domain]
605 def getDomains(self):
606 return self.domains.keys()
608 def getFilesInCommit(self, rev):
609 try:
610 res = self.cache['files_in_tree'][rev]
611 except:
612 res = int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev, 'wc -l']).split('\n')[0])
613 if 'files_in_tree' not in self.cache:
614 self.cache['files_in_tree'] = {}
615 self.cache['files_in_tree'][rev] = res
617 return res
619 def getFirstCommitDate(self):
620 return datetime.datetime.fromtimestamp(self.first_commit_stamp)
622 def getLastCommitDate(self):
623 return datetime.datetime.fromtimestamp(self.last_commit_stamp)
625 def getLinesInBlob(self, sha1):
626 try:
627 res = self.cache['lines_in_blob'][sha1]
628 except:
629 res = int(getpipeoutput(['git cat-file blob %s' % sha1, 'wc -l']).split()[0])
630 if 'lines_in_blob' not in self.cache:
631 self.cache['lines_in_blob'] = {}
632 self.cache['lines_in_blob'][sha1] = res
633 return res
635 def getTags(self):
636 lines = getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
637 return lines.split('\n')
639 def getTagDate(self, tag):
640 return self.revToDate('tags/' + tag)
642 def getTotalAuthors(self):
643 return self.total_authors
645 def getTotalCommits(self):
646 return self.total_commits
648 def getTotalFiles(self):
649 return self.total_files
651 def getTotalLOC(self):
652 return self.total_lines
654 def getTotalSize(self):
655 return self.total_size
657 def revToDate(self, rev):
658 stamp = int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev]))
659 return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d')
661 class ReportCreator:
662 """Creates the actual report based on given data."""
663 def __init__(self):
664 pass
666 def create(self, data, path):
667 self.data = data
668 self.path = path
670 def html_linkify(text):
671 return text.lower().replace(' ', '_')
673 def html_header(level, text):
674 name = html_linkify(text)
675 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level, name, name, text, level)
677 class HTMLReportCreator(ReportCreator):
678 def create(self, data, path):
679 ReportCreator.create(self, data, path)
680 self.title = data.projectname
682 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
683 binarypath = os.path.dirname(os.path.abspath(__file__))
684 secondarypath = os.path.join(binarypath, '..', 'share', 'gitstats')
685 basedirs = [binarypath, secondarypath, '/usr/share/gitstats']
686 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
687 for base in basedirs:
688 src = base + '/' + file
689 if os.path.exists(src):
690 shutil.copyfile(src, path + '/' + file)
691 break
692 else:
693 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs)
695 f = open(path + "/index.html", 'w')
696 format = '%Y-%m-%d %H:%M:%S'
697 self.printHeader(f)
699 f.write('<h1>GitStats - %s</h1>' % data.projectname)
701 self.printNav(f)
703 f.write('<dl>')
704 f.write('<dt>Project name</dt><dd>%s</dd>' % (data.projectname))
705 f.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime.datetime.now().strftime(format), time.time() - data.getStampCreated()))
706 f.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
707 f.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data.getFirstCommitDate().strftime(format), data.getLastCommitDate().strftime(format)))
708 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())))
709 f.write('<dt>Total Files</dt><dd>%s</dd>' % data.getTotalFiles())
710 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))
711 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()))
712 f.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data.getTotalAuthors(), (1.0 * data.getTotalCommits()) / data.getTotalAuthors()))
713 f.write('</dl>')
715 f.write('</body>\n</html>')
716 f.close()
719 # Activity
720 f = open(path + '/activity.html', 'w')
721 self.printHeader(f)
722 f.write('<h1>Activity</h1>')
723 self.printNav(f)
725 #f.write('<h2>Last 30 days</h2>')
727 #f.write('<h2>Last 12 months</h2>')
729 # Weekly activity
730 WEEKS = 32
731 f.write(html_header(2, 'Weekly activity'))
732 f.write('<p>Last %d weeks</p>' % WEEKS)
734 # generate weeks to show (previous N weeks from now)
735 now = datetime.datetime.now()
736 deltaweek = datetime.timedelta(7)
737 weeks = []
738 stampcur = now
739 for i in range(0, WEEKS):
740 weeks.insert(0, stampcur.strftime('%Y-%W'))
741 stampcur -= deltaweek
743 # top row: commits & bar
744 f.write('<table class="noborders"><tr>')
745 for i in range(0, WEEKS):
746 commits = 0
747 if weeks[i] in data.activity_by_year_week:
748 commits = data.activity_by_year_week[weeks[i]]
750 percentage = 0
751 if weeks[i] in data.activity_by_year_week:
752 percentage = float(data.activity_by_year_week[weeks[i]]) / data.activity_by_year_week_peak
753 height = max(1, int(200 * percentage))
754 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))
756 # bottom row: year/week
757 f.write('</tr><tr>')
758 for i in range(0, WEEKS):
759 f.write('<td>%s</td>' % (WEEKS - i))
760 f.write('</tr></table>')
762 # Hour of Day
763 f.write(html_header(2, 'Hour of Day'))
764 hour_of_day = data.getActivityByHourOfDay()
765 f.write('<table><tr><th>Hour</th>')
766 for i in range(0, 24):
767 f.write('<th>%d</th>' % i)
768 f.write('</tr>\n<tr><th>Commits</th>')
769 fp = open(path + '/hour_of_day.dat', 'w')
770 for i in range(0, 24):
771 if i in hour_of_day:
772 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
773 f.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r, hour_of_day[i]))
774 fp.write('%d %d\n' % (i, hour_of_day[i]))
775 else:
776 f.write('<td>0</td>')
777 fp.write('%d 0\n' % i)
778 fp.close()
779 f.write('</tr>\n<tr><th>%</th>')
780 totalcommits = data.getTotalCommits()
781 for i in range(0, 24):
782 if i in hour_of_day:
783 r = 127 + int((float(hour_of_day[i]) / data.activity_by_hour_of_day_busiest) * 128)
784 f.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r, (100.0 * hour_of_day[i]) / totalcommits))
785 else:
786 f.write('<td>0.00</td>')
787 f.write('</tr></table>')
788 f.write('<img src="hour_of_day.png" alt="Hour of Day" />')
789 fg = open(path + '/hour_of_day.dat', 'w')
790 for i in range(0, 24):
791 if i in hour_of_day:
792 fg.write('%d %d\n' % (i + 1, hour_of_day[i]))
793 else:
794 fg.write('%d 0\n' % (i + 1))
795 fg.close()
797 # Day of Week
798 f.write(html_header(2, 'Day of Week'))
799 day_of_week = data.getActivityByDayOfWeek()
800 f.write('<div class="vtable"><table>')
801 f.write('<tr><th>Day</th><th>Total (%)</th></tr>')
802 fp = open(path + '/day_of_week.dat', 'w')
803 for d in range(0, 7):
804 commits = 0
805 if d in day_of_week:
806 commits = day_of_week[d]
807 fp.write('%d %s %d\n' % (d + 1, WEEKDAYS[d], commits))
808 f.write('<tr>')
809 f.write('<th>%s</th>' % (WEEKDAYS[d]))
810 if d in day_of_week:
811 f.write('<td>%d (%.2f%%)</td>' % (day_of_week[d], (100.0 * day_of_week[d]) / totalcommits))
812 else:
813 f.write('<td>0</td>')
814 f.write('</tr>')
815 f.write('</table></div>')
816 f.write('<img src="day_of_week.png" alt="Day of Week" />')
817 fp.close()
819 # Hour of Week
820 f.write(html_header(2, 'Hour of Week'))
821 f.write('<table>')
823 f.write('<tr><th>Weekday</th>')
824 for hour in range(0, 24):
825 f.write('<th>%d</th>' % (hour))
826 f.write('</tr>')
828 for weekday in range(0, 7):
829 f.write('<tr><th>%s</th>' % (WEEKDAYS[weekday]))
830 for hour in range(0, 24):
831 try:
832 commits = data.activity_by_hour_of_week[weekday][hour]
833 except KeyError:
834 commits = 0
835 if commits != 0:
836 f.write('<td')
837 r = 127 + int((float(commits) / data.activity_by_hour_of_week_busiest) * 128)
838 f.write(' style="background-color: rgb(%d, 0, 0)"' % r)
839 f.write('>%d</td>' % commits)
840 else:
841 f.write('<td></td>')
842 f.write('</tr>')
844 f.write('</table>')
846 # Month of Year
847 f.write(html_header(2, 'Month of Year'))
848 f.write('<div class="vtable"><table>')
849 f.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
850 fp = open (path + '/month_of_year.dat', 'w')
851 for mm in range(1, 13):
852 commits = 0
853 if mm in data.activity_by_month_of_year:
854 commits = data.activity_by_month_of_year[mm]
855 f.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm, commits, (100.0 * commits) / data.getTotalCommits()))
856 fp.write('%d %d\n' % (mm, commits))
857 fp.close()
858 f.write('</table></div>')
859 f.write('<img src="month_of_year.png" alt="Month of Year" />')
861 # Commits by year/month
862 f.write(html_header(2, 'Commits by year/month'))
863 f.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th><th>Lines added</th><th>Lines removed</th></tr>')
864 for yymm in reversed(sorted(data.commits_by_month.keys())):
865 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)))
866 f.write('</table></div>')
867 f.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
868 fg = open(path + '/commits_by_year_month.dat', 'w')
869 for yymm in sorted(data.commits_by_month.keys()):
870 fg.write('%s %s\n' % (yymm, data.commits_by_month[yymm]))
871 fg.close()
873 # Commits by year
874 f.write(html_header(2, 'Commits by Year'))
875 f.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th><th>Lines added</th><th>Lines removed</th></tr>')
876 for yy in reversed(sorted(data.commits_by_year.keys())):
877 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)))
878 f.write('</table></div>')
879 f.write('<img src="commits_by_year.png" alt="Commits by Year" />')
880 fg = open(path + '/commits_by_year.dat', 'w')
881 for yy in sorted(data.commits_by_year.keys()):
882 fg.write('%d %d\n' % (yy, data.commits_by_year[yy]))
883 fg.close()
885 # Commits by timezone
886 f.write(html_header(2, 'Commits by Timezone'))
887 f.write('<table><tr>')
888 f.write('<th>Timezone</th><th>Commits</th>')
889 max_commits_on_tz = max(data.commits_by_timezone.values())
890 for i in sorted(data.commits_by_timezone.keys(), key = lambda n : int(n)):
891 commits = data.commits_by_timezone[i]
892 r = 127 + int((float(commits) / max_commits_on_tz) * 128)
893 f.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i, r, commits))
894 f.write('</tr></table>')
896 f.write('</body></html>')
897 f.close()
900 # Authors
901 f = open(path + '/authors.html', 'w')
902 self.printHeader(f)
904 f.write('<h1>Authors</h1>')
905 self.printNav(f)
907 # Authors :: List of authors
908 f.write(html_header(2, 'List of Authors'))
910 f.write('<table class="authors sortable" id="authors">')
911 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>')
912 for author in data.getAuthors(conf['max_authors']):
913 info = data.getAuthorInfo(author)
914 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']))
915 f.write('</table>')
917 allauthors = data.getAuthors()
918 if len(allauthors) > conf['max_authors']:
919 rest = allauthors[conf['max_authors']:]
920 f.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest))
922 f.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
923 f.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
924 if len(allauthors) > conf['max_authors']:
925 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
927 f.write(html_header(2, 'Commits per Author'))
928 f.write('<img src="commits_by_author.png" alt="Commits per Author" />')
929 if len(allauthors) > conf['max_authors']:
930 f.write('<p class="moreauthors">Only top %d authors shown</p>' % conf['max_authors'])
932 fgl = open(path + '/lines_of_code_by_author.dat', 'w')
933 fgc = open(path + '/commits_by_author.dat', 'w')
935 lines_by_authors = {} # cumulated added lines by
936 # author. to save memory,
937 # changes_by_date_by_author[stamp][author] is defined
938 # only at points where author commits.
939 # lines_by_authors allows us to generate all the
940 # points in the .dat file.
942 # Don't rely on getAuthors to give the same order each
943 # time. Be robust and keep the list in a variable.
944 commits_by_authors = {} # cumulated added lines by
946 self.authors_to_plot = data.getAuthors(conf['max_authors'])
947 for author in self.authors_to_plot:
948 lines_by_authors[author] = 0
949 commits_by_authors[author] = 0
950 for stamp in sorted(data.changes_by_date_by_author.keys()):
951 fgl.write('%d' % stamp)
952 fgc.write('%d' % stamp)
953 for author in self.authors_to_plot:
954 if author in data.changes_by_date_by_author[stamp].keys():
955 lines_by_authors[author] = data.changes_by_date_by_author[stamp][author]['lines_added']
956 commits_by_authors[author] = data.changes_by_date_by_author[stamp][author]['commits']
957 fgl.write(' %d' % lines_by_authors[author])
958 fgc.write(' %d' % commits_by_authors[author])
959 fgl.write('\n')
960 fgc.write('\n')
961 fgl.close()
962 fgc.close()
964 # Authors :: Author of Month
965 f.write(html_header(2, 'Author of Month'))
966 f.write('<table class="sortable" id="aom">')
967 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'])
968 for yymm in reversed(sorted(data.author_of_month.keys())):
969 authordict = data.author_of_month[yymm]
970 authors = getkeyssortedbyvalues(authordict)
971 authors.reverse()
972 commits = data.author_of_month[yymm][authors[0]]
973 next = ', '.join(authors[1:conf['authors_top']+1])
974 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)))
976 f.write('</table>')
978 f.write(html_header(2, 'Author of Year'))
979 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'])
980 for yy in reversed(sorted(data.author_of_year.keys())):
981 authordict = data.author_of_year[yy]
982 authors = getkeyssortedbyvalues(authordict)
983 authors.reverse()
984 commits = data.author_of_year[yy][authors[0]]
985 next = ', '.join(authors[1:conf['authors_top']+1])
986 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)))
987 f.write('</table>')
989 # Domains
990 f.write(html_header(2, 'Commits by Domains'))
991 domains_by_commits = getkeyssortedbyvaluekey(data.domains, 'commits')
992 domains_by_commits.reverse() # most first
993 f.write('<div class="vtable"><table>')
994 f.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
995 fp = open(path + '/domains.dat', 'w')
996 n = 0
997 for domain in domains_by_commits:
998 if n == conf['max_domains']:
999 break
1000 commits = 0
1001 n += 1
1002 info = data.getDomainInfo(domain)
1003 fp.write('%s %d %d\n' % (domain, n , info['commits']))
1004 f.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain, info['commits'], (100.0 * info['commits'] / totalcommits)))
1005 f.write('</table></div>')
1006 f.write('<img src="domains.png" alt="Commits by Domains" />')
1007 fp.close()
1009 f.write('</body></html>')
1010 f.close()
1013 # Files
1014 f = open(path + '/files.html', 'w')
1015 self.printHeader(f)
1016 f.write('<h1>Files</h1>')
1017 self.printNav(f)
1019 f.write('<dl>\n')
1020 f.write('<dt>Total files</dt><dd>%d</dd>' % data.getTotalFiles())
1021 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1022 f.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % (float(data.getTotalSize()) / data.getTotalFiles()))
1023 f.write('</dl>\n')
1025 # Files :: File count by date
1026 f.write(html_header(2, 'File count by date'))
1028 # use set to get rid of duplicate/unnecessary entries
1029 files_by_date = set()
1030 for stamp in sorted(data.files_by_stamp.keys()):
1031 files_by_date.add('%s %d' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1033 fg = open(path + '/files_by_date.dat', 'w')
1034 for line in sorted(list(files_by_date)):
1035 fg.write('%s\n' % line)
1036 #for stamp in sorted(data.files_by_stamp.keys()):
1037 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1038 fg.close()
1040 f.write('<img src="files_by_date.png" alt="Files by Date" />')
1042 #f.write('<h2>Average file size by date</h2>')
1044 # Files :: Extensions
1045 f.write(html_header(2, 'Extensions'))
1046 f.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
1047 for ext in sorted(data.extensions.keys()):
1048 files = data.extensions[ext]['files']
1049 lines = data.extensions[ext]['lines']
1050 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))
1051 f.write('</table>')
1053 f.write('</body></html>')
1054 f.close()
1057 # Lines
1058 f = open(path + '/lines.html', 'w')
1059 self.printHeader(f)
1060 f.write('<h1>Lines</h1>')
1061 self.printNav(f)
1063 f.write('<dl>\n')
1064 f.write('<dt>Total lines</dt><dd>%d</dd>' % data.getTotalLOC())
1065 f.write('</dl>\n')
1067 f.write(html_header(2, 'Lines of Code'))
1068 f.write('<img src="lines_of_code.png" />')
1070 fg = open(path + '/lines_of_code.dat', 'w')
1071 for stamp in sorted(data.changes_by_date.keys()):
1072 fg.write('%d %d\n' % (stamp, data.changes_by_date[stamp]['lines']))
1073 fg.close()
1075 f.write('</body></html>')
1076 f.close()
1079 # tags.html
1080 f = open(path + '/tags.html', 'w')
1081 self.printHeader(f)
1082 f.write('<h1>Tags</h1>')
1083 self.printNav(f)
1085 f.write('<dl>')
1086 f.write('<dt>Total tags</dt><dd>%d</dd>' % len(data.tags))
1087 if len(data.tags) > 0:
1088 f.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data.getTotalCommits() / len(data.tags)))
1089 f.write('</dl>')
1091 f.write('<table class="tags">')
1092 f.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1093 # sort the tags by date desc
1094 tags_sorted_by_date_desc = map(lambda el : el[1], reversed(sorted(map(lambda el : (el[1]['date'], el[0]), data.tags.items()))))
1095 for tag in tags_sorted_by_date_desc:
1096 authorinfo = []
1097 self.authors_by_commits = getkeyssortedbyvalues(data.tags[tag]['authors'])
1098 for i in reversed(self.authors_by_commits):
1099 authorinfo.append('%s (%d)' % (i, data.tags[tag]['authors'][i]))
1100 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)))
1101 f.write('</table>')
1103 f.write('</body></html>')
1104 f.close()
1106 self.createGraphs(path)
1108 def createGraphs(self, path):
1109 print 'Generating graphs...'
1111 # hour of day
1112 f = open(path + '/hour_of_day.plot', 'w')
1113 f.write(GNUPLOT_COMMON)
1114 f.write(
1116 set output 'hour_of_day.png'
1117 unset key
1118 set xrange [0.5:24.5]
1119 set xtics 4
1120 set grid y
1121 set ylabel "Commits"
1122 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1123 """)
1124 f.close()
1126 # day of week
1127 f = open(path + '/day_of_week.plot', 'w')
1128 f.write(GNUPLOT_COMMON)
1129 f.write(
1131 set output 'day_of_week.png'
1132 unset key
1133 set xrange [0.5:7.5]
1134 set xtics 1
1135 set grid y
1136 set ylabel "Commits"
1137 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1138 """)
1139 f.close()
1141 # Domains
1142 f = open(path + '/domains.plot', 'w')
1143 f.write(GNUPLOT_COMMON)
1144 f.write(
1146 set output 'domains.png'
1147 unset key
1148 unset xtics
1149 set yrange [0:]
1150 set grid y
1151 set ylabel "Commits"
1152 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1153 """)
1154 f.close()
1156 # Month of Year
1157 f = open(path + '/month_of_year.plot', 'w')
1158 f.write(GNUPLOT_COMMON)
1159 f.write(
1161 set output 'month_of_year.png'
1162 unset key
1163 set xrange [0.5:12.5]
1164 set xtics 1
1165 set grid y
1166 set ylabel "Commits"
1167 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1168 """)
1169 f.close()
1171 # commits_by_year_month
1172 f = open(path + '/commits_by_year_month.plot', 'w')
1173 f.write(GNUPLOT_COMMON)
1174 f.write(
1176 set output 'commits_by_year_month.png'
1177 unset key
1178 set xdata time
1179 set timefmt "%Y-%m"
1180 set format x "%Y-%m"
1181 set xtics rotate
1182 set bmargin 5
1183 set grid y
1184 set ylabel "Commits"
1185 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1186 """)
1187 f.close()
1189 # commits_by_year
1190 f = open(path + '/commits_by_year.plot', 'w')
1191 f.write(GNUPLOT_COMMON)
1192 f.write(
1194 set output 'commits_by_year.png'
1195 unset key
1196 set xtics 1 rotate
1197 set grid y
1198 set ylabel "Commits"
1199 set yrange [0:]
1200 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1201 """)
1202 f.close()
1204 # Files by date
1205 f = open(path + '/files_by_date.plot', 'w')
1206 f.write(GNUPLOT_COMMON)
1207 f.write(
1209 set output 'files_by_date.png'
1210 unset key
1211 set xdata time
1212 set timefmt "%Y-%m-%d"
1213 set format x "%Y-%m-%d"
1214 set grid y
1215 set ylabel "Files"
1216 set xtics rotate
1217 set ytics autofreq
1218 set bmargin 6
1219 plot 'files_by_date.dat' using 1:2 w steps
1220 """)
1221 f.close()
1223 # Lines of Code
1224 f = open(path + '/lines_of_code.plot', 'w')
1225 f.write(GNUPLOT_COMMON)
1226 f.write(
1228 set output 'lines_of_code.png'
1229 unset key
1230 set xdata time
1231 set timefmt "%s"
1232 set format x "%Y-%m-%d"
1233 set grid y
1234 set ylabel "Lines"
1235 set xtics rotate
1236 set bmargin 6
1237 plot 'lines_of_code.dat' using 1:2 w lines
1238 """)
1239 f.close()
1241 # Lines of Code Added per author
1242 f = open(path + '/lines_of_code_by_author.plot', 'w')
1243 f.write(GNUPLOT_COMMON)
1244 f.write(
1246 set terminal png transparent size 640,480
1247 set output 'lines_of_code_by_author.png'
1248 set key left top
1249 set xdata time
1250 set timefmt "%s"
1251 set format x "%Y-%m-%d"
1252 set grid y
1253 set ylabel "Lines"
1254 set xtics rotate
1255 set bmargin 6
1256 plot """
1258 i = 1
1259 plots = []
1260 for a in self.authors_to_plot:
1261 i = i + 1
1262 plots.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1263 f.write(", ".join(plots))
1264 f.write('\n')
1266 f.close()
1268 # Commits per author
1269 f = open(path + '/commits_by_author.plot', 'w')
1270 f.write(GNUPLOT_COMMON)
1271 f.write(
1273 set terminal png transparent size 640,480
1274 set output 'commits_by_author.png'
1275 set key left top
1276 set xdata time
1277 set timefmt "%s"
1278 set format x "%Y-%m-%d"
1279 set grid y
1280 set ylabel "Commits"
1281 set xtics rotate
1282 set bmargin 6
1283 plot """
1285 i = 1
1286 plots = []
1287 for a in self.authors_to_plot:
1288 i = i + 1
1289 plots.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i, a.replace("\"", "\\\"")))
1290 f.write(", ".join(plots))
1291 f.write('\n')
1293 f.close()
1295 os.chdir(path)
1296 files = glob.glob(path + '/*.plot')
1297 for f in files:
1298 out = getpipeoutput([gnuplot_cmd + ' "%s"' % f])
1299 if len(out) > 0:
1300 print out
1302 def printHeader(self, f, title = ''):
1303 f.write(
1304 """<?xml version="1.0" encoding="UTF-8"?>
1305 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1306 <html xmlns="http://www.w3.org/1999/xhtml">
1307 <head>
1308 <title>GitStats - %s</title>
1309 <link rel="stylesheet" href="%s" type="text/css" />
1310 <meta name="generator" content="GitStats %s" />
1311 <script type="text/javascript" src="sortable.js"></script>
1312 </head>
1313 <body>
1314 """ % (self.title, conf['style'], getversion()))
1316 def printNav(self, f):
1317 f.write("""
1318 <div class="nav">
1319 <ul>
1320 <li><a href="index.html">General</a></li>
1321 <li><a href="activity.html">Activity</a></li>
1322 <li><a href="authors.html">Authors</a></li>
1323 <li><a href="files.html">Files</a></li>
1324 <li><a href="lines.html">Lines</a></li>
1325 <li><a href="tags.html">Tags</a></li>
1326 </ul>
1327 </div>
1328 """)
1331 class GitStats:
1332 def run(self, args_orig):
1333 optlist, args = getopt.getopt(args_orig, 'c:')
1334 for o,v in optlist:
1335 if o == '-c':
1336 key, value = v.split('=', 1)
1337 if key not in conf:
1338 raise KeyError('no such key "%s" in config' % key)
1339 if isinstance(conf[key], int):
1340 conf[key] = int(value)
1341 else:
1342 conf[key] = value
1344 if len(args) < 2:
1345 print """
1346 Usage: gitstats [options] <gitpath..> <outputpath>
1348 Options:
1349 -c key=value Override configuration value
1351 Default config values:
1353 """ % conf
1354 sys.exit(0)
1356 outputpath = os.path.abspath(args[-1])
1357 rundir = os.getcwd()
1359 try:
1360 os.makedirs(outputpath)
1361 except OSError:
1362 pass
1363 if not os.path.isdir(outputpath):
1364 print 'FATAL: Output path is not a directory or does not exist'
1365 sys.exit(1)
1367 print 'Output path: %s' % outputpath
1368 cachefile = os.path.join(outputpath, 'gitstats.cache')
1370 data = GitDataCollector()
1371 data.loadCache(cachefile)
1373 for gitpath in args[0:-1]:
1374 print 'Git path: %s' % gitpath
1376 os.chdir(gitpath)
1378 print 'Collecting data...'
1379 data.collect(gitpath)
1381 print 'Refining data...'
1382 data.saveCache(cachefile)
1383 data.refine()
1385 os.chdir(rundir)
1387 print 'Generating report...'
1388 report = HTMLReportCreator()
1389 report.create(data, outputpath)
1391 time_end = time.time()
1392 exectime_internal = time_end - time_start
1393 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal)
1394 if sys.stdin.isatty():
1395 print 'You may now run:'
1396 print
1397 print ' sensible-browser \'%s\'' % os.path.join(outputpath, 'index.html').replace("'", "'\\''")
1398 print
1400 if __name__=='__main__':
1401 g = GitStats()
1402 g.run(sys.argv[1:])