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