2 # Copyright (c) 2007-2013 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/author.txt)
17 if sys
.version_info
< (2, 6):
18 print >> sys
.stderr
, "Python 2.6 or higher is required for gitstats"
21 from multiprocessing
import Pool
23 os
.environ
['LC_ALL'] = 'C'
25 GNUPLOT_COMMON
= 'set terminal png transparent size 640,240\nset size 1.0,1.0\n'
26 ON_LINUX
= (platform
.system() == 'Linux')
27 WEEKDAYS
= ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
29 exectime_internal
= 0.0
30 exectime_external
= 0.0
31 time_start
= time
.time()
33 # By default, gnuplot is searched from path, but can be overridden with the
34 # environment variable "GNUPLOT"
35 gnuplot_cmd
= 'gnuplot'
36 if 'GNUPLOT' in os
.environ
:
37 gnuplot_cmd
= os
.environ
['GNUPLOT']
42 'style': 'gitstats.css',
47 'linear_linestats': 1,
52 def getpipeoutput(cmds
, quiet
= False):
53 global exectime_external
55 if not quiet
and ON_LINUX
and os
.isatty(1):
56 print '>> ' + ' | '.join(cmds
),
58 p0
= subprocess
.Popen(cmds
[0], stdout
= subprocess
.PIPE
, shell
= True)
61 p
= subprocess
.Popen(x
, stdin
= p0
.stdout
, stdout
= subprocess
.PIPE
, shell
= True)
63 output
= p
.communicate()[0]
66 if ON_LINUX
and os
.isatty(1):
68 print '[%.5f] >> %s' % (end
- start
, ' | '.join(cmds
))
69 exectime_external
+= (end
- start
)
70 return output
.rstrip('\n')
72 def getcommitrange(defaultrange
= 'HEAD', end_only
= False):
73 if len(conf
['commit_end']) > 0:
74 if end_only
or len(conf
['commit_begin']) == 0:
75 return conf
['commit_end']
76 return '%s..%s' % (conf
['commit_begin'], conf
['commit_end'])
79 def getkeyssortedbyvalues(dict):
80 return map(lambda el
: el
[1], sorted(map(lambda el
: (el
[1], el
[0]), dict.items())))
82 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
83 def getkeyssortedbyvaluekey(d
, key
):
84 return map(lambda el
: el
[1], sorted(map(lambda el
: (d
[el
][key
], el
), d
.keys())))
86 def getstatsummarycounts(line
):
87 numbers
= re
.findall('\d+', line
)
89 # neither insertions nor deletions: may probably only happen for "0 files changed"
92 elif len(numbers
) == 2 and line
.find('(+)') != -1:
93 numbers
.append(0); # only insertions were printed on line
94 elif len(numbers
) == 2 and line
.find('(-)') != -1:
95 numbers
.insert(1, 0); # only deletions were printed on line
102 gitstats_repo
= os
.path
.dirname(os
.path
.abspath(__file__
))
103 VERSION
= getpipeoutput(["git --git-dir=%s/.git --work-tree=%s rev-parse --short %s" %
104 (gitstats_repo
, gitstats_repo
, getcommitrange('HEAD').split('\n')[0])])
108 return getpipeoutput(['git --version']).split('\n')[0]
110 def getgnuplotversion():
111 return getpipeoutput(['%s --version' % gnuplot_cmd
]).split('\n')[0]
113 def getnumoffilesfromrev(time_rev
):
115 Get number of files changed in commit
118 return (int(time
), rev
, int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0]))
120 def getnumoflinesinblob(ext_blob
):
122 Get number of lines in blob
124 ext
, blob_id
= ext_blob
125 return (ext
, blob_id
, int(getpipeoutput(['git cat-file blob %s' % blob_id
, 'wc -l']).split()[0]))
128 """Manages data collection from a revision control repository."""
130 self
.stamp_created
= time
.time()
132 self
.total_authors
= 0
133 self
.activity_by_hour_of_day
= {} # hour -> commits
134 self
.activity_by_day_of_week
= {} # day -> commits
135 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
136 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
137 self
.activity_by_hour_of_day_busiest
= 0
138 self
.activity_by_hour_of_week_busiest
= 0
139 self
.activity_by_year_week
= {} # yy_wNN -> commits
140 self
.activity_by_year_week_peak
= 0
142 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
144 self
.total_commits
= 0
146 self
.authors_by_commits
= 0
149 self
.domains
= {} # domain -> commits
151 # author of the month
152 self
.author_of_month
= {} # month -> author -> commits
153 self
.author_of_year
= {} # year -> author -> commits
154 self
.commits_by_month
= {} # month -> commits
155 self
.commits_by_year
= {} # year -> commits
156 self
.lines_added_by_month
= {} # month -> lines added
157 self
.lines_added_by_year
= {} # year -> lines added
158 self
.lines_removed_by_month
= {} # month -> lines removed
159 self
.lines_removed_by_year
= {} # year -> lines removed
160 self
.first_commit_stamp
= 0
161 self
.last_commit_stamp
= 0
162 self
.last_active_day
= None
163 self
.active_days
= set()
167 self
.total_lines_added
= 0
168 self
.total_lines_removed
= 0
174 self
.commits_by_timezone
= {} # timezone -> commits
179 self
.files_by_stamp
= {} # stamp -> files
182 self
.extensions
= {} # extension -> files, lines
185 self
.changes_by_date
= {} # stamp -> { files, ins, del }
188 # This should be the main function to extract data from the repository.
189 def collect(self
, dir):
191 if len(conf
['project_name']) == 0:
192 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
194 self
.projectname
= conf
['project_name']
197 # Load cacheable data
198 def loadCache(self
, cachefile
):
199 if not os
.path
.exists(cachefile
):
201 print 'Loading cache...'
202 f
= open(cachefile
, 'rb')
204 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
206 # temporary hack to upgrade non-compressed caches
208 self
.cache
= pickle
.load(f
)
212 # Produce any additional statistics from the extracted data.
217 # : get a dictionary of author
218 def getAuthorInfo(self
, author
):
221 def getActivityByDayOfWeek(self
):
224 def getActivityByHourOfDay(self
):
227 # : get a dictionary of domains
228 def getDomainInfo(self
, domain
):
232 # Get a list of authors
233 def getAuthors(self
):
236 def getFirstCommitDate(self
):
237 return datetime
.datetime
.now()
239 def getLastCommitDate(self
):
240 return datetime
.datetime
.now()
242 def getStampCreated(self
):
243 return self
.stamp_created
248 def getTotalAuthors(self
):
251 def getTotalCommits(self
):
254 def getTotalFiles(self
):
257 def getTotalLOC(self
):
261 # Save cacheable data
262 def saveCache(self
, cachefile
):
263 print 'Saving cache...'
264 tempfile
= cachefile
+ '.tmp'
265 f
= open(tempfile
, 'wb')
266 #pickle.dump(self.cache, f)
267 data
= zlib
.compress(pickle
.dumps(self
.cache
))
274 os
.rename(tempfile
, cachefile
)
276 class GitDataCollector(DataCollector
):
277 def collect(self
, dir):
278 DataCollector
.collect(self
, dir)
280 self
.total_authors
+= int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
281 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
284 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
288 (hash, tag
) = line
.split(' ')
290 tag
= tag
.replace('refs/tags/', '')
291 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
293 parts
= output
.split(' ')
296 stamp
= int(parts
[0])
299 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
301 # collect info on tags, starting from latest
302 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), self
.tags
.items()))))
304 for tag
in reversed(tags_sorted_by_date_desc
):
305 cmd
= 'git shortlog -s "%s"' % tag
307 cmd
+= ' "^%s"' % prev
308 output
= getpipeoutput([cmd
])
312 for line
in output
.split('\n'):
313 parts
= re
.split('\s+', line
, 2)
314 commits
= int(parts
[1])
316 if author
in conf
['merge_authors']:
317 author
= conf
['merge_authors'][author
]
318 self
.tags
[tag
]['commits'] += commits
319 self
.tags
[tag
]['authors'][author
] = commits
321 # Collect revision statistics
322 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
323 lines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
325 parts
= line
.split(' ', 4)
328 stamp
= int(parts
[0])
332 author
, mail
= parts
[4].split('<', 1)
333 author
= author
.rstrip()
334 if author
in conf
['merge_authors']:
335 author
= conf
['merge_authors'][author
]
336 mail
= mail
.rstrip('>')
338 if mail
.find('@') != -1:
339 domain
= mail
.rsplit('@', 1)[1]
340 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
342 # First and last commit stamp (may be in any order because of cherry-picking and patches)
343 if stamp
> self
.last_commit_stamp
:
344 self
.last_commit_stamp
= stamp
345 if self
.first_commit_stamp
== 0 or stamp
< self
.first_commit_stamp
:
346 self
.first_commit_stamp
= stamp
351 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
353 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
354 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
358 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
361 if domain
not in self
.domains
:
362 self
.domains
[domain
] = {}
364 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
367 if day
not in self
.activity_by_hour_of_week
:
368 self
.activity_by_hour_of_week
[day
] = {}
369 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
371 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
372 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
376 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
378 # yearly/weekly activity
379 yyw
= date
.strftime('%Y-%W')
380 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
381 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
382 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
385 if author
not in self
.authors
:
386 self
.authors
[author
] = {}
387 # commits, note again that commits may be in any date order because of cherry-picking and patches
388 if 'last_commit_stamp' not in self
.authors
[author
]:
389 self
.authors
[author
]['last_commit_stamp'] = stamp
390 if stamp
> self
.authors
[author
]['last_commit_stamp']:
391 self
.authors
[author
]['last_commit_stamp'] = stamp
392 if 'first_commit_stamp' not in self
.authors
[author
]:
393 self
.authors
[author
]['first_commit_stamp'] = stamp
394 if stamp
< self
.authors
[author
]['first_commit_stamp']:
395 self
.authors
[author
]['first_commit_stamp'] = stamp
397 # author of the month/year
398 yymm
= date
.strftime('%Y-%m')
399 if yymm
in self
.author_of_month
:
400 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
402 self
.author_of_month
[yymm
] = {}
403 self
.author_of_month
[yymm
][author
] = 1
404 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
407 if yy
in self
.author_of_year
:
408 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
410 self
.author_of_year
[yy
] = {}
411 self
.author_of_year
[yy
][author
] = 1
412 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
414 # authors: active days
415 yymmdd
= date
.strftime('%Y-%m-%d')
416 if 'last_active_day' not in self
.authors
[author
]:
417 self
.authors
[author
]['last_active_day'] = yymmdd
418 self
.authors
[author
]['active_days'] = set([yymmdd
])
419 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
420 self
.authors
[author
]['last_active_day'] = yymmdd
421 self
.authors
[author
]['active_days'].add(yymmdd
)
423 # project: active days
424 if yymmdd
!= self
.last_active_day
:
425 self
.last_active_day
= yymmdd
426 self
.active_days
.add(yymmdd
)
429 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
431 # outputs "<stamp> <files>" for each revision
432 revlines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
436 #Look up rev in cache and take info from cache if found
437 #If not append rev to list of rev to read from repo
438 for revline
in revlines
:
439 time
, rev
= revline
.split(' ')
440 #if cache empty then add time and rev to list of new rev's
441 #otherwise try to read needed info from cache
442 if 'files_in_tree' not in self
.cache
.keys():
443 revs_to_read
.append((time
,rev
))
445 if rev
in self
.cache
['files_in_tree'].keys():
446 lines
.append('%d %d' % (int(time
), self
.cache
['files_in_tree'][rev
]))
448 revs_to_read
.append((time
,rev
))
450 #Read revisions from repo
451 time_rev_count
= Pool(processes
=24).map(getnumoffilesfromrev
, revs_to_read
)
453 #Update cache with new revisions and append then to general list
454 for (time
, rev
, count
) in time_rev_count
:
455 if 'files_in_tree' not in self
.cache
:
456 self
.cache
['files_in_tree'] = {}
457 self
.cache
['files_in_tree'][rev
] = count
458 lines
.append('%d %d' % (int(time
), count
))
460 self
.total_commits
+= len(lines
)
462 parts
= line
.split(' ')
465 (stamp
, files
) = parts
[0:2]
467 self
.files_by_stamp
[int(stamp
)] = int(files
)
469 print 'Warning: failed to parse line "%s"' % line
471 # extensions and size of files
472 lines
= getpipeoutput(['git ls-tree -r -l -z %s' % getcommitrange('HEAD', end_only
= True)]).split('\000')
477 parts
= re
.split('\s+', line
, 5)
478 if parts
[0] == '160000' and parts
[3] == '-':
485 self
.total_size
+= size
486 self
.total_files
+= 1
488 filename
= fullpath
.split('/')[-1] # strip directories
489 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
492 ext
= filename
[(filename
.rfind('.') + 1):]
493 if len(ext
) > conf
['max_ext_length']:
495 if ext
not in self
.extensions
:
496 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
497 self
.extensions
[ext
]['files'] += 1
498 #if cache empty then add ext and blob id to list of new blob's
499 #otherwise try to read needed info from cache
500 if 'lines_in_blob' not in self
.cache
.keys():
501 blobs_to_read
.append((ext
,blob_id
))
503 if blob_id
in self
.cache
['lines_in_blob'].keys():
504 self
.extensions
[ext
]['lines'] += self
.cache
['lines_in_blob'][blob_id
]
506 blobs_to_read
.append((ext
,blob_id
))
508 #Get info abount line count for new blob's that wasn't found in cache
509 ext_blob_linecount
= Pool(processes
=24).map(getnumoflinesinblob
, blobs_to_read
)
511 #Update cache and write down info about number of number of lines
512 for (ext
, blob_id
, linecount
) in ext_blob_linecount
:
513 if 'lines_in_blob' not in self
.cache
:
514 self
.cache
['lines_in_blob'] = {}
515 self
.cache
['lines_in_blob'][blob_id
] = linecount
516 self
.extensions
[ext
]['lines'] += self
.cache
['lines_in_blob'][blob_id
]
520 # N files changed, N insertions (+), N deletions(-)
522 self
.changes_by_date
= {} # stamp -> { files, ins, del }
523 # computation of lines of code by date is better done
524 # on a linear history.
526 if conf
['linear_linestats']:
527 extra
= '--first-parent -m'
528 lines
= getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra
, getcommitrange('HEAD'))]).split('\n')
530 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
537 if re
.search('files? changed', line
) == None:
541 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
542 if author
in conf
['merge_authors']:
543 author
= conf
['merge_authors'][author
]
544 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
546 date
= datetime
.datetime
.fromtimestamp(stamp
)
547 yymm
= date
.strftime('%Y-%m')
548 self
.lines_added_by_month
[yymm
] = self
.lines_added_by_month
.get(yymm
, 0) + inserted
549 self
.lines_removed_by_month
[yymm
] = self
.lines_removed_by_month
.get(yymm
, 0) + deleted
552 self
.lines_added_by_year
[yy
] = self
.lines_added_by_year
.get(yy
,0) + inserted
553 self
.lines_removed_by_year
[yy
] = self
.lines_removed_by_year
.get(yy
, 0) + deleted
555 files
, inserted
, deleted
= 0, 0, 0
557 print 'Warning: unexpected line "%s"' % line
559 print 'Warning: unexpected line "%s"' % line
561 numbers
= getstatsummarycounts(line
)
563 if len(numbers
) == 3:
564 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
565 total_lines
+= inserted
566 total_lines
-= deleted
567 self
.total_lines_added
+= inserted
568 self
.total_lines_removed
+= deleted
571 print 'Warning: failed to handle line "%s"' % line
572 (files
, inserted
, deleted
) = (0, 0, 0)
573 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
574 self
.total_lines
+= total_lines
576 # Per-author statistics
578 # defined for stamp, author only if author commited at this timestamp.
579 self
.changes_by_date_by_author
= {} # stamp -> author -> lines_added
581 # Similar to the above, but never use --first-parent
582 # (we need to walk through every commit to know who
583 # committed what, not just through mainline)
584 lines
= getpipeoutput(['git log --shortstat --date-order --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
586 files
= 0; inserted
= 0; deleted
= 0
594 if re
.search('files? changed', line
) == None:
599 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
600 if author
in conf
['merge_authors']:
601 author
= conf
['merge_authors'][author
]
603 # clock skew, keep old timestamp to avoid having ugly graph
605 if author
not in self
.authors
:
606 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
607 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
608 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
609 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
610 if stamp
not in self
.changes_by_date_by_author
:
611 self
.changes_by_date_by_author
[stamp
] = {}
612 if author
not in self
.changes_by_date_by_author
[stamp
]:
613 self
.changes_by_date_by_author
[stamp
][author
] = {}
614 self
.changes_by_date_by_author
[stamp
][author
]['lines_added'] = self
.authors
[author
]['lines_added']
615 self
.changes_by_date_by_author
[stamp
][author
]['commits'] = self
.authors
[author
]['commits']
616 files
, inserted
, deleted
= 0, 0, 0
618 print 'Warning: unexpected line "%s"' % line
620 print 'Warning: unexpected line "%s"' % line
622 numbers
= getstatsummarycounts(line
);
624 if len(numbers
) == 3:
625 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
627 print 'Warning: failed to handle line "%s"' % line
628 (files
, inserted
, deleted
) = (0, 0, 0)
632 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
633 self
.authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
634 self
.authors_by_commits
.reverse() # most first
635 for i
, name
in enumerate(self
.authors_by_commits
):
636 self
.authors
[name
]['place_by_commits'] = i
+ 1
638 for name
in self
.authors
.keys():
639 a
= self
.authors
[name
]
640 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
641 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
642 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
643 delta
= date_last
- date_first
644 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
645 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
646 a
['timedelta'] = delta
647 if 'lines_added' not in a
: a
['lines_added'] = 0
648 if 'lines_removed' not in a
: a
['lines_removed'] = 0
650 def getActiveDays(self
):
651 return self
.active_days
653 def getActivityByDayOfWeek(self
):
654 return self
.activity_by_day_of_week
656 def getActivityByHourOfDay(self
):
657 return self
.activity_by_hour_of_day
659 def getAuthorInfo(self
, author
):
660 return self
.authors
[author
]
662 def getAuthors(self
, limit
= None):
663 res
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
667 def getCommitDeltaDays(self
):
668 return (self
.last_commit_stamp
/ 86400 - self
.first_commit_stamp
/ 86400) + 1
670 def getDomainInfo(self
, domain
):
671 return self
.domains
[domain
]
673 def getDomains(self
):
674 return self
.domains
.keys()
676 def getFirstCommitDate(self
):
677 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
679 def getLastCommitDate(self
):
680 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
683 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
684 return lines
.split('\n')
686 def getTagDate(self
, tag
):
687 return self
.revToDate('tags/' + tag
)
689 def getTotalAuthors(self
):
690 return self
.total_authors
692 def getTotalCommits(self
):
693 return self
.total_commits
695 def getTotalFiles(self
):
696 return self
.total_files
698 def getTotalLOC(self
):
699 return self
.total_lines
701 def getTotalSize(self
):
702 return self
.total_size
704 def revToDate(self
, rev
):
705 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
706 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
709 """Creates the actual report based on given data."""
713 def create(self
, data
, path
):
717 def html_linkify(text
):
718 return text
.lower().replace(' ', '_')
720 def html_header(level
, text
):
721 name
= html_linkify(text
)
722 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
724 class HTMLReportCreator(ReportCreator
):
725 def create(self
, data
, path
):
726 ReportCreator
.create(self
, data
, path
)
727 self
.title
= data
.projectname
729 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
730 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
731 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
732 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
733 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
734 for base
in basedirs
:
735 src
= base
+ '/' + file
736 if os
.path
.exists(src
):
737 shutil
.copyfile(src
, path
+ '/' + file)
740 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
742 f
= open(path
+ "/index.html", 'w')
743 format
= '%Y-%m-%d %H:%M:%S'
746 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
751 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
752 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
753 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
754 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
755 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())))
756 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
757 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
))
758 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()))
759 f
.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data
.getTotalAuthors(), (1.0 * data
.getTotalCommits()) / data
.getTotalAuthors()))
762 f
.write('</body>\n</html>')
767 f
= open(path
+ '/activity.html', 'w')
769 f
.write('<h1>Activity</h1>')
772 #f.write('<h2>Last 30 days</h2>')
774 #f.write('<h2>Last 12 months</h2>')
778 f
.write(html_header(2, 'Weekly activity'))
779 f
.write('<p>Last %d weeks</p>' % WEEKS
)
781 # generate weeks to show (previous N weeks from now)
782 now
= datetime
.datetime
.now()
783 deltaweek
= datetime
.timedelta(7)
786 for i
in range(0, WEEKS
):
787 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
788 stampcur
-= deltaweek
790 # top row: commits & bar
791 f
.write('<table class="noborders"><tr>')
792 for i
in range(0, WEEKS
):
794 if weeks
[i
] in data
.activity_by_year_week
:
795 commits
= data
.activity_by_year_week
[weeks
[i
]]
798 if weeks
[i
] in data
.activity_by_year_week
:
799 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
800 height
= max(1, int(200 * percentage
))
801 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
))
803 # bottom row: year/week
805 for i
in range(0, WEEKS
):
806 f
.write('<td>%s</td>' % (WEEKS
- i
))
807 f
.write('</tr></table>')
810 f
.write(html_header(2, 'Hour of Day'))
811 hour_of_day
= data
.getActivityByHourOfDay()
812 f
.write('<table><tr><th>Hour</th>')
813 for i
in range(0, 24):
814 f
.write('<th>%d</th>' % i
)
815 f
.write('</tr>\n<tr><th>Commits</th>')
816 fp
= open(path
+ '/hour_of_day.dat', 'w')
817 for i
in range(0, 24):
819 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
820 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
821 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
823 f
.write('<td>0</td>')
824 fp
.write('%d 0\n' % i
)
826 f
.write('</tr>\n<tr><th>%</th>')
827 totalcommits
= data
.getTotalCommits()
828 for i
in range(0, 24):
830 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
831 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
833 f
.write('<td>0.00</td>')
834 f
.write('</tr></table>')
835 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
836 fg
= open(path
+ '/hour_of_day.dat', 'w')
837 for i
in range(0, 24):
839 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
841 fg
.write('%d 0\n' % (i
+ 1))
845 f
.write(html_header(2, 'Day of Week'))
846 day_of_week
= data
.getActivityByDayOfWeek()
847 f
.write('<div class="vtable"><table>')
848 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
849 fp
= open(path
+ '/day_of_week.dat', 'w')
850 for d
in range(0, 7):
853 commits
= day_of_week
[d
]
854 fp
.write('%d %s %d\n' % (d
+ 1, WEEKDAYS
[d
], commits
))
856 f
.write('<th>%s</th>' % (WEEKDAYS
[d
]))
858 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
860 f
.write('<td>0</td>')
862 f
.write('</table></div>')
863 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
867 f
.write(html_header(2, 'Hour of Week'))
870 f
.write('<tr><th>Weekday</th>')
871 for hour
in range(0, 24):
872 f
.write('<th>%d</th>' % (hour
))
875 for weekday
in range(0, 7):
876 f
.write('<tr><th>%s</th>' % (WEEKDAYS
[weekday
]))
877 for hour
in range(0, 24):
879 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
884 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
885 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
886 f
.write('>%d</td>' % commits
)
894 f
.write(html_header(2, 'Month of Year'))
895 f
.write('<div class="vtable"><table>')
896 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
897 fp
= open (path
+ '/month_of_year.dat', 'w')
898 for mm
in range(1, 13):
900 if mm
in data
.activity_by_month_of_year
:
901 commits
= data
.activity_by_month_of_year
[mm
]
902 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
903 fp
.write('%d %d\n' % (mm
, commits
))
905 f
.write('</table></div>')
906 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
908 # Commits by year/month
909 f
.write(html_header(2, 'Commits by year/month'))
910 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th><th>Lines added</th><th>Lines removed</th></tr>')
911 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
912 f
.write('<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td></tr>' % (yymm
, data
.commits_by_month
.get(yymm
,0), data
.lines_added_by_month
.get(yymm
,0), data
.lines_removed_by_month
.get(yymm
,0)))
913 f
.write('</table></div>')
914 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
915 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
916 for yymm
in sorted(data
.commits_by_month
.keys()):
917 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
921 f
.write(html_header(2, 'Commits by Year'))
922 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th><th>Lines added</th><th>Lines removed</th></tr>')
923 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
924 f
.write('<tr><td>%s</td><td>%d (%.2f%%)</td><td>%d</td><td>%d</td></tr>' % (yy
, data
.commits_by_year
.get(yy
,0), (100.0 * data
.commits_by_year
.get(yy
,0)) / data
.getTotalCommits(), data
.lines_added_by_year
.get(yy
,0), data
.lines_removed_by_year
.get(yy
,0)))
925 f
.write('</table></div>')
926 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
927 fg
= open(path
+ '/commits_by_year.dat', 'w')
928 for yy
in sorted(data
.commits_by_year
.keys()):
929 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
932 # Commits by timezone
933 f
.write(html_header(2, 'Commits by Timezone'))
934 f
.write('<table><tr>')
935 f
.write('<th>Timezone</th><th>Commits</th>')
936 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
937 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
938 commits
= data
.commits_by_timezone
[i
]
939 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
940 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
941 f
.write('</tr></table>')
943 f
.write('</body></html>')
948 f
= open(path
+ '/authors.html', 'w')
951 f
.write('<h1>Authors</h1>')
954 # Authors :: List of authors
955 f
.write(html_header(2, 'List of Authors'))
957 f
.write('<table class="authors sortable" id="authors">')
958 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>')
959 for author
in data
.getAuthors(conf
['max_authors']):
960 info
= data
.getAuthorInfo(author
)
961 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'], len(info
['active_days']), info
['place_by_commits']))
964 allauthors
= data
.getAuthors()
965 if len(allauthors
) > conf
['max_authors']:
966 rest
= allauthors
[conf
['max_authors']:]
967 f
.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest
))
969 f
.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
970 f
.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
971 if len(allauthors
) > conf
['max_authors']:
972 f
.write('<p class="moreauthors">Only top %d authors shown</p>' % conf
['max_authors'])
974 f
.write(html_header(2, 'Commits per Author'))
975 f
.write('<img src="commits_by_author.png" alt="Commits per Author" />')
976 if len(allauthors
) > conf
['max_authors']:
977 f
.write('<p class="moreauthors">Only top %d authors shown</p>' % conf
['max_authors'])
979 fgl
= open(path
+ '/lines_of_code_by_author.dat', 'w')
980 fgc
= open(path
+ '/commits_by_author.dat', 'w')
982 lines_by_authors
= {} # cumulated added lines by
983 # author. to save memory,
984 # changes_by_date_by_author[stamp][author] is defined
985 # only at points where author commits.
986 # lines_by_authors allows us to generate all the
987 # points in the .dat file.
989 # Don't rely on getAuthors to give the same order each
990 # time. Be robust and keep the list in a variable.
991 commits_by_authors
= {} # cumulated added lines by
993 self
.authors_to_plot
= data
.getAuthors(conf
['max_authors'])
994 for author
in self
.authors_to_plot
:
995 lines_by_authors
[author
] = 0
996 commits_by_authors
[author
] = 0
997 for stamp
in sorted(data
.changes_by_date_by_author
.keys()):
998 fgl
.write('%d' % stamp
)
999 fgc
.write('%d' % stamp
)
1000 for author
in self
.authors_to_plot
:
1001 if author
in data
.changes_by_date_by_author
[stamp
].keys():
1002 lines_by_authors
[author
] = data
.changes_by_date_by_author
[stamp
][author
]['lines_added']
1003 commits_by_authors
[author
] = data
.changes_by_date_by_author
[stamp
][author
]['commits']
1004 fgl
.write(' %d' % lines_by_authors
[author
])
1005 fgc
.write(' %d' % commits_by_authors
[author
])
1011 # Authors :: Author of Month
1012 f
.write(html_header(2, 'Author of Month'))
1013 f
.write('<table class="sortable" id="aom">')
1014 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'])
1015 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
1016 authordict
= data
.author_of_month
[yymm
]
1017 authors
= getkeyssortedbyvalues(authordict
)
1019 commits
= data
.author_of_month
[yymm
][authors
[0]]
1020 next
= ', '.join(authors
[1:conf
['authors_top']+1])
1021 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
)))
1025 f
.write(html_header(2, 'Author of Year'))
1026 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'])
1027 for yy
in reversed(sorted(data
.author_of_year
.keys())):
1028 authordict
= data
.author_of_year
[yy
]
1029 authors
= getkeyssortedbyvalues(authordict
)
1031 commits
= data
.author_of_year
[yy
][authors
[0]]
1032 next
= ', '.join(authors
[1:conf
['authors_top']+1])
1033 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
)))
1037 f
.write(html_header(2, 'Commits by Domains'))
1038 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
1039 domains_by_commits
.reverse() # most first
1040 f
.write('<div class="vtable"><table>')
1041 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
1042 fp
= open(path
+ '/domains.dat', 'w')
1044 for domain
in domains_by_commits
:
1045 if n
== conf
['max_domains']:
1049 info
= data
.getDomainInfo(domain
)
1050 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
1051 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
1052 f
.write('</table></div>')
1053 f
.write('<img src="domains.png" alt="Commits by Domains" />')
1056 f
.write('</body></html>')
1061 f
= open(path
+ '/files.html', 'w')
1063 f
.write('<h1>Files</h1>')
1067 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
1068 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
1070 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % (float(data
.getTotalSize()) / data
.getTotalFiles()))
1071 except ZeroDivisionError:
1075 # Files :: File count by date
1076 f
.write(html_header(2, 'File count by date'))
1078 # use set to get rid of duplicate/unnecessary entries
1079 files_by_date
= set()
1080 for stamp
in sorted(data
.files_by_stamp
.keys()):
1081 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
1083 fg
= open(path
+ '/files_by_date.dat', 'w')
1084 for line
in sorted(list(files_by_date
)):
1085 fg
.write('%s\n' % line
)
1086 #for stamp in sorted(data.files_by_stamp.keys()):
1087 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1090 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
1092 #f.write('<h2>Average file size by date</h2>')
1094 # Files :: Extensions
1095 f
.write(html_header(2, 'Extensions'))
1096 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
1097 for ext
in sorted(data
.extensions
.keys()):
1098 files
= data
.extensions
[ext
]['files']
1099 lines
= data
.extensions
[ext
]['lines']
1101 loc_percentage
= (100.0 * lines
) / data
.getTotalLOC()
1102 except ZeroDivisionError:
1104 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
, loc_percentage
, lines
/ files
))
1107 f
.write('</body></html>')
1112 f
= open(path
+ '/lines.html', 'w')
1114 f
.write('<h1>Lines</h1>')
1118 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
1121 f
.write(html_header(2, 'Lines of Code'))
1122 f
.write('<img src="lines_of_code.png" />')
1124 fg
= open(path
+ '/lines_of_code.dat', 'w')
1125 for stamp
in sorted(data
.changes_by_date
.keys()):
1126 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
1129 f
.write('</body></html>')
1134 f
= open(path
+ '/tags.html', 'w')
1136 f
.write('<h1>Tags</h1>')
1140 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
1141 if len(data
.tags
) > 0:
1142 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
1145 f
.write('<table class="tags">')
1146 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1147 # sort the tags by date desc
1148 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
1149 for tag
in tags_sorted_by_date_desc
:
1151 self
.authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
1152 for i
in reversed(self
.authors_by_commits
):
1153 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
1154 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
)))
1157 f
.write('</body></html>')
1160 self
.createGraphs(path
)
1162 def createGraphs(self
, path
):
1163 print 'Generating graphs...'
1166 f
= open(path
+ '/hour_of_day.plot', 'w')
1167 f
.write(GNUPLOT_COMMON
)
1170 set output 'hour_of_day.png'
1172 set xrange [0.5:24.5]
1175 set ylabel "Commits"
1176 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1181 f
= open(path
+ '/day_of_week.plot', 'w')
1182 f
.write(GNUPLOT_COMMON
)
1185 set output 'day_of_week.png'
1187 set xrange [0.5:7.5]
1190 set ylabel "Commits"
1191 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1196 f
= open(path
+ '/domains.plot', 'w')
1197 f
.write(GNUPLOT_COMMON
)
1200 set output 'domains.png'
1205 set ylabel "Commits"
1206 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1211 f
= open(path
+ '/month_of_year.plot', 'w')
1212 f
.write(GNUPLOT_COMMON
)
1215 set output 'month_of_year.png'
1217 set xrange [0.5:12.5]
1220 set ylabel "Commits"
1221 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1225 # commits_by_year_month
1226 f
= open(path
+ '/commits_by_year_month.plot', 'w')
1227 f
.write(GNUPLOT_COMMON
)
1230 set output 'commits_by_year_month.png'
1234 set format x "%Y-%m"
1238 set ylabel "Commits"
1239 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1244 f
= open(path
+ '/commits_by_year.plot', 'w')
1245 f
.write(GNUPLOT_COMMON
)
1248 set output 'commits_by_year.png'
1252 set ylabel "Commits"
1254 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1259 f
= open(path
+ '/files_by_date.plot', 'w')
1260 f
.write(GNUPLOT_COMMON
)
1263 set output 'files_by_date.png'
1266 set timefmt "%Y-%m-%d"
1267 set format x "%Y-%m-%d"
1273 plot 'files_by_date.dat' using 1:2 w steps
1278 f
= open(path
+ '/lines_of_code.plot', 'w')
1279 f
.write(GNUPLOT_COMMON
)
1282 set output 'lines_of_code.png'
1286 set format x "%Y-%m-%d"
1291 plot 'lines_of_code.dat' using 1:2 w lines
1295 # Lines of Code Added per author
1296 f
= open(path
+ '/lines_of_code_by_author.plot', 'w')
1297 f
.write(GNUPLOT_COMMON
)
1300 set terminal png transparent size 640,480
1301 set output 'lines_of_code_by_author.png'
1305 set format x "%Y-%m-%d"
1314 for a
in self
.authors_to_plot
:
1316 plots
.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i
, a
.replace("\"", "\\\"")))
1317 f
.write(", ".join(plots
))
1322 # Commits per author
1323 f
= open(path
+ '/commits_by_author.plot', 'w')
1324 f
.write(GNUPLOT_COMMON
)
1327 set terminal png transparent size 640,480
1328 set output 'commits_by_author.png'
1332 set format x "%Y-%m-%d"
1334 set ylabel "Commits"
1341 for a
in self
.authors_to_plot
:
1343 plots
.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i
, a
.replace("\"", "\\\"")))
1344 f
.write(", ".join(plots
))
1350 files
= glob
.glob(path
+ '/*.plot')
1352 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1356 def printHeader(self
, f
, title
= ''):
1358 """<?xml version="1.0" encoding="UTF-8"?>
1359 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1360 <html xmlns="http://www.w3.org/1999/xhtml">
1362 <title>GitStats - %s</title>
1363 <link rel="stylesheet" href="%s" type="text/css" />
1364 <meta name="generator" content="GitStats %s" />
1365 <script type="text/javascript" src="sortable.js"></script>
1368 """ % (self
.title
, conf
['style'], getversion()))
1370 def printNav(self
, f
):
1374 <li><a href="index.html">General</a></li>
1375 <li><a href="activity.html">Activity</a></li>
1376 <li><a href="authors.html">Authors</a></li>
1377 <li><a href="files.html">Files</a></li>
1378 <li><a href="lines.html">Lines</a></li>
1379 <li><a href="tags.html">Tags</a></li>
1386 Usage: gitstats [options] <gitpath..> <outputpath>
1389 -c key=value Override configuration value
1391 Default config values:
1394 Please see the manual page for more details.
1399 def run(self
, args_orig
):
1400 optlist
, args
= getopt
.getopt(args_orig
, 'hc:', ["help"])
1403 key
, value
= v
.split('=', 1)
1405 raise KeyError('no such key "%s" in config' % key
)
1406 if isinstance(conf
[key
], int):
1407 conf
[key
] = int(value
)
1408 elif isinstance(conf
[key
], dict):
1409 kk
,vv
= value
.split(',', 1)
1413 elif o
in ('-h', '--help'):
1421 outputpath
= os
.path
.abspath(args
[-1])
1422 rundir
= os
.getcwd()
1425 os
.makedirs(outputpath
)
1428 if not os
.path
.isdir(outputpath
):
1429 print 'FATAL: Output path is not a directory or does not exist'
1432 if not getgnuplotversion():
1433 print 'gnuplot not found'
1436 print 'Output path: %s' % outputpath
1437 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1439 data
= GitDataCollector()
1440 data
.loadCache(cachefile
)
1442 for gitpath
in args
[0:-1]:
1443 print 'Git path: %s' % gitpath
1447 print 'Collecting data...'
1448 data
.collect(gitpath
)
1450 print 'Refining data...'
1451 data
.saveCache(cachefile
)
1456 print 'Generating report...'
1457 report
= HTMLReportCreator()
1458 report
.create(data
, outputpath
)
1460 time_end
= time
.time()
1461 exectime_internal
= time_end
- time_start
1462 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)
1463 if sys
.stdin
.isatty():
1464 print 'You may now run:'
1466 print ' sensible-browser \'%s\'' % os
.path
.join(outputpath
, 'index.html').replace("'", "'\\''")
1469 if __name__
=='__main__':