2 # Copyright (c) 2007-2014 Heikki Hokkanen <hoxu@users.sf.net> & others (see doc/AUTHOR)
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,
53 def getpipeoutput(cmds
, quiet
= False):
54 global exectime_external
56 if not quiet
and ON_LINUX
and os
.isatty(1):
57 print '>> ' + ' | '.join(cmds
),
59 p0
= subprocess
.Popen(cmds
[0], stdout
= subprocess
.PIPE
, shell
= True)
62 p
= subprocess
.Popen(x
, stdin
= p0
.stdout
, stdout
= subprocess
.PIPE
, shell
= True)
64 output
= p
.communicate()[0]
67 if ON_LINUX
and os
.isatty(1):
69 print '[%.5f] >> %s' % (end
- start
, ' | '.join(cmds
))
70 exectime_external
+= (end
- start
)
71 return output
.rstrip('\n')
73 def getcommitrange(defaultrange
= 'HEAD', end_only
= False):
74 if len(conf
['commit_end']) > 0:
75 if end_only
or len(conf
['commit_begin']) == 0:
76 return conf
['commit_end']
77 return '%s..%s' % (conf
['commit_begin'], conf
['commit_end'])
80 def getkeyssortedbyvalues(dict):
81 return map(lambda el
: el
[1], sorted(map(lambda el
: (el
[1], el
[0]), dict.items())))
83 # dict['author'] = { 'commits': 512 } - ...key(dict, 'commits')
84 def getkeyssortedbyvaluekey(d
, key
):
85 return map(lambda el
: el
[1], sorted(map(lambda el
: (d
[el
][key
], el
), d
.keys())))
87 def getstatsummarycounts(line
):
88 numbers
= re
.findall('\d+', line
)
90 # neither insertions nor deletions: may probably only happen for "0 files changed"
93 elif len(numbers
) == 2 and line
.find('(+)') != -1:
94 numbers
.append(0); # only insertions were printed on line
95 elif len(numbers
) == 2 and line
.find('(-)') != -1:
96 numbers
.insert(1, 0); # only deletions were printed on line
103 gitstats_repo
= os
.path
.dirname(os
.path
.abspath(__file__
))
104 VERSION
= getpipeoutput(["git --git-dir=%s/.git --work-tree=%s rev-parse --short %s" %
105 (gitstats_repo
, gitstats_repo
, getcommitrange('HEAD').split('\n')[0])])
109 return getpipeoutput(['git --version']).split('\n')[0]
111 def getgnuplotversion():
112 return getpipeoutput(['%s --version' % gnuplot_cmd
]).split('\n')[0]
114 def getnumoffilesfromrev(time_rev
):
116 Get number of files changed in commit
119 return (int(time
), rev
, int(getpipeoutput(['git ls-tree -r --name-only "%s"' % rev
, 'wc -l']).split('\n')[0]))
121 def getnumoflinesinblob(ext_blob
):
123 Get number of lines in blob
125 ext
, blob_id
= ext_blob
126 return (ext
, blob_id
, int(getpipeoutput(['git cat-file blob %s' % blob_id
, 'wc -l']).split()[0]))
129 """Manages data collection from a revision control repository."""
131 self
.stamp_created
= time
.time()
133 self
.total_authors
= 0
134 self
.activity_by_hour_of_day
= {} # hour -> commits
135 self
.activity_by_day_of_week
= {} # day -> commits
136 self
.activity_by_month_of_year
= {} # month [1-12] -> commits
137 self
.activity_by_hour_of_week
= {} # weekday -> hour -> commits
138 self
.activity_by_hour_of_day_busiest
= 0
139 self
.activity_by_hour_of_week_busiest
= 0
140 self
.activity_by_year_week
= {} # yy_wNN -> commits
141 self
.activity_by_year_week_peak
= 0
143 self
.authors
= {} # name -> {commits, first_commit_stamp, last_commit_stamp, last_active_day, active_days, lines_added, lines_removed}
145 self
.total_commits
= 0
147 self
.authors_by_commits
= 0
150 self
.domains
= {} # domain -> commits
152 # author of the month
153 self
.author_of_month
= {} # month -> author -> commits
154 self
.author_of_year
= {} # year -> author -> commits
155 self
.commits_by_month
= {} # month -> commits
156 self
.commits_by_year
= {} # year -> commits
157 self
.lines_added_by_month
= {} # month -> lines added
158 self
.lines_added_by_year
= {} # year -> lines added
159 self
.lines_removed_by_month
= {} # month -> lines removed
160 self
.lines_removed_by_year
= {} # year -> lines removed
161 self
.first_commit_stamp
= 0
162 self
.last_commit_stamp
= 0
163 self
.last_active_day
= None
164 self
.active_days
= set()
168 self
.total_lines_added
= 0
169 self
.total_lines_removed
= 0
175 self
.commits_by_timezone
= {} # timezone -> commits
180 self
.files_by_stamp
= {} # stamp -> files
183 self
.extensions
= {} # extension -> files, lines
186 self
.changes_by_date
= {} # stamp -> { files, ins, del }
189 # This should be the main function to extract data from the repository.
190 def collect(self
, dir):
192 if len(conf
['project_name']) == 0:
193 self
.projectname
= os
.path
.basename(os
.path
.abspath(dir))
195 self
.projectname
= conf
['project_name']
198 # Load cacheable data
199 def loadCache(self
, cachefile
):
200 if not os
.path
.exists(cachefile
):
202 print 'Loading cache...'
203 f
= open(cachefile
, 'rb')
205 self
.cache
= pickle
.loads(zlib
.decompress(f
.read()))
207 # temporary hack to upgrade non-compressed caches
209 self
.cache
= pickle
.load(f
)
213 # Produce any additional statistics from the extracted data.
218 # : get a dictionary of author
219 def getAuthorInfo(self
, author
):
222 def getActivityByDayOfWeek(self
):
225 def getActivityByHourOfDay(self
):
228 # : get a dictionary of domains
229 def getDomainInfo(self
, domain
):
233 # Get a list of authors
234 def getAuthors(self
):
237 def getFirstCommitDate(self
):
238 return datetime
.datetime
.now()
240 def getLastCommitDate(self
):
241 return datetime
.datetime
.now()
243 def getStampCreated(self
):
244 return self
.stamp_created
249 def getTotalAuthors(self
):
252 def getTotalCommits(self
):
255 def getTotalFiles(self
):
258 def getTotalLOC(self
):
262 # Save cacheable data
263 def saveCache(self
, cachefile
):
264 print 'Saving cache...'
265 tempfile
= cachefile
+ '.tmp'
266 f
= open(tempfile
, 'wb')
267 #pickle.dump(self.cache, f)
268 data
= zlib
.compress(pickle
.dumps(self
.cache
))
275 os
.rename(tempfile
, cachefile
)
277 class GitDataCollector(DataCollector
):
278 def collect(self
, dir):
279 DataCollector
.collect(self
, dir)
281 self
.total_authors
+= int(getpipeoutput(['git shortlog -s %s' % getcommitrange(), 'wc -l']))
282 #self.total_lines = int(getoutput('git-ls-files -z |xargs -0 cat |wc -l'))
285 lines
= getpipeoutput(['git show-ref --tags']).split('\n')
289 (hash, tag
) = line
.split(' ')
291 tag
= tag
.replace('refs/tags/', '')
292 output
= getpipeoutput(['git log "%s" --pretty=format:"%%at %%aN" -n 1' % hash])
294 parts
= output
.split(' ')
297 stamp
= int(parts
[0])
300 self
.tags
[tag
] = { 'stamp': stamp
, 'hash' : hash, 'date' : datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), 'commits': 0, 'authors': {} }
302 # collect info on tags, starting from latest
303 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), self
.tags
.items()))))
305 for tag
in reversed(tags_sorted_by_date_desc
):
306 cmd
= 'git shortlog -s "%s"' % tag
308 cmd
+= ' "^%s"' % prev
309 output
= getpipeoutput([cmd
])
313 for line
in output
.split('\n'):
314 parts
= re
.split('\s+', line
, 2)
315 commits
= int(parts
[1])
317 if author
in conf
['merge_authors']:
318 author
= conf
['merge_authors'][author
]
319 self
.tags
[tag
]['commits'] += commits
320 self
.tags
[tag
]['authors'][author
] = commits
322 # Collect revision statistics
323 # Outputs "<stamp> <date> <time> <timezone> <author> '<' <mail> '>'"
324 lines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%ai %%aN <%%aE>" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).split('\n')
326 parts
= line
.split(' ', 4)
329 stamp
= int(parts
[0])
333 author
, mail
= parts
[4].split('<', 1)
334 author
= author
.rstrip()
335 if author
in conf
['merge_authors']:
336 author
= conf
['merge_authors'][author
]
337 mail
= mail
.rstrip('>')
339 if mail
.find('@') != -1:
340 domain
= mail
.rsplit('@', 1)[1]
341 date
= datetime
.datetime
.fromtimestamp(float(stamp
))
343 # First and last commit stamp (may be in any order because of cherry-picking and patches)
344 if stamp
> self
.last_commit_stamp
:
345 self
.last_commit_stamp
= stamp
346 if self
.first_commit_stamp
== 0 or stamp
< self
.first_commit_stamp
:
347 self
.first_commit_stamp
= stamp
352 self
.activity_by_hour_of_day
[hour
] = self
.activity_by_hour_of_day
.get(hour
, 0) + 1
354 if self
.activity_by_hour_of_day
[hour
] > self
.activity_by_hour_of_day_busiest
:
355 self
.activity_by_hour_of_day_busiest
= self
.activity_by_hour_of_day
[hour
]
359 self
.activity_by_day_of_week
[day
] = self
.activity_by_day_of_week
.get(day
, 0) + 1
362 if domain
not in self
.domains
:
363 self
.domains
[domain
] = {}
365 self
.domains
[domain
]['commits'] = self
.domains
[domain
].get('commits', 0) + 1
368 if day
not in self
.activity_by_hour_of_week
:
369 self
.activity_by_hour_of_week
[day
] = {}
370 self
.activity_by_hour_of_week
[day
][hour
] = self
.activity_by_hour_of_week
[day
].get(hour
, 0) + 1
372 if self
.activity_by_hour_of_week
[day
][hour
] > self
.activity_by_hour_of_week_busiest
:
373 self
.activity_by_hour_of_week_busiest
= self
.activity_by_hour_of_week
[day
][hour
]
377 self
.activity_by_month_of_year
[month
] = self
.activity_by_month_of_year
.get(month
, 0) + 1
379 # yearly/weekly activity
380 yyw
= date
.strftime('%Y-%W')
381 self
.activity_by_year_week
[yyw
] = self
.activity_by_year_week
.get(yyw
, 0) + 1
382 if self
.activity_by_year_week_peak
< self
.activity_by_year_week
[yyw
]:
383 self
.activity_by_year_week_peak
= self
.activity_by_year_week
[yyw
]
386 if author
not in self
.authors
:
387 self
.authors
[author
] = {}
388 # commits, note again that commits may be in any date order because of cherry-picking and patches
389 if 'last_commit_stamp' not in self
.authors
[author
]:
390 self
.authors
[author
]['last_commit_stamp'] = stamp
391 if stamp
> self
.authors
[author
]['last_commit_stamp']:
392 self
.authors
[author
]['last_commit_stamp'] = stamp
393 if 'first_commit_stamp' not in self
.authors
[author
]:
394 self
.authors
[author
]['first_commit_stamp'] = stamp
395 if stamp
< self
.authors
[author
]['first_commit_stamp']:
396 self
.authors
[author
]['first_commit_stamp'] = stamp
398 # author of the month/year
399 yymm
= date
.strftime('%Y-%m')
400 if yymm
in self
.author_of_month
:
401 self
.author_of_month
[yymm
][author
] = self
.author_of_month
[yymm
].get(author
, 0) + 1
403 self
.author_of_month
[yymm
] = {}
404 self
.author_of_month
[yymm
][author
] = 1
405 self
.commits_by_month
[yymm
] = self
.commits_by_month
.get(yymm
, 0) + 1
408 if yy
in self
.author_of_year
:
409 self
.author_of_year
[yy
][author
] = self
.author_of_year
[yy
].get(author
, 0) + 1
411 self
.author_of_year
[yy
] = {}
412 self
.author_of_year
[yy
][author
] = 1
413 self
.commits_by_year
[yy
] = self
.commits_by_year
.get(yy
, 0) + 1
415 # authors: active days
416 yymmdd
= date
.strftime('%Y-%m-%d')
417 if 'last_active_day' not in self
.authors
[author
]:
418 self
.authors
[author
]['last_active_day'] = yymmdd
419 self
.authors
[author
]['active_days'] = set([yymmdd
])
420 elif yymmdd
!= self
.authors
[author
]['last_active_day']:
421 self
.authors
[author
]['last_active_day'] = yymmdd
422 self
.authors
[author
]['active_days'].add(yymmdd
)
424 # project: active days
425 if yymmdd
!= self
.last_active_day
:
426 self
.last_active_day
= yymmdd
427 self
.active_days
.add(yymmdd
)
430 self
.commits_by_timezone
[timezone
] = self
.commits_by_timezone
.get(timezone
, 0) + 1
432 # outputs "<stamp> <files>" for each revision
433 revlines
= getpipeoutput(['git rev-list --pretty=format:"%%at %%T" %s' % getcommitrange('HEAD'), 'grep -v ^commit']).strip().split('\n')
437 #Look up rev in cache and take info from cache if found
438 #If not append rev to list of rev to read from repo
439 for revline
in revlines
:
440 time
, rev
= revline
.split(' ')
441 #if cache empty then add time and rev to list of new rev's
442 #otherwise try to read needed info from cache
443 if 'files_in_tree' not in self
.cache
.keys():
444 revs_to_read
.append((time
,rev
))
446 if rev
in self
.cache
['files_in_tree'].keys():
447 lines
.append('%d %d' % (int(time
), self
.cache
['files_in_tree'][rev
]))
449 revs_to_read
.append((time
,rev
))
451 #Read revisions from repo
452 time_rev_count
= Pool(processes
=conf
['processes']).map(getnumoffilesfromrev
, revs_to_read
)
454 #Update cache with new revisions and append then to general list
455 for (time
, rev
, count
) in time_rev_count
:
456 if 'files_in_tree' not in self
.cache
:
457 self
.cache
['files_in_tree'] = {}
458 self
.cache
['files_in_tree'][rev
] = count
459 lines
.append('%d %d' % (int(time
), count
))
461 self
.total_commits
+= len(lines
)
463 parts
= line
.split(' ')
466 (stamp
, files
) = parts
[0:2]
468 self
.files_by_stamp
[int(stamp
)] = int(files
)
470 print 'Warning: failed to parse line "%s"' % line
472 # extensions and size of files
473 lines
= getpipeoutput(['git ls-tree -r -l -z %s' % getcommitrange('HEAD', end_only
= True)]).split('\000')
478 parts
= re
.split('\s+', line
, 5)
479 if parts
[0] == '160000' and parts
[3] == '-':
486 self
.total_size
+= size
487 self
.total_files
+= 1
489 filename
= fullpath
.split('/')[-1] # strip directories
490 if filename
.find('.') == -1 or filename
.rfind('.') == 0:
493 ext
= filename
[(filename
.rfind('.') + 1):]
494 if len(ext
) > conf
['max_ext_length']:
496 if ext
not in self
.extensions
:
497 self
.extensions
[ext
] = {'files': 0, 'lines': 0}
498 self
.extensions
[ext
]['files'] += 1
499 #if cache empty then add ext and blob id to list of new blob's
500 #otherwise try to read needed info from cache
501 if 'lines_in_blob' not in self
.cache
.keys():
502 blobs_to_read
.append((ext
,blob_id
))
504 if blob_id
in self
.cache
['lines_in_blob'].keys():
505 self
.extensions
[ext
]['lines'] += self
.cache
['lines_in_blob'][blob_id
]
507 blobs_to_read
.append((ext
,blob_id
))
509 #Get info abount line count for new blob's that wasn't found in cache
510 ext_blob_linecount
= Pool(processes
=conf
['processes']).map(getnumoflinesinblob
, blobs_to_read
)
512 #Update cache and write down info about number of number of lines
513 for (ext
, blob_id
, linecount
) in ext_blob_linecount
:
514 if 'lines_in_blob' not in self
.cache
:
515 self
.cache
['lines_in_blob'] = {}
516 self
.cache
['lines_in_blob'][blob_id
] = linecount
517 self
.extensions
[ext
]['lines'] += self
.cache
['lines_in_blob'][blob_id
]
521 # N files changed, N insertions (+), N deletions(-)
523 self
.changes_by_date
= {} # stamp -> { files, ins, del }
524 # computation of lines of code by date is better done
525 # on a linear history.
527 if conf
['linear_linestats']:
528 extra
= '--first-parent -m'
529 lines
= getpipeoutput(['git log --shortstat %s --pretty=format:"%%at %%aN" %s' % (extra
, getcommitrange('HEAD'))]).split('\n')
531 files
= 0; inserted
= 0; deleted
= 0; total_lines
= 0
538 if re
.search('files? changed', line
) == None:
542 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
543 if author
in conf
['merge_authors']:
544 author
= conf
['merge_authors'][author
]
545 self
.changes_by_date
[stamp
] = { 'files': files
, 'ins': inserted
, 'del': deleted
, 'lines': total_lines
}
547 date
= datetime
.datetime
.fromtimestamp(stamp
)
548 yymm
= date
.strftime('%Y-%m')
549 self
.lines_added_by_month
[yymm
] = self
.lines_added_by_month
.get(yymm
, 0) + inserted
550 self
.lines_removed_by_month
[yymm
] = self
.lines_removed_by_month
.get(yymm
, 0) + deleted
553 self
.lines_added_by_year
[yy
] = self
.lines_added_by_year
.get(yy
,0) + inserted
554 self
.lines_removed_by_year
[yy
] = self
.lines_removed_by_year
.get(yy
, 0) + deleted
556 files
, inserted
, deleted
= 0, 0, 0
558 print 'Warning: unexpected line "%s"' % line
560 print 'Warning: unexpected line "%s"' % line
562 numbers
= getstatsummarycounts(line
)
564 if len(numbers
) == 3:
565 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
566 total_lines
+= inserted
567 total_lines
-= deleted
568 self
.total_lines_added
+= inserted
569 self
.total_lines_removed
+= deleted
572 print 'Warning: failed to handle line "%s"' % line
573 (files
, inserted
, deleted
) = (0, 0, 0)
574 #self.changes_by_date[stamp] = { 'files': files, 'ins': inserted, 'del': deleted }
575 self
.total_lines
+= total_lines
577 # Per-author statistics
579 # defined for stamp, author only if author commited at this timestamp.
580 self
.changes_by_date_by_author
= {} # stamp -> author -> lines_added
582 # Similar to the above, but never use --first-parent
583 # (we need to walk through every commit to know who
584 # committed what, not just through mainline)
585 lines
= getpipeoutput(['git log --shortstat --date-order --pretty=format:"%%at %%aN" %s' % (getcommitrange('HEAD'))]).split('\n')
587 files
= 0; inserted
= 0; deleted
= 0
595 if re
.search('files? changed', line
) == None:
600 (stamp
, author
) = (int(line
[:pos
]), line
[pos
+1:])
601 if author
in conf
['merge_authors']:
602 author
= conf
['merge_authors'][author
]
604 # clock skew, keep old timestamp to avoid having ugly graph
606 if author
not in self
.authors
:
607 self
.authors
[author
] = { 'lines_added' : 0, 'lines_removed' : 0, 'commits' : 0}
608 self
.authors
[author
]['commits'] = self
.authors
[author
].get('commits', 0) + 1
609 self
.authors
[author
]['lines_added'] = self
.authors
[author
].get('lines_added', 0) + inserted
610 self
.authors
[author
]['lines_removed'] = self
.authors
[author
].get('lines_removed', 0) + deleted
611 if stamp
not in self
.changes_by_date_by_author
:
612 self
.changes_by_date_by_author
[stamp
] = {}
613 if author
not in self
.changes_by_date_by_author
[stamp
]:
614 self
.changes_by_date_by_author
[stamp
][author
] = {}
615 self
.changes_by_date_by_author
[stamp
][author
]['lines_added'] = self
.authors
[author
]['lines_added']
616 self
.changes_by_date_by_author
[stamp
][author
]['commits'] = self
.authors
[author
]['commits']
617 files
, inserted
, deleted
= 0, 0, 0
619 print 'Warning: unexpected line "%s"' % line
621 print 'Warning: unexpected line "%s"' % line
623 numbers
= getstatsummarycounts(line
);
625 if len(numbers
) == 3:
626 (files
, inserted
, deleted
) = map(lambda el
: int(el
), numbers
)
628 print 'Warning: failed to handle line "%s"' % line
629 (files
, inserted
, deleted
) = (0, 0, 0)
633 # name -> {place_by_commits, commits_frac, date_first, date_last, timedelta}
634 self
.authors_by_commits
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
635 self
.authors_by_commits
.reverse() # most first
636 for i
, name
in enumerate(self
.authors_by_commits
):
637 self
.authors
[name
]['place_by_commits'] = i
+ 1
639 for name
in self
.authors
.keys():
640 a
= self
.authors
[name
]
641 a
['commits_frac'] = (100 * float(a
['commits'])) / self
.getTotalCommits()
642 date_first
= datetime
.datetime
.fromtimestamp(a
['first_commit_stamp'])
643 date_last
= datetime
.datetime
.fromtimestamp(a
['last_commit_stamp'])
644 delta
= date_last
- date_first
645 a
['date_first'] = date_first
.strftime('%Y-%m-%d')
646 a
['date_last'] = date_last
.strftime('%Y-%m-%d')
647 a
['timedelta'] = delta
648 if 'lines_added' not in a
: a
['lines_added'] = 0
649 if 'lines_removed' not in a
: a
['lines_removed'] = 0
651 def getActiveDays(self
):
652 return self
.active_days
654 def getActivityByDayOfWeek(self
):
655 return self
.activity_by_day_of_week
657 def getActivityByHourOfDay(self
):
658 return self
.activity_by_hour_of_day
660 def getAuthorInfo(self
, author
):
661 return self
.authors
[author
]
663 def getAuthors(self
, limit
= None):
664 res
= getkeyssortedbyvaluekey(self
.authors
, 'commits')
668 def getCommitDeltaDays(self
):
669 return (self
.last_commit_stamp
/ 86400 - self
.first_commit_stamp
/ 86400) + 1
671 def getDomainInfo(self
, domain
):
672 return self
.domains
[domain
]
674 def getDomains(self
):
675 return self
.domains
.keys()
677 def getFirstCommitDate(self
):
678 return datetime
.datetime
.fromtimestamp(self
.first_commit_stamp
)
680 def getLastCommitDate(self
):
681 return datetime
.datetime
.fromtimestamp(self
.last_commit_stamp
)
684 lines
= getpipeoutput(['git show-ref --tags', 'cut -d/ -f3'])
685 return lines
.split('\n')
687 def getTagDate(self
, tag
):
688 return self
.revToDate('tags/' + tag
)
690 def getTotalAuthors(self
):
691 return self
.total_authors
693 def getTotalCommits(self
):
694 return self
.total_commits
696 def getTotalFiles(self
):
697 return self
.total_files
699 def getTotalLOC(self
):
700 return self
.total_lines
702 def getTotalSize(self
):
703 return self
.total_size
705 def revToDate(self
, rev
):
706 stamp
= int(getpipeoutput(['git log --pretty=format:%%at "%s" -n 1' % rev
]))
707 return datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d')
710 """Creates the actual report based on given data."""
714 def create(self
, data
, path
):
718 def html_linkify(text
):
719 return text
.lower().replace(' ', '_')
721 def html_header(level
, text
):
722 name
= html_linkify(text
)
723 return '\n<h%d><a href="#%s" name="%s">%s</a></h%d>\n\n' % (level
, name
, name
, text
, level
)
725 class HTMLReportCreator(ReportCreator
):
726 def create(self
, data
, path
):
727 ReportCreator
.create(self
, data
, path
)
728 self
.title
= data
.projectname
730 # copy static files. Looks in the binary directory, ../share/gitstats and /usr/share/gitstats
731 binarypath
= os
.path
.dirname(os
.path
.abspath(__file__
))
732 secondarypath
= os
.path
.join(binarypath
, '..', 'share', 'gitstats')
733 basedirs
= [binarypath
, secondarypath
, '/usr/share/gitstats']
734 for file in ('gitstats.css', 'sortable.js', 'arrow-up.gif', 'arrow-down.gif', 'arrow-none.gif'):
735 for base
in basedirs
:
736 src
= base
+ '/' + file
737 if os
.path
.exists(src
):
738 shutil
.copyfile(src
, path
+ '/' + file)
741 print 'Warning: "%s" not found, so not copied (searched: %s)' % (file, basedirs
)
743 f
= open(path
+ "/index.html", 'w')
744 format
= '%Y-%m-%d %H:%M:%S'
747 f
.write('<h1>GitStats - %s</h1>' % data
.projectname
)
752 f
.write('<dt>Project name</dt><dd>%s</dd>' % (data
.projectname
))
753 f
.write('<dt>Generated</dt><dd>%s (in %d seconds)</dd>' % (datetime
.datetime
.now().strftime(format
), time
.time() - data
.getStampCreated()))
754 f
.write('<dt>Generator</dt><dd><a href="http://gitstats.sourceforge.net/">GitStats</a> (version %s), %s, %s</dd>' % (getversion(), getgitversion(), getgnuplotversion()))
755 f
.write('<dt>Report Period</dt><dd>%s to %s</dd>' % (data
.getFirstCommitDate().strftime(format
), data
.getLastCommitDate().strftime(format
)))
756 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())))
757 f
.write('<dt>Total Files</dt><dd>%s</dd>' % data
.getTotalFiles())
758 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
))
759 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()))
760 f
.write('<dt>Authors</dt><dd>%s (average %.1f commits per author)</dd>' % (data
.getTotalAuthors(), (1.0 * data
.getTotalCommits()) / data
.getTotalAuthors()))
763 f
.write('</body>\n</html>')
768 f
= open(path
+ '/activity.html', 'w')
770 f
.write('<h1>Activity</h1>')
773 #f.write('<h2>Last 30 days</h2>')
775 #f.write('<h2>Last 12 months</h2>')
779 f
.write(html_header(2, 'Weekly activity'))
780 f
.write('<p>Last %d weeks</p>' % WEEKS
)
782 # generate weeks to show (previous N weeks from now)
783 now
= datetime
.datetime
.now()
784 deltaweek
= datetime
.timedelta(7)
787 for i
in range(0, WEEKS
):
788 weeks
.insert(0, stampcur
.strftime('%Y-%W'))
789 stampcur
-= deltaweek
791 # top row: commits & bar
792 f
.write('<table class="noborders"><tr>')
793 for i
in range(0, WEEKS
):
795 if weeks
[i
] in data
.activity_by_year_week
:
796 commits
= data
.activity_by_year_week
[weeks
[i
]]
799 if weeks
[i
] in data
.activity_by_year_week
:
800 percentage
= float(data
.activity_by_year_week
[weeks
[i
]]) / data
.activity_by_year_week_peak
801 height
= max(1, int(200 * percentage
))
802 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
))
804 # bottom row: year/week
806 for i
in range(0, WEEKS
):
807 f
.write('<td>%s</td>' % (WEEKS
- i
))
808 f
.write('</tr></table>')
811 f
.write(html_header(2, 'Hour of Day'))
812 hour_of_day
= data
.getActivityByHourOfDay()
813 f
.write('<table><tr><th>Hour</th>')
814 for i
in range(0, 24):
815 f
.write('<th>%d</th>' % i
)
816 f
.write('</tr>\n<tr><th>Commits</th>')
817 fp
= open(path
+ '/hour_of_day.dat', 'w')
818 for i
in range(0, 24):
820 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
821 f
.write('<td style="background-color: rgb(%d, 0, 0)">%d</td>' % (r
, hour_of_day
[i
]))
822 fp
.write('%d %d\n' % (i
, hour_of_day
[i
]))
824 f
.write('<td>0</td>')
825 fp
.write('%d 0\n' % i
)
827 f
.write('</tr>\n<tr><th>%</th>')
828 totalcommits
= data
.getTotalCommits()
829 for i
in range(0, 24):
831 r
= 127 + int((float(hour_of_day
[i
]) / data
.activity_by_hour_of_day_busiest
) * 128)
832 f
.write('<td style="background-color: rgb(%d, 0, 0)">%.2f</td>' % (r
, (100.0 * hour_of_day
[i
]) / totalcommits
))
834 f
.write('<td>0.00</td>')
835 f
.write('</tr></table>')
836 f
.write('<img src="hour_of_day.png" alt="Hour of Day" />')
837 fg
= open(path
+ '/hour_of_day.dat', 'w')
838 for i
in range(0, 24):
840 fg
.write('%d %d\n' % (i
+ 1, hour_of_day
[i
]))
842 fg
.write('%d 0\n' % (i
+ 1))
846 f
.write(html_header(2, 'Day of Week'))
847 day_of_week
= data
.getActivityByDayOfWeek()
848 f
.write('<div class="vtable"><table>')
849 f
.write('<tr><th>Day</th><th>Total (%)</th></tr>')
850 fp
= open(path
+ '/day_of_week.dat', 'w')
851 for d
in range(0, 7):
854 commits
= day_of_week
[d
]
855 fp
.write('%d %s %d\n' % (d
+ 1, WEEKDAYS
[d
], commits
))
857 f
.write('<th>%s</th>' % (WEEKDAYS
[d
]))
859 f
.write('<td>%d (%.2f%%)</td>' % (day_of_week
[d
], (100.0 * day_of_week
[d
]) / totalcommits
))
861 f
.write('<td>0</td>')
863 f
.write('</table></div>')
864 f
.write('<img src="day_of_week.png" alt="Day of Week" />')
868 f
.write(html_header(2, 'Hour of Week'))
871 f
.write('<tr><th>Weekday</th>')
872 for hour
in range(0, 24):
873 f
.write('<th>%d</th>' % (hour
))
876 for weekday
in range(0, 7):
877 f
.write('<tr><th>%s</th>' % (WEEKDAYS
[weekday
]))
878 for hour
in range(0, 24):
880 commits
= data
.activity_by_hour_of_week
[weekday
][hour
]
885 r
= 127 + int((float(commits
) / data
.activity_by_hour_of_week_busiest
) * 128)
886 f
.write(' style="background-color: rgb(%d, 0, 0)"' % r
)
887 f
.write('>%d</td>' % commits
)
895 f
.write(html_header(2, 'Month of Year'))
896 f
.write('<div class="vtable"><table>')
897 f
.write('<tr><th>Month</th><th>Commits (%)</th></tr>')
898 fp
= open (path
+ '/month_of_year.dat', 'w')
899 for mm
in range(1, 13):
901 if mm
in data
.activity_by_month_of_year
:
902 commits
= data
.activity_by_month_of_year
[mm
]
903 f
.write('<tr><td>%d</td><td>%d (%.2f %%)</td></tr>' % (mm
, commits
, (100.0 * commits
) / data
.getTotalCommits()))
904 fp
.write('%d %d\n' % (mm
, commits
))
906 f
.write('</table></div>')
907 f
.write('<img src="month_of_year.png" alt="Month of Year" />')
909 # Commits by year/month
910 f
.write(html_header(2, 'Commits by year/month'))
911 f
.write('<div class="vtable"><table><tr><th>Month</th><th>Commits</th><th>Lines added</th><th>Lines removed</th></tr>')
912 for yymm
in reversed(sorted(data
.commits_by_month
.keys())):
913 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)))
914 f
.write('</table></div>')
915 f
.write('<img src="commits_by_year_month.png" alt="Commits by year/month" />')
916 fg
= open(path
+ '/commits_by_year_month.dat', 'w')
917 for yymm
in sorted(data
.commits_by_month
.keys()):
918 fg
.write('%s %s\n' % (yymm
, data
.commits_by_month
[yymm
]))
922 f
.write(html_header(2, 'Commits by Year'))
923 f
.write('<div class="vtable"><table><tr><th>Year</th><th>Commits (% of all)</th><th>Lines added</th><th>Lines removed</th></tr>')
924 for yy
in reversed(sorted(data
.commits_by_year
.keys())):
925 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)))
926 f
.write('</table></div>')
927 f
.write('<img src="commits_by_year.png" alt="Commits by Year" />')
928 fg
= open(path
+ '/commits_by_year.dat', 'w')
929 for yy
in sorted(data
.commits_by_year
.keys()):
930 fg
.write('%d %d\n' % (yy
, data
.commits_by_year
[yy
]))
933 # Commits by timezone
934 f
.write(html_header(2, 'Commits by Timezone'))
935 f
.write('<table><tr>')
936 f
.write('<th>Timezone</th><th>Commits</th>')
937 max_commits_on_tz
= max(data
.commits_by_timezone
.values())
938 for i
in sorted(data
.commits_by_timezone
.keys(), key
= lambda n
: int(n
)):
939 commits
= data
.commits_by_timezone
[i
]
940 r
= 127 + int((float(commits
) / max_commits_on_tz
) * 128)
941 f
.write('<tr><th>%s</th><td style="background-color: rgb(%d, 0, 0)">%d</td></tr>' % (i
, r
, commits
))
942 f
.write('</tr></table>')
944 f
.write('</body></html>')
949 f
= open(path
+ '/authors.html', 'w')
952 f
.write('<h1>Authors</h1>')
955 # Authors :: List of authors
956 f
.write(html_header(2, 'List of Authors'))
958 f
.write('<table class="authors sortable" id="authors">')
959 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>')
960 for author
in data
.getAuthors(conf
['max_authors']):
961 info
= data
.getAuthorInfo(author
)
962 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']))
965 allauthors
= data
.getAuthors()
966 if len(allauthors
) > conf
['max_authors']:
967 rest
= allauthors
[conf
['max_authors']:]
968 f
.write('<p class="moreauthors">These didn\'t make it to the top: %s</p>' % ', '.join(rest
))
970 f
.write(html_header(2, 'Cumulated Added Lines of Code per Author'))
971 f
.write('<img src="lines_of_code_by_author.png" alt="Lines of code per Author" />')
972 if len(allauthors
) > conf
['max_authors']:
973 f
.write('<p class="moreauthors">Only top %d authors shown</p>' % conf
['max_authors'])
975 f
.write(html_header(2, 'Commits per Author'))
976 f
.write('<img src="commits_by_author.png" alt="Commits per Author" />')
977 if len(allauthors
) > conf
['max_authors']:
978 f
.write('<p class="moreauthors">Only top %d authors shown</p>' % conf
['max_authors'])
980 fgl
= open(path
+ '/lines_of_code_by_author.dat', 'w')
981 fgc
= open(path
+ '/commits_by_author.dat', 'w')
983 lines_by_authors
= {} # cumulated added lines by
984 # author. to save memory,
985 # changes_by_date_by_author[stamp][author] is defined
986 # only at points where author commits.
987 # lines_by_authors allows us to generate all the
988 # points in the .dat file.
990 # Don't rely on getAuthors to give the same order each
991 # time. Be robust and keep the list in a variable.
992 commits_by_authors
= {} # cumulated added lines by
994 self
.authors_to_plot
= data
.getAuthors(conf
['max_authors'])
995 for author
in self
.authors_to_plot
:
996 lines_by_authors
[author
] = 0
997 commits_by_authors
[author
] = 0
998 for stamp
in sorted(data
.changes_by_date_by_author
.keys()):
999 fgl
.write('%d' % stamp
)
1000 fgc
.write('%d' % stamp
)
1001 for author
in self
.authors_to_plot
:
1002 if author
in data
.changes_by_date_by_author
[stamp
].keys():
1003 lines_by_authors
[author
] = data
.changes_by_date_by_author
[stamp
][author
]['lines_added']
1004 commits_by_authors
[author
] = data
.changes_by_date_by_author
[stamp
][author
]['commits']
1005 fgl
.write(' %d' % lines_by_authors
[author
])
1006 fgc
.write(' %d' % commits_by_authors
[author
])
1012 # Authors :: Author of Month
1013 f
.write(html_header(2, 'Author of Month'))
1014 f
.write('<table class="sortable" id="aom">')
1015 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'])
1016 for yymm
in reversed(sorted(data
.author_of_month
.keys())):
1017 authordict
= data
.author_of_month
[yymm
]
1018 authors
= getkeyssortedbyvalues(authordict
)
1020 commits
= data
.author_of_month
[yymm
][authors
[0]]
1021 next
= ', '.join(authors
[1:conf
['authors_top']+1])
1022 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
)))
1026 f
.write(html_header(2, 'Author of Year'))
1027 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'])
1028 for yy
in reversed(sorted(data
.author_of_year
.keys())):
1029 authordict
= data
.author_of_year
[yy
]
1030 authors
= getkeyssortedbyvalues(authordict
)
1032 commits
= data
.author_of_year
[yy
][authors
[0]]
1033 next
= ', '.join(authors
[1:conf
['authors_top']+1])
1034 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
)))
1038 f
.write(html_header(2, 'Commits by Domains'))
1039 domains_by_commits
= getkeyssortedbyvaluekey(data
.domains
, 'commits')
1040 domains_by_commits
.reverse() # most first
1041 f
.write('<div class="vtable"><table>')
1042 f
.write('<tr><th>Domains</th><th>Total (%)</th></tr>')
1043 fp
= open(path
+ '/domains.dat', 'w')
1045 for domain
in domains_by_commits
:
1046 if n
== conf
['max_domains']:
1050 info
= data
.getDomainInfo(domain
)
1051 fp
.write('%s %d %d\n' % (domain
, n
, info
['commits']))
1052 f
.write('<tr><th>%s</th><td>%d (%.2f%%)</td></tr>' % (domain
, info
['commits'], (100.0 * info
['commits'] / totalcommits
)))
1053 f
.write('</table></div>')
1054 f
.write('<img src="domains.png" alt="Commits by Domains" />')
1057 f
.write('</body></html>')
1062 f
= open(path
+ '/files.html', 'w')
1064 f
.write('<h1>Files</h1>')
1068 f
.write('<dt>Total files</dt><dd>%d</dd>' % data
.getTotalFiles())
1069 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
1071 f
.write('<dt>Average file size</dt><dd>%.2f bytes</dd>' % (float(data
.getTotalSize()) / data
.getTotalFiles()))
1072 except ZeroDivisionError:
1076 # Files :: File count by date
1077 f
.write(html_header(2, 'File count by date'))
1079 # use set to get rid of duplicate/unnecessary entries
1080 files_by_date
= set()
1081 for stamp
in sorted(data
.files_by_stamp
.keys()):
1082 files_by_date
.add('%s %d' % (datetime
.datetime
.fromtimestamp(stamp
).strftime('%Y-%m-%d'), data
.files_by_stamp
[stamp
]))
1084 fg
= open(path
+ '/files_by_date.dat', 'w')
1085 for line
in sorted(list(files_by_date
)):
1086 fg
.write('%s\n' % line
)
1087 #for stamp in sorted(data.files_by_stamp.keys()):
1088 # fg.write('%s %d\n' % (datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d'), data.files_by_stamp[stamp]))
1091 f
.write('<img src="files_by_date.png" alt="Files by Date" />')
1093 #f.write('<h2>Average file size by date</h2>')
1095 # Files :: Extensions
1096 f
.write(html_header(2, 'Extensions'))
1097 f
.write('<table class="sortable" id="ext"><tr><th>Extension</th><th>Files (%)</th><th>Lines (%)</th><th>Lines/file</th></tr>')
1098 for ext
in sorted(data
.extensions
.keys()):
1099 files
= data
.extensions
[ext
]['files']
1100 lines
= data
.extensions
[ext
]['lines']
1102 loc_percentage
= (100.0 * lines
) / data
.getTotalLOC()
1103 except ZeroDivisionError:
1105 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
))
1108 f
.write('</body></html>')
1113 f
= open(path
+ '/lines.html', 'w')
1115 f
.write('<h1>Lines</h1>')
1119 f
.write('<dt>Total lines</dt><dd>%d</dd>' % data
.getTotalLOC())
1122 f
.write(html_header(2, 'Lines of Code'))
1123 f
.write('<img src="lines_of_code.png" />')
1125 fg
= open(path
+ '/lines_of_code.dat', 'w')
1126 for stamp
in sorted(data
.changes_by_date
.keys()):
1127 fg
.write('%d %d\n' % (stamp
, data
.changes_by_date
[stamp
]['lines']))
1130 f
.write('</body></html>')
1135 f
= open(path
+ '/tags.html', 'w')
1137 f
.write('<h1>Tags</h1>')
1141 f
.write('<dt>Total tags</dt><dd>%d</dd>' % len(data
.tags
))
1142 if len(data
.tags
) > 0:
1143 f
.write('<dt>Average commits per tag</dt><dd>%.2f</dd>' % (1.0 * data
.getTotalCommits() / len(data
.tags
)))
1146 f
.write('<table class="tags">')
1147 f
.write('<tr><th>Name</th><th>Date</th><th>Commits</th><th>Authors</th></tr>')
1148 # sort the tags by date desc
1149 tags_sorted_by_date_desc
= map(lambda el
: el
[1], reversed(sorted(map(lambda el
: (el
[1]['date'], el
[0]), data
.tags
.items()))))
1150 for tag
in tags_sorted_by_date_desc
:
1152 self
.authors_by_commits
= getkeyssortedbyvalues(data
.tags
[tag
]['authors'])
1153 for i
in reversed(self
.authors_by_commits
):
1154 authorinfo
.append('%s (%d)' % (i
, data
.tags
[tag
]['authors'][i
]))
1155 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
)))
1158 f
.write('</body></html>')
1161 self
.createGraphs(path
)
1163 def createGraphs(self
, path
):
1164 print 'Generating graphs...'
1167 f
= open(path
+ '/hour_of_day.plot', 'w')
1168 f
.write(GNUPLOT_COMMON
)
1171 set output 'hour_of_day.png'
1173 set xrange [0.5:24.5]
1177 set ylabel "Commits"
1178 plot 'hour_of_day.dat' using 1:2:(0.5) w boxes fs solid
1183 f
= open(path
+ '/day_of_week.plot', 'w')
1184 f
.write(GNUPLOT_COMMON
)
1187 set output 'day_of_week.png'
1189 set xrange [0.5:7.5]
1193 set ylabel "Commits"
1194 plot 'day_of_week.dat' using 1:3:(0.5):xtic(2) w boxes fs solid
1199 f
= open(path
+ '/domains.plot', 'w')
1200 f
.write(GNUPLOT_COMMON
)
1203 set output 'domains.png'
1208 set ylabel "Commits"
1209 plot 'domains.dat' using 2:3:(0.5) with boxes fs solid, '' using 2:3:1 with labels rotate by 45 offset 0,1
1214 f
= open(path
+ '/month_of_year.plot', 'w')
1215 f
.write(GNUPLOT_COMMON
)
1218 set output 'month_of_year.png'
1220 set xrange [0.5:12.5]
1224 set ylabel "Commits"
1225 plot 'month_of_year.dat' using 1:2:(0.5) w boxes fs solid
1229 # commits_by_year_month
1230 f
= open(path
+ '/commits_by_year_month.plot', 'w')
1231 f
.write(GNUPLOT_COMMON
)
1234 set output 'commits_by_year_month.png'
1239 set format x "%Y-%m"
1243 set ylabel "Commits"
1244 plot 'commits_by_year_month.dat' using 1:2:(0.5) w boxes fs solid
1249 f
= open(path
+ '/commits_by_year.plot', 'w')
1250 f
.write(GNUPLOT_COMMON
)
1253 set output 'commits_by_year.png'
1258 set ylabel "Commits"
1260 plot 'commits_by_year.dat' using 1:2:(0.5) w boxes fs solid
1265 f
= open(path
+ '/files_by_date.plot', 'w')
1266 f
.write(GNUPLOT_COMMON
)
1269 set output 'files_by_date.png'
1273 set timefmt "%Y-%m-%d"
1274 set format x "%Y-%m-%d"
1280 plot 'files_by_date.dat' using 1:2 w steps
1285 f
= open(path
+ '/lines_of_code.plot', 'w')
1286 f
.write(GNUPLOT_COMMON
)
1289 set output 'lines_of_code.png'
1294 set format x "%Y-%m-%d"
1299 plot 'lines_of_code.dat' using 1:2 w lines
1303 # Lines of Code Added per author
1304 f
= open(path
+ '/lines_of_code_by_author.plot', 'w')
1305 f
.write(GNUPLOT_COMMON
)
1308 set terminal png transparent size 640,480
1309 set output 'lines_of_code_by_author.png'
1314 set format x "%Y-%m-%d"
1323 for a
in self
.authors_to_plot
:
1325 author
= a
.replace("\"", "\\\"").replace("`", "")
1326 plots
.append("""'lines_of_code_by_author.dat' using 1:%d title "%s" w lines""" % (i
, author
))
1327 f
.write(", ".join(plots
))
1332 # Commits per author
1333 f
= open(path
+ '/commits_by_author.plot', 'w')
1334 f
.write(GNUPLOT_COMMON
)
1337 set terminal png transparent size 640,480
1338 set output 'commits_by_author.png'
1343 set format x "%Y-%m-%d"
1345 set ylabel "Commits"
1352 for a
in self
.authors_to_plot
:
1354 author
= a
.replace("\"", "\\\"").replace("`", "")
1355 plots
.append("""'commits_by_author.dat' using 1:%d title "%s" w lines""" % (i
, author
))
1356 f
.write(", ".join(plots
))
1362 files
= glob
.glob(path
+ '/*.plot')
1364 out
= getpipeoutput([gnuplot_cmd
+ ' "%s"' % f
])
1368 def printHeader(self
, f
, title
= ''):
1370 """<?xml version="1.0" encoding="UTF-8"?>
1371 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1372 <html xmlns="http://www.w3.org/1999/xhtml">
1374 <title>GitStats - %s</title>
1375 <link rel="stylesheet" href="%s" type="text/css" />
1376 <meta name="generator" content="GitStats %s" />
1377 <script type="text/javascript" src="sortable.js"></script>
1380 """ % (self
.title
, conf
['style'], getversion()))
1382 def printNav(self
, f
):
1386 <li><a href="index.html">General</a></li>
1387 <li><a href="activity.html">Activity</a></li>
1388 <li><a href="authors.html">Authors</a></li>
1389 <li><a href="files.html">Files</a></li>
1390 <li><a href="lines.html">Lines</a></li>
1391 <li><a href="tags.html">Tags</a></li>
1398 Usage: gitstats [options] <gitpath..> <outputpath>
1401 -c key=value Override configuration value
1403 Default config values:
1406 Please see the manual page for more details.
1411 def run(self
, args_orig
):
1412 optlist
, args
= getopt
.getopt(args_orig
, 'hc:', ["help"])
1415 key
, value
= v
.split('=', 1)
1417 raise KeyError('no such key "%s" in config' % key
)
1418 if isinstance(conf
[key
], int):
1419 conf
[key
] = int(value
)
1420 elif isinstance(conf
[key
], dict):
1421 kk
,vv
= value
.split(',', 1)
1425 elif o
in ('-h', '--help'):
1433 outputpath
= os
.path
.abspath(args
[-1])
1434 rundir
= os
.getcwd()
1437 os
.makedirs(outputpath
)
1440 if not os
.path
.isdir(outputpath
):
1441 print 'FATAL: Output path is not a directory or does not exist'
1444 if not getgnuplotversion():
1445 print 'gnuplot not found'
1448 print 'Output path: %s' % outputpath
1449 cachefile
= os
.path
.join(outputpath
, 'gitstats.cache')
1451 data
= GitDataCollector()
1452 data
.loadCache(cachefile
)
1454 for gitpath
in args
[0:-1]:
1455 print 'Git path: %s' % gitpath
1459 print 'Collecting data...'
1460 data
.collect(gitpath
)
1462 print 'Refining data...'
1463 data
.saveCache(cachefile
)
1468 print 'Generating report...'
1469 report
= HTMLReportCreator()
1470 report
.create(data
, outputpath
)
1472 time_end
= time
.time()
1473 exectime_internal
= time_end
- time_start
1474 print 'Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (exectime_internal
, exectime_external
, (100.0 * exectime_external
) / exectime_internal
)
1475 if sys
.stdin
.isatty():
1476 print 'You may now run:'
1478 print ' sensible-browser \'%s\'' % os
.path
.join(outputpath
, 'index.html').replace("'", "'\\''")
1481 if __name__
=='__main__':