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')
20 exectime_internal
= 0.0
21 exectime_external
= 0.0
22 time_start
= time
.time()
24 # By default, gnuplot is searched from path, but can be overridden with the
25 # environment variable "GNUPLOT"
26 gnuplot_cmd
= 'gnuplot'
27 if 'GNUPLOT' in os
.environ
:
28 gnuplot_cmd
= os
.environ
['GNUPLOT']
33 'style': 'gitstats.css',
37 def getpipeoutput(cmds
, quiet
= False):
38 global exectime_external
40 if not quiet
and ON_LINUX
and os
.isatty(1):
41 print '>> ' + ' | '.join(cmds
),
43 p0
= subprocess
.Popen(cmds
[0], stdout
= subprocess
.PIPE
, shell
= True)
46 p
= subprocess
.Popen(x
, stdin
= p0
.stdout
, stdout
= subprocess
.PIPE
, shell
= True)
48 output
= p
.communicate()[0]
51 if ON_LINUX
and os
.isatty(1):
53 print '[%.5f] >> %s' % (end
- start
, ' | '.join(cmds
))
54 exectime_external
+= (end
- start
)
55 return output
.rstrip('\n')
57 def getkeyssortedbyvalues(dict):
58 return map(lambda el
: el
[1], sorted(map(lambda el
: (el
[1], el
[0]), dict.items())))
60 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
61 def getkeyssortedbyvaluekey(d
, key
):
62 return map(lambda el
: el
[1], sorted(map(lambda el
: (d
[el
][key
], el
), d
.keys())))
68 VERSION
= getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
72 """Manages data collection from a revision control repository."""
74 self
.stamp_created
= time
.time()
78 # This should be the main function to extract data from the repository.
79 def collect(self
, dir):
81 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
85 def loadCache(self
, cachefile
):
86 if not os
.path
.exists(cachefile
):
88 print 'Loading cache...'
91 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
93 # temporary hack to upgrade non-compressed caches
95 self
.cache
= pickle
.load(f
)
99 # Produce any additional statistics from the extracted data.
104 # : get a dictionary of author
105 def getAuthorInfo(self
, author
):
108 def getActivityByDayOfWeek(self
):
111 def getActivityByHourOfDay(self
):
114 # : get a dictionary of domains
115 def getDomainInfo(self
, domain
):
119 # Get a list of authors
120 def getAuthors(self
):
123 def getFirstCommitDate(self
):
124 return datetime
.datetime
.now()
126 def getLastCommitDate(self
):
127 return datetime
.datetime
.now()
129 def getStampCreated(self
):
130 return self
.stamp_created
135 def getTotalAuthors(self
):
138 def getTotalCommits(self
):
141 def getTotalFiles(self
):
144 def getTotalLOC(self
):
148 # Save cacheable data
149 def saveCache(self
, cachefile
):
150 print 'Saving cache...'
151 f
= open(cachefile
, 'w')
152 #pickle.dump(self.cache, f)
153 data
= zlib
.compress(pickle
.dumps(self
.cache
))
157 class GitDataCollector(DataCollector
):
158 def collect(self
, dir):
159 DataCollector
.collect(self
, dir)
162 self
.total_authors
= int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
164 self
.total_authors
= 0
165 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
167 self
.activity_by_hour_of_day
= {} # hour -> commits
168 self
.activity_by_day_of_week
= {} # day -> commits
169 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
170 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
171 self
.activity_by_hour_of_day_busiest
= 0
172 self
.activity_by_hour_of_week_busiest
= 0
173 self
.activity_by_year_week
= {} # yy_wNN -> commits
174 self
.activity_by_year_week_peak
= 0
176 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
179 self
.domains
= {} # domain -> commits
181 # author of the month
182 self
.author_of_month
= {} # month -> author -> commits
183 self
.author_of_year
= {} # year -> author -> commits
184 self
.commits_by_month
= {} # month -> commits
185 self
.commits_by_year
= {} # year -> commits
186 self
.first_commit_stamp
= 0
187 self
.last_commit_stamp
= 0
188 self
.last_active_day
= None
189 self
.active_days
= set()
193 self
.total_lines_added
= 0
194 self
.total_lines_removed
= 0
197 self
.commits_by_timezone
= {} # timezone -> commits
201 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
205 (hash, tag
) = line
.split(' ')
207 tag
= tag
.replace('refs/tags/', '')
208 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
210 parts
= output
.split(' ')
213 stamp
= int(parts
[0])
216 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
218 # collect info on tags, starting from latest
219 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), self
.tags
.items()))))
221 for tag
in reversed(tags_sorted_by_date_desc
):
222 cmd
= 'git shortlog -s "%s"' % tag
224 cmd
+= ' "^%s"' % prev
225 output
= getpipeoutput([cmd
])
229 for line
in output
.split('\n'):
230 parts
= re
.split('\s+', line
, 2)
231 commits
= int(parts
[1])
233 self
.tags
[tag
]['commits'] += commits
234 self
.tags
[tag
]['authors'][author
] = commits
236 # Collect revision statistics
237 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
238 lines
= getpipeoutput(['git rev-list --pretty=format:"%at %ai %an <%aE>" HEAD', 'grep -v ^commit']).split('\n')
240 parts
= line
.split(' ', 4)
243 stamp
= int(parts
[0])
247 author
, mail
= parts
[4].split('<', 1)
248 author
= author
.rstrip()
249 mail
= mail
.rstrip('>')
251 if mail
.find('@') != -1:
252 domain
= mail
.rsplit('@', 1)[1]
253 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
255 # First and last commit stamp
256 if self
.last_commit_stamp
== 0:
257 self
.last_commit_stamp
= stamp
258 self
.first_commit_stamp
= stamp
263 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
265 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
266 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
270 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
273 if domain
not in self
.domains
:
274 self
.domains
[domain
] = {}
276 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
279 if day
not in self
.activity_by_hour_of_week
:
280 self
.activity_by_hour_of_week
[day
] = {}
281 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
283 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
284 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
288 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
290 # yearly/weekly activity
291 yyw
= date
.strftime('%Y-%W')
292 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
293 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
294 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
297 if author
not in self
.authors
:
298 self
.authors
[author
] = {}
300 if 'last_commit_stamp' not in self
.authors
[author
]:
301 self
.authors
[author
]['last_commit_stamp'] = stamp
302 self
.authors
[author
]['first_commit_stamp'] = stamp
303 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
305 # author of the month/year
306 yymm
= date
.strftime('%Y-%m')
307 if yymm
in self
.author_of_month
:
308 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
310 self
.author_of_month
[yymm
] = {}
311 self
.author_of_month
[yymm
][author
] = 1
312 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
315 if yy
in self
.author_of_year
:
316 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
318 self
.author_of_year
[yy
] = {}
319 self
.author_of_year
[yy
][author
] = 1
320 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
322 # authors: active days
323 yymmdd
= date
.strftime('%Y-%m-%d')
324 if 'last_active_day' not in self
.authors
[author
]:
325 self
.authors
[author
]['last_active_day'] = yymmdd
326 self
.authors
[author
]['active_days'] = 1
327 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
328 self
.authors
[author
]['last_active_day'] = yymmdd
329 self
.authors
[author
]['active_days'] += 1
331 # project: active days
332 if yymmdd
!= self
.last_active_day
:
333 self
.last_active_day
= yymmdd
334 self
.active_days
.add(yymmdd
)
337 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
339 # TODO Optimize this, it's the worst bottleneck
340 # outputs "<stamp> <files>" for each revision
341 self
.files_by_stamp
= {} # stamp -> files
342 revlines
= getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
344 for revline
in revlines
:
345 time
, rev
= revline
.split(' ')
346 linecount
= self
.getFilesInCommit(rev
)
347 lines
.append('%d %d' % (int(time
), linecount
))
349 self
.total_commits
= len(lines
)
351 parts
= line
.split(' ')
354 (stamp
, files
) = parts
[0:2]
356 self
.files_by_stamp
[int(stamp
)] = int(files
)
358 print 'Warning: failed to parse line "%s"' % line
361 self
.extensions
= {} # extension -> files, lines
362 lines
= getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
363 self
.total_files
= len(lines
)
367 parts
= re
.split('\s+', line
, 4)
371 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
374 ext
= filename
[(filename
.rfind('.') + 1):]
375 if len(ext
) > conf
['max_ext_length']:
378 if ext
not in self
.extensions
:
379 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
381 self
.extensions
[ext
]['files'] += 1
383 self
.extensions
[ext
]['lines'] += self
.getLinesInBlob(sha1
)
385 print 'Warning: Could not count lines for file "%s"' % line
389 # N files changed, N insertions (+), N deletions(-)
391 self
.changes_by_date
= {} # stamp -> { files, ins, del }
392 lines
= getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
394 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
401 if line
.find('files changed,') == -1:
405 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
406 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
407 if author
not in self
.authors
:
408 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0 }
409 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
410 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
412 print 'Warning: unexpected line "%s"' % line
414 print 'Warning: unexpected line "%s"' % line
416 numbers
= re
.findall('\d+', line
)
417 if len(numbers
) == 3:
418 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
419 total_lines
+= inserted
420 total_lines
-= deleted
421 self
.total_lines_added
+= inserted
422 self
.total_lines_removed
+= deleted
424 print 'Warning: failed to handle line "%s"' % line
425 (files
, inserted
, deleted
) = (0, 0, 0)
426 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
427 self
.total_lines
= total_lines
431 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
432 authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
433 authors_by_commits
.reverse() # most first
434 for i
, name
in enumerate(authors_by_commits
):
435 self
.authors
[name
]['place_by_commits'] = i
+ 1
437 for name
in self
.authors
.keys():
438 a
= self
.authors
[name
]
439 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
440 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
441 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
442 delta
= date_last
- date_first
443 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
444 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
445 a
['timedelta'] = delta
447 def getActiveDays(self
):
448 return self
.active_days
450 def getActivityByDayOfWeek(self
):
451 return self
.activity_by_day_of_week
453 def getActivityByHourOfDay(self
):
454 return self
.activity_by_hour_of_day
456 def getAuthorInfo(self
, author
):
457 return self
.authors
[author
]
459 def getAuthors(self
, limit
= None):
460 res
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
464 def getCommitDeltaDays(self
):
465 return (self
.last_commit_stamp
- self
.first_commit_stamp
) / 86400 + 1
467 def getDomainInfo(self
, domain
):
468 return self
.domains
[domain
]
470 def getDomains(self
):
471 return self
.domains
.keys()
473 def getFilesInCommit(self
, rev
):
475 res
= self
.cache
['files_in_tree'][rev
]
477 res
= int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0])
478 if 'files_in_tree' not in self
.cache
:
479 self
.cache
['files_in_tree'] = {}
480 self
.cache
['files_in_tree'][rev
] = res
484 def getFirstCommitDate(self
):
485 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
487 def getLastCommitDate(self
):
488 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
490 def getLinesInBlob(self
, sha1
):
492 res
= self
.cache
['lines_in_blob'][sha1
]
494 res
= int(getpipeoutput(['git cat-file blob %s' % sha1
, 'wc -l']).split()[0])
495 if 'lines_in_blob' not in self
.cache
:
496 self
.cache
['lines_in_blob'] = {}
497 self
.cache
['lines_in_blob'][sha1
] = res
501 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
502 return lines
.split('\n')
504 def getTagDate(self
, tag
):
505 return self
.revToDate('tags/' + tag
)
507 def getTotalAuthors(self
):
508 return self
.total_authors
510 def getTotalCommits(self
):
511 return self
.total_commits
513 def getTotalFiles(self
):
514 return self
.total_files
516 def getTotalLOC(self
):
517 return self
.total_lines
519 def revToDate(self
, rev
):
520 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
521 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
524 """Creates the actual report based on given data."""
528 def create(self
, data
, path
):
532 def html_linkify(text
):
533 return text
.lower().replace(' ', '_')
535 def html_header(level
, text
):
536 name
= html_linkify(text
)
537 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
539 class HTMLReportCreator(ReportCreator
):
540 def create(self
, data
, path
):
541 ReportCreator
.create(self
, data
, path
)
542 self
.title
= data
.projectname
544 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
545 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
546 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
547 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
548 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
549 for base
in basedirs
:
550 src
= base
+ '/' + file
551 if os
.path
.exists(src
):
552 shutil
.copyfile(src
, path
+ '/' + file)
555 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
557 f
= open(path
+ "/index.html", 'w')
558 format
= '%Y-%m-%d %H:%M:%S'
561 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
566 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
567 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
568 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
569 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
570 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())))
571 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
572 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
))
573 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()))
574 f
.write('<dt>Authors</dt><dd>%s</dd>' % data
.getTotalAuthors())
577 f
.write('</body>\n</html>')
582 f
= open(path
+ '/activity.html', 'w')
584 f
.write('<h1>Activity</h1>')
587 #f.write('<h2>Last 30 days</h2>')
589 #f.write('<h2>Last 12 months</h2>')
593 f
.write(html_header(2, 'Weekly activity'))
594 f
.write('<p>Last %d weeks</p>' % WEEKS
)
596 # generate weeks to show (previous N weeks from now)
597 now
= datetime
.datetime
.now()
598 deltaweek
= datetime
.timedelta(7)
601 for i
in range(0, WEEKS
):
602 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
603 stampcur
-= deltaweek
605 # top row: commits & bar
606 f
.write('<table class="noborders"><tr>')
607 for i
in range(0, WEEKS
):
609 if weeks
[i
] in data
.activity_by_year_week
:
610 commits
= data
.activity_by_year_week
[weeks
[i
]]
613 if weeks
[i
] in data
.activity_by_year_week
:
614 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
615 height
= max(1, int(200 * percentage
))
616 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
))
618 # bottom row: year/week
620 for i
in range(0, WEEKS
):
621 f
.write('<td>%s</td>' % (WEEKS
- i
))
622 f
.write('</tr></table>')
625 f
.write(html_header(2, 'Hour of Day'))
626 hour_of_day
= data
.getActivityByHourOfDay()
627 f
.write('<table><tr><th>Hour</th>')
628 for i
in range(0, 24):
629 f
.write('<th>%d</th>' % i
)
630 f
.write('</tr>\n<tr><th>Commits</th>')
631 fp
= open(path
+ '/hour_of_day.dat', 'w')
632 for i
in range(0, 24):
634 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
635 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
636 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
638 f
.write('<td>0</td>')
639 fp
.write('%d 0\n' % i
)
641 f
.write('</tr>\n<tr><th>%</th>')
642 totalcommits
= data
.getTotalCommits()
643 for i
in range(0, 24):
645 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
646 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
648 f
.write('<td>0.00</td>')
649 f
.write('</tr></table>')
650 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
651 fg
= open(path
+ '/hour_of_day.dat', 'w')
652 for i
in range(0, 24):
654 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
656 fg
.write('%d 0\n' % (i
+ 1))
660 f
.write(html_header(2, 'Day of Week'))
661 day_of_week
= data
.getActivityByDayOfWeek()
662 f
.write('<div class="vtable"><table>')
663 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
664 fp
= open(path
+ '/day_of_week.dat', 'w')
665 for d
in range(0, 7):
668 commits
= day_of_week
[d
]
669 fp
.write('%d %d\n' % (d
+ 1, commits
))
671 f
.write('<th>%d</th>' % (d
+ 1))
673 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
675 f
.write('<td>0</td>')
677 f
.write('</table></div>')
678 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
682 f
.write(html_header(2, 'Hour of Week'))
685 f
.write('<tr><th>Weekday</th>')
686 for hour
in range(0, 24):
687 f
.write('<th>%d</th>' % (hour
))
690 for weekday
in range(0, 7):
691 f
.write('<tr><th>%d</th>' % (weekday
+ 1))
692 for hour
in range(0, 24):
694 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
699 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
700 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
701 f
.write('>%d</td>' % commits
)
709 f
.write(html_header(2, 'Month of Year'))
710 f
.write('<div class="vtable"><table>')
711 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
712 fp
= open (path
+ '/month_of_year.dat', 'w')
713 for mm
in range(1, 13):
715 if mm
in data
.activity_by_month_of_year
:
716 commits
= data
.activity_by_month_of_year
[mm
]
717 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
718 fp
.write('%d %d\n' % (mm
, commits
))
720 f
.write('</table></div>')
721 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
723 # Commits by year/month
724 f
.write(html_header(2, 'Commits by year/month'))
725 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
726 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
727 f
.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
[yymm
]))
728 f
.write('</table></div>')
729 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
730 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
731 for yymm
in sorted(data
.commits_by_month
.keys()):
732 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
736 f
.write(html_header(2, 'Commits by Year'))
737 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
738 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
739 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()))
740 f
.write('</table></div>')
741 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
742 fg
= open(path
+ '/commits_by_year.dat', 'w')
743 for yy
in sorted(data
.commits_by_year
.keys()):
744 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
747 # Commits by timezone
748 f
.write(html_header(2, 'Commits by Timezone'))
749 f
.write('<table><tr>')
750 f
.write('<th>Timezone</th><th>Commits</th>')
751 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
752 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
753 commits
= data
.commits_by_timezone
[i
]
754 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
755 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
756 f
.write('</tr></table>')
758 f
.write('</body></html>')
763 f
= open(path
+ '/authors.html', 'w')
766 f
.write('<h1>Authors</h1>')
769 # Authors :: List of authors
770 f
.write(html_header(2, 'List of Authors'))
772 f
.write('<table class="authors sortable" id="authors">')
773 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>')
774 for author
in sorted(data
.getAuthors(conf
['max_authors'])):
775 info
= data
.getAuthorInfo(author
)
776 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']))
779 allauthors
= data
.getAuthors()
780 if len(allauthors
) > conf
['max_authors']:
781 rest
= allauthors
[conf
['max_authors']:]
782 f
.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest
))
784 # Authors :: Author of Month
785 f
.write(html_header(2, 'Author of Month'))
786 f
.write('<table class="sortable" id="aom">')
787 f
.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
788 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
789 authordict
= data
.author_of_month
[yymm
]
790 authors
= getkeyssortedbyvalues(authordict
)
792 commits
= data
.author_of_month
[yymm
][authors
[0]]
793 next
= ', '.join(authors
[1:5])
794 f
.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yymm
, authors
[0], commits
, (100.0 * commits
) / data
.commits_by_month
[yymm
], data
.commits_by_month
[yymm
], next
))
798 f
.write(html_header(2, 'Author of Year'))
799 f
.write('<table class="sortable" id="aoy"><tr><th>Year</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
800 for yy
in reversed(sorted(data
.author_of_year
.keys())):
801 authordict
= data
.author_of_year
[yy
]
802 authors
= getkeyssortedbyvalues(authordict
)
804 commits
= data
.author_of_year
[yy
][authors
[0]]
805 next
= ', '.join(authors
[1:5])
806 f
.write('<tr><td>%s</td><td>%s</td><td>%d (%.2f%% of %d)</td><td>%s</td></tr>' % (yy
, authors
[0], commits
, (100.0 * commits
) / data
.commits_by_year
[yy
], data
.commits_by_year
[yy
], next
))
810 f
.write(html_header(2, 'Commits by Domains'))
811 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
812 domains_by_commits
.reverse() # most first
813 f
.write('<div class="vtable"><table>')
814 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
815 fp
= open(path
+ '/domains.dat', 'w')
817 for domain
in domains_by_commits
:
818 if n
== conf
['max_domains']:
822 info
= data
.getDomainInfo(domain
)
823 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
824 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
825 f
.write('</table></div>')
826 f
.write('<img src="domains.png" alt="Commits by Domains" />')
829 f
.write('</body></html>')
834 f
= open(path
+ '/files.html', 'w')
836 f
.write('<h1>Files</h1>')
840 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
841 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
842 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data
.getTotalLOC()) / data
.getTotalFiles()))
845 # Files :: File count by date
846 f
.write(html_header(2, 'File count by date'))
848 # use set to get rid of duplicate/unnecessary entries
849 files_by_date
= set()
850 for stamp
in sorted(data
.files_by_stamp
.keys()):
851 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
853 fg
= open(path
+ '/files_by_date.dat', 'w')
854 for line
in sorted(list(files_by_date
)):
855 fg
.write('%s\n' % line
)
856 #for stamp in sorted(data.files_by_stamp.keys()):
857 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
860 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
862 #f.write('<h2>Average file size by date</h2>')
864 # Files :: Extensions
865 f
.write(html_header(2, 'Extensions'))
866 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
867 for ext
in sorted(data
.extensions
.keys()):
868 files
= data
.extensions
[ext
]['files']
869 lines
= data
.extensions
[ext
]['lines']
870 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
))
873 f
.write('</body></html>')
878 f
= open(path
+ '/lines.html', 'w')
880 f
.write('<h1>Lines</h1>')
884 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
887 f
.write(html_header(2, 'Lines of Code'))
888 f
.write('<img src="lines_of_code.png" />')
890 fg
= open(path
+ '/lines_of_code.dat', 'w')
891 for stamp
in sorted(data
.changes_by_date
.keys()):
892 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
895 f
.write('</body></html>')
900 f
= open(path
+ '/tags.html', 'w')
902 f
.write('<h1>Tags</h1>')
906 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
907 if len(data
.tags
) > 0:
908 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
911 f
.write('<table class="tags">')
912 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
913 # sort the tags by date desc
914 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
915 for tag
in tags_sorted_by_date_desc
:
917 authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
918 for i
in reversed(authors_by_commits
):
919 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
920 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
)))
923 f
.write('</body></html>')
926 self
.createGraphs(path
)
928 def createGraphs(self
, path
):
929 print 'Generating graphs...'
932 f
= open(path
+ '/hour_of_day.plot', 'w')
933 f
.write(GNUPLOT_COMMON
)
936 set output 'hour_of_day.png'
938 set xrange [0.5:24.5]
941 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
946 f
= open(path
+ '/day_of_week.plot', 'w')
947 f
.write(GNUPLOT_COMMON
)
950 set output 'day_of_week.png'
955 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
960 f
= open(path
+ '/domains.plot', 'w')
961 f
.write(GNUPLOT_COMMON
)
964 set output 'domains.png'
969 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
974 f
= open(path
+ '/month_of_year.plot', 'w')
975 f
.write(GNUPLOT_COMMON
)
978 set output 'month_of_year.png'
980 set xrange [0.5:12.5]
983 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
987 # commits_by_year_month
988 f
= open(path
+ '/commits_by_year_month.plot', 'w')
989 f
.write(GNUPLOT_COMMON
)
992 set output 'commits_by_year_month.png'
997 set xtics rotate by 90 15768000
1000 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1005 f
= open(path
+ '/commits_by_year.plot', 'w')
1006 f
.write(GNUPLOT_COMMON
)
1009 set output 'commits_by_year.png'
1011 set xtics 1 rotate by 90
1012 set ylabel "Commits"
1014 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1019 f
= open(path
+ '/files_by_date.plot', 'w')
1020 f
.write(GNUPLOT_COMMON
)
1023 set output 'files_by_date.png'
1026 set timefmt "%Y-%m-%d"
1027 set format x "%Y-%m-%d"
1029 set xtics rotate by 90
1032 plot 'files_by_date.dat' using 1:2 w steps
1037 f
= open(path
+ '/lines_of_code.plot', 'w')
1038 f
.write(GNUPLOT_COMMON
)
1041 set output 'lines_of_code.png'
1045 set format x "%Y-%m-%d"
1047 set xtics rotate by 90
1049 plot 'lines_of_code.dat' using 1:2 w lines
1054 files
= glob
.glob(path
+ '/*.plot')
1056 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1060 def printHeader(self
, f
, title
= ''):
1062 """<?xml version="1.0" encoding="UTF-8"?>
1063 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1064 <html xmlns="http://www.w3.org/1999/xhtml">
1066 <title>GitStats - %s</title>
1067 <link rel="stylesheet" href="%s" type="text/css" />
1068 <meta name="generator" content="GitStats %s" />
1069 <script type="text/javascript" src="sortable.js"></script>
1072 """ % (self
.title
, conf
['style'], getversion()))
1074 def printNav(self
, f
):
1078 <li><a href="index.html">General</a></li>
1079 <li><a href="activity.html">Activity</a></li>
1080 <li><a href="authors.html">Authors</a></li>
1081 <li><a href="files.html">Files</a></li>
1082 <li><a href="lines.html">Lines</a></li>
1083 <li><a href="tags.html">Tags</a></li>
1090 def run(self
, args_orig
):
1091 optlist
, args
= getopt
.getopt(args_orig
, 'c:')
1094 key
, value
= v
.split('=', 1)
1096 raise 'Error: no such key "%s" in config' % key
1097 if isinstance(conf
[key
], int):
1098 conf
[key
] = int(value
)
1104 Usage: gitstats [options] <gitpath> <outputpath>
1107 -c key=value Override configuration value
1109 Default config values:
1115 outputpath
= os
.path
.abspath(args
[1])
1116 rundir
= os
.getcwd()
1119 os
.makedirs(outputpath
)
1122 if not os
.path
.isdir(outputpath
):
1123 print 'FATAL: Output path is not a directory or does not exist'
1126 print 'Git path: %s' % gitpath
1127 print 'Output path: %s' % outputpath
1131 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1133 print 'Collecting data...'
1134 data
= GitDataCollector()
1135 data
.loadCache(cachefile
)
1136 data
.collect(gitpath
)
1137 print 'Refining data...'
1138 data
.saveCache(cachefile
)
1143 print 'Generating report...'
1144 report
= HTMLReportCreator()
1145 report
.create(data
, outputpath
)
1147 time_end
= time
.time()
1148 exectime_internal
= time_end
- time_start
1149 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)