2 # Copyright (c) 2007-2009 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
16 GNUPLOT_COMMON
= 'set terminal png transparent\nset size 0.5,0.5\n'
17 MAX_EXT_LENGTH
= 10 # maximum file extension length
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']
30 def getpipeoutput(cmds
, quiet
= False):
31 global exectime_external
33 if not quiet
and ON_LINUX
and os
.isatty(1):
34 print '>> ' + ' | '.join(cmds
),
36 p0
= subprocess
.Popen(cmds
[0], stdout
= subprocess
.PIPE
, shell
= True)
39 p
= subprocess
.Popen(x
, stdin
= p0
.stdout
, stdout
= subprocess
.PIPE
, shell
= True)
41 output
= p
.communicate()[0]
44 if ON_LINUX
and os
.isatty(1):
46 print '[%.5f] >> %s' % (end
- start
, ' | '.join(cmds
))
47 exectime_external
+= (end
- start
)
48 return output
.rstrip('\n')
50 def getkeyssortedbyvalues(dict):
51 return map(lambda el
: el
[1], sorted(map(lambda el
: (el
[1], el
[0]), dict.items())))
53 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
54 def getkeyssortedbyvaluekey(d
, key
):
55 return map(lambda el
: el
[1], sorted(map(lambda el
: (d
[el
][key
], el
), d
.keys())))
61 VERSION
= getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
65 """Manages data collection from a revision control repository."""
67 self
.stamp_created
= time
.time()
71 # This should be the main function to extract data from the repository.
72 def collect(self
, dir):
74 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
78 def loadCache(self
, cachefile
):
79 if not os
.path
.exists(cachefile
):
81 print 'Loading cache...'
84 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
86 # temporary hack to upgrade non-compressed caches
88 self
.cache
= pickle
.load(f
)
92 # Produce any additional statistics from the extracted data.
97 # : get a dictionary of author
98 def getAuthorInfo(self
, author
):
101 def getActivityByDayOfWeek(self
):
104 def getActivityByHourOfDay(self
):
107 # : get a dictionary of domains
108 def getDomainInfo(self
, domain
):
112 # Get a list of authors
113 def getAuthors(self
):
116 def getFirstCommitDate(self
):
117 return datetime
.datetime
.now()
119 def getLastCommitDate(self
):
120 return datetime
.datetime
.now()
122 def getStampCreated(self
):
123 return self
.stamp_created
128 def getTotalAuthors(self
):
131 def getTotalCommits(self
):
134 def getTotalFiles(self
):
137 def getTotalLOC(self
):
141 # Save cacheable data
142 def saveCache(self
, filename
):
143 print 'Saving cache...'
144 f
= open(cachefile
, 'w')
145 #pickle.dump(self.cache, f)
146 data
= zlib
.compress(pickle
.dumps(self
.cache
))
150 class GitDataCollector(DataCollector
):
151 def collect(self
, dir):
152 DataCollector
.collect(self
, dir)
155 self
.total_authors
= int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
157 self
.total_authors
= 0
158 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
160 self
.activity_by_hour_of_day
= {} # hour -> commits
161 self
.activity_by_day_of_week
= {} # day -> commits
162 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
163 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
164 self
.activity_by_hour_of_day_busiest
= 0
165 self
.activity_by_hour_of_week_busiest
= 0
166 self
.activity_by_year_week
= {} # yy_wNN -> commits
167 self
.activity_by_year_week_peak
= 0
169 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
172 self
.domains
= {} # domain -> commits
174 # author of the month
175 self
.author_of_month
= {} # month -> author -> commits
176 self
.author_of_year
= {} # year -> author -> commits
177 self
.commits_by_month
= {} # month -> commits
178 self
.commits_by_year
= {} # year -> commits
179 self
.first_commit_stamp
= 0
180 self
.last_commit_stamp
= 0
181 self
.last_active_day
= None
182 self
.active_days
= set()
186 self
.total_lines_added
= 0
187 self
.total_lines_removed
= 0
190 self
.commits_by_timezone
= {} # timezone -> commits
194 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
198 (hash, tag
) = line
.split(' ')
200 tag
= tag
.replace('refs/tags/', '')
201 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
203 parts
= output
.split(' ')
206 stamp
= int(parts
[0])
209 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
211 # collect info on tags, starting from latest
212 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
214 for tag
in reversed(tags_sorted_by_date_desc
):
215 cmd
= 'git shortlog -s "%s"' % tag
217 cmd
+= ' "^%s"' % prev
218 output
= getpipeoutput([cmd
])
222 for line
in output
.split('\n'):
223 parts
= re
.split('\s+', line
, 2)
224 commits
= int(parts
[1])
226 self
.tags
[tag
]['commits'] += commits
227 self
.tags
[tag
]['authors'][author
] = commits
229 # Collect revision statistics
230 # Outputs "<stamp> <author>"
231 lines
= getpipeoutput(['git rev-list --pretty=format:"%at %ai %aE %an" HEAD', 'grep -v ^commit']).split('\n')
233 parts
= line
.split(' ')
236 stamp
= int(parts
[0])
240 domain
= parts
[4].rsplit('@', 1)[1]
242 author
= ' '.join(parts
[5:])
243 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
245 # First and last commit stamp
246 if self
.last_commit_stamp
== 0:
247 self
.last_commit_stamp
= stamp
248 self
.first_commit_stamp
= stamp
253 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
255 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
256 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
260 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
263 if domain
not in self
.domains
:
264 self
.domains
[domain
] = {}
266 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
269 if day
not in self
.activity_by_hour_of_week
:
270 self
.activity_by_hour_of_week
[day
] = {}
271 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
273 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
274 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
278 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
280 # yearly/weekly activity
281 yyw
= date
.strftime('%Y-%W')
282 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
283 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
284 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
287 if author
not in self
.authors
:
288 self
.authors
[author
] = {}
290 if 'last_commit_stamp' not in self
.authors
[author
]:
291 self
.authors
[author
]['last_commit_stamp'] = stamp
292 self
.authors
[author
]['first_commit_stamp'] = stamp
293 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
295 # author of the month/year
296 yymm
= date
.strftime('%Y-%m')
297 if yymm
in self
.author_of_month
:
298 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
300 self
.author_of_month
[yymm
] = {}
301 self
.author_of_month
[yymm
][author
] = 1
302 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
305 if yy
in self
.author_of_year
:
306 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
308 self
.author_of_year
[yy
] = {}
309 self
.author_of_year
[yy
][author
] = 1
310 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
312 # authors: active days
313 yymmdd
= date
.strftime('%Y-%m-%d')
314 if 'last_active_day' not in self
.authors
[author
]:
315 self
.authors
[author
]['last_active_day'] = yymmdd
316 self
.authors
[author
]['active_days'] = 1
317 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
318 self
.authors
[author
]['last_active_day'] = yymmdd
319 self
.authors
[author
]['active_days'] += 1
321 # project: active days
322 if yymmdd
!= self
.last_active_day
:
323 self
.last_active_day
= yymmdd
324 self
.active_days
.add(yymmdd
)
327 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
329 # TODO Optimize this, it's the worst bottleneck
330 # outputs "<stamp> <files>" for each revision
331 self
.files_by_stamp
= {} # stamp -> files
332 revlines
= getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
334 for revline
in revlines
:
335 time
, rev
= revline
.split(' ')
336 linecount
= self
.getFilesInCommit(rev
)
337 lines
.append('%d %d' % (int(time
), linecount
))
339 self
.total_commits
= len(lines
)
341 parts
= line
.split(' ')
344 (stamp
, files
) = parts
[0:2]
346 self
.files_by_stamp
[int(stamp
)] = int(files
)
348 print 'Warning: failed to parse line "%s"' % line
351 self
.extensions
= {} # extension -> files, lines
352 lines
= getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
353 self
.total_files
= len(lines
)
357 parts
= re
.split('\s+', line
, 4)
361 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
364 ext
= filename
[(filename
.rfind('.') + 1):]
365 if len(ext
) > MAX_EXT_LENGTH
:
368 if ext
not in self
.extensions
:
369 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
371 self
.extensions
[ext
]['files'] += 1
373 self
.extensions
[ext
]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1
, 'wc -l']).split()[0])
375 print 'Warning: Could not count lines for file "%s"' % line
379 # N files changed, N insertions (+), N deletions(-)
381 self
.changes_by_date
= {} # stamp -> { files, ins, del }
382 lines
= getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
384 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
391 if line
.find('files changed,') == -1:
395 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
396 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
397 if author
not in self
.authors
:
398 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0 }
399 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
400 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
402 print 'Warning: unexpected line "%s"' % line
404 print 'Warning: unexpected line "%s"' % line
406 numbers
= re
.findall('\d+', line
)
407 if len(numbers
) == 3:
408 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
409 total_lines
+= inserted
410 total_lines
-= deleted
411 self
.total_lines_added
+= inserted
412 self
.total_lines_removed
+= deleted
414 print 'Warning: failed to handle line "%s"' % line
415 (files
, inserted
, deleted
) = (0, 0, 0)
416 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
417 self
.total_lines
= total_lines
421 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
422 authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
423 authors_by_commits
.reverse() # most first
424 for i
, name
in enumerate(authors_by_commits
):
425 self
.authors
[name
]['place_by_commits'] = i
+ 1
427 for name
in self
.authors
.keys():
428 a
= self
.authors
[name
]
429 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
430 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
431 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
432 delta
= date_last
- date_first
433 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
434 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
435 a
['timedelta'] = delta
437 def getActiveDays(self
):
438 return self
.active_days
440 def getActivityByDayOfWeek(self
):
441 return self
.activity_by_day_of_week
443 def getActivityByHourOfDay(self
):
444 return self
.activity_by_hour_of_day
446 def getAuthorInfo(self
, author
):
447 return self
.authors
[author
]
449 def getAuthors(self
):
450 return self
.authors
.keys()
452 def getCommitDeltaDays(self
):
453 return (self
.last_commit_stamp
- self
.first_commit_stamp
) / 86400
455 def getDomainInfo(self
, domain
):
456 return self
.domains
[domain
]
458 def getDomains(self
):
459 return self
.domains
.keys()
461 def getFilesInCommit(self
, rev
):
463 res
= self
.cache
['files_in_tree'][rev
]
465 res
= int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0])
466 if 'files_in_tree' not in self
.cache
:
467 self
.cache
['files_in_tree'] = {}
468 self
.cache
['files_in_tree'][rev
] = res
472 def getFirstCommitDate(self
):
473 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
475 def getLastCommitDate(self
):
476 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
479 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
480 return lines
.split('\n')
482 def getTagDate(self
, tag
):
483 return self
.revToDate('tags/' + tag
)
485 def getTotalAuthors(self
):
486 return self
.total_authors
488 def getTotalCommits(self
):
489 return self
.total_commits
491 def getTotalFiles(self
):
492 return self
.total_files
494 def getTotalLOC(self
):
495 return self
.total_lines
497 def revToDate(self
, rev
):
498 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
499 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
502 """Creates the actual report based on given data."""
506 def create(self
, data
, path
):
510 def html_linkify(text
):
511 return text
.lower().replace(' ', '_')
513 def html_header(level
, text
):
514 name
= html_linkify(text
)
515 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
517 class HTMLReportCreator(ReportCreator
):
518 def create(self
, data
, path
):
519 ReportCreator
.create(self
, data
, path
)
520 self
.title
= data
.projectname
522 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
523 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
524 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
525 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
526 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
527 for base
in basedirs
:
528 src
= base
+ '/' + file
529 if os
.path
.exists(src
):
530 shutil
.copyfile(src
, path
+ '/' + file)
533 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
535 f
= open(path
+ "/index.html", 'w')
536 format
= '%Y-%m-%d %H:%M:%S'
539 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
544 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
545 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
546 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
547 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
548 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())))
549 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
550 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
))
551 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()))
552 f
.write('<dt>Authors</dt><dd>%s</dd>' % data
.getTotalAuthors())
555 f
.write('</body>\n</html>')
560 f
= open(path
+ '/activity.html', 'w')
562 f
.write('<h1>Activity</h1>')
565 #f.write('<h2>Last 30 days</h2>')
567 #f.write('<h2>Last 12 months</h2>')
571 f
.write(html_header(2, 'Weekly activity'))
572 f
.write('<p>Last %d weeks</p>' % WEEKS
)
574 # generate weeks to show (previous N weeks from now)
575 now
= datetime
.datetime
.now()
576 deltaweek
= datetime
.timedelta(7)
579 for i
in range(0, WEEKS
):
580 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
581 stampcur
-= deltaweek
583 # top row: commits & bar
584 f
.write('<table class="noborders"><tr>')
585 for i
in range(0, WEEKS
):
587 if weeks
[i
] in data
.activity_by_year_week
:
588 commits
= data
.activity_by_year_week
[weeks
[i
]]
591 if weeks
[i
] in data
.activity_by_year_week
:
592 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
593 height
= max(1, int(200 * percentage
))
594 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
))
596 # bottom row: year/week
598 for i
in range(0, WEEKS
):
599 f
.write('<td>%s</td>' % (WEEKS
- i
))
600 f
.write('</tr></table>')
603 f
.write(html_header(2, 'Hour of Day'))
604 hour_of_day
= data
.getActivityByHourOfDay()
605 f
.write('<table><tr><th>Hour</th>')
606 for i
in range(0, 24):
607 f
.write('<th>%d</th>' % i
)
608 f
.write('</tr>\n<tr><th>Commits</th>')
609 fp
= open(path
+ '/hour_of_day.dat', 'w')
610 for i
in range(0, 24):
612 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
613 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
614 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
616 f
.write('<td>0</td>')
617 fp
.write('%d 0\n' % i
)
619 f
.write('</tr>\n<tr><th>%</th>')
620 totalcommits
= data
.getTotalCommits()
621 for i
in range(0, 24):
623 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
624 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
626 f
.write('<td>0.00</td>')
627 f
.write('</tr></table>')
628 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
629 fg
= open(path
+ '/hour_of_day.dat', 'w')
630 for i
in range(0, 24):
632 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
634 fg
.write('%d 0\n' % (i
+ 1))
638 f
.write(html_header(2, 'Day of Week'))
639 day_of_week
= data
.getActivityByDayOfWeek()
640 f
.write('<div class="vtable"><table>')
641 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
642 fp
= open(path
+ '/day_of_week.dat', 'w')
643 for d
in range(0, 7):
646 commits
= day_of_week
[d
]
647 fp
.write('%d %d\n' % (d
+ 1, commits
))
649 f
.write('<th>%d</th>' % (d
+ 1))
651 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
653 f
.write('<td>0</td>')
655 f
.write('</table></div>')
656 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
660 f
.write(html_header(2, 'Commits by Domains'))
661 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
662 domains_by_commits
.reverse() # most first
663 f
.write('<div class="vtable"><table>')
664 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
665 fp
= open(path
+ '/domains.dat', 'w')
668 for domain
in domains_by_commits
:
673 info
= data
.getDomainInfo(domain
)
674 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
675 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
676 f
.write('</table></div>')
677 f
.write('<img src="domains.png" alt="Commits by Domains" />')
681 f
.write(html_header(2, 'Hour of Week'))
684 f
.write('<tr><th>Weekday</th>')
685 for hour
in range(0, 24):
686 f
.write('<th>%d</th>' % (hour
))
689 for weekday
in range(0, 7):
690 f
.write('<tr><th>%d</th>' % (weekday
+ 1))
691 for hour
in range(0, 24):
693 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
698 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
699 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
700 f
.write('>%d</td>' % commits
)
708 f
.write(html_header(2, 'Month of Year'))
709 f
.write('<div class="vtable"><table>')
710 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
711 fp
= open (path
+ '/month_of_year.dat', 'w')
712 for mm
in range(1, 13):
714 if mm
in data
.activity_by_month_of_year
:
715 commits
= data
.activity_by_month_of_year
[mm
]
716 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
717 fp
.write('%d %d\n' % (mm
, commits
))
719 f
.write('</table></div>')
720 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
722 # Commits by year/month
723 f
.write(html_header(2, 'Commits by year/month'))
724 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
725 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
726 f
.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
[yymm
]))
727 f
.write('</table></div>')
728 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
729 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
730 for yymm
in sorted(data
.commits_by_month
.keys()):
731 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
735 f
.write(html_header(2, 'Commits by Year'))
736 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
737 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
738 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()))
739 f
.write('</table></div>')
740 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
741 fg
= open(path
+ '/commits_by_year.dat', 'w')
742 for yy
in sorted(data
.commits_by_year
.keys()):
743 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
746 # Commits by timezone
747 f
.write(html_header(2, 'Commits by Timezone'))
748 f
.write('<table><tr>')
749 f
.write('<th>Timezone</th><th>Commits</th>')
750 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
751 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
752 commits
= data
.commits_by_timezone
[i
]
753 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
754 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
755 f
.write('</tr></table>')
757 f
.write('</body></html>')
762 f
= open(path
+ '/authors.html', 'w')
765 f
.write('<h1>Authors</h1>')
768 # Authors :: List of authors
769 f
.write(html_header(2, 'List of Authors'))
771 f
.write('<table class="authors sortable" id="authors">')
772 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>')
773 for author
in sorted(data
.getAuthors()):
774 info
= data
.getAuthorInfo(author
)
775 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']))
778 # Authors :: Author of Month
779 f
.write(html_header(2, 'Author of Month'))
780 f
.write('<table class="sortable" id="aom">')
781 f
.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
782 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
783 authordict
= data
.author_of_month
[yymm
]
784 authors
= getkeyssortedbyvalues(authordict
)
786 commits
= data
.author_of_month
[yymm
][authors
[0]]
787 next
= ', '.join(authors
[1:5])
788 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
))
792 f
.write(html_header(2, 'Author of Year'))
793 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>')
794 for yy
in reversed(sorted(data
.author_of_year
.keys())):
795 authordict
= data
.author_of_year
[yy
]
796 authors
= getkeyssortedbyvalues(authordict
)
798 commits
= data
.author_of_year
[yy
][authors
[0]]
799 next
= ', '.join(authors
[1:5])
800 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
))
803 f
.write('</body></html>')
808 f
= open(path
+ '/files.html', 'w')
810 f
.write('<h1>Files</h1>')
814 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
815 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
816 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data
.getTotalLOC()) / data
.getTotalFiles()))
819 # Files :: File count by date
820 f
.write(html_header(2, 'File count by date'))
822 # use set to get rid of duplicate/unnecessary entries
823 files_by_date
= set()
824 for stamp
in sorted(data
.files_by_stamp
.keys()):
825 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
827 fg
= open(path
+ '/files_by_date.dat', 'w')
828 for line
in sorted(list(files_by_date
)):
829 fg
.write('%s\n' % line
)
830 #for stamp in sorted(data.files_by_stamp.keys()):
831 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
834 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
836 #f.write('<h2>Average file size by date</h2>')
838 # Files :: Extensions
839 f
.write(html_header(2, 'Extensions'))
840 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
841 for ext
in sorted(data
.extensions
.keys()):
842 files
= data
.extensions
[ext
]['files']
843 lines
= data
.extensions
[ext
]['lines']
844 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
))
847 f
.write('</body></html>')
852 f
= open(path
+ '/lines.html', 'w')
854 f
.write('<h1>Lines</h1>')
858 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
861 f
.write(html_header(2, 'Lines of Code'))
862 f
.write('<img src="lines_of_code.png" />')
864 fg
= open(path
+ '/lines_of_code.dat', 'w')
865 for stamp
in sorted(data
.changes_by_date
.keys()):
866 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
869 f
.write('</body></html>')
874 f
= open(path
+ '/tags.html', 'w')
876 f
.write('<h1>Tags</h1>')
880 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
881 if len(data
.tags
) > 0:
882 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
885 f
.write('<table class="tags">')
886 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
887 # sort the tags by date desc
888 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
889 for tag
in tags_sorted_by_date_desc
:
891 authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
892 for i
in reversed(authors_by_commits
):
893 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
894 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
)))
897 f
.write('</body></html>')
900 self
.createGraphs(path
)
902 def createGraphs(self
, path
):
903 print 'Generating graphs...'
906 f
= open(path
+ '/hour_of_day.plot', 'w')
907 f
.write(GNUPLOT_COMMON
)
910 set output 'hour_of_day.png'
912 set xrange [0.5:24.5]
915 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
920 f
= open(path
+ '/day_of_week.plot', 'w')
921 f
.write(GNUPLOT_COMMON
)
924 set output 'day_of_week.png'
929 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
934 f
= open(path
+ '/domains.plot', 'w')
935 f
.write(GNUPLOT_COMMON
)
938 set output 'domains.png'
943 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
948 f
= open(path
+ '/month_of_year.plot', 'w')
949 f
.write(GNUPLOT_COMMON
)
952 set output 'month_of_year.png'
954 set xrange [0.5:12.5]
957 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
961 # commits_by_year_month
962 f
= open(path
+ '/commits_by_year_month.plot', 'w')
963 f
.write(GNUPLOT_COMMON
)
966 set output 'commits_by_year_month.png'
971 set xtics rotate by 90 15768000
974 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
979 f
= open(path
+ '/commits_by_year.plot', 'w')
980 f
.write(GNUPLOT_COMMON
)
983 set output 'commits_by_year.png'
988 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
993 f
= open(path
+ '/files_by_date.plot', 'w')
994 f
.write(GNUPLOT_COMMON
)
997 set output 'files_by_date.png'
1000 set timefmt "%Y-%m-%d"
1001 set format x "%Y-%m-%d"
1003 set xtics rotate by 90
1006 plot 'files_by_date.dat' using 1:2 w steps
1011 f
= open(path
+ '/lines_of_code.plot', 'w')
1012 f
.write(GNUPLOT_COMMON
)
1015 set output 'lines_of_code.png'
1019 set format x "%Y-%m-%d"
1021 set xtics rotate by 90
1023 plot 'lines_of_code.dat' using 1:2 w lines
1028 files
= glob
.glob(path
+ '/*.plot')
1030 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1034 def printHeader(self
, f
, title
= ''):
1036 """<?xml version="1.0" encoding="UTF-8"?>
1037 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1038 <html xmlns="http://www.w3.org/1999/xhtml">
1040 <title>GitStats - %s</title>
1041 <link rel="stylesheet" href="gitstats.css" type="text/css" />
1042 <meta name="generator" content="GitStats %s" />
1043 <script type="text/javascript" src="sortable.js"></script>
1046 """ % (self
.title
, getversion()))
1048 def printNav(self
, f
):
1052 <li><a href="index.html">General</a></li>
1053 <li><a href="activity.html">Activity</a></li>
1054 <li><a href="authors.html">Authors</a></li>
1055 <li><a href="files.html">Files</a></li>
1056 <li><a href="lines.html">Lines</a></li>
1057 <li><a href="tags.html">Tags</a></li>
1064 Usage: gitstats [options] <gitpath> <outputpath>
1069 if len(sys
.argv
) < 3:
1073 gitpath
= sys
.argv
[1]
1074 outputpath
= os
.path
.abspath(sys
.argv
[2])
1075 rundir
= os
.getcwd()
1078 os
.makedirs(outputpath
)
1081 if not os
.path
.isdir(outputpath
):
1082 print 'FATAL: Output path is not a directory or does not exist'
1085 print 'Git path: %s' % gitpath
1086 print 'Output path: %s' % outputpath
1090 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1092 print 'Collecting data...'
1093 data
= GitDataCollector()
1094 data
.loadCache(cachefile
)
1095 data
.collect(gitpath
)
1096 print 'Refining data...'
1097 data
.saveCache(cachefile
)
1102 print 'Generating report...'
1103 report
= HTMLReportCreator()
1104 report
.create(data
, outputpath
)
1106 time_end
= time
.time()
1107 exectime_internal
= time_end
- time_start
1108 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)