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
):
108 # Get a list of authors
109 def getAuthors(self
):
112 def getFirstCommitDate(self
):
113 return datetime
.datetime
.now()
115 def getLastCommitDate(self
):
116 return datetime
.datetime
.now()
118 def getStampCreated(self
):
119 return self
.stamp_created
124 def getTotalAuthors(self
):
127 def getTotalCommits(self
):
130 def getTotalFiles(self
):
133 def getTotalLOC(self
):
137 # Save cacheable data
138 def saveCache(self
, filename
):
139 print 'Saving cache...'
140 f
= open(cachefile
, 'w')
141 #pickle.dump(self.cache, f)
142 data
= zlib
.compress(pickle
.dumps(self
.cache
))
146 class GitDataCollector(DataCollector
):
147 def collect(self
, dir):
148 DataCollector
.collect(self
, dir)
151 self
.total_authors
= int(getpipeoutput(['git log', 'git shortlog -s', 'wc -l']))
153 self
.total_authors
= 0
154 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
156 self
.activity_by_hour_of_day
= {} # hour -> commits
157 self
.activity_by_day_of_week
= {} # day -> commits
158 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
159 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
160 self
.activity_by_hour_of_day_busiest
= 0
161 self
.activity_by_hour_of_week_busiest
= 0
162 self
.activity_by_year_week
= {} # yy_wNN -> commits
163 self
.activity_by_year_week_peak
= 0
165 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days}
167 # author of the month
168 self
.author_of_month
= {} # month -> author -> commits
169 self
.author_of_year
= {} # year -> author -> commits
170 self
.commits_by_month
= {} # month -> commits
171 self
.commits_by_year
= {} # year -> commits
172 self
.first_commit_stamp
= 0
173 self
.last_commit_stamp
= 0
174 self
.last_active_day
= None
178 self
.commits_by_timezone
= {} # timezone -> commits
182 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
186 (hash, tag
) = line
.split(' ')
188 tag
= tag
.replace('refs/tags/', '')
189 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%an" -n 1' % hash])
191 parts
= output
.split(' ')
194 stamp
= int(parts
[0])
197 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
199 # collect info on tags, starting from latest
200 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
202 for tag
in reversed(tags_sorted_by_date_desc
):
203 cmd
= 'git shortlog -s "%s"' % tag
205 cmd
+= ' "^%s"' % prev
206 output
= getpipeoutput([cmd
])
210 for line
in output
.split('\n'):
211 parts
= re
.split('\s+', line
, 2)
212 commits
= int(parts
[1])
214 self
.tags
[tag
]['commits'] += commits
215 self
.tags
[tag
]['authors'][author
] = commits
217 # Collect revision statistics
218 # Outputs "<stamp> <author>"
219 lines
= getpipeoutput(['git rev-list --pretty=format:"%at %ai %an" HEAD', 'grep -v ^commit']).split('\n')
221 # linux-2.6 says "<unknown>" for one line O_o
222 parts
= line
.split(' ')
225 stamp
= int(parts
[0])
230 author
= ' '.join(parts
[4:])
231 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
233 # First and last commit stamp
234 if self
.last_commit_stamp
== 0:
235 self
.last_commit_stamp
= stamp
236 self
.first_commit_stamp
= stamp
241 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
243 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
244 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
248 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
251 if day
not in self
.activity_by_hour_of_week
:
252 self
.activity_by_hour_of_week
[day
] = {}
253 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
255 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
256 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
260 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
262 # yearly/weekly activity
263 yyw
= date
.strftime('%Y-%W')
264 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
265 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
266 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
269 if author
not in self
.authors
:
270 self
.authors
[author
] = {}
272 if 'last_commit_stamp' not in self
.authors
[author
]:
273 self
.authors
[author
]['last_commit_stamp'] = stamp
274 self
.authors
[author
]['first_commit_stamp'] = stamp
275 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
277 # author of the month/year
278 yymm
= date
.strftime('%Y-%m')
279 if yymm
in self
.author_of_month
:
280 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
282 self
.author_of_month
[yymm
] = {}
283 self
.author_of_month
[yymm
][author
] = 1
284 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
287 if yy
in self
.author_of_year
:
288 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
290 self
.author_of_year
[yy
] = {}
291 self
.author_of_year
[yy
][author
] = 1
292 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
294 # authors: active days
295 yymmdd
= date
.strftime('%Y-%m-%d')
296 if 'last_active_day' not in self
.authors
[author
]:
297 self
.authors
[author
]['last_active_day'] = yymmdd
298 self
.authors
[author
]['active_days'] = 1
299 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
300 self
.authors
[author
]['last_active_day'] = yymmdd
301 self
.authors
[author
]['active_days'] += 1
303 # project: active days
304 if yymmdd
!= self
.last_active_day
:
305 self
.last_active_day
= yymmdd
306 self
.active_days
+= 1
309 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
311 # TODO Optimize this, it's the worst bottleneck
312 # outputs "<stamp> <files>" for each revision
313 self
.files_by_stamp
= {} # stamp -> files
314 revlines
= getpipeoutput(['git rev-list --pretty=format:"%at %T" HEAD', 'grep -v ^commit']).strip().split('\n')
316 for revline
in revlines
:
317 time
, rev
= revline
.split(' ')
318 linecount
= self
.getFilesInCommit(rev
)
319 lines
.append('%d %d' % (int(time
), linecount
))
321 self
.total_commits
= len(lines
)
323 parts
= line
.split(' ')
326 (stamp
, files
) = parts
[0:2]
328 self
.files_by_stamp
[int(stamp
)] = int(files
)
330 print 'Warning: failed to parse line "%s"' % line
333 self
.extensions
= {} # extension -> files, lines
334 lines
= getpipeoutput(['git ls-tree -r -z HEAD']).split('\000')
335 self
.total_files
= len(lines
)
339 parts
= re
.split('\s+', line
, 4)
343 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
346 ext
= filename
[(filename
.rfind('.') + 1):]
347 if len(ext
) > MAX_EXT_LENGTH
:
350 if ext
not in self
.extensions
:
351 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
353 self
.extensions
[ext
]['files'] += 1
355 self
.extensions
[ext
]['lines'] += int(getpipeoutput(['git cat-file blob %s' % sha1
, 'wc -l']).split()[0])
357 print 'Warning: Could not count lines for file "%s"' % line
361 # N files changed, N insertions (+), N deletions(-)
363 self
.changes_by_date
= {} # stamp -> { files, ins, del }
364 lines
= getpipeoutput(['git log --shortstat --pretty=format:"%at %an"']).split('\n')
366 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
372 if line
.find('files changed,') == -1:
376 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
377 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
379 print 'Warning: unexpected line "%s"' % line
381 print 'Warning: unexpected line "%s"' % line
383 numbers
= re
.findall('\d+', line
)
384 if len(numbers
) == 3:
385 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
386 total_lines
+= inserted
387 total_lines
-= deleted
389 print 'Warning: failed to handle line "%s"' % line
390 (files
, inserted
, deleted
) = (0, 0, 0)
391 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
392 self
.total_lines
= total_lines
396 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
397 authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
398 authors_by_commits
.reverse() # most first
399 for i
, name
in enumerate(authors_by_commits
):
400 self
.authors
[name
]['place_by_commits'] = i
+ 1
402 for name
in self
.authors
.keys():
403 a
= self
.authors
[name
]
404 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
405 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
406 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
407 delta
= date_last
- date_first
408 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
409 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
410 a
['timedelta'] = delta
412 def getActiveDays(self
):
413 return self
.active_days
415 def getActivityByDayOfWeek(self
):
416 return self
.activity_by_day_of_week
418 def getActivityByHourOfDay(self
):
419 return self
.activity_by_hour_of_day
421 def getAuthorInfo(self
, author
):
422 return self
.authors
[author
]
424 def getAuthors(self
):
425 return self
.authors
.keys()
427 def getCommitDeltaDays(self
):
428 return (self
.last_commit_stamp
- self
.first_commit_stamp
) / 86400
430 def getFilesInCommit(self
, rev
):
432 res
= self
.cache
['files_in_tree'][rev
]
434 res
= int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0])
435 if 'files_in_tree' not in self
.cache
:
436 self
.cache
['files_in_tree'] = {}
437 self
.cache
['files_in_tree'][rev
] = res
441 def getFirstCommitDate(self
):
442 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
444 def getLastCommitDate(self
):
445 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
448 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
449 return lines
.split('\n')
451 def getTagDate(self
, tag
):
452 return self
.revToDate('tags/' + tag
)
454 def getTotalAuthors(self
):
455 return self
.total_authors
457 def getTotalCommits(self
):
458 return self
.total_commits
460 def getTotalFiles(self
):
461 return self
.total_files
463 def getTotalLOC(self
):
464 return self
.total_lines
466 def revToDate(self
, rev
):
467 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
468 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
471 """Creates the actual report based on given data."""
475 def create(self
, data
, path
):
479 def html_linkify(text
):
480 return text
.lower().replace(' ', '_')
482 def html_header(level
, text
):
483 name
= html_linkify(text
)
484 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
486 class HTMLReportCreator(ReportCreator
):
487 def create(self
, data
, path
):
488 ReportCreator
.create(self
, data
, path
)
489 self
.title
= data
.projectname
491 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
492 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
493 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
494 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
495 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
496 for base
in basedirs
:
497 src
= base
+ '/' + file
498 if os
.path
.exists(src
):
499 shutil
.copyfile(src
, path
+ '/' + file)
502 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
504 f
= open(path
+ "/index.html", 'w')
505 format
= '%Y-%m-%d %H:%M:%S'
508 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
513 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
514 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
515 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s)</dd>' % getversion())
516 f
.write('<dt>Report Period</dt><dd>%s to %s (%d days, %d active days)</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
), data
.getCommitDeltaDays(), data
.getActiveDays()))
517 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
518 f
.write('<dt>Total Lines of Code</dt><dd>%s</dd>' % data
.getTotalLOC())
519 f
.write('<dt>Total Commits</dt><dd>%s</dd>' % data
.getTotalCommits())
520 f
.write('<dt>Authors</dt><dd>%s</dd>' % data
.getTotalAuthors())
523 f
.write('</body>\n</html>')
528 f
= open(path
+ '/activity.html', 'w')
530 f
.write('<h1>Activity</h1>')
533 #f.write('<h2>Last 30 days</h2>')
535 #f.write('<h2>Last 12 months</h2>')
539 f
.write(html_header(2, 'Weekly activity'))
540 f
.write('<p>Last %d weeks</p>' % WEEKS
)
542 # generate weeks to show (previous N weeks from now)
543 now
= datetime
.datetime
.now()
544 deltaweek
= datetime
.timedelta(7)
547 for i
in range(0, WEEKS
):
548 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
549 stampcur
-= deltaweek
551 # top row: commits & bar
552 f
.write('<table class="noborders"><tr>')
553 for i
in range(0, WEEKS
):
555 if weeks
[i
] in data
.activity_by_year_week
:
556 commits
= data
.activity_by_year_week
[weeks
[i
]]
559 if weeks
[i
] in data
.activity_by_year_week
:
560 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
561 height
= max(1, int(200 * percentage
))
562 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
))
564 # bottom row: year/week
566 for i
in range(0, WEEKS
):
567 f
.write('<td>%s</td>' % (WEEKS
- i
))
568 f
.write('</tr></table>')
571 f
.write(html_header(2, 'Hour of Day'))
572 hour_of_day
= data
.getActivityByHourOfDay()
573 f
.write('<table><tr><th>Hour</th>')
574 for i
in range(0, 24):
575 f
.write('<th>%d</th>' % i
)
576 f
.write('</tr>\n<tr><th>Commits</th>')
577 fp
= open(path
+ '/hour_of_day.dat', 'w')
578 for i
in range(0, 24):
580 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
581 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
582 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
584 f
.write('<td>0</td>')
585 fp
.write('%d 0\n' % i
)
587 f
.write('</tr>\n<tr><th>%</th>')
588 totalcommits
= data
.getTotalCommits()
589 for i
in range(0, 24):
591 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
592 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
594 f
.write('<td>0.00</td>')
595 f
.write('</tr></table>')
596 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
597 fg
= open(path
+ '/hour_of_day.dat', 'w')
598 for i
in range(0, 24):
600 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
602 fg
.write('%d 0\n' % (i
+ 1))
606 f
.write(html_header(2, 'Day of Week'))
607 day_of_week
= data
.getActivityByDayOfWeek()
608 f
.write('<div class="vtable"><table>')
609 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
610 fp
= open(path
+ '/day_of_week.dat', 'w')
611 for d
in range(0, 7):
614 commits
= day_of_week
[d
]
615 fp
.write('%d %d\n' % (d
+ 1, commits
))
617 f
.write('<th>%d</th>' % (d
+ 1))
619 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
621 f
.write('<td>0</td>')
623 f
.write('</table></div>')
624 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
628 f
.write(html_header(2, 'Hour of Week'))
631 f
.write('<tr><th>Weekday</th>')
632 for hour
in range(0, 24):
633 f
.write('<th>%d</th>' % (hour
))
636 for weekday
in range(0, 7):
637 f
.write('<tr><th>%d</th>' % (weekday
+ 1))
638 for hour
in range(0, 24):
640 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
645 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
646 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
647 f
.write('>%d</td>' % commits
)
655 f
.write(html_header(2, 'Month of Year'))
656 f
.write('<div class="vtable"><table>')
657 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
658 fp
= open (path
+ '/month_of_year.dat', 'w')
659 for mm
in range(1, 13):
661 if mm
in data
.activity_by_month_of_year
:
662 commits
= data
.activity_by_month_of_year
[mm
]
663 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
664 fp
.write('%d %d\n' % (mm
, commits
))
666 f
.write('</table></div>')
667 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
669 # Commits by year/month
670 f
.write(html_header(2, 'Commits by year/month'))
671 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th></tr>')
672 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
673 f
.write('<tr><td>%s</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
[yymm
]))
674 f
.write('</table></div>')
675 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
676 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
677 for yymm
in sorted(data
.commits_by_month
.keys()):
678 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
682 f
.write(html_header(2, 'Commits by Year'))
683 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th></tr>')
684 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
685 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()))
686 f
.write('</table></div>')
687 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
688 fg
= open(path
+ '/commits_by_year.dat', 'w')
689 for yy
in sorted(data
.commits_by_year
.keys()):
690 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
693 # Commits by timezone
694 f
.write(html_header(2, 'Commits by Timezone'))
695 f
.write('<table><tr>')
696 f
.write('<th>Timezone</th><th>Commits</th>')
697 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
698 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
699 commits
= data
.commits_by_timezone
[i
]
700 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
701 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
702 f
.write('</tr></table>')
704 f
.write('</body></html>')
709 f
= open(path
+ '/authors.html', 'w')
712 f
.write('<h1>Authors</h1>')
715 # Authors :: List of authors
716 f
.write(html_header(2, 'List of Authors'))
718 f
.write('<table class="authors sortable" id="authors">')
719 f
.write('<tr><th>Author</th><th>Commits (%)</th><th>First commit</th><th>Last commit</th><th class="unsortable">Age</th><th>Active days</th><th># by commits</th></tr>')
720 for author
in sorted(data
.getAuthors()):
721 info
= data
.getAuthorInfo(author
)
722 f
.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (author
, info
['commits'], info
['commits_frac'], info
['date_first'], info
['date_last'], info
['timedelta'], info
['active_days'], info
['place_by_commits']))
725 # Authors :: Author of Month
726 f
.write(html_header(2, 'Author of Month'))
727 f
.write('<table class="sortable" id="aom">')
728 f
.write('<tr><th>Month</th><th>Author</th><th>Commits (%)</th><th class="unsortable">Next top 5</th></tr>')
729 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
730 authordict
= data
.author_of_month
[yymm
]
731 authors
= getkeyssortedbyvalues(authordict
)
733 commits
= data
.author_of_month
[yymm
][authors
[0]]
734 next
= ', '.join(authors
[1:5])
735 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
))
739 f
.write(html_header(2, 'Author of Year'))
740 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>')
741 for yy
in reversed(sorted(data
.author_of_year
.keys())):
742 authordict
= data
.author_of_year
[yy
]
743 authors
= getkeyssortedbyvalues(authordict
)
745 commits
= data
.author_of_year
[yy
][authors
[0]]
746 next
= ', '.join(authors
[1:5])
747 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
))
750 f
.write('</body></html>')
755 f
= open(path
+ '/files.html', 'w')
757 f
.write('<h1>Files</h1>')
761 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
762 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
763 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % ((100.0 * data
.getTotalLOC()) / data
.getTotalFiles()))
766 # Files :: File count by date
767 f
.write(html_header(2, 'File count by date'))
769 fg
= open(path
+ '/files_by_date.dat', 'w')
770 for stamp
in sorted(data
.files_by_stamp
.keys()):
771 fg
.write('%s %d\n' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
774 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
776 #f.write('<h2>Average file size by date</h2>')
778 # Files :: Extensions
779 f
.write(html_header(2, 'Extensions'))
780 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
781 for ext
in sorted(data
.extensions
.keys()):
782 files
= data
.extensions
[ext
]['files']
783 lines
= data
.extensions
[ext
]['lines']
784 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
))
787 f
.write('</body></html>')
792 f
= open(path
+ '/lines.html', 'w')
794 f
.write('<h1>Lines</h1>')
798 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
801 f
.write(html_header(2, 'Lines of Code'))
802 f
.write('<img src="lines_of_code.png" />')
804 fg
= open(path
+ '/lines_of_code.dat', 'w')
805 for stamp
in sorted(data
.changes_by_date
.keys()):
806 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
809 f
.write('</body></html>')
814 f
= open(path
+ '/tags.html', 'w')
816 f
.write('<h1>Tags</h1>')
820 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
821 if len(data
.tags
) > 0:
822 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
826 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
827 # sort the tags by date desc
828 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
829 for tag
in tags_sorted_by_date_desc
:
831 authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
832 for i
in reversed(authors_by_commits
):
833 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
834 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
)))
837 f
.write('</body></html>')
840 self
.createGraphs(path
)
842 def createGraphs(self
, path
):
843 print 'Generating graphs...'
846 f
= open(path
+ '/hour_of_day.plot', 'w')
847 f
.write(GNUPLOT_COMMON
)
850 set output 'hour_of_day.png'
852 set xrange [0.5:24.5]
855 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
860 f
= open(path
+ '/day_of_week.plot', 'w')
861 f
.write(GNUPLOT_COMMON
)
864 set output 'day_of_week.png'
869 plot 'day_of_week.dat' using 1:2:(0.5) w boxes fs solid
874 f
= open(path
+ '/month_of_year.plot', 'w')
875 f
.write(GNUPLOT_COMMON
)
878 set output 'month_of_year.png'
880 set xrange [0.5:12.5]
883 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
887 # commits_by_year_month
888 f
= open(path
+ '/commits_by_year_month.plot', 'w')
889 f
.write(GNUPLOT_COMMON
)
892 set output 'commits_by_year_month.png'
897 set xtics rotate by 90 15768000
900 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
905 f
= open(path
+ '/commits_by_year.plot', 'w')
906 f
.write(GNUPLOT_COMMON
)
909 set output 'commits_by_year.png'
914 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
919 f
= open(path
+ '/files_by_date.plot', 'w')
920 f
.write(GNUPLOT_COMMON
)
923 set output 'files_by_date.png'
926 set timefmt "%Y-%m-%d"
927 set format x "%Y-%m-%d"
929 set xtics rotate by 90
932 plot 'files_by_date.dat' using 1:2 w steps
937 f
= open(path
+ '/lines_of_code.plot', 'w')
938 f
.write(GNUPLOT_COMMON
)
941 set output 'lines_of_code.png'
945 set format x "%Y-%m-%d"
947 set xtics rotate by 90
949 plot 'lines_of_code.dat' using 1:2 w lines
954 files
= glob
.glob(path
+ '/*.plot')
956 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
960 def printHeader(self
, f
, title
= ''):
962 """<?xml version="1.0" encoding="UTF-8"?>
963 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
964 <html xmlns="http://www.w3.org/1999/xhtml">
966 <title>GitStats - %s</title>
967 <link rel="stylesheet" href="gitstats.css" type="text/css" />
968 <meta name="generator" content="GitStats %s" />
969 <script type="text/javascript" src="sortable.js"></script>
972 """ % (self
.title
, getversion()))
974 def printNav(self
, f
):
978 <li><a href="index.html">General</a></li>
979 <li><a href="activity.html">Activity</a></li>
980 <li><a href="authors.html">Authors</a></li>
981 <li><a href="files.html">Files</a></li>
982 <li><a href="lines.html">Lines</a></li>
983 <li><a href="tags.html">Tags</a></li>
990 Usage: gitstats [options] <gitpath> <outputpath>
995 if len(sys
.argv
) < 3:
999 gitpath
= sys
.argv
[1]
1000 outputpath
= os
.path
.abspath(sys
.argv
[2])
1001 rundir
= os
.getcwd()
1004 os
.makedirs(outputpath
)
1007 if not os
.path
.isdir(outputpath
):
1008 print 'FATAL: Output path is not a directory or does not exist'
1011 print 'Git path: %s' % gitpath
1012 print 'Output path: %s' % outputpath
1016 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1018 print 'Collecting data...'
1019 data
= GitDataCollector()
1020 data
.loadCache(cachefile
)
1021 data
.collect(gitpath
)
1022 print 'Refining data...'
1023 data
.saveCache(cachefile
)
1028 print 'Generating report...'
1029 report
= HTMLReportCreator()
1030 report
.create(data
, outputpath
)
1032 time_end
= time
.time()
1033 exectime_internal
= time_end
- time_start
1034 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)