2 # Copyright (c) 2007-2010 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
17 GNUPLOT_COMMON
= 'set terminal png transparent\nset size 1.0,0.5\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',
41 def getpipeoutput(cmds
, quiet
= False):
42 global exectime_external
44 if not quiet
and ON_LINUX
and os
.isatty(1):
45 print '>> ' + ' | '.join(cmds
),
47 p0
= subprocess
.Popen(cmds
[0], stdout
= subprocess
.PIPE
, shell
= True)
50 p
= subprocess
.Popen(x
, stdin
= p0
.stdout
, stdout
= subprocess
.PIPE
, shell
= True)
52 output
= p
.communicate()[0]
55 if ON_LINUX
and os
.isatty(1):
57 print '[%.5f] >> %s' % (end
- start
, ' | '.join(cmds
))
58 exectime_external
+= (end
- start
)
59 return output
.rstrip('\n')
61 def getcommitrange(defaultrange
= '', end_only
= False):
62 if len(conf
['commit_end']) > 0:
63 if end_only
or len(conf
['commit_begin']) == 0:
64 return conf
['commit_end']
65 return '%s..%s' % (conf
['commit_begin'], conf
['commit_end'])
68 def getkeyssortedbyvalues(dict):
69 return map(lambda el
: el
[1], sorted(map(lambda el
: (el
[1], el
[0]), dict.items())))
71 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
72 def getkeyssortedbyvaluekey(d
, key
):
73 return map(lambda el
: el
[1], sorted(map(lambda el
: (d
[el
][key
], el
), d
.keys())))
79 VERSION
= getpipeoutput(["git rev-parse --short %s" % getcommitrange('HEAD')]).split('\n')[0]
83 """Manages data collection from a revision control repository."""
85 self
.stamp_created
= time
.time()
89 # This should be the main function to extract data from the repository.
90 def collect(self
, dir):
92 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
96 def loadCache(self
, cachefile
):
97 if not os
.path
.exists(cachefile
):
99 print 'Loading cache...'
100 f
= open(cachefile
, 'rb')
102 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
104 # temporary hack to upgrade non-compressed caches
106 self
.cache
= pickle
.load(f
)
110 # Produce any additional statistics from the extracted data.
115 # : get a dictionary of author
116 def getAuthorInfo(self
, author
):
119 def getActivityByDayOfWeek(self
):
122 def getActivityByHourOfDay(self
):
125 # : get a dictionary of domains
126 def getDomainInfo(self
, domain
):
130 # Get a list of authors
131 def getAuthors(self
):
134 def getFirstCommitDate(self
):
135 return datetime
.datetime
.now()
137 def getLastCommitDate(self
):
138 return datetime
.datetime
.now()
140 def getStampCreated(self
):
141 return self
.stamp_created
146 def getTotalAuthors(self
):
149 def getTotalCommits(self
):
152 def getTotalFiles(self
):
155 def getTotalLOC(self
):
159 # Save cacheable data
160 def saveCache(self
, cachefile
):
161 print 'Saving cache...'
162 f
= open(cachefile
, 'wb')
163 #pickle.dump(self.cache, f)
164 data
= zlib
.compress(pickle
.dumps(self
.cache
))
168 class GitDataCollector(DataCollector
):
169 def collect(self
, dir):
170 DataCollector
.collect(self
, dir)
173 self
.total_authors
= int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
175 self
.total_authors
= 0
176 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
178 self
.activity_by_hour_of_day
= {} # hour -> commits
179 self
.activity_by_day_of_week
= {} # day -> commits
180 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
181 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
182 self
.activity_by_hour_of_day_busiest
= 0
183 self
.activity_by_hour_of_week_busiest
= 0
184 self
.activity_by_year_week
= {} # yy_wNN -> commits
185 self
.activity_by_year_week_peak
= 0
187 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
190 self
.domains
= {} # domain -> commits
192 # author of the month
193 self
.author_of_month
= {} # month -> author -> commits
194 self
.author_of_year
= {} # year -> author -> commits
195 self
.commits_by_month
= {} # month -> commits
196 self
.commits_by_year
= {} # year -> commits
197 self
.first_commit_stamp
= 0
198 self
.last_commit_stamp
= 0
199 self
.last_active_day
= None
200 self
.active_days
= set()
204 self
.total_lines_added
= 0
205 self
.total_lines_removed
= 0
208 self
.commits_by_timezone
= {} # timezone -> commits
212 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
216 (hash, tag
) = line
.split(' ')
218 tag
= tag
.replace('refs/tags/', '')
219 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
221 parts
= output
.split(' ')
224 stamp
= int(parts
[0])
227 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
229 # collect info on tags, starting from latest
230 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), self
.tags
.items()))))
232 for tag
in reversed(tags_sorted_by_date_desc
):
233 cmd
= 'git shortlog -s "%s"' % tag
235 cmd
+= ' "^%s"' % prev
236 output
= getpipeoutput([cmd
])
240 for line
in output
.split('\n'):
241 parts
= re
.split('\s+', line
, 2)
242 commits
= int(parts
[1])
244 self
.tags
[tag
]['commits'] += commits
245 self
.tags
[tag
]['authors'][author
] = commits
247 # Collect revision statistics
248 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
249 lines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
251 parts
= line
.split(' ', 4)
254 stamp
= int(parts
[0])
258 author
, mail
= parts
[4].split('<', 1)
259 author
= author
.rstrip()
260 mail
= mail
.rstrip('>')
262 if mail
.find('@') != -1:
263 domain
= mail
.rsplit('@', 1)[1]
264 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
266 # First and last commit stamp
267 if self
.last_commit_stamp
== 0:
268 self
.last_commit_stamp
= stamp
269 self
.first_commit_stamp
= stamp
274 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
276 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
277 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
281 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
284 if domain
not in self
.domains
:
285 self
.domains
[domain
] = {}
287 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
290 if day
not in self
.activity_by_hour_of_week
:
291 self
.activity_by_hour_of_week
[day
] = {}
292 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
294 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
295 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
299 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
301 # yearly/weekly activity
302 yyw
= date
.strftime('%Y-%W')
303 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
304 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
305 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
308 if author
not in self
.authors
:
309 self
.authors
[author
] = {}
311 if 'last_commit_stamp' not in self
.authors
[author
]:
312 self
.authors
[author
]['last_commit_stamp'] = stamp
313 self
.authors
[author
]['first_commit_stamp'] = stamp
314 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
316 # author of the month/year
317 yymm
= date
.strftime('%Y-%m')
318 if yymm
in self
.author_of_month
:
319 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
321 self
.author_of_month
[yymm
] = {}
322 self
.author_of_month
[yymm
][author
] = 1
323 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
326 if yy
in self
.author_of_year
:
327 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
329 self
.author_of_year
[yy
] = {}
330 self
.author_of_year
[yy
][author
] = 1
331 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
333 # authors: active days
334 yymmdd
= date
.strftime('%Y-%m-%d')
335 if 'last_active_day' not in self
.authors
[author
]:
336 self
.authors
[author
]['last_active_day'] = yymmdd
337 self
.authors
[author
]['active_days'] = 1
338 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
339 self
.authors
[author
]['last_active_day'] = yymmdd
340 self
.authors
[author
]['active_days'] += 1
342 # project: active days
343 if yymmdd
!= self
.last_active_day
:
344 self
.last_active_day
= yymmdd
345 self
.active_days
.add(yymmdd
)
348 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
350 # TODO Optimize this, it's the worst bottleneck
351 # outputs "<stamp> <files>" for each revision
352 self
.files_by_stamp
= {} # stamp -> files
353 revlines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
355 for revline
in revlines
:
356 time
, rev
= revline
.split(' ')
357 linecount
= self
.getFilesInCommit(rev
)
358 lines
.append('%d %d' % (int(time
), linecount
))
360 self
.total_commits
= len(lines
)
362 parts
= line
.split(' ')
365 (stamp
, files
) = parts
[0:2]
367 self
.files_by_stamp
[int(stamp
)] = int(files
)
369 print 'Warning: failed to parse line "%s"' % line
372 self
.extensions
= {} # extension -> files, lines
373 lines
= getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only
= True)]).split('\000')
374 self
.total_files
= len(lines
)
378 parts
= re
.split('\s+', line
, 4)
382 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
385 ext
= filename
[(filename
.rfind('.') + 1):]
386 if len(ext
) > conf
['max_ext_length']:
389 if ext
not in self
.extensions
:
390 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
392 self
.extensions
[ext
]['files'] += 1
394 self
.extensions
[ext
]['lines'] += self
.getLinesInBlob(sha1
)
396 print 'Warning: Could not count lines for file "%s"' % line
400 # N files changed, N insertions (+), N deletions(-)
402 self
.changes_by_date
= {} # stamp -> { files, ins, del }
403 lines
= getpipeoutput(['git log --shortstat --pretty=format:"%%at %%aN" %s' % getcommitrange('HEAD')]).split('\n')
405 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
412 if line
.find('files changed,') == -1:
416 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
417 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
418 if author
not in self
.authors
:
419 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0 }
420 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
421 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
422 files
, inserted
, deleted
= 0, 0, 0
424 print 'Warning: unexpected line "%s"' % line
426 print 'Warning: unexpected line "%s"' % line
428 numbers
= re
.findall('\d+', line
)
429 if len(numbers
) == 3:
430 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
431 total_lines
+= inserted
432 total_lines
-= deleted
433 self
.total_lines_added
+= inserted
434 self
.total_lines_removed
+= deleted
436 print 'Warning: failed to handle line "%s"' % line
437 (files
, inserted
, deleted
) = (0, 0, 0)
438 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
439 self
.total_lines
= total_lines
443 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
444 authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
445 authors_by_commits
.reverse() # most first
446 for i
, name
in enumerate(authors_by_commits
):
447 self
.authors
[name
]['place_by_commits'] = i
+ 1
449 for name
in self
.authors
.keys():
450 a
= self
.authors
[name
]
451 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
452 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
453 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
454 delta
= date_last
- date_first
455 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
456 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
457 a
['timedelta'] = delta
459 def getActiveDays(self
):
460 return self
.active_days
462 def getActivityByDayOfWeek(self
):
463 return self
.activity_by_day_of_week
465 def getActivityByHourOfDay(self
):
466 return self
.activity_by_hour_of_day
468 def getAuthorInfo(self
, author
):
469 return self
.authors
[author
]
471 def getAuthors(self
, limit
= None):
472 res
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
476 def getCommitDeltaDays(self
):
477 return (self
.last_commit_stamp
- self
.first_commit_stamp
) / 86400 + 1
479 def getDomainInfo(self
, domain
):
480 return self
.domains
[domain
]
482 def getDomains(self
):
483 return self
.domains
.keys()
485 def getFilesInCommit(self
, rev
):
487 res
= self
.cache
['files_in_tree'][rev
]
489 res
= int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0])
490 if 'files_in_tree' not in self
.cache
:
491 self
.cache
['files_in_tree'] = {}
492 self
.cache
['files_in_tree'][rev
] = res
496 def getFirstCommitDate(self
):
497 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
499 def getLastCommitDate(self
):
500 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
502 def getLinesInBlob(self
, sha1
):
504 res
= self
.cache
['lines_in_blob'][sha1
]
506 res
= int(getpipeoutput(['git cat-file blob %s' % sha1
, 'wc -l']).split()[0])
507 if 'lines_in_blob' not in self
.cache
:
508 self
.cache
['lines_in_blob'] = {}
509 self
.cache
['lines_in_blob'][sha1
] = res
513 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
514 return lines
.split('\n')
516 def getTagDate(self
, tag
):
517 return self
.revToDate('tags/' + tag
)
519 def getTotalAuthors(self
):
520 return self
.total_authors
522 def getTotalCommits(self
):
523 return self
.total_commits
525 def getTotalFiles(self
):
526 return self
.total_files
528 def getTotalLOC(self
):
529 return self
.total_lines
531 def revToDate(self
, rev
):
532 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
533 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
536 """Creates the actual report based on given data."""
540 def create(self
, data
, path
):
544 def html_linkify(text
):
545 return text
.lower().replace(' ', '_')
547 def html_header(level
, text
):
548 name
= html_linkify(text
)
549 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
551 class HTMLReportCreator(ReportCreator
):
552 def create(self
, data
, path
):
553 ReportCreator
.create(self
, data
, path
)
554 self
.title
= data
.projectname
556 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
557 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
558 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
559 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
560 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
561 for base
in basedirs
:
562 src
= base
+ '/' + file
563 if os
.path
.exists(src
):
564 shutil
.copyfile(src
, path
+ '/' + file)
567 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
569 f
= open(path
+ "/index.html", 'w')
570 format
= '%Y-%m-%d %H:%M:%S'
573 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
578 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
579 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
580 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
581 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
582 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())))
583 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
584 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
))
585 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()))
586 f
.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data
.getTotalAuthors(), (1.0 * data
.getTotalCommits()) / data
.getTotalAuthors()))
589 f
.write('</body>\n</html>')
594 f
= open(path
+ '/activity.html', 'w')
596 f
.write('<h1>Activity</h1>')
599 #f.write('<h2>Last 30 days</h2>')
601 #f.write('<h2>Last 12 months</h2>')
605 f
.write(html_header(2, 'Weekly activity'))
606 f
.write('<p>Last %d weeks</p>' % WEEKS
)
608 # generate weeks to show (previous N weeks from now)
609 now
= datetime
.datetime
.now()
610 deltaweek
= datetime
.timedelta(7)
613 for i
in range(0, WEEKS
):
614 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
615 stampcur
-= deltaweek
617 # top row: commits & bar
618 f
.write('<table class="noborders"><tr>')
619 for i
in range(0, WEEKS
):
621 if weeks
[i
] in data
.activity_by_year_week
:
622 commits
= data
.activity_by_year_week
[weeks
[i
]]
625 if weeks
[i
] in data
.activity_by_year_week
:
626 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
627 height
= max(1, int(200 * percentage
))
628 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
))
630 # bottom row: year/week
632 for i
in range(0, WEEKS
):
633 f
.write('<td>%s</td>' % (WEEKS
- i
))
634 f
.write('</tr></table>')
637 f
.write(html_header(2, 'Hour of Day'))
638 hour_of_day
= data
.getActivityByHourOfDay()
639 f
.write('<table><tr><th>Hour</th>')
640 for i
in range(0, 24):
641 f
.write('<th>%d</th>' % i
)
642 f
.write('</tr>\n<tr><th>Commits</th>')
643 fp
= open(path
+ '/hour_of_day.dat', 'w')
644 for i
in range(0, 24):
646 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
647 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
648 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
650 f
.write('<td>0</td>')
651 fp
.write('%d 0\n' % i
)
653 f
.write('</tr>\n<tr><th>%</th>')
654 totalcommits
= data
.getTotalCommits()
655 for i
in range(0, 24):
657 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
658 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
660 f
.write('<td>0.00</td>')
661 f
.write('</tr></table>')
662 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
663 fg
= open(path
+ '/hour_of_day.dat', 'w')
664 for i
in range(0, 24):
666 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
668 fg
.write('%d 0\n' % (i
+ 1))
672 f
.write(html_header(2, 'Day of Week'))
673 day_of_week
= data
.getActivityByDayOfWeek()
674 f
.write('<div class="vtable"><table>')
675 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
676 fp
= open(path
+ '/day_of_week.dat', 'w')
677 for d
in range(0, 7):
680 commits
= day_of_week
[d
]
681 fp
.write('%d %s %d\n' % (d
+ 1, WEEKDAYS
[d
], commits
))
683 f
.write('<th>%s</th>' % (WEEKDAYS
[d
]))
685 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
687 f
.write('<td>0</td>')
689 f
.write('</table></div>')
690 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
694 f
.write(html_header(2, 'Hour of Week'))
697 f
.write('<tr><th>Weekday</th>')
698 for hour
in range(0, 24):
699 f
.write('<th>%d</th>' % (hour
))
702 for weekday
in range(0, 7):
703 f
.write('<tr><th>%s</th>' % (WEEKDAYS
[weekday
]))
704 for hour
in range(0, 24):
706 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
711 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
712 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
713 f
.write('>%d</td>' % commits
)
721 f
.write(html_header(2, 'Month of Year'))
722 f
.write('<div class="vtable"><table>')
723 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
724 fp
= open (path
+ '/month_of_year.dat', 'w')
725 for mm
in range(1, 13):
727 if mm
in data
.activity_by_month_of_year
:
728 commits
= data
.activity_by_month_of_year
[mm
]
729 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
730 fp
.write('%d %d\n' % (mm
, commits
))
732 f
.write('</table></div>')
733 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
735 # Commits by year/month
736 f
.write(html_header(2, 'Commits by year/month'))
737 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
738 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
739 f
.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
[yymm
]))
740 f
.write('</table></div>')
741 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
742 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
743 for yymm
in sorted(data
.commits_by_month
.keys()):
744 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
748 f
.write(html_header(2, 'Commits by Year'))
749 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
750 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
751 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()))
752 f
.write('</table></div>')
753 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
754 fg
= open(path
+ '/commits_by_year.dat', 'w')
755 for yy
in sorted(data
.commits_by_year
.keys()):
756 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
759 # Commits by timezone
760 f
.write(html_header(2, 'Commits by Timezone'))
761 f
.write('<table><tr>')
762 f
.write('<th>Timezone</th><th>Commits</th>')
763 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
764 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
765 commits
= data
.commits_by_timezone
[i
]
766 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
767 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
768 f
.write('</tr></table>')
770 f
.write('</body></html>')
775 f
= open(path
+ '/authors.html', 'w')
778 f
.write('<h1>Authors</h1>')
781 # Authors :: List of authors
782 f
.write(html_header(2, 'List of Authors'))
784 f
.write('<table class="authors sortable" id="authors">')
785 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>')
786 for author
in data
.getAuthors(conf
['max_authors']):
787 info
= data
.getAuthorInfo(author
)
788 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'], info
['active_days'], info
['place_by_commits']))
791 allauthors
= data
.getAuthors()
792 if len(allauthors
) > conf
['max_authors']:
793 rest
= allauthors
[conf
['max_authors']:]
794 f
.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest
))
796 # Authors :: Author of Month
797 f
.write(html_header(2, 'Author of Month'))
798 f
.write('<table class="sortable" id="aom">')
799 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'])
800 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
801 authordict
= data
.author_of_month
[yymm
]
802 authors
= getkeyssortedbyvalues(authordict
)
804 commits
= data
.author_of_month
[yymm
][authors
[0]]
805 next
= ', '.join(authors
[1:conf
['authors_top']+1])
806 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
)))
810 f
.write(html_header(2, 'Author of Year'))
811 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'])
812 for yy
in reversed(sorted(data
.author_of_year
.keys())):
813 authordict
= data
.author_of_year
[yy
]
814 authors
= getkeyssortedbyvalues(authordict
)
816 commits
= data
.author_of_year
[yy
][authors
[0]]
817 next
= ', '.join(authors
[1:conf
['authors_top']+1])
818 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
)))
822 f
.write(html_header(2, 'Commits by Domains'))
823 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
824 domains_by_commits
.reverse() # most first
825 f
.write('<div class="vtable"><table>')
826 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
827 fp
= open(path
+ '/domains.dat', 'w')
829 for domain
in domains_by_commits
:
830 if n
== conf
['max_domains']:
834 info
= data
.getDomainInfo(domain
)
835 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
836 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
837 f
.write('</table></div>')
838 f
.write('<img src="domains.png" alt="Commits by Domains" />')
841 f
.write('</body></html>')
846 f
= open(path
+ '/files.html', 'w')
848 f
.write('<h1>Files</h1>')
852 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
853 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
854 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data
.getTotalLOC()) / data
.getTotalFiles()))
857 # Files :: File count by date
858 f
.write(html_header(2, 'File count by date'))
860 # use set to get rid of duplicate/unnecessary entries
861 files_by_date
= set()
862 for stamp
in sorted(data
.files_by_stamp
.keys()):
863 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
865 fg
= open(path
+ '/files_by_date.dat', 'w')
866 for line
in sorted(list(files_by_date
)):
867 fg
.write('%s\n' % line
)
868 #for stamp in sorted(data.files_by_stamp.keys()):
869 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
872 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
874 #f.write('<h2>Average file size by date</h2>')
876 # Files :: Extensions
877 f
.write(html_header(2, 'Extensions'))
878 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
879 for ext
in sorted(data
.extensions
.keys()):
880 files
= data
.extensions
[ext
]['files']
881 lines
= data
.extensions
[ext
]['lines']
882 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
))
885 f
.write('</body></html>')
890 f
= open(path
+ '/lines.html', 'w')
892 f
.write('<h1>Lines</h1>')
896 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
899 f
.write(html_header(2, 'Lines of Code'))
900 f
.write('<img src="lines_of_code.png" />')
902 fg
= open(path
+ '/lines_of_code.dat', 'w')
903 for stamp
in sorted(data
.changes_by_date
.keys()):
904 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
907 f
.write('</body></html>')
912 f
= open(path
+ '/tags.html', 'w')
914 f
.write('<h1>Tags</h1>')
918 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
919 if len(data
.tags
) > 0:
920 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
923 f
.write('<table class="tags">')
924 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
925 # sort the tags by date desc
926 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
927 for tag
in tags_sorted_by_date_desc
:
929 authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
930 for i
in reversed(authors_by_commits
):
931 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
932 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
)))
935 f
.write('</body></html>')
938 self
.createGraphs(path
)
940 def createGraphs(self
, path
):
941 print 'Generating graphs...'
944 f
= open(path
+ '/hour_of_day.plot', 'w')
945 f
.write(GNUPLOT_COMMON
)
948 set output 'hour_of_day.png'
950 set xrange [0.5:24.5]
954 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
959 f
= open(path
+ '/day_of_week.plot', 'w')
960 f
.write(GNUPLOT_COMMON
)
963 set output 'day_of_week.png'
969 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
974 f
= open(path
+ '/domains.plot', 'w')
975 f
.write(GNUPLOT_COMMON
)
978 set output 'domains.png'
984 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
989 f
= open(path
+ '/month_of_year.plot', 'w')
990 f
.write(GNUPLOT_COMMON
)
993 set output 'month_of_year.png'
995 set xrange [0.5:12.5]
999 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1003 # commits_by_year_month
1004 f
= open(path
+ '/commits_by_year_month.plot', 'w')
1005 f
.write(GNUPLOT_COMMON
)
1008 set output 'commits_by_year_month.png'
1012 set format x "%Y-%m"
1013 set xtics rotate by 90 15768000
1016 set ylabel "Commits"
1017 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1022 f
= open(path
+ '/commits_by_year.plot', 'w')
1023 f
.write(GNUPLOT_COMMON
)
1026 set output 'commits_by_year.png'
1028 set xtics 1 rotate by 90
1030 set ylabel "Commits"
1032 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1037 f
= open(path
+ '/files_by_date.plot', 'w')
1038 f
.write(GNUPLOT_COMMON
)
1041 set output 'files_by_date.png'
1044 set timefmt "%Y-%m-%d"
1045 set format x "%Y-%m-%d"
1048 set xtics rotate by 90
1051 plot 'files_by_date.dat' using 1:2 w steps
1056 f
= open(path
+ '/lines_of_code.plot', 'w')
1057 f
.write(GNUPLOT_COMMON
)
1060 set output 'lines_of_code.png'
1064 set format x "%Y-%m-%d"
1067 set xtics rotate by 90
1069 plot 'lines_of_code.dat' using 1:2 w lines
1074 files
= glob
.glob(path
+ '/*.plot')
1076 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1080 def printHeader(self
, f
, title
= ''):
1082 """<?xml version="1.0" encoding="UTF-8"?>
1083 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1084 <html xmlns="http://www.w3.org/1999/xhtml">
1086 <title>GitStats - %s</title>
1087 <link rel="stylesheet" href="%s" type="text/css" />
1088 <meta name="generator" content="GitStats %s" />
1089 <script type="text/javascript" src="sortable.js"></script>
1092 """ % (self
.title
, conf
['style'], getversion()))
1094 def printNav(self
, f
):
1098 <li><a href="index.html">General</a></li>
1099 <li><a href="activity.html">Activity</a></li>
1100 <li><a href="authors.html">Authors</a></li>
1101 <li><a href="files.html">Files</a></li>
1102 <li><a href="lines.html">Lines</a></li>
1103 <li><a href="tags.html">Tags</a></li>
1110 def run(self
, args_orig
):
1111 optlist
, args
= getopt
.getopt(args_orig
, 'c:')
1114 key
, value
= v
.split('=', 1)
1116 raise KeyError('no such key "%s" in config' % key
)
1117 if isinstance(conf
[key
], int):
1118 conf
[key
] = int(value
)
1124 Usage: gitstats [options] <gitpath> <outputpath>
1127 -c key=value Override configuration value
1129 Default config values:
1135 outputpath
= os
.path
.abspath(args
[1])
1136 rundir
= os
.getcwd()
1139 os
.makedirs(outputpath
)
1142 if not os
.path
.isdir(outputpath
):
1143 print 'FATAL: Output path is not a directory or does not exist'
1146 print 'Git path: %s' % gitpath
1147 print 'Output path: %s' % outputpath
1151 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1153 print 'Collecting data...'
1154 data
= GitDataCollector()
1155 data
.loadCache(cachefile
)
1156 data
.collect(gitpath
)
1157 print 'Refining data...'
1158 data
.saveCache(cachefile
)
1163 print 'Generating report...'
1164 report
= HTMLReportCreator()
1165 report
.create(data
, outputpath
)
1167 time_end
= time
.time()
1168 exectime_internal
= time_end
- time_start
1169 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)