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