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,
42 def getpipeoutput(cmds
, quiet
= False):
43 global exectime_external
45 if not quiet
and ON_LINUX
and os
.isatty(1):
46 print '>> ' + ' | '.join(cmds
),
48 p0
= subprocess
.Popen(cmds
[0], stdout
= subprocess
.PIPE
, shell
= True)
51 p
= subprocess
.Popen(x
, stdin
= p0
.stdout
, stdout
= subprocess
.PIPE
, shell
= True)
53 output
= p
.communicate()[0]
56 if ON_LINUX
and os
.isatty(1):
58 print '[%.5f] >> %s' % (end
- start
, ' | '.join(cmds
))
59 exectime_external
+= (end
- start
)
60 return output
.rstrip('\n')
62 def getcommitrange(defaultrange
= 'HEAD', end_only
= False):
63 if len(conf
['commit_end']) > 0:
64 if end_only
or len(conf
['commit_begin']) == 0:
65 return conf
['commit_end']
66 return '%s..%s' % (conf
['commit_begin'], conf
['commit_end'])
69 def getkeyssortedbyvalues(dict):
70 return map(lambda el
: el
[1], sorted(map(lambda el
: (el
[1], el
[0]), dict.items())))
72 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
73 def getkeyssortedbyvaluekey(d
, key
):
74 return map(lambda el
: el
[1], sorted(map(lambda el
: (d
[el
][key
], el
), d
.keys())))
80 VERSION
= getpipeoutput(["git rev-parse --short %s" % getcommitrange('HEAD')]).split('\n')[0]
84 """Manages data collection from a revision control repository."""
86 self
.stamp_created
= time
.time()
90 # This should be the main function to extract data from the repository.
91 def collect(self
, dir):
93 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
97 def loadCache(self
, cachefile
):
98 if not os
.path
.exists(cachefile
):
100 print 'Loading cache...'
101 f
= open(cachefile
, 'rb')
103 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
105 # temporary hack to upgrade non-compressed caches
107 self
.cache
= pickle
.load(f
)
111 # Produce any additional statistics from the extracted data.
116 # : get a dictionary of author
117 def getAuthorInfo(self
, author
):
120 def getActivityByDayOfWeek(self
):
123 def getActivityByHourOfDay(self
):
126 # : get a dictionary of domains
127 def getDomainInfo(self
, domain
):
131 # Get a list of authors
132 def getAuthors(self
):
135 def getFirstCommitDate(self
):
136 return datetime
.datetime
.now()
138 def getLastCommitDate(self
):
139 return datetime
.datetime
.now()
141 def getStampCreated(self
):
142 return self
.stamp_created
147 def getTotalAuthors(self
):
150 def getTotalCommits(self
):
153 def getTotalFiles(self
):
156 def getTotalLOC(self
):
160 # Save cacheable data
161 def saveCache(self
, cachefile
):
162 print 'Saving cache...'
163 f
= open(cachefile
, 'wb')
164 #pickle.dump(self.cache, f)
165 data
= zlib
.compress(pickle
.dumps(self
.cache
))
169 class GitDataCollector(DataCollector
):
170 def collect(self
, dir):
171 DataCollector
.collect(self
, dir)
174 self
.total_authors
= int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
176 self
.total_authors
= 0
177 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
179 self
.activity_by_hour_of_day
= {} # hour -> commits
180 self
.activity_by_day_of_week
= {} # day -> commits
181 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
182 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
183 self
.activity_by_hour_of_day_busiest
= 0
184 self
.activity_by_hour_of_week_busiest
= 0
185 self
.activity_by_year_week
= {} # yy_wNN -> commits
186 self
.activity_by_year_week_peak
= 0
188 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
191 self
.domains
= {} # domain -> commits
193 # author of the month
194 self
.author_of_month
= {} # month -> author -> commits
195 self
.author_of_year
= {} # year -> author -> commits
196 self
.commits_by_month
= {} # month -> commits
197 self
.commits_by_year
= {} # year -> commits
198 self
.first_commit_stamp
= 0
199 self
.last_commit_stamp
= 0
200 self
.last_active_day
= None
201 self
.active_days
= set()
205 self
.total_lines_added
= 0
206 self
.total_lines_removed
= 0
209 self
.commits_by_timezone
= {} # timezone -> commits
213 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
217 (hash, tag
) = line
.split(' ')
219 tag
= tag
.replace('refs/tags/', '')
220 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
222 parts
= output
.split(' ')
225 stamp
= int(parts
[0])
228 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
230 # collect info on tags, starting from latest
231 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), self
.tags
.items()))))
233 for tag
in reversed(tags_sorted_by_date_desc
):
234 cmd
= 'git shortlog -s "%s"' % tag
236 cmd
+= ' "^%s"' % prev
237 output
= getpipeoutput([cmd
])
241 for line
in output
.split('\n'):
242 parts
= re
.split('\s+', line
, 2)
243 commits
= int(parts
[1])
245 self
.tags
[tag
]['commits'] += commits
246 self
.tags
[tag
]['authors'][author
] = commits
248 # Collect revision statistics
249 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
250 lines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
252 parts
= line
.split(' ', 4)
255 stamp
= int(parts
[0])
259 author
, mail
= parts
[4].split('<', 1)
260 author
= author
.rstrip()
261 mail
= mail
.rstrip('>')
263 if mail
.find('@') != -1:
264 domain
= mail
.rsplit('@', 1)[1]
265 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
267 # First and last commit stamp
268 if self
.last_commit_stamp
== 0:
269 self
.last_commit_stamp
= stamp
270 self
.first_commit_stamp
= stamp
275 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
277 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
278 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
282 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
285 if domain
not in self
.domains
:
286 self
.domains
[domain
] = {}
288 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
291 if day
not in self
.activity_by_hour_of_week
:
292 self
.activity_by_hour_of_week
[day
] = {}
293 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
295 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
296 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
300 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
302 # yearly/weekly activity
303 yyw
= date
.strftime('%Y-%W')
304 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
305 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
306 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
309 if author
not in self
.authors
:
310 self
.authors
[author
] = {}
312 if 'last_commit_stamp' not in self
.authors
[author
]:
313 self
.authors
[author
]['last_commit_stamp'] = stamp
314 self
.authors
[author
]['first_commit_stamp'] = stamp
315 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
317 # author of the month/year
318 yymm
= date
.strftime('%Y-%m')
319 if yymm
in self
.author_of_month
:
320 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
322 self
.author_of_month
[yymm
] = {}
323 self
.author_of_month
[yymm
][author
] = 1
324 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
327 if yy
in self
.author_of_year
:
328 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
330 self
.author_of_year
[yy
] = {}
331 self
.author_of_year
[yy
][author
] = 1
332 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
334 # authors: active days
335 yymmdd
= date
.strftime('%Y-%m-%d')
336 if 'last_active_day' not in self
.authors
[author
]:
337 self
.authors
[author
]['last_active_day'] = yymmdd
338 self
.authors
[author
]['active_days'] = 1
339 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
340 self
.authors
[author
]['last_active_day'] = yymmdd
341 self
.authors
[author
]['active_days'] += 1
343 # project: active days
344 if yymmdd
!= self
.last_active_day
:
345 self
.last_active_day
= yymmdd
346 self
.active_days
.add(yymmdd
)
349 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
351 # TODO Optimize this, it's the worst bottleneck
352 # outputs "<stamp> <files>" for each revision
353 self
.files_by_stamp
= {} # stamp -> files
354 revlines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
356 for revline
in revlines
:
357 time
, rev
= revline
.split(' ')
358 linecount
= self
.getFilesInCommit(rev
)
359 lines
.append('%d %d' % (int(time
), linecount
))
361 self
.total_commits
= len(lines
)
363 parts
= line
.split(' ')
366 (stamp
, files
) = parts
[0:2]
368 self
.files_by_stamp
[int(stamp
)] = int(files
)
370 print 'Warning: failed to parse line "%s"' % line
373 self
.extensions
= {} # extension -> files, lines
374 lines
= getpipeoutput(['git ls-tree -r -z %s' % getcommitrange('HEAD', end_only
= True)]).split('\000')
375 self
.total_files
= len(lines
)
379 parts
= re
.split('\s+', line
, 4)
383 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
386 ext
= filename
[(filename
.rfind('.') + 1):]
387 if len(ext
) > conf
['max_ext_length']:
390 if ext
not in self
.extensions
:
391 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
393 self
.extensions
[ext
]['files'] += 1
395 self
.extensions
[ext
]['lines'] += self
.getLinesInBlob(sha1
)
397 print 'Warning: Could not count lines for file "%s"' % line
401 # N files changed, N insertions (+), N deletions(-)
403 self
.changes_by_date
= {} # stamp -> { files, ins, del }
405 if conf
['linear_linestats']:
406 extra
= '--first-parent -m'
407 lines
= getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra
, getcommitrange('HEAD'))]).split('\n')
409 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
416 if line
.find('files changed,') == -1:
420 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
421 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
422 if author
not in self
.authors
:
423 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0 }
424 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
425 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
426 files
, inserted
, deleted
= 0, 0, 0
428 print 'Warning: unexpected line "%s"' % line
430 print 'Warning: unexpected line "%s"' % line
432 numbers
= re
.findall('\d+', line
)
433 if len(numbers
) == 3:
434 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
435 total_lines
+= inserted
436 total_lines
-= deleted
437 self
.total_lines_added
+= inserted
438 self
.total_lines_removed
+= deleted
440 print 'Warning: failed to handle line "%s"' % line
441 (files
, inserted
, deleted
) = (0, 0, 0)
442 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
443 self
.total_lines
= total_lines
447 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
448 authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
449 authors_by_commits
.reverse() # most first
450 for i
, name
in enumerate(authors_by_commits
):
451 self
.authors
[name
]['place_by_commits'] = i
+ 1
453 for name
in self
.authors
.keys():
454 a
= self
.authors
[name
]
455 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
456 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
457 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
458 delta
= date_last
- date_first
459 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
460 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
461 a
['timedelta'] = delta
462 if 'lines_added' not in a
: a
['lines_added'] = 0
463 if 'lines_removed' not in a
: a
['lines_removed'] = 0
465 def getActiveDays(self
):
466 return self
.active_days
468 def getActivityByDayOfWeek(self
):
469 return self
.activity_by_day_of_week
471 def getActivityByHourOfDay(self
):
472 return self
.activity_by_hour_of_day
474 def getAuthorInfo(self
, author
):
475 return self
.authors
[author
]
477 def getAuthors(self
, limit
= None):
478 res
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
482 def getCommitDeltaDays(self
):
483 return (self
.last_commit_stamp
- self
.first_commit_stamp
) / 86400 + 1
485 def getDomainInfo(self
, domain
):
486 return self
.domains
[domain
]
488 def getDomains(self
):
489 return self
.domains
.keys()
491 def getFilesInCommit(self
, rev
):
493 res
= self
.cache
['files_in_tree'][rev
]
495 res
= int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0])
496 if 'files_in_tree' not in self
.cache
:
497 self
.cache
['files_in_tree'] = {}
498 self
.cache
['files_in_tree'][rev
] = res
502 def getFirstCommitDate(self
):
503 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
505 def getLastCommitDate(self
):
506 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
508 def getLinesInBlob(self
, sha1
):
510 res
= self
.cache
['lines_in_blob'][sha1
]
512 res
= int(getpipeoutput(['git cat-file blob %s' % sha1
, 'wc -l']).split()[0])
513 if 'lines_in_blob' not in self
.cache
:
514 self
.cache
['lines_in_blob'] = {}
515 self
.cache
['lines_in_blob'][sha1
] = res
519 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
520 return lines
.split('\n')
522 def getTagDate(self
, tag
):
523 return self
.revToDate('tags/' + tag
)
525 def getTotalAuthors(self
):
526 return self
.total_authors
528 def getTotalCommits(self
):
529 return self
.total_commits
531 def getTotalFiles(self
):
532 return self
.total_files
534 def getTotalLOC(self
):
535 return self
.total_lines
537 def revToDate(self
, rev
):
538 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
539 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
542 """Creates the actual report based on given data."""
546 def create(self
, data
, path
):
550 def html_linkify(text
):
551 return text
.lower().replace(' ', '_')
553 def html_header(level
, text
):
554 name
= html_linkify(text
)
555 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
557 class HTMLReportCreator(ReportCreator
):
558 def create(self
, data
, path
):
559 ReportCreator
.create(self
, data
, path
)
560 self
.title
= data
.projectname
562 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
563 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
564 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
565 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
566 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
567 for base
in basedirs
:
568 src
= base
+ '/' + file
569 if os
.path
.exists(src
):
570 shutil
.copyfile(src
, path
+ '/' + file)
573 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
575 f
= open(path
+ "/index.html", 'w')
576 format
= '%Y-%m-%d %H:%M:%S'
579 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
584 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
585 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
586 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
587 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
588 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())))
589 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
590 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
))
591 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()))
592 f
.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data
.getTotalAuthors(), (1.0 * data
.getTotalCommits()) / data
.getTotalAuthors()))
595 f
.write('</body>\n</html>')
600 f
= open(path
+ '/activity.html', 'w')
602 f
.write('<h1>Activity</h1>')
605 #f.write('<h2>Last 30 days</h2>')
607 #f.write('<h2>Last 12 months</h2>')
611 f
.write(html_header(2, 'Weekly activity'))
612 f
.write('<p>Last %d weeks</p>' % WEEKS
)
614 # generate weeks to show (previous N weeks from now)
615 now
= datetime
.datetime
.now()
616 deltaweek
= datetime
.timedelta(7)
619 for i
in range(0, WEEKS
):
620 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
621 stampcur
-= deltaweek
623 # top row: commits & bar
624 f
.write('<table class="noborders"><tr>')
625 for i
in range(0, WEEKS
):
627 if weeks
[i
] in data
.activity_by_year_week
:
628 commits
= data
.activity_by_year_week
[weeks
[i
]]
631 if weeks
[i
] in data
.activity_by_year_week
:
632 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
633 height
= max(1, int(200 * percentage
))
634 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
))
636 # bottom row: year/week
638 for i
in range(0, WEEKS
):
639 f
.write('<td>%s</td>' % (WEEKS
- i
))
640 f
.write('</tr></table>')
643 f
.write(html_header(2, 'Hour of Day'))
644 hour_of_day
= data
.getActivityByHourOfDay()
645 f
.write('<table><tr><th>Hour</th>')
646 for i
in range(0, 24):
647 f
.write('<th>%d</th>' % i
)
648 f
.write('</tr>\n<tr><th>Commits</th>')
649 fp
= open(path
+ '/hour_of_day.dat', 'w')
650 for i
in range(0, 24):
652 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
653 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
654 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
656 f
.write('<td>0</td>')
657 fp
.write('%d 0\n' % i
)
659 f
.write('</tr>\n<tr><th>%</th>')
660 totalcommits
= data
.getTotalCommits()
661 for i
in range(0, 24):
663 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
664 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
666 f
.write('<td>0.00</td>')
667 f
.write('</tr></table>')
668 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
669 fg
= open(path
+ '/hour_of_day.dat', 'w')
670 for i
in range(0, 24):
672 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
674 fg
.write('%d 0\n' % (i
+ 1))
678 f
.write(html_header(2, 'Day of Week'))
679 day_of_week
= data
.getActivityByDayOfWeek()
680 f
.write('<div class="vtable"><table>')
681 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
682 fp
= open(path
+ '/day_of_week.dat', 'w')
683 for d
in range(0, 7):
686 commits
= day_of_week
[d
]
687 fp
.write('%d %s %d\n' % (d
+ 1, WEEKDAYS
[d
], commits
))
689 f
.write('<th>%s</th>' % (WEEKDAYS
[d
]))
691 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
693 f
.write('<td>0</td>')
695 f
.write('</table></div>')
696 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
700 f
.write(html_header(2, 'Hour of Week'))
703 f
.write('<tr><th>Weekday</th>')
704 for hour
in range(0, 24):
705 f
.write('<th>%d</th>' % (hour
))
708 for weekday
in range(0, 7):
709 f
.write('<tr><th>%s</th>' % (WEEKDAYS
[weekday
]))
710 for hour
in range(0, 24):
712 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
717 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
718 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
719 f
.write('>%d</td>' % commits
)
727 f
.write(html_header(2, 'Month of Year'))
728 f
.write('<div class="vtable"><table>')
729 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
730 fp
= open (path
+ '/month_of_year.dat', 'w')
731 for mm
in range(1, 13):
733 if mm
in data
.activity_by_month_of_year
:
734 commits
= data
.activity_by_month_of_year
[mm
]
735 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
736 fp
.write('%d %d\n' % (mm
, commits
))
738 f
.write('</table></div>')
739 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
741 # Commits by year/month
742 f
.write(html_header(2, 'Commits by year/month'))
743 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
744 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
745 f
.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
[yymm
]))
746 f
.write('</table></div>')
747 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
748 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
749 for yymm
in sorted(data
.commits_by_month
.keys()):
750 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
754 f
.write(html_header(2, 'Commits by Year'))
755 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
756 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
757 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()))
758 f
.write('</table></div>')
759 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
760 fg
= open(path
+ '/commits_by_year.dat', 'w')
761 for yy
in sorted(data
.commits_by_year
.keys()):
762 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
765 # Commits by timezone
766 f
.write(html_header(2, 'Commits by Timezone'))
767 f
.write('<table><tr>')
768 f
.write('<th>Timezone</th><th>Commits</th>')
769 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
770 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
771 commits
= data
.commits_by_timezone
[i
]
772 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
773 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
774 f
.write('</tr></table>')
776 f
.write('</body></html>')
781 f
= open(path
+ '/authors.html', 'w')
784 f
.write('<h1>Authors</h1>')
787 # Authors :: List of authors
788 f
.write(html_header(2, 'List of Authors'))
790 f
.write('<table class="authors sortable" id="authors">')
791 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>')
792 for author
in data
.getAuthors(conf
['max_authors']):
793 info
= data
.getAuthorInfo(author
)
794 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']))
797 allauthors
= data
.getAuthors()
798 if len(allauthors
) > conf
['max_authors']:
799 rest
= allauthors
[conf
['max_authors']:]
800 f
.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest
))
802 # Authors :: Author of Month
803 f
.write(html_header(2, 'Author of Month'))
804 f
.write('<table class="sortable" id="aom">')
805 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'])
806 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
807 authordict
= data
.author_of_month
[yymm
]
808 authors
= getkeyssortedbyvalues(authordict
)
810 commits
= data
.author_of_month
[yymm
][authors
[0]]
811 next
= ', '.join(authors
[1:conf
['authors_top']+1])
812 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
)))
816 f
.write(html_header(2, 'Author of Year'))
817 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'])
818 for yy
in reversed(sorted(data
.author_of_year
.keys())):
819 authordict
= data
.author_of_year
[yy
]
820 authors
= getkeyssortedbyvalues(authordict
)
822 commits
= data
.author_of_year
[yy
][authors
[0]]
823 next
= ', '.join(authors
[1:conf
['authors_top']+1])
824 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
)))
828 f
.write(html_header(2, 'Commits by Domains'))
829 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
830 domains_by_commits
.reverse() # most first
831 f
.write('<div class="vtable"><table>')
832 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
833 fp
= open(path
+ '/domains.dat', 'w')
835 for domain
in domains_by_commits
:
836 if n
== conf
['max_domains']:
840 info
= data
.getDomainInfo(domain
)
841 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
842 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
843 f
.write('</table></div>')
844 f
.write('<img src="domains.png" alt="Commits by Domains" />')
847 f
.write('</body></html>')
852 f
= open(path
+ '/files.html', 'w')
854 f
.write('<h1>Files</h1>')
858 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
859 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
860 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data
.getTotalLOC()) / data
.getTotalFiles()))
863 # Files :: File count by date
864 f
.write(html_header(2, 'File count by date'))
866 # use set to get rid of duplicate/unnecessary entries
867 files_by_date
= set()
868 for stamp
in sorted(data
.files_by_stamp
.keys()):
869 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
871 fg
= open(path
+ '/files_by_date.dat', 'w')
872 for line
in sorted(list(files_by_date
)):
873 fg
.write('%s\n' % line
)
874 #for stamp in sorted(data.files_by_stamp.keys()):
875 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
878 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
880 #f.write('<h2>Average file size by date</h2>')
882 # Files :: Extensions
883 f
.write(html_header(2, 'Extensions'))
884 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
885 for ext
in sorted(data
.extensions
.keys()):
886 files
= data
.extensions
[ext
]['files']
887 lines
= data
.extensions
[ext
]['lines']
888 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
))
891 f
.write('</body></html>')
896 f
= open(path
+ '/lines.html', 'w')
898 f
.write('<h1>Lines</h1>')
902 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
905 f
.write(html_header(2, 'Lines of Code'))
906 f
.write('<img src="lines_of_code.png" />')
908 fg
= open(path
+ '/lines_of_code.dat', 'w')
909 for stamp
in sorted(data
.changes_by_date
.keys()):
910 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
913 f
.write('</body></html>')
918 f
= open(path
+ '/tags.html', 'w')
920 f
.write('<h1>Tags</h1>')
924 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
925 if len(data
.tags
) > 0:
926 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
929 f
.write('<table class="tags">')
930 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
931 # sort the tags by date desc
932 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
933 for tag
in tags_sorted_by_date_desc
:
935 authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
936 for i
in reversed(authors_by_commits
):
937 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
938 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
)))
941 f
.write('</body></html>')
944 self
.createGraphs(path
)
946 def createGraphs(self
, path
):
947 print 'Generating graphs...'
950 f
= open(path
+ '/hour_of_day.plot', 'w')
951 f
.write(GNUPLOT_COMMON
)
954 set output 'hour_of_day.png'
956 set xrange [0.5:24.5]
960 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
965 f
= open(path
+ '/day_of_week.plot', 'w')
966 f
.write(GNUPLOT_COMMON
)
969 set output 'day_of_week.png'
975 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
980 f
= open(path
+ '/domains.plot', 'w')
981 f
.write(GNUPLOT_COMMON
)
984 set output 'domains.png'
990 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
995 f
= open(path
+ '/month_of_year.plot', 'w')
996 f
.write(GNUPLOT_COMMON
)
999 set output 'month_of_year.png'
1001 set xrange [0.5:12.5]
1004 set ylabel "Commits"
1005 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1009 # commits_by_year_month
1010 f
= open(path
+ '/commits_by_year_month.plot', 'w')
1011 f
.write(GNUPLOT_COMMON
)
1014 set output 'commits_by_year_month.png'
1018 set format x "%Y-%m"
1019 set xtics rotate by 90 15768000
1022 set ylabel "Commits"
1023 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1028 f
= open(path
+ '/commits_by_year.plot', 'w')
1029 f
.write(GNUPLOT_COMMON
)
1032 set output 'commits_by_year.png'
1034 set xtics 1 rotate by 90
1036 set ylabel "Commits"
1038 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1043 f
= open(path
+ '/files_by_date.plot', 'w')
1044 f
.write(GNUPLOT_COMMON
)
1047 set output 'files_by_date.png'
1050 set timefmt "%Y-%m-%d"
1051 set format x "%Y-%m-%d"
1054 set xtics rotate by 90
1057 plot 'files_by_date.dat' using 1:2 w steps
1062 f
= open(path
+ '/lines_of_code.plot', 'w')
1063 f
.write(GNUPLOT_COMMON
)
1066 set output 'lines_of_code.png'
1070 set format x "%Y-%m-%d"
1073 set xtics rotate by 90
1075 plot 'lines_of_code.dat' using 1:2 w lines
1080 files
= glob
.glob(path
+ '/*.plot')
1082 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1086 def printHeader(self
, f
, title
= ''):
1088 """<?xml version="1.0" encoding="UTF-8"?>
1089 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1090 <html xmlns="http://www.w3.org/1999/xhtml">
1092 <title>GitStats - %s</title>
1093 <link rel="stylesheet" href="%s" type="text/css" />
1094 <meta name="generator" content="GitStats %s" />
1095 <script type="text/javascript" src="sortable.js"></script>
1098 """ % (self
.title
, conf
['style'], getversion()))
1100 def printNav(self
, f
):
1104 <li><a href="index.html">General</a></li>
1105 <li><a href="activity.html">Activity</a></li>
1106 <li><a href="authors.html">Authors</a></li>
1107 <li><a href="files.html">Files</a></li>
1108 <li><a href="lines.html">Lines</a></li>
1109 <li><a href="tags.html">Tags</a></li>
1116 def run(self
, args_orig
):
1117 optlist
, args
= getopt
.getopt(args_orig
, 'c:')
1120 key
, value
= v
.split('=', 1)
1122 raise KeyError('no such key "%s" in config' % key
)
1123 if isinstance(conf
[key
], int):
1124 conf
[key
] = int(value
)
1130 Usage: gitstats [options] <gitpath> <outputpath>
1133 -c key=value Override configuration value
1135 Default config values:
1141 outputpath
= os
.path
.abspath(args
[1])
1142 rundir
= os
.getcwd()
1145 os
.makedirs(outputpath
)
1148 if not os
.path
.isdir(outputpath
):
1149 print 'FATAL: Output path is not a directory or does not exist'
1152 print 'Git path: %s' % gitpath
1153 print 'Output path: %s' % outputpath
1157 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1159 print 'Collecting data...'
1160 data
= GitDataCollector()
1161 data
.loadCache(cachefile
)
1162 data
.collect(gitpath
)
1163 print 'Refining data...'
1164 data
.saveCache(cachefile
)
1169 print 'Generating report...'
1170 report
= HTMLReportCreator()
1171 report
.create(data
, outputpath
)
1173 time_end
= time
.time()
1174 exectime_internal
= time_end
- time_start
1175 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)
1177 if __name__
=='__main__':