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',
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 """Manages data collection from a revision control repository."""
87 self
.stamp_created
= time
.time()
91 # This should be the main function to extract data from the repository.
92 def collect(self
, dir):
94 if len(conf
['project_name']) == 0:
95 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
97 self
.projectname
= conf
['project_name']
100 # Load cacheable data
101 def loadCache(self
, cachefile
):
102 if not os
.path
.exists(cachefile
):
104 print 'Loading cache...'
105 f
= open(cachefile
, 'rb')
107 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
109 # temporary hack to upgrade non-compressed caches
111 self
.cache
= pickle
.load(f
)
115 # Produce any additional statistics from the extracted data.
120 # : get a dictionary of author
121 def getAuthorInfo(self
, author
):
124 def getActivityByDayOfWeek(self
):
127 def getActivityByHourOfDay(self
):
130 # : get a dictionary of domains
131 def getDomainInfo(self
, domain
):
135 # Get a list of authors
136 def getAuthors(self
):
139 def getFirstCommitDate(self
):
140 return datetime
.datetime
.now()
142 def getLastCommitDate(self
):
143 return datetime
.datetime
.now()
145 def getStampCreated(self
):
146 return self
.stamp_created
151 def getTotalAuthors(self
):
154 def getTotalCommits(self
):
157 def getTotalFiles(self
):
160 def getTotalLOC(self
):
164 # Save cacheable data
165 def saveCache(self
, cachefile
):
166 print 'Saving cache...'
167 f
= open(cachefile
, 'wb')
168 #pickle.dump(self.cache, f)
169 data
= zlib
.compress(pickle
.dumps(self
.cache
))
173 class GitDataCollector(DataCollector
):
174 def collect(self
, dir):
175 DataCollector
.collect(self
, dir)
178 self
.total_authors
= int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
180 self
.total_authors
= 0
181 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
183 self
.activity_by_hour_of_day
= {} # hour -> commits
184 self
.activity_by_day_of_week
= {} # day -> commits
185 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
186 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
187 self
.activity_by_hour_of_day_busiest
= 0
188 self
.activity_by_hour_of_week_busiest
= 0
189 self
.activity_by_year_week
= {} # yy_wNN -> commits
190 self
.activity_by_year_week_peak
= 0
192 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
195 self
.domains
= {} # domain -> commits
197 # author of the month
198 self
.author_of_month
= {} # month -> author -> commits
199 self
.author_of_year
= {} # year -> author -> commits
200 self
.commits_by_month
= {} # month -> commits
201 self
.commits_by_year
= {} # year -> commits
202 self
.first_commit_stamp
= 0
203 self
.last_commit_stamp
= 0
204 self
.last_active_day
= None
205 self
.active_days
= set()
209 self
.total_lines_added
= 0
210 self
.total_lines_removed
= 0
213 self
.commits_by_timezone
= {} # timezone -> commits
217 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
221 (hash, tag
) = line
.split(' ')
223 tag
= tag
.replace('refs/tags/', '')
224 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
226 parts
= output
.split(' ')
229 stamp
= int(parts
[0])
232 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
234 # collect info on tags, starting from latest
235 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), self
.tags
.items()))))
237 for tag
in reversed(tags_sorted_by_date_desc
):
238 cmd
= 'git shortlog -s "%s"' % tag
240 cmd
+= ' "^%s"' % prev
241 output
= getpipeoutput([cmd
])
245 for line
in output
.split('\n'):
246 parts
= re
.split('\s+', line
, 2)
247 commits
= int(parts
[1])
249 self
.tags
[tag
]['commits'] += commits
250 self
.tags
[tag
]['authors'][author
] = commits
252 # Collect revision statistics
253 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
254 lines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
256 parts
= line
.split(' ', 4)
259 stamp
= int(parts
[0])
263 author
, mail
= parts
[4].split('<', 1)
264 author
= author
.rstrip()
265 mail
= mail
.rstrip('>')
267 if mail
.find('@') != -1:
268 domain
= mail
.rsplit('@', 1)[1]
269 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
271 # First and last commit stamp
272 if self
.last_commit_stamp
== 0:
273 self
.last_commit_stamp
= stamp
274 self
.first_commit_stamp
= stamp
279 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
281 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
282 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
286 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
289 if domain
not in self
.domains
:
290 self
.domains
[domain
] = {}
292 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
295 if day
not in self
.activity_by_hour_of_week
:
296 self
.activity_by_hour_of_week
[day
] = {}
297 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
299 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
300 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
304 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
306 # yearly/weekly activity
307 yyw
= date
.strftime('%Y-%W')
308 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
309 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
310 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
313 if author
not in self
.authors
:
314 self
.authors
[author
] = {}
316 if 'last_commit_stamp' not in self
.authors
[author
]:
317 self
.authors
[author
]['last_commit_stamp'] = stamp
318 self
.authors
[author
]['first_commit_stamp'] = stamp
319 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
321 # author of the month/year
322 yymm
= date
.strftime('%Y-%m')
323 if yymm
in self
.author_of_month
:
324 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
326 self
.author_of_month
[yymm
] = {}
327 self
.author_of_month
[yymm
][author
] = 1
328 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
331 if yy
in self
.author_of_year
:
332 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
334 self
.author_of_year
[yy
] = {}
335 self
.author_of_year
[yy
][author
] = 1
336 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
338 # authors: active days
339 yymmdd
= date
.strftime('%Y-%m-%d')
340 if 'last_active_day' not in self
.authors
[author
]:
341 self
.authors
[author
]['last_active_day'] = yymmdd
342 self
.authors
[author
]['active_days'] = 1
343 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
344 self
.authors
[author
]['last_active_day'] = yymmdd
345 self
.authors
[author
]['active_days'] += 1
347 # project: active days
348 if yymmdd
!= self
.last_active_day
:
349 self
.last_active_day
= yymmdd
350 self
.active_days
.add(yymmdd
)
353 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
355 # TODO Optimize this, it's the worst bottleneck
356 # outputs "<stamp> <files>" for each revision
357 self
.files_by_stamp
= {} # stamp -> files
358 revlines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
360 for revline
in revlines
:
361 time
, rev
= revline
.split(' ')
362 linecount
= self
.getFilesInCommit(rev
)
363 lines
.append('%d %d' % (int(time
), linecount
))
365 self
.total_commits
= len(lines
)
367 parts
= line
.split(' ')
370 (stamp
, files
) = parts
[0:2]
372 self
.files_by_stamp
[int(stamp
)] = int(files
)
374 print 'Warning: failed to parse line "%s"' % line
377 self
.extensions
= {} # extension -> files, lines
378 lines
= getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only
= True)]).split('\000')
379 self
.total_files
= len(lines
)
383 parts
= re
.split('\s+', line
, 4)
387 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
390 ext
= filename
[(filename
.rfind('.') + 1):]
391 if len(ext
) > conf
['max_ext_length']:
394 if ext
not in self
.extensions
:
395 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
397 self
.extensions
[ext
]['files'] += 1
399 self
.extensions
[ext
]['lines'] += self
.getLinesInBlob(sha1
)
401 print 'Warning: Could not count lines for file "%s"' % line
405 # N files changed, N insertions (+), N deletions(-)
407 self
.changes_by_date
= {} # stamp -> { files, ins, del }
409 if conf
['linear_linestats']:
410 extra
= '--first-parent -m'
411 lines
= getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra
, getcommitrange('HEAD'))]).split('\n')
413 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
420 if line
.find('files changed,') == -1:
424 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
425 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
426 if author
not in self
.authors
:
427 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0 }
428 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
429 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
430 files
, inserted
, deleted
= 0, 0, 0
432 print 'Warning: unexpected line "%s"' % line
434 print 'Warning: unexpected line "%s"' % line
436 numbers
= re
.findall('\d+', line
)
437 if len(numbers
) == 3:
438 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
439 total_lines
+= inserted
440 total_lines
-= deleted
441 self
.total_lines_added
+= inserted
442 self
.total_lines_removed
+= deleted
444 print 'Warning: failed to handle line "%s"' % line
445 (files
, inserted
, deleted
) = (0, 0, 0)
446 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
447 self
.total_lines
= total_lines
451 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
452 authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
453 authors_by_commits
.reverse() # most first
454 for i
, name
in enumerate(authors_by_commits
):
455 self
.authors
[name
]['place_by_commits'] = i
+ 1
457 for name
in self
.authors
.keys():
458 a
= self
.authors
[name
]
459 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
460 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
461 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
462 delta
= date_last
- date_first
463 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
464 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
465 a
['timedelta'] = delta
466 if 'lines_added' not in a
: a
['lines_added'] = 0
467 if 'lines_removed' not in a
: a
['lines_removed'] = 0
469 def getActiveDays(self
):
470 return self
.active_days
472 def getActivityByDayOfWeek(self
):
473 return self
.activity_by_day_of_week
475 def getActivityByHourOfDay(self
):
476 return self
.activity_by_hour_of_day
478 def getAuthorInfo(self
, author
):
479 return self
.authors
[author
]
481 def getAuthors(self
, limit
= None):
482 res
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
486 def getCommitDeltaDays(self
):
487 return (self
.last_commit_stamp
- self
.first_commit_stamp
) / 86400 + 1
489 def getDomainInfo(self
, domain
):
490 return self
.domains
[domain
]
492 def getDomains(self
):
493 return self
.domains
.keys()
495 def getFilesInCommit(self
, rev
):
497 res
= self
.cache
['files_in_tree'][rev
]
499 res
= int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0])
500 if 'files_in_tree' not in self
.cache
:
501 self
.cache
['files_in_tree'] = {}
502 self
.cache
['files_in_tree'][rev
] = res
506 def getFirstCommitDate(self
):
507 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
509 def getLastCommitDate(self
):
510 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
512 def getLinesInBlob(self
, sha1
):
514 res
= self
.cache
['lines_in_blob'][sha1
]
516 res
= int(getpipeoutput(['git cat-file blob %s' % sha1
, 'wc -l']).split()[0])
517 if 'lines_in_blob' not in self
.cache
:
518 self
.cache
['lines_in_blob'] = {}
519 self
.cache
['lines_in_blob'][sha1
] = res
523 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
524 return lines
.split('\n')
526 def getTagDate(self
, tag
):
527 return self
.revToDate('tags/' + tag
)
529 def getTotalAuthors(self
):
530 return self
.total_authors
532 def getTotalCommits(self
):
533 return self
.total_commits
535 def getTotalFiles(self
):
536 return self
.total_files
538 def getTotalLOC(self
):
539 return self
.total_lines
541 def revToDate(self
, rev
):
542 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
543 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
546 """Creates the actual report based on given data."""
550 def create(self
, data
, path
):
554 def html_linkify(text
):
555 return text
.lower().replace(' ', '_')
557 def html_header(level
, text
):
558 name
= html_linkify(text
)
559 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
561 class HTMLReportCreator(ReportCreator
):
562 def create(self
, data
, path
):
563 ReportCreator
.create(self
, data
, path
)
564 self
.title
= data
.projectname
566 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
567 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
568 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
569 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
570 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
571 for base
in basedirs
:
572 src
= base
+ '/' + file
573 if os
.path
.exists(src
):
574 shutil
.copyfile(src
, path
+ '/' + file)
577 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
579 f
= open(path
+ "/index.html", 'w')
580 format
= '%Y-%m-%d %H:%M:%S'
583 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
588 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
589 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
590 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
591 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
592 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())))
593 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
594 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
))
595 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()))
596 f
.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data
.getTotalAuthors(), (1.0 * data
.getTotalCommits()) / data
.getTotalAuthors()))
599 f
.write('</body>\n</html>')
604 f
= open(path
+ '/activity.html', 'w')
606 f
.write('<h1>Activity</h1>')
609 #f.write('<h2>Last 30 days</h2>')
611 #f.write('<h2>Last 12 months</h2>')
615 f
.write(html_header(2, 'Weekly activity'))
616 f
.write('<p>Last %d weeks</p>' % WEEKS
)
618 # generate weeks to show (previous N weeks from now)
619 now
= datetime
.datetime
.now()
620 deltaweek
= datetime
.timedelta(7)
623 for i
in range(0, WEEKS
):
624 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
625 stampcur
-= deltaweek
627 # top row: commits & bar
628 f
.write('<table class="noborders"><tr>')
629 for i
in range(0, WEEKS
):
631 if weeks
[i
] in data
.activity_by_year_week
:
632 commits
= data
.activity_by_year_week
[weeks
[i
]]
635 if weeks
[i
] in data
.activity_by_year_week
:
636 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
637 height
= max(1, int(200 * percentage
))
638 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
))
640 # bottom row: year/week
642 for i
in range(0, WEEKS
):
643 f
.write('<td>%s</td>' % (WEEKS
- i
))
644 f
.write('</tr></table>')
647 f
.write(html_header(2, 'Hour of Day'))
648 hour_of_day
= data
.getActivityByHourOfDay()
649 f
.write('<table><tr><th>Hour</th>')
650 for i
in range(0, 24):
651 f
.write('<th>%d</th>' % i
)
652 f
.write('</tr>\n<tr><th>Commits</th>')
653 fp
= open(path
+ '/hour_of_day.dat', 'w')
654 for i
in range(0, 24):
656 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
657 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
658 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
660 f
.write('<td>0</td>')
661 fp
.write('%d 0\n' % i
)
663 f
.write('</tr>\n<tr><th>%</th>')
664 totalcommits
= data
.getTotalCommits()
665 for i
in range(0, 24):
667 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
668 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
670 f
.write('<td>0.00</td>')
671 f
.write('</tr></table>')
672 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
673 fg
= open(path
+ '/hour_of_day.dat', 'w')
674 for i
in range(0, 24):
676 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
678 fg
.write('%d 0\n' % (i
+ 1))
682 f
.write(html_header(2, 'Day of Week'))
683 day_of_week
= data
.getActivityByDayOfWeek()
684 f
.write('<div class="vtable"><table>')
685 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
686 fp
= open(path
+ '/day_of_week.dat', 'w')
687 for d
in range(0, 7):
690 commits
= day_of_week
[d
]
691 fp
.write('%d %s %d\n' % (d
+ 1, WEEKDAYS
[d
], commits
))
693 f
.write('<th>%s</th>' % (WEEKDAYS
[d
]))
695 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
697 f
.write('<td>0</td>')
699 f
.write('</table></div>')
700 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
704 f
.write(html_header(2, 'Hour of Week'))
707 f
.write('<tr><th>Weekday</th>')
708 for hour
in range(0, 24):
709 f
.write('<th>%d</th>' % (hour
))
712 for weekday
in range(0, 7):
713 f
.write('<tr><th>%s</th>' % (WEEKDAYS
[weekday
]))
714 for hour
in range(0, 24):
716 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
721 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
722 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
723 f
.write('>%d</td>' % commits
)
731 f
.write(html_header(2, 'Month of Year'))
732 f
.write('<div class="vtable"><table>')
733 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
734 fp
= open (path
+ '/month_of_year.dat', 'w')
735 for mm
in range(1, 13):
737 if mm
in data
.activity_by_month_of_year
:
738 commits
= data
.activity_by_month_of_year
[mm
]
739 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
740 fp
.write('%d %d\n' % (mm
, commits
))
742 f
.write('</table></div>')
743 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
745 # Commits by year/month
746 f
.write(html_header(2, 'Commits by year/month'))
747 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
748 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
749 f
.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
[yymm
]))
750 f
.write('</table></div>')
751 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
752 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
753 for yymm
in sorted(data
.commits_by_month
.keys()):
754 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
758 f
.write(html_header(2, 'Commits by Year'))
759 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
760 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
761 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()))
762 f
.write('</table></div>')
763 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
764 fg
= open(path
+ '/commits_by_year.dat', 'w')
765 for yy
in sorted(data
.commits_by_year
.keys()):
766 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
769 # Commits by timezone
770 f
.write(html_header(2, 'Commits by Timezone'))
771 f
.write('<table><tr>')
772 f
.write('<th>Timezone</th><th>Commits</th>')
773 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
774 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
775 commits
= data
.commits_by_timezone
[i
]
776 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
777 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
778 f
.write('</tr></table>')
780 f
.write('</body></html>')
785 f
= open(path
+ '/authors.html', 'w')
788 f
.write('<h1>Authors</h1>')
791 # Authors :: List of authors
792 f
.write(html_header(2, 'List of Authors'))
794 f
.write('<table class="authors sortable" id="authors">')
795 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>')
796 for author
in data
.getAuthors(conf
['max_authors']):
797 info
= data
.getAuthorInfo(author
)
798 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']))
801 allauthors
= data
.getAuthors()
802 if len(allauthors
) > conf
['max_authors']:
803 rest
= allauthors
[conf
['max_authors']:]
804 f
.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest
))
806 # Authors :: Author of Month
807 f
.write(html_header(2, 'Author of Month'))
808 f
.write('<table class="sortable" id="aom">')
809 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'])
810 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
811 authordict
= data
.author_of_month
[yymm
]
812 authors
= getkeyssortedbyvalues(authordict
)
814 commits
= data
.author_of_month
[yymm
][authors
[0]]
815 next
= ', '.join(authors
[1:conf
['authors_top']+1])
816 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
)))
820 f
.write(html_header(2, 'Author of Year'))
821 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'])
822 for yy
in reversed(sorted(data
.author_of_year
.keys())):
823 authordict
= data
.author_of_year
[yy
]
824 authors
= getkeyssortedbyvalues(authordict
)
826 commits
= data
.author_of_year
[yy
][authors
[0]]
827 next
= ', '.join(authors
[1:conf
['authors_top']+1])
828 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
)))
832 f
.write(html_header(2, 'Commits by Domains'))
833 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
834 domains_by_commits
.reverse() # most first
835 f
.write('<div class="vtable"><table>')
836 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
837 fp
= open(path
+ '/domains.dat', 'w')
839 for domain
in domains_by_commits
:
840 if n
== conf
['max_domains']:
844 info
= data
.getDomainInfo(domain
)
845 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
846 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
847 f
.write('</table></div>')
848 f
.write('<img src="domains.png" alt="Commits by Domains" />')
851 f
.write('</body></html>')
856 f
= open(path
+ '/files.html', 'w')
858 f
.write('<h1>Files</h1>')
862 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
863 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
864 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data
.getTotalLOC()) / data
.getTotalFiles()))
867 # Files :: File count by date
868 f
.write(html_header(2, 'File count by date'))
870 # use set to get rid of duplicate/unnecessary entries
871 files_by_date
= set()
872 for stamp
in sorted(data
.files_by_stamp
.keys()):
873 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
875 fg
= open(path
+ '/files_by_date.dat', 'w')
876 for line
in sorted(list(files_by_date
)):
877 fg
.write('%s\n' % line
)
878 #for stamp in sorted(data.files_by_stamp.keys()):
879 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
882 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
884 #f.write('<h2>Average file size by date</h2>')
886 # Files :: Extensions
887 f
.write(html_header(2, 'Extensions'))
888 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
889 for ext
in sorted(data
.extensions
.keys()):
890 files
= data
.extensions
[ext
]['files']
891 lines
= data
.extensions
[ext
]['lines']
892 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
))
895 f
.write('</body></html>')
900 f
= open(path
+ '/lines.html', 'w')
902 f
.write('<h1>Lines</h1>')
906 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
909 f
.write(html_header(2, 'Lines of Code'))
910 f
.write('<img src="lines_of_code.png" />')
912 fg
= open(path
+ '/lines_of_code.dat', 'w')
913 for stamp
in sorted(data
.changes_by_date
.keys()):
914 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
917 f
.write('</body></html>')
922 f
= open(path
+ '/tags.html', 'w')
924 f
.write('<h1>Tags</h1>')
928 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
929 if len(data
.tags
) > 0:
930 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
933 f
.write('<table class="tags">')
934 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
935 # sort the tags by date desc
936 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
937 for tag
in tags_sorted_by_date_desc
:
939 authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
940 for i
in reversed(authors_by_commits
):
941 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
942 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
)))
945 f
.write('</body></html>')
948 self
.createGraphs(path
)
950 def createGraphs(self
, path
):
951 print 'Generating graphs...'
954 f
= open(path
+ '/hour_of_day.plot', 'w')
955 f
.write(GNUPLOT_COMMON
)
958 set output 'hour_of_day.png'
960 set xrange [0.5:24.5]
964 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
969 f
= open(path
+ '/day_of_week.plot', 'w')
970 f
.write(GNUPLOT_COMMON
)
973 set output 'day_of_week.png'
979 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
984 f
= open(path
+ '/domains.plot', 'w')
985 f
.write(GNUPLOT_COMMON
)
988 set output 'domains.png'
994 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
999 f
= open(path
+ '/month_of_year.plot', 'w')
1000 f
.write(GNUPLOT_COMMON
)
1003 set output 'month_of_year.png'
1005 set xrange [0.5:12.5]
1008 set ylabel "Commits"
1009 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1013 # commits_by_year_month
1014 f
= open(path
+ '/commits_by_year_month.plot', 'w')
1015 f
.write(GNUPLOT_COMMON
)
1018 set output 'commits_by_year_month.png'
1022 set format x "%Y-%m"
1023 set xtics rotate by 90 15768000
1026 set ylabel "Commits"
1027 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1032 f
= open(path
+ '/commits_by_year.plot', 'w')
1033 f
.write(GNUPLOT_COMMON
)
1036 set output 'commits_by_year.png'
1038 set xtics 1 rotate by 90
1040 set ylabel "Commits"
1042 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1047 f
= open(path
+ '/files_by_date.plot', 'w')
1048 f
.write(GNUPLOT_COMMON
)
1051 set output 'files_by_date.png'
1054 set timefmt "%Y-%m-%d"
1055 set format x "%Y-%m-%d"
1058 set xtics rotate by 90
1061 plot 'files_by_date.dat' using 1:2 w steps
1066 f
= open(path
+ '/lines_of_code.plot', 'w')
1067 f
.write(GNUPLOT_COMMON
)
1070 set output 'lines_of_code.png'
1074 set format x "%Y-%m-%d"
1077 set xtics rotate by 90
1079 plot 'lines_of_code.dat' using 1:2 w lines
1084 files
= glob
.glob(path
+ '/*.plot')
1086 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1090 def printHeader(self
, f
, title
= ''):
1092 """<?xml version="1.0" encoding="UTF-8"?>
1093 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1094 <html xmlns="http://www.w3.org/1999/xhtml">
1096 <title>GitStats - %s</title>
1097 <link rel="stylesheet" href="%s" type="text/css" />
1098 <meta name="generator" content="GitStats %s" />
1099 <script type="text/javascript" src="sortable.js"></script>
1102 """ % (self
.title
, conf
['style'], getversion()))
1104 def printNav(self
, f
):
1108 <li><a href="index.html">General</a></li>
1109 <li><a href="activity.html">Activity</a></li>
1110 <li><a href="authors.html">Authors</a></li>
1111 <li><a href="files.html">Files</a></li>
1112 <li><a href="lines.html">Lines</a></li>
1113 <li><a href="tags.html">Tags</a></li>
1120 def run(self
, args_orig
):
1121 optlist
, args
= getopt
.getopt(args_orig
, 'c:')
1124 key
, value
= v
.split('=', 1)
1126 raise KeyError('no such key "%s" in config' % key
)
1127 if isinstance(conf
[key
], int):
1128 conf
[key
] = int(value
)
1134 Usage: gitstats [options] <gitpath> <outputpath>
1137 -c key=value Override configuration value
1139 Default config values:
1145 outputpath
= os
.path
.abspath(args
[1])
1146 rundir
= os
.getcwd()
1149 os
.makedirs(outputpath
)
1152 if not os
.path
.isdir(outputpath
):
1153 print 'FATAL: Output path is not a directory or does not exist'
1156 print 'Git path: %s' % gitpath
1157 print 'Output path: %s' % outputpath
1161 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1163 print 'Collecting data...'
1164 data
= GitDataCollector()
1165 data
.loadCache(cachefile
)
1166 data
.collect(gitpath
)
1167 print 'Refining data...'
1168 data
.saveCache(cachefile
)
1173 print 'Generating report...'
1174 report
= HTMLReportCreator()
1175 report
.create(data
, outputpath
)
1177 time_end
= time
.time()
1178 exectime_internal
= time_end
- time_start
1179 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)
1181 if __name__
=='__main__':