2 # Copyright (c) 2007-2011 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
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']
34 'style': 'gitstats.css',
39 'linear_linestats': 1,
43 def getpipeoutput(cmds
, quiet
= False):
44 global exectime_external
46 if not quiet
and ON_LINUX
and os
.isatty(1):
47 print '>> ' + ' | '.join(cmds
),
49 p0
= subprocess
.Popen(cmds
[0], stdout
= subprocess
.PIPE
, shell
= True)
52 p
= subprocess
.Popen(x
, stdin
= p0
.stdout
, stdout
= subprocess
.PIPE
, shell
= True)
54 output
= p
.communicate()[0]
57 if ON_LINUX
and os
.isatty(1):
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'])
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())))
81 VERSION
= getpipeoutput(["git rev-parse --short %s" % getcommitrange('HEAD')]).split('\n')[0]
85 return getpipeoutput(['git --version']).split('\n')[0]
87 def getgnuplotversion():
88 return getpipeoutput(['gnuplot --version']).split('\n')[0]
91 """Manages data collection from a revision control repository."""
93 self
.stamp_created
= time
.time()
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
109 self
.authors_by_commits
= 0
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()
126 self
.total_lines_added
= 0
127 self
.total_lines_removed
= 0
130 self
.commits_by_timezone
= {} # timezone -> commits
135 self
.files_by_stamp
= {} # stamp -> files
138 self
.extensions
= {} # extension -> files, lines
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):
147 if len(conf
['project_name']) == 0:
148 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
150 self
.projectname
= conf
['project_name']
153 # Load cacheable data
154 def loadCache(self
, cachefile
):
155 if not os
.path
.exists(cachefile
):
157 print 'Loading cache...'
158 f
= open(cachefile
, 'rb')
160 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
162 # temporary hack to upgrade non-compressed caches
164 self
.cache
= pickle
.load(f
)
168 # Produce any additional statistics from the extracted data.
173 # : get a dictionary of author
174 def getAuthorInfo(self
, author
):
177 def getActivityByDayOfWeek(self
):
180 def getActivityByHourOfDay(self
):
183 # : get a dictionary of domains
184 def getDomainInfo(self
, domain
):
188 # Get a list of authors
189 def getAuthors(self
):
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
204 def getTotalAuthors(self
):
207 def getTotalCommits(self
):
210 def getTotalFiles(self
):
213 def getTotalLOC(self
):
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
))
226 class GitDataCollector(DataCollector
):
227 def collect(self
, dir):
228 DataCollector
.collect(self
, dir)
231 self
.total_authors
+= int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
233 self
.total_authors
= 0
234 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
237 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
241 (hash, tag
) = line
.split(' ')
243 tag
= tag
.replace('refs/tags/', '')
244 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
246 parts
= output
.split(' ')
249 stamp
= int(parts
[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()))))
257 for tag
in reversed(tags_sorted_by_date_desc
):
258 cmd
= 'git shortlog -s "%s"' % tag
260 cmd
+= ' "^%s"' % prev
261 output
= getpipeoutput([cmd
])
265 for line
in output
.split('\n'):
266 parts
= re
.split('\s+', line
, 2)
267 commits
= int(parts
[1])
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')
276 parts
= line
.split(' ', 4)
279 stamp
= int(parts
[0])
283 author
, mail
= parts
[4].split('<', 1)
284 author
= author
.rstrip()
285 mail
= mail
.rstrip('>')
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
300 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
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
]
307 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
310 if domain
not in self
.domains
:
311 self
.domains
[domain
] = {}
313 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
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
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
]
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
]
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
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
356 if yy
in self
.author_of_year
:
357 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
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
)
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')
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
)
391 parts
= line
.split(' ')
394 (stamp
, files
) = parts
[0:2]
396 self
.files_by_stamp
[int(stamp
)] = int(files
)
398 print 'Warning: failed to parse line "%s"' % line
401 lines
= getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only
= True)]).split('\000')
402 self
.total_files
+= len(lines
)
406 parts
= re
.split('\s+', line
, 4)
410 filename
= fullpath
.split('/')[-1] # strip directories
411 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
414 ext
= filename
[(filename
.rfind('.') + 1):]
415 if len(ext
) > conf
['max_ext_length']:
418 if ext
not in self
.extensions
:
419 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
421 self
.extensions
[ext
]['files'] += 1
423 self
.extensions
[ext
]['lines'] += self
.getLinesInBlob(sha1
)
425 print 'Warning: Could not count lines for file "%s"' % line
429 # N files changed, N insertions (+), N deletions(-)
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.
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')
439 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
446 if line
.find('files changed,') == -1:
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
454 print 'Warning: unexpected line "%s"' % line
456 print 'Warning: unexpected line "%s"' % line
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
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')
481 files
= 0; inserted
= 0; deleted
= 0
489 if line
.find('files changed,') == -1:
494 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
496 # clock skew, keep old timestamp to avoid having ugly graph
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
511 print 'Warning: unexpected line "%s"' % line
513 print 'Warning: unexpected line "%s"' % line
515 numbers
= re
.findall('\d+', line
)
516 if len(numbers
) == 3:
517 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
519 print 'Warning: failed to handle line "%s"' % line
520 (files
, inserted
, deleted
) = (0, 0, 0)
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')
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
):
570 res
= self
.cache
['files_in_tree'][rev
]
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
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
):
587 res
= self
.cache
['lines_in_blob'][sha1
]
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
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')
619 """Creates the actual report based on given data."""
623 def create(self
, data
, 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)
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'
656 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
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()))
672 f
.write('</body>\n</html>')
677 f
= open(path
+ '/activity.html', 'w')
679 f
.write('<h1>Activity</h1>')
682 #f.write('<h2>Last 30 days</h2>')
684 #f.write('<h2>Last 12 months</h2>')
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)
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
):
704 if weeks
[i
] in data
.activity_by_year_week
:
705 commits
= data
.activity_by_year_week
[weeks
[i
]]
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
715 for i
in range(0, WEEKS
):
716 f
.write('<td>%s</td>' % (WEEKS
- i
))
717 f
.write('</tr></table>')
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):
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
]))
733 f
.write('<td>0</td>')
734 fp
.write('%d 0\n' % i
)
736 f
.write('</tr>\n<tr><th>%</th>')
737 totalcommits
= data
.getTotalCommits()
738 for i
in range(0, 24):
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
))
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):
749 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
751 fg
.write('%d 0\n' % (i
+ 1))
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):
763 commits
= day_of_week
[d
]
764 fp
.write('%d %s %d\n' % (d
+ 1, WEEKDAYS
[d
], commits
))
766 f
.write('<th>%s</th>' % (WEEKDAYS
[d
]))
768 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
770 f
.write('<td>0</td>')
772 f
.write('</table></div>')
773 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
777 f
.write(html_header(2, 'Hour of Week'))
780 f
.write('<tr><th>Weekday</th>')
781 for hour
in range(0, 24):
782 f
.write('<th>%d</th>' % (hour
))
785 for weekday
in range(0, 7):
786 f
.write('<tr><th>%s</th>' % (WEEKDAYS
[weekday
]))
787 for hour
in range(0, 24):
789 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
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
)
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):
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
))
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
]))
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
]))
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>')
858 f
= open(path
+ '/authors.html', 'w')
861 f
.write('<h1>Authors</h1>')
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']))
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
])
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
)
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
)))
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
)
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
)))
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')
954 for domain
in domains_by_commits
:
955 if n
== conf
['max_domains']:
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" />')
966 f
.write('</body></html>')
971 f
= open(path
+ '/files.html', 'w')
973 f
.write('<h1>Files</h1>')
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()))
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]))
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
))
1010 f
.write('</body></html>')
1015 f
= open(path
+ '/lines.html', 'w')
1017 f
.write('<h1>Lines</h1>')
1021 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
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']))
1032 f
.write('</body></html>')
1037 f
= open(path
+ '/tags.html', 'w')
1039 f
.write('<h1>Tags</h1>')
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
)))
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
:
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
)))
1060 f
.write('</body></html>')
1063 self
.createGraphs(path
)
1065 def createGraphs(self
, path
):
1066 print 'Generating graphs...'
1069 f
= open(path
+ '/hour_of_day.plot', 'w')
1070 f
.write(GNUPLOT_COMMON
)
1073 set output 'hour_of_day.png'
1075 set xrange [0.5:24.5]
1078 set ylabel "Commits"
1079 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1084 f
= open(path
+ '/day_of_week.plot', 'w')
1085 f
.write(GNUPLOT_COMMON
)
1088 set output 'day_of_week.png'
1090 set xrange [0.5:7.5]
1093 set ylabel "Commits"
1094 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1099 f
= open(path
+ '/domains.plot', 'w')
1100 f
.write(GNUPLOT_COMMON
)
1103 set output 'domains.png'
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
1114 f
= open(path
+ '/month_of_year.plot', 'w')
1115 f
.write(GNUPLOT_COMMON
)
1118 set output 'month_of_year.png'
1120 set xrange [0.5:12.5]
1123 set ylabel "Commits"
1124 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1128 # commits_by_year_month
1129 f
= open(path
+ '/commits_by_year_month.plot', 'w')
1130 f
.write(GNUPLOT_COMMON
)
1133 set output 'commits_by_year_month.png'
1137 set format x "%Y-%m"
1141 set ylabel "Commits"
1142 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1147 f
= open(path
+ '/commits_by_year.plot', 'w')
1148 f
.write(GNUPLOT_COMMON
)
1151 set output 'commits_by_year.png'
1155 set ylabel "Commits"
1157 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1162 f
= open(path
+ '/files_by_date.plot', 'w')
1163 f
.write(GNUPLOT_COMMON
)
1166 set output 'files_by_date.png'
1169 set timefmt "%Y-%m-%d"
1170 set format x "%Y-%m-%d"
1176 plot 'files_by_date.dat' using 1:2 w steps
1181 f
= open(path
+ '/lines_of_code.plot', 'w')
1182 f
.write(GNUPLOT_COMMON
)
1185 set output 'lines_of_code.png'
1189 set format x "%Y-%m-%d"
1194 plot 'lines_of_code.dat' using 1:2 w lines
1198 # Lines of Code Added per author
1199 f
= open(path
+ '/lines_of_code_by_author.plot', 'w')
1200 f
.write(GNUPLOT_COMMON
)
1203 set terminal png transparent size 640,480
1204 set output 'lines_of_code_by_author.png'
1208 set format x "%Y-%m-%d"
1217 for a
in self
.authors_to_plot
:
1219 plots
.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i
, a
.replace("\"", "\\\"")))
1220 f
.write(", ".join(plots
))
1225 # Commits per author
1226 f
= open(path
+ '/commits_by_author.plot', 'w')
1227 f
.write(GNUPLOT_COMMON
)
1230 set terminal png transparent size 640,480
1231 set output 'commits_by_author.png'
1235 set format x "%Y-%m-%d"
1237 set ylabel "Commits"
1244 for a
in self
.authors_to_plot
:
1246 plots
.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i
, a
.replace("\"", "\\\"")))
1247 f
.write(", ".join(plots
))
1253 files
= glob
.glob(path
+ '/*.plot')
1255 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1259 def printHeader(self
, f
, title
= ''):
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">
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>
1271 """ % (self
.title
, conf
['style'], getversion()))
1273 def printNav(self
, f
):
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>
1289 def run(self
, args_orig
):
1290 optlist
, args
= getopt
.getopt(args_orig
, 'c:')
1293 key
, value
= v
.split('=', 1)
1295 raise KeyError('no such key "%s" in config' % key
)
1296 if isinstance(conf
[key
], int):
1297 conf
[key
] = int(value
)
1303 Usage: gitstats [options] <gitpath..> <outputpath>
1306 -c key=value Override configuration value
1308 Default config values:
1313 outputpath
= os
.path
.abspath(args
[-1])
1314 rundir
= os
.getcwd()
1317 os
.makedirs(outputpath
)
1320 if not os
.path
.isdir(outputpath
):
1321 print 'FATAL: Output path is not a directory or does not exist'
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
1335 print 'Collecting data...'
1336 data
.collect(gitpath
)
1338 print 'Refining data...'
1339 data
.saveCache(cachefile
)
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__':