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 def getpipeoutput(cmds
, quiet
= False):
40 global exectime_external
42 if not quiet
and ON_LINUX
and os
.isatty(1):
43 print '>> ' + ' | '.join(cmds
),
45 p0
= subprocess
.Popen(cmds
[0], stdout
= subprocess
.PIPE
, shell
= True)
48 p
= subprocess
.Popen(x
, stdin
= p0
.stdout
, stdout
= subprocess
.PIPE
, shell
= True)
50 output
= p
.communicate()[0]
53 if ON_LINUX
and os
.isatty(1):
55 print '[%.5f] >> %s' % (end
- start
, ' | '.join(cmds
))
56 exectime_external
+= (end
- start
)
57 return output
.rstrip('\n')
59 def getkeyssortedbyvalues(dict):
60 return map(lambda el
: el
[1], sorted(map(lambda el
: (el
[1], el
[0]), dict.items())))
62 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
63 def getkeyssortedbyvaluekey(d
, key
):
64 return map(lambda el
: el
[1], sorted(map(lambda el
: (d
[el
][key
], el
), d
.keys())))
70 VERSION
= getpipeoutput(["git rev-parse --short HEAD"]).split('\n')[0]
74 """Manages data collection from a revision control repository."""
76 self
.stamp_created
= time
.time()
80 # This should be the main function to extract data from the repository.
81 def collect(self
, dir):
83 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
87 def loadCache(self
, cachefile
):
88 if not os
.path
.exists(cachefile
):
90 print 'Loading cache...'
91 f
= open(cachefile
, 'rb')
93 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
95 # temporary hack to upgrade non-compressed caches
97 self
.cache
= pickle
.load(f
)
101 # Produce any additional statistics from the extracted data.
106 # : get a dictionary of author
107 def getAuthorInfo(self
, author
):
110 def getActivityByDayOfWeek(self
):
113 def getActivityByHourOfDay(self
):
116 # : get a dictionary of domains
117 def getDomainInfo(self
, domain
):
121 # Get a list of authors
122 def getAuthors(self
):
125 def getFirstCommitDate(self
):
126 return datetime
.datetime
.now()
128 def getLastCommitDate(self
):
129 return datetime
.datetime
.now()
131 def getStampCreated(self
):
132 return self
.stamp_created
137 def getTotalAuthors(self
):
140 def getTotalCommits(self
):
143 def getTotalFiles(self
):
146 def getTotalLOC(self
):
150 # Save cacheable data
151 def saveCache(self
, cachefile
):
152 print 'Saving cache...'
153 f
= open(cachefile
, 'wb')
154 #pickle.dump(self.cache, f)
155 data
= zlib
.compress(pickle
.dumps(self
.cache
))
159 class GitDataCollector(DataCollector
):
160 def collect(self
, dir):
161 DataCollector
.collect(self
, dir)
164 self
.total_authors
= int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
166 self
.total_authors
= 0
167 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
169 self
.activity_by_hour_of_day
= {} # hour -> commits
170 self
.activity_by_day_of_week
= {} # day -> commits
171 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
172 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
173 self
.activity_by_hour_of_day_busiest
= 0
174 self
.activity_by_hour_of_week_busiest
= 0
175 self
.activity_by_year_week
= {} # yy_wNN -> commits
176 self
.activity_by_year_week_peak
= 0
178 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
181 self
.domains
= {} # domain -> commits
183 # author of the month
184 self
.author_of_month
= {} # month -> author -> commits
185 self
.author_of_year
= {} # year -> author -> commits
186 self
.commits_by_month
= {} # month -> commits
187 self
.commits_by_year
= {} # year -> commits
188 self
.first_commit_stamp
= 0
189 self
.last_commit_stamp
= 0
190 self
.last_active_day
= None
191 self
.active_days
= set()
195 self
.total_lines_added
= 0
196 self
.total_lines_removed
= 0
199 self
.commits_by_timezone
= {} # timezone -> commits
203 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
207 (hash, tag
) = line
.split(' ')
209 tag
= tag
.replace('refs/tags/', '')
210 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
212 parts
= output
.split(' ')
215 stamp
= int(parts
[0])
218 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
220 # collect info on tags, starting from latest
221 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), self
.tags
.items()))))
223 for tag
in reversed(tags_sorted_by_date_desc
):
224 cmd
= 'git shortlog -s "%s"' % tag
226 cmd
+= ' "^%s"' % prev
227 output
= getpipeoutput([cmd
])
231 for line
in output
.split('\n'):
232 parts
= re
.split('\s+', line
, 2)
233 commits
= int(parts
[1])
235 self
.tags
[tag
]['commits'] += commits
236 self
.tags
[tag
]['authors'][author
] = commits
238 # Collect revision statistics
239 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
240 lines
= getpipeoutput(['git rev-list --pretty=format:"%at %ai %an <%aE>" HEAD', 'grep -v ^commit']).split('\n')
242 parts
= line
.split(' ', 4)
245 stamp
= int(parts
[0])
249 author
, mail
= parts
[4].split('<', 1)
250 author
= author
.rstrip()
251 mail
= mail
.rstrip('>')
253 if mail
.find('@') != -1:
254 domain
= mail
.rsplit('@', 1)[1]
255 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
257 # First and last commit stamp
258 if self
.last_commit_stamp
== 0:
259 self
.last_commit_stamp
= stamp
260 self
.first_commit_stamp
= stamp
265 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
267 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
268 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
272 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
275 if domain
not in self
.domains
:
276 self
.domains
[domain
] = {}
278 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
281 if day
not in self
.activity_by_hour_of_week
:
282 self
.activity_by_hour_of_week
[day
] = {}
283 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
285 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
286 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
290 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
292 # yearly/weekly activity
293 yyw
= date
.strftime('%Y-%W')
294 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
295 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
296 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
299 if author
not in self
.authors
:
300 self
.authors
[author
] = {}
302 if 'last_commit_stamp' not in self
.authors
[author
]:
303 self
.authors
[author
]['last_commit_stamp'] = stamp
304 self
.authors
[author
]['first_commit_stamp'] = stamp
305 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
307 # author of the month/year
308 yymm
= date
.strftime('%Y-%m')
309 if yymm
in self
.author_of_month
:
310 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
312 self
.author_of_month
[yymm
] = {}
313 self
.author_of_month
[yymm
][author
] = 1
314 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
317 if yy
in self
.author_of_year
:
318 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
320 self
.author_of_year
[yy
] = {}
321 self
.author_of_year
[yy
][author
] = 1
322 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
324 # authors: active days
325 yymmdd
= date
.strftime('%Y-%m-%d')
326 if 'last_active_day' not in self
.authors
[author
]:
327 self
.authors
[author
]['last_active_day'] = yymmdd
328 self
.authors
[author
]['active_days'] = 1
329 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
330 self
.authors
[author
]['last_active_day'] = yymmdd
331 self
.authors
[author
]['active_days'] += 1
333 # project: active days
334 if yymmdd
!= self
.last_active_day
:
335 self
.last_active_day
= yymmdd
336 self
.active_days
.add(yymmdd
)
339 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
341 # TODO Optimize this, it's the worst bottleneck
342 # outputs "<stamp> <files>" for each revision
343 self
.files_by_stamp
= {} # stamp -> files
344 revlines
= getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
346 for revline
in revlines
:
347 time
, rev
= revline
.split(' ')
348 linecount
= self
.getFilesInCommit(rev
)
349 lines
.append('%d %d' % (int(time
), linecount
))
351 self
.total_commits
= len(lines
)
353 parts
= line
.split(' ')
356 (stamp
, files
) = parts
[0:2]
358 self
.files_by_stamp
[int(stamp
)] = int(files
)
360 print 'Warning: failed to parse line "%s"' % line
363 self
.extensions
= {} # extension -> files, lines
364 lines
= getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
365 self
.total_files
= len(lines
)
369 parts
= re
.split('\s+', line
, 4)
373 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
376 ext
= filename
[(filename
.rfind('.') + 1):]
377 if len(ext
) > conf
['max_ext_length']:
380 if ext
not in self
.extensions
:
381 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
383 self
.extensions
[ext
]['files'] += 1
385 self
.extensions
[ext
]['lines'] += self
.getLinesInBlob(sha1
)
387 print 'Warning: Could not count lines for file "%s"' % line
391 # N files changed, N insertions (+), N deletions(-)
393 self
.changes_by_date
= {} # stamp -> { files, ins, del }
394 lines
= getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
396 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
403 if line
.find('files changed,') == -1:
407 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
408 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
409 if author
not in self
.authors
:
410 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0 }
411 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
412 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
413 files
, inserted
, deleted
= 0, 0, 0
415 print 'Warning: unexpected line "%s"' % line
417 print 'Warning: unexpected line "%s"' % line
419 numbers
= re
.findall('\d+', line
)
420 if len(numbers
) == 3:
421 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
422 total_lines
+= inserted
423 total_lines
-= deleted
424 self
.total_lines_added
+= inserted
425 self
.total_lines_removed
+= deleted
427 print 'Warning: failed to handle line "%s"' % line
428 (files
, inserted
, deleted
) = (0, 0, 0)
429 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
430 self
.total_lines
= total_lines
434 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
435 authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
436 authors_by_commits
.reverse() # most first
437 for i
, name
in enumerate(authors_by_commits
):
438 self
.authors
[name
]['place_by_commits'] = i
+ 1
440 for name
in self
.authors
.keys():
441 a
= self
.authors
[name
]
442 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
443 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
444 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
445 delta
= date_last
- date_first
446 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
447 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
448 a
['timedelta'] = delta
450 def getActiveDays(self
):
451 return self
.active_days
453 def getActivityByDayOfWeek(self
):
454 return self
.activity_by_day_of_week
456 def getActivityByHourOfDay(self
):
457 return self
.activity_by_hour_of_day
459 def getAuthorInfo(self
, author
):
460 return self
.authors
[author
]
462 def getAuthors(self
, limit
= None):
463 res
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
467 def getCommitDeltaDays(self
):
468 return (self
.last_commit_stamp
- self
.first_commit_stamp
) / 86400 + 1
470 def getDomainInfo(self
, domain
):
471 return self
.domains
[domain
]
473 def getDomains(self
):
474 return self
.domains
.keys()
476 def getFilesInCommit(self
, rev
):
478 res
= self
.cache
['files_in_tree'][rev
]
480 res
= int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0])
481 if 'files_in_tree' not in self
.cache
:
482 self
.cache
['files_in_tree'] = {}
483 self
.cache
['files_in_tree'][rev
] = res
487 def getFirstCommitDate(self
):
488 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
490 def getLastCommitDate(self
):
491 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
493 def getLinesInBlob(self
, sha1
):
495 res
= self
.cache
['lines_in_blob'][sha1
]
497 res
= int(getpipeoutput(['git cat-file blob %s' % sha1
, 'wc -l']).split()[0])
498 if 'lines_in_blob' not in self
.cache
:
499 self
.cache
['lines_in_blob'] = {}
500 self
.cache
['lines_in_blob'][sha1
] = res
504 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
505 return lines
.split('\n')
507 def getTagDate(self
, tag
):
508 return self
.revToDate('tags/' + tag
)
510 def getTotalAuthors(self
):
511 return self
.total_authors
513 def getTotalCommits(self
):
514 return self
.total_commits
516 def getTotalFiles(self
):
517 return self
.total_files
519 def getTotalLOC(self
):
520 return self
.total_lines
522 def revToDate(self
, rev
):
523 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
524 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
527 """Creates the actual report based on given data."""
531 def create(self
, data
, path
):
535 def html_linkify(text
):
536 return text
.lower().replace(' ', '_')
538 def html_header(level
, text
):
539 name
= html_linkify(text
)
540 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
542 class HTMLReportCreator(ReportCreator
):
543 def create(self
, data
, path
):
544 ReportCreator
.create(self
, data
, path
)
545 self
.title
= data
.projectname
547 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
548 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
549 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
550 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
551 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
552 for base
in basedirs
:
553 src
= base
+ '/' + file
554 if os
.path
.exists(src
):
555 shutil
.copyfile(src
, path
+ '/' + file)
558 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
560 f
= open(path
+ "/index.html", 'w')
561 format
= '%Y-%m-%d %H:%M:%S'
564 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
569 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
570 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
571 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
572 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
573 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())))
574 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
575 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
))
576 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()))
577 f
.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data
.getTotalAuthors(), (1.0 * data
.getTotalCommits()) / data
.getTotalAuthors()))
580 f
.write('</body>\n</html>')
585 f
= open(path
+ '/activity.html', 'w')
587 f
.write('<h1>Activity</h1>')
590 #f.write('<h2>Last 30 days</h2>')
592 #f.write('<h2>Last 12 months</h2>')
596 f
.write(html_header(2, 'Weekly activity'))
597 f
.write('<p>Last %d weeks</p>' % WEEKS
)
599 # generate weeks to show (previous N weeks from now)
600 now
= datetime
.datetime
.now()
601 deltaweek
= datetime
.timedelta(7)
604 for i
in range(0, WEEKS
):
605 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
606 stampcur
-= deltaweek
608 # top row: commits & bar
609 f
.write('<table class="noborders"><tr>')
610 for i
in range(0, WEEKS
):
612 if weeks
[i
] in data
.activity_by_year_week
:
613 commits
= data
.activity_by_year_week
[weeks
[i
]]
616 if weeks
[i
] in data
.activity_by_year_week
:
617 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
618 height
= max(1, int(200 * percentage
))
619 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
))
621 # bottom row: year/week
623 for i
in range(0, WEEKS
):
624 f
.write('<td>%s</td>' % (WEEKS
- i
))
625 f
.write('</tr></table>')
628 f
.write(html_header(2, 'Hour of Day'))
629 hour_of_day
= data
.getActivityByHourOfDay()
630 f
.write('<table><tr><th>Hour</th>')
631 for i
in range(0, 24):
632 f
.write('<th>%d</th>' % i
)
633 f
.write('</tr>\n<tr><th>Commits</th>')
634 fp
= open(path
+ '/hour_of_day.dat', 'w')
635 for i
in range(0, 24):
637 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
638 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
639 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
641 f
.write('<td>0</td>')
642 fp
.write('%d 0\n' % i
)
644 f
.write('</tr>\n<tr><th>%</th>')
645 totalcommits
= data
.getTotalCommits()
646 for i
in range(0, 24):
648 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
649 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
651 f
.write('<td>0.00</td>')
652 f
.write('</tr></table>')
653 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
654 fg
= open(path
+ '/hour_of_day.dat', 'w')
655 for i
in range(0, 24):
657 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
659 fg
.write('%d 0\n' % (i
+ 1))
663 f
.write(html_header(2, 'Day of Week'))
664 day_of_week
= data
.getActivityByDayOfWeek()
665 f
.write('<div class="vtable"><table>')
666 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
667 fp
= open(path
+ '/day_of_week.dat', 'w')
668 for d
in range(0, 7):
671 commits
= day_of_week
[d
]
672 fp
.write('%d %s %d\n' % (d
+ 1, WEEKDAYS
[d
], commits
))
674 f
.write('<th>%s</th>' % (WEEKDAYS
[d
]))
676 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
678 f
.write('<td>0</td>')
680 f
.write('</table></div>')
681 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
685 f
.write(html_header(2, 'Hour of Week'))
688 f
.write('<tr><th>Weekday</th>')
689 for hour
in range(0, 24):
690 f
.write('<th>%d</th>' % (hour
))
693 for weekday
in range(0, 7):
694 f
.write('<tr><th>%s</th>' % (WEEKDAYS
[weekday
]))
695 for hour
in range(0, 24):
697 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
702 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
703 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
704 f
.write('>%d</td>' % commits
)
712 f
.write(html_header(2, 'Month of Year'))
713 f
.write('<div class="vtable"><table>')
714 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
715 fp
= open (path
+ '/month_of_year.dat', 'w')
716 for mm
in range(1, 13):
718 if mm
in data
.activity_by_month_of_year
:
719 commits
= data
.activity_by_month_of_year
[mm
]
720 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
721 fp
.write('%d %d\n' % (mm
, commits
))
723 f
.write('</table></div>')
724 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
726 # Commits by year/month
727 f
.write(html_header(2, 'Commits by year/month'))
728 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
729 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
730 f
.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
[yymm
]))
731 f
.write('</table></div>')
732 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
733 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
734 for yymm
in sorted(data
.commits_by_month
.keys()):
735 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
739 f
.write(html_header(2, 'Commits by Year'))
740 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
741 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
742 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()))
743 f
.write('</table></div>')
744 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
745 fg
= open(path
+ '/commits_by_year.dat', 'w')
746 for yy
in sorted(data
.commits_by_year
.keys()):
747 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
750 # Commits by timezone
751 f
.write(html_header(2, 'Commits by Timezone'))
752 f
.write('<table><tr>')
753 f
.write('<th>Timezone</th><th>Commits</th>')
754 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
755 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
756 commits
= data
.commits_by_timezone
[i
]
757 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
758 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
759 f
.write('</tr></table>')
761 f
.write('</body></html>')
766 f
= open(path
+ '/authors.html', 'w')
769 f
.write('<h1>Authors</h1>')
772 # Authors :: List of authors
773 f
.write(html_header(2, 'List of Authors'))
775 f
.write('<table class="authors sortable" id="authors">')
776 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>')
777 for author
in data
.getAuthors(conf
['max_authors']):
778 info
= data
.getAuthorInfo(author
)
779 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']))
782 allauthors
= data
.getAuthors()
783 if len(allauthors
) > conf
['max_authors']:
784 rest
= allauthors
[conf
['max_authors']:]
785 f
.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest
))
787 # Authors :: Author of Month
788 f
.write(html_header(2, 'Author of Month'))
789 f
.write('<table class="sortable" id="aom">')
790 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'])
791 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
792 authordict
= data
.author_of_month
[yymm
]
793 authors
= getkeyssortedbyvalues(authordict
)
795 commits
= data
.author_of_month
[yymm
][authors
[0]]
796 next
= ', '.join(authors
[1:conf
['authors_top']+1])
797 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
)))
801 f
.write(html_header(2, 'Author of Year'))
802 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'])
803 for yy
in reversed(sorted(data
.author_of_year
.keys())):
804 authordict
= data
.author_of_year
[yy
]
805 authors
= getkeyssortedbyvalues(authordict
)
807 commits
= data
.author_of_year
[yy
][authors
[0]]
808 next
= ', '.join(authors
[1:conf
['authors_top']+1])
809 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
)))
813 f
.write(html_header(2, 'Commits by Domains'))
814 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
815 domains_by_commits
.reverse() # most first
816 f
.write('<div class="vtable"><table>')
817 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
818 fp
= open(path
+ '/domains.dat', 'w')
820 for domain
in domains_by_commits
:
821 if n
== conf
['max_domains']:
825 info
= data
.getDomainInfo(domain
)
826 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
827 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
828 f
.write('</table></div>')
829 f
.write('<img src="domains.png" alt="Commits by Domains" />')
832 f
.write('</body></html>')
837 f
= open(path
+ '/files.html', 'w')
839 f
.write('<h1>Files</h1>')
843 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
844 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
845 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data
.getTotalLOC()) / data
.getTotalFiles()))
848 # Files :: File count by date
849 f
.write(html_header(2, 'File count by date'))
851 # use set to get rid of duplicate/unnecessary entries
852 files_by_date
= set()
853 for stamp
in sorted(data
.files_by_stamp
.keys()):
854 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
856 fg
= open(path
+ '/files_by_date.dat', 'w')
857 for line
in sorted(list(files_by_date
)):
858 fg
.write('%s\n' % line
)
859 #for stamp in sorted(data.files_by_stamp.keys()):
860 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
863 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
865 #f.write('<h2>Average file size by date</h2>')
867 # Files :: Extensions
868 f
.write(html_header(2, 'Extensions'))
869 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
870 for ext
in sorted(data
.extensions
.keys()):
871 files
= data
.extensions
[ext
]['files']
872 lines
= data
.extensions
[ext
]['lines']
873 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
))
876 f
.write('</body></html>')
881 f
= open(path
+ '/lines.html', 'w')
883 f
.write('<h1>Lines</h1>')
887 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
890 f
.write(html_header(2, 'Lines of Code'))
891 f
.write('<img src="lines_of_code.png" />')
893 fg
= open(path
+ '/lines_of_code.dat', 'w')
894 for stamp
in sorted(data
.changes_by_date
.keys()):
895 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
898 f
.write('</body></html>')
903 f
= open(path
+ '/tags.html', 'w')
905 f
.write('<h1>Tags</h1>')
909 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
910 if len(data
.tags
) > 0:
911 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
914 f
.write('<table class="tags">')
915 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
916 # sort the tags by date desc
917 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
918 for tag
in tags_sorted_by_date_desc
:
920 authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
921 for i
in reversed(authors_by_commits
):
922 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
923 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
)))
926 f
.write('</body></html>')
929 self
.createGraphs(path
)
931 def createGraphs(self
, path
):
932 print 'Generating graphs...'
935 f
= open(path
+ '/hour_of_day.plot', 'w')
936 f
.write(GNUPLOT_COMMON
)
939 set output 'hour_of_day.png'
941 set xrange [0.5:24.5]
945 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
950 f
= open(path
+ '/day_of_week.plot', 'w')
951 f
.write(GNUPLOT_COMMON
)
954 set output 'day_of_week.png'
960 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
965 f
= open(path
+ '/domains.plot', 'w')
966 f
.write(GNUPLOT_COMMON
)
969 set output 'domains.png'
974 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
979 f
= open(path
+ '/month_of_year.plot', 'w')
980 f
.write(GNUPLOT_COMMON
)
983 set output 'month_of_year.png'
985 set xrange [0.5:12.5]
989 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
993 # commits_by_year_month
994 f
= open(path
+ '/commits_by_year_month.plot', 'w')
995 f
.write(GNUPLOT_COMMON
)
998 set output 'commits_by_year_month.png'
1002 set format x "%Y-%m"
1003 set xtics rotate by 90 15768000
1006 set ylabel "Commits"
1007 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1012 f
= open(path
+ '/commits_by_year.plot', 'w')
1013 f
.write(GNUPLOT_COMMON
)
1016 set output 'commits_by_year.png'
1018 set xtics 1 rotate by 90
1020 set ylabel "Commits"
1022 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1027 f
= open(path
+ '/files_by_date.plot', 'w')
1028 f
.write(GNUPLOT_COMMON
)
1031 set output 'files_by_date.png'
1034 set timefmt "%Y-%m-%d"
1035 set format x "%Y-%m-%d"
1038 set xtics rotate by 90
1041 plot 'files_by_date.dat' using 1:2 w steps
1046 f
= open(path
+ '/lines_of_code.plot', 'w')
1047 f
.write(GNUPLOT_COMMON
)
1050 set output 'lines_of_code.png'
1054 set format x "%Y-%m-%d"
1057 set xtics rotate by 90
1059 plot 'lines_of_code.dat' using 1:2 w lines
1064 files
= glob
.glob(path
+ '/*.plot')
1066 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1070 def printHeader(self
, f
, title
= ''):
1072 """<?xml version="1.0" encoding="UTF-8"?>
1073 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1074 <html xmlns="http://www.w3.org/1999/xhtml">
1076 <title>GitStats - %s</title>
1077 <link rel="stylesheet" href="%s" type="text/css" />
1078 <meta name="generator" content="GitStats %s" />
1079 <script type="text/javascript" src="sortable.js"></script>
1082 """ % (self
.title
, conf
['style'], getversion()))
1084 def printNav(self
, f
):
1088 <li><a href="index.html">General</a></li>
1089 <li><a href="activity.html">Activity</a></li>
1090 <li><a href="authors.html">Authors</a></li>
1091 <li><a href="files.html">Files</a></li>
1092 <li><a href="lines.html">Lines</a></li>
1093 <li><a href="tags.html">Tags</a></li>
1100 def run(self
, args_orig
):
1101 optlist
, args
= getopt
.getopt(args_orig
, 'c:')
1104 key
, value
= v
.split('=', 1)
1106 raise 'Error: no such key "%s" in config' % key
1107 if isinstance(conf
[key
], int):
1108 conf
[key
] = int(value
)
1114 Usage: gitstats [options] <gitpath> <outputpath>
1117 -c key=value Override configuration value
1119 Default config values:
1125 outputpath
= os
.path
.abspath(args
[1])
1126 rundir
= os
.getcwd()
1129 os
.makedirs(outputpath
)
1132 if not os
.path
.isdir(outputpath
):
1133 print 'FATAL: Output path is not a directory or does not exist'
1136 print 'Git path: %s' % gitpath
1137 print 'Output path: %s' % outputpath
1141 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1143 print 'Collecting data...'
1144 data
= GitDataCollector()
1145 data
.loadCache(cachefile
)
1146 data
.collect(gitpath
)
1147 print 'Refining data...'
1148 data
.saveCache(cachefile
)
1153 print 'Generating report...'
1154 report
= HTMLReportCreator()
1155 report
.create(data
, outputpath
)
1157 time_end
= time
.time()
1158 exectime_internal
= time_end
- time_start
1159 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)