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> <date> <time> <timezone> <author> '<' <mail> '>'"
231 lines
= getpipeoutput(['git rev-list --pretty=format:"%at %ai %an <%aE>" HEAD', 'grep -v ^commit']).split('\n')
233 parts
= line
.split(' ', 4)
236 stamp
= int(parts
[0])
240 author
, mail
= parts
[4].split('<', 1)
241 author
= author
.rstrip()
242 mail
= mail
.rstrip('>')
243 domain
= mail
.rsplit('@', 1)[1]
244 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
246 # First and last commit stamp
247 if self
.last_commit_stamp
== 0:
248 self
.last_commit_stamp
= stamp
249 self
.first_commit_stamp
= stamp
254 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
256 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
257 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
261 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
264 if domain
not in self
.domains
:
265 self
.domains
[domain
] = {}
267 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
270 if day
not in self
.activity_by_hour_of_week
:
271 self
.activity_by_hour_of_week
[day
] = {}
272 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
274 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
275 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
279 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
281 # yearly/weekly activity
282 yyw
= date
.strftime('%Y-%W')
283 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
284 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
285 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
288 if author
not in self
.authors
:
289 self
.authors
[author
] = {}
291 if 'last_commit_stamp' not in self
.authors
[author
]:
292 self
.authors
[author
]['last_commit_stamp'] = stamp
293 self
.authors
[author
]['first_commit_stamp'] = stamp
294 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
296 # author of the month/year
297 yymm
= date
.strftime('%Y-%m')
298 if yymm
in self
.author_of_month
:
299 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
301 self
.author_of_month
[yymm
] = {}
302 self
.author_of_month
[yymm
][author
] = 1
303 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
306 if yy
in self
.author_of_year
:
307 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
309 self
.author_of_year
[yy
] = {}
310 self
.author_of_year
[yy
][author
] = 1
311 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
313 # authors: active days
314 yymmdd
= date
.strftime('%Y-%m-%d')
315 if 'last_active_day' not in self
.authors
[author
]:
316 self
.authors
[author
]['last_active_day'] = yymmdd
317 self
.authors
[author
]['active_days'] = 1
318 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
319 self
.authors
[author
]['last_active_day'] = yymmdd
320 self
.authors
[author
]['active_days'] += 1
322 # project: active days
323 if yymmdd
!= self
.last_active_day
:
324 self
.last_active_day
= yymmdd
325 self
.active_days
.add(yymmdd
)
328 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
330 # TODO Optimize this, it's the worst bottleneck
331 # outputs "<stamp> <files>" for each revision
332 self
.files_by_stamp
= {} # stamp -> files
333 revlines
= getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
335 for revline
in revlines
:
336 time
, rev
= revline
.split(' ')
337 linecount
= self
.getFilesInCommit(rev
)
338 lines
.append('%d %d' % (int(time
), linecount
))
340 self
.total_commits
= len(lines
)
342 parts
= line
.split(' ')
345 (stamp
, files
) = parts
[0:2]
347 self
.files_by_stamp
[int(stamp
)] = int(files
)
349 print 'Warning: failed to parse line "%s"' % line
352 self
.extensions
= {} # extension -> files, lines
353 lines
= getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
354 self
.total_files
= len(lines
)
358 parts
= re
.split('\s+', line
, 4)
362 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
365 ext
= filename
[(filename
.rfind('.') + 1):]
366 if len(ext
) > MAX_EXT_LENGTH
:
369 if ext
not in self
.extensions
:
370 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
372 self
.extensions
[ext
]['files'] += 1
374 self
.extensions
[ext
]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1
, 'wc -l']).split()[0])
376 print 'Warning: Could not count lines for file "%s"' % line
380 # N files changed, N insertions (+), N deletions(-)
382 self
.changes_by_date
= {} # stamp -> { files, ins, del }
383 lines
= getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
385 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
392 if line
.find('files changed,') == -1:
396 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
397 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
398 if author
not in self
.authors
:
399 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0 }
400 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
401 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
403 print 'Warning: unexpected line "%s"' % line
405 print 'Warning: unexpected line "%s"' % line
407 numbers
= re
.findall('\d+', line
)
408 if len(numbers
) == 3:
409 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
410 total_lines
+= inserted
411 total_lines
-= deleted
412 self
.total_lines_added
+= inserted
413 self
.total_lines_removed
+= deleted
415 print 'Warning: failed to handle line "%s"' % line
416 (files
, inserted
, deleted
) = (0, 0, 0)
417 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
418 self
.total_lines
= total_lines
422 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
423 authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
424 authors_by_commits
.reverse() # most first
425 for i
, name
in enumerate(authors_by_commits
):
426 self
.authors
[name
]['place_by_commits'] = i
+ 1
428 for name
in self
.authors
.keys():
429 a
= self
.authors
[name
]
430 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
431 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
432 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
433 delta
= date_last
- date_first
434 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
435 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
436 a
['timedelta'] = delta
438 def getActiveDays(self
):
439 return self
.active_days
441 def getActivityByDayOfWeek(self
):
442 return self
.activity_by_day_of_week
444 def getActivityByHourOfDay(self
):
445 return self
.activity_by_hour_of_day
447 def getAuthorInfo(self
, author
):
448 return self
.authors
[author
]
450 def getAuthors(self
):
451 return self
.authors
.keys()
453 def getCommitDeltaDays(self
):
454 return (self
.last_commit_stamp
- self
.first_commit_stamp
) / 86400
456 def getDomainInfo(self
, domain
):
457 return self
.domains
[domain
]
459 def getDomains(self
):
460 return self
.domains
.keys()
462 def getFilesInCommit(self
, rev
):
464 res
= self
.cache
['files_in_tree'][rev
]
466 res
= int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0])
467 if 'files_in_tree' not in self
.cache
:
468 self
.cache
['files_in_tree'] = {}
469 self
.cache
['files_in_tree'][rev
] = res
473 def getFirstCommitDate(self
):
474 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
476 def getLastCommitDate(self
):
477 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
480 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
481 return lines
.split('\n')
483 def getTagDate(self
, tag
):
484 return self
.revToDate('tags/' + tag
)
486 def getTotalAuthors(self
):
487 return self
.total_authors
489 def getTotalCommits(self
):
490 return self
.total_commits
492 def getTotalFiles(self
):
493 return self
.total_files
495 def getTotalLOC(self
):
496 return self
.total_lines
498 def revToDate(self
, rev
):
499 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
500 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
503 """Creates the actual report based on given data."""
507 def create(self
, data
, path
):
511 def html_linkify(text
):
512 return text
.lower().replace(' ', '_')
514 def html_header(level
, text
):
515 name
= html_linkify(text
)
516 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
518 class HTMLReportCreator(ReportCreator
):
519 def create(self
, data
, path
):
520 ReportCreator
.create(self
, data
, path
)
521 self
.title
= data
.projectname
523 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
524 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
525 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
526 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
527 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
528 for base
in basedirs
:
529 src
= base
+ '/' + file
530 if os
.path
.exists(src
):
531 shutil
.copyfile(src
, path
+ '/' + file)
534 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
536 f
= open(path
+ "/index.html", 'w')
537 format
= '%Y-%m-%d %H:%M:%S'
540 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
545 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
546 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
547 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
548 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
549 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())))
550 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
551 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
))
552 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()))
553 f
.write('<dt>Authors</dt><dd>%s</dd>' % data
.getTotalAuthors())
556 f
.write('</body>\n</html>')
561 f
= open(path
+ '/activity.html', 'w')
563 f
.write('<h1>Activity</h1>')
566 #f.write('<h2>Last 30 days</h2>')
568 #f.write('<h2>Last 12 months</h2>')
572 f
.write(html_header(2, 'Weekly activity'))
573 f
.write('<p>Last %d weeks</p>' % WEEKS
)
575 # generate weeks to show (previous N weeks from now)
576 now
= datetime
.datetime
.now()
577 deltaweek
= datetime
.timedelta(7)
580 for i
in range(0, WEEKS
):
581 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
582 stampcur
-= deltaweek
584 # top row: commits & bar
585 f
.write('<table class="noborders"><tr>')
586 for i
in range(0, WEEKS
):
588 if weeks
[i
] in data
.activity_by_year_week
:
589 commits
= data
.activity_by_year_week
[weeks
[i
]]
592 if weeks
[i
] in data
.activity_by_year_week
:
593 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
594 height
= max(1, int(200 * percentage
))
595 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
))
597 # bottom row: year/week
599 for i
in range(0, WEEKS
):
600 f
.write('<td>%s</td>' % (WEEKS
- i
))
601 f
.write('</tr></table>')
604 f
.write(html_header(2, 'Hour of Day'))
605 hour_of_day
= data
.getActivityByHourOfDay()
606 f
.write('<table><tr><th>Hour</th>')
607 for i
in range(0, 24):
608 f
.write('<th>%d</th>' % i
)
609 f
.write('</tr>\n<tr><th>Commits</th>')
610 fp
= open(path
+ '/hour_of_day.dat', 'w')
611 for i
in range(0, 24):
613 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
614 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
615 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
617 f
.write('<td>0</td>')
618 fp
.write('%d 0\n' % i
)
620 f
.write('</tr>\n<tr><th>%</th>')
621 totalcommits
= data
.getTotalCommits()
622 for i
in range(0, 24):
624 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
625 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
627 f
.write('<td>0.00</td>')
628 f
.write('</tr></table>')
629 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
630 fg
= open(path
+ '/hour_of_day.dat', 'w')
631 for i
in range(0, 24):
633 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
635 fg
.write('%d 0\n' % (i
+ 1))
639 f
.write(html_header(2, 'Day of Week'))
640 day_of_week
= data
.getActivityByDayOfWeek()
641 f
.write('<div class="vtable"><table>')
642 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
643 fp
= open(path
+ '/day_of_week.dat', 'w')
644 for d
in range(0, 7):
647 commits
= day_of_week
[d
]
648 fp
.write('%d %d\n' % (d
+ 1, commits
))
650 f
.write('<th>%d</th>' % (d
+ 1))
652 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
654 f
.write('<td>0</td>')
656 f
.write('</table></div>')
657 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
661 f
.write(html_header(2, 'Hour of Week'))
664 f
.write('<tr><th>Weekday</th>')
665 for hour
in range(0, 24):
666 f
.write('<th>%d</th>' % (hour
))
669 for weekday
in range(0, 7):
670 f
.write('<tr><th>%d</th>' % (weekday
+ 1))
671 for hour
in range(0, 24):
673 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
678 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
679 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
680 f
.write('>%d</td>' % commits
)
688 f
.write(html_header(2, 'Month of Year'))
689 f
.write('<div class="vtable"><table>')
690 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
691 fp
= open (path
+ '/month_of_year.dat', 'w')
692 for mm
in range(1, 13):
694 if mm
in data
.activity_by_month_of_year
:
695 commits
= data
.activity_by_month_of_year
[mm
]
696 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
697 fp
.write('%d %d\n' % (mm
, commits
))
699 f
.write('</table></div>')
700 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
702 # Commits by year/month
703 f
.write(html_header(2, 'Commits by year/month'))
704 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
705 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
706 f
.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
[yymm
]))
707 f
.write('</table></div>')
708 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
709 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
710 for yymm
in sorted(data
.commits_by_month
.keys()):
711 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
715 f
.write(html_header(2, 'Commits by Year'))
716 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
717 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
718 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()))
719 f
.write('</table></div>')
720 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
721 fg
= open(path
+ '/commits_by_year.dat', 'w')
722 for yy
in sorted(data
.commits_by_year
.keys()):
723 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
726 # Commits by timezone
727 f
.write(html_header(2, 'Commits by Timezone'))
728 f
.write('<table><tr>')
729 f
.write('<th>Timezone</th><th>Commits</th>')
730 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
731 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
732 commits
= data
.commits_by_timezone
[i
]
733 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
734 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
735 f
.write('</tr></table>')
737 f
.write('</body></html>')
742 f
= open(path
+ '/authors.html', 'w')
745 f
.write('<h1>Authors</h1>')
748 # Authors :: List of authors
749 f
.write(html_header(2, 'List of Authors'))
751 f
.write('<table class="authors sortable" id="authors">')
752 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>')
753 for author
in sorted(data
.getAuthors()):
754 info
= data
.getAuthorInfo(author
)
755 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']))
758 # Authors :: Author of Month
759 f
.write(html_header(2, 'Author of Month'))
760 f
.write('<table class="sortable" id="aom">')
761 f
.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
762 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
763 authordict
= data
.author_of_month
[yymm
]
764 authors
= getkeyssortedbyvalues(authordict
)
766 commits
= data
.author_of_month
[yymm
][authors
[0]]
767 next
= ', '.join(authors
[1:5])
768 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
))
772 f
.write(html_header(2, 'Author of Year'))
773 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>')
774 for yy
in reversed(sorted(data
.author_of_year
.keys())):
775 authordict
= data
.author_of_year
[yy
]
776 authors
= getkeyssortedbyvalues(authordict
)
778 commits
= data
.author_of_year
[yy
][authors
[0]]
779 next
= ', '.join(authors
[1:5])
780 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
))
784 f
.write(html_header(2, 'Commits by Domains'))
785 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
786 domains_by_commits
.reverse() # most first
787 f
.write('<div class="vtable"><table>')
788 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
789 fp
= open(path
+ '/domains.dat', 'w')
792 for domain
in domains_by_commits
:
797 info
= data
.getDomainInfo(domain
)
798 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
799 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
800 f
.write('</table></div>')
801 f
.write('<img src="domains.png" alt="Commits by Domains" />')
804 f
.write('</body></html>')
809 f
= open(path
+ '/files.html', 'w')
811 f
.write('<h1>Files</h1>')
815 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
816 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
817 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data
.getTotalLOC()) / data
.getTotalFiles()))
820 # Files :: File count by date
821 f
.write(html_header(2, 'File count by date'))
823 # use set to get rid of duplicate/unnecessary entries
824 files_by_date
= set()
825 for stamp
in sorted(data
.files_by_stamp
.keys()):
826 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
828 fg
= open(path
+ '/files_by_date.dat', 'w')
829 for line
in sorted(list(files_by_date
)):
830 fg
.write('%s\n' % line
)
831 #for stamp in sorted(data.files_by_stamp.keys()):
832 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
835 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
837 #f.write('<h2>Average file size by date</h2>')
839 # Files :: Extensions
840 f
.write(html_header(2, 'Extensions'))
841 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
842 for ext
in sorted(data
.extensions
.keys()):
843 files
= data
.extensions
[ext
]['files']
844 lines
= data
.extensions
[ext
]['lines']
845 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
))
848 f
.write('</body></html>')
853 f
= open(path
+ '/lines.html', 'w')
855 f
.write('<h1>Lines</h1>')
859 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
862 f
.write(html_header(2, 'Lines of Code'))
863 f
.write('<img src="lines_of_code.png" />')
865 fg
= open(path
+ '/lines_of_code.dat', 'w')
866 for stamp
in sorted(data
.changes_by_date
.keys()):
867 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
870 f
.write('</body></html>')
875 f
= open(path
+ '/tags.html', 'w')
877 f
.write('<h1>Tags</h1>')
881 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
882 if len(data
.tags
) > 0:
883 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
886 f
.write('<table class="tags">')
887 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
888 # sort the tags by date desc
889 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
890 for tag
in tags_sorted_by_date_desc
:
892 authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
893 for i
in reversed(authors_by_commits
):
894 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
895 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
)))
898 f
.write('</body></html>')
901 self
.createGraphs(path
)
903 def createGraphs(self
, path
):
904 print 'Generating graphs...'
907 f
= open(path
+ '/hour_of_day.plot', 'w')
908 f
.write(GNUPLOT_COMMON
)
911 set output 'hour_of_day.png'
913 set xrange [0.5:24.5]
916 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
921 f
= open(path
+ '/day_of_week.plot', 'w')
922 f
.write(GNUPLOT_COMMON
)
925 set output 'day_of_week.png'
930 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
935 f
= open(path
+ '/domains.plot', 'w')
936 f
.write(GNUPLOT_COMMON
)
939 set output 'domains.png'
944 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
949 f
= open(path
+ '/month_of_year.plot', 'w')
950 f
.write(GNUPLOT_COMMON
)
953 set output 'month_of_year.png'
955 set xrange [0.5:12.5]
958 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
962 # commits_by_year_month
963 f
= open(path
+ '/commits_by_year_month.plot', 'w')
964 f
.write(GNUPLOT_COMMON
)
967 set output 'commits_by_year_month.png'
972 set xtics rotate by 90 15768000
975 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
980 f
= open(path
+ '/commits_by_year.plot', 'w')
981 f
.write(GNUPLOT_COMMON
)
984 set output 'commits_by_year.png'
989 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
994 f
= open(path
+ '/files_by_date.plot', 'w')
995 f
.write(GNUPLOT_COMMON
)
998 set output 'files_by_date.png'
1001 set timefmt "%Y-%m-%d"
1002 set format x "%Y-%m-%d"
1004 set xtics rotate by 90
1007 plot 'files_by_date.dat' using 1:2 w steps
1012 f
= open(path
+ '/lines_of_code.plot', 'w')
1013 f
.write(GNUPLOT_COMMON
)
1016 set output 'lines_of_code.png'
1020 set format x "%Y-%m-%d"
1022 set xtics rotate by 90
1024 plot 'lines_of_code.dat' using 1:2 w lines
1029 files
= glob
.glob(path
+ '/*.plot')
1031 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1035 def printHeader(self
, f
, title
= ''):
1037 """<?xml version="1.0" encoding="UTF-8"?>
1038 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1039 <html xmlns="http://www.w3.org/1999/xhtml">
1041 <title>GitStats - %s</title>
1042 <link rel="stylesheet" href="gitstats.css" type="text/css" />
1043 <meta name="generator" content="GitStats %s" />
1044 <script type="text/javascript" src="sortable.js"></script>
1047 """ % (self
.title
, getversion()))
1049 def printNav(self
, f
):
1053 <li><a href="index.html">General</a></li>
1054 <li><a href="activity.html">Activity</a></li>
1055 <li><a href="authors.html">Authors</a></li>
1056 <li><a href="files.html">Files</a></li>
1057 <li><a href="lines.html">Lines</a></li>
1058 <li><a href="tags.html">Tags</a></li>
1065 Usage: gitstats [options] <gitpath> <outputpath>
1070 if len(sys
.argv
) < 3:
1074 gitpath
= sys
.argv
[1]
1075 outputpath
= os
.path
.abspath(sys
.argv
[2])
1076 rundir
= os
.getcwd()
1079 os
.makedirs(outputpath
)
1082 if not os
.path
.isdir(outputpath
):
1083 print 'FATAL: Output path is not a directory or does not exist'
1086 print 'Git path: %s' % gitpath
1087 print 'Output path: %s' % outputpath
1091 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1093 print 'Collecting data...'
1094 data
= GitDataCollector()
1095 data
.loadCache(cachefile
)
1096 data
.collect(gitpath
)
1097 print 'Refining data...'
1098 data
.saveCache(cachefile
)
1103 print 'Generating report...'
1104 report
= HTMLReportCreator()
1105 report
.create(data
, outputpath
)
1107 time_end
= time
.time()
1108 exectime_internal
= time_end
- time_start
1109 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)