-
Notifications
You must be signed in to change notification settings - Fork 1
/
code-age.py
2427 lines (1932 loc) · 91.1 KB
/
code-age.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Analyzes code age in a git repository
Writes reports in the following locations
e.g. For repository "cpython"
[root] Defaults to ~/git.stats
├── cpython Directory for https://github.com/python/cpython.git
│ └── reports
│ ├── 2011-03-06.d68ed6fc.2_0 Revision `d68ed6fc` which was created on 2011-03-06 on
│ │ │ branch `2.0`.
│ │ └── __c.__cpp.__h Report on *.c, *.cpp and *.h files in this revision
│ │ ├── Guido_van_Rossum Sub-report on author `Guido van Rossum`
│ │ │ ├── code-age.png Graph of code age. LoC / day vs date
│ │ │ ├── code-age.txt List of commits in the peaks in the code-age.png graph
│ │ │ ├── details.csv LoC in each directory in for these files and authors
│ │ │ ├── newest-commits.txt List of newest commits for these files and authors
│ │ │ └── oldest-commits.txt List of oldest commits for these files and authors
"""
from __future__ import division, print_function
import subprocess
from subprocess import CalledProcessError
from collections import defaultdict, Counter
import sys
import time
import re
import os
import stat
import glob
import errno
import numpy as np
from scipy import signal
import pandas as pd
from pandas import Series, DataFrame, Timestamp
import matplotlib
import matplotlib.pylab as plt
from matplotlib.pylab import cycler
import bz2
from multiprocessing import Pool, cpu_count
from multiprocessing.pool import ThreadPool
import pygments
from pygments import lex
from pygments.token import Text, Comment, Punctuation, Literal
from pygments.lexers import guess_lexer_for_filename
# Python 2 / 3 stuff
PY2 = sys.version_info[0] < 3
try:
import cPickle as pickle
except ImportError:
import pickle
try:
reload(sys)
sys.setdefaultencoding('utf-8')
except:
pass
#
# Configuration.
#
CACHE_FILE_VERSION = 3 # Update when making incompatible changes to cache file format
TIMEZONE = 'Australia/Melbourne' # The timezone used for all commit times. TODO Make configurable
SHA_LEN = 8 # The number of characters used when displaying git SHA-1 hashes
STRICT_CHECKING = False # For validating code.
N_BLAME_PROCESSES = max(1, cpu_count() - 1) # Number of processes to use for blaming
N_SHOW_THREADS = 8 # Number of threads for running the many git show commands
DO_MULTIPROCESSING = True # For test non-threaded performance
# Set graphing style
matplotlib.style.use('ggplot')
plt.rcParams['axes.prop_cycle'] = cycler('color', ['b', 'y', 'k', '#707040', '#404070'])
plt.rcParams['savefig.dpi'] = 300
PATH_MAX = 255
# Files that we don't analyze. These are files that don't have lines of code so that blaming
# doesn't make sense.
IGNORED_EXTS = {
'.air', '.bin', '.bmp', '.cer', '.cert', '.der', '.developerprofile', '.dll', '.doc', '.docx',
'.exe', '.gif', '.icns', '.ico', '.jar', '.jpeg', '.jpg', '.keychain', '.launch', '.pdf',
'.pem', '.pfx', '.png', '.prn', '.so', '.spc', '.svg', '.swf', '.tif', '.tiff', '.xls', '.xlsx',
'.tar', '.zip', '.gz', '.7z', '.rar',
'.patch',
'.dump',
'.h5'
}
def _is_windows():
"""Returns: True if running on a MS-Windows operating system."""
try:
sys.getwindowsversion()
except:
return False
else:
return True
IS_WINDOWS = _is_windows()
if IS_WINDOWS:
import win32api
import win32process
import win32con
def lowpriority():
""" Set the priority of the process to below-normal.
http://stackoverflow.com/questions/1023038/change-process-priority-in-python-cross-platform
"""
pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)
else:
def lowpriority():
os.nice(1)
class ProcessPool(object):
"""Package of Pool and ThreadPool for 'with' usage.
"""
SINGLE = 0
THREAD = 1
PROCESS = 2
def __init__(self, process_type, n_pool):
if not DO_MULTIPROCESSING:
process_type = ProcessPool.SINGLE
self.process_type = process_type
if process_type != ProcessPool.SINGLE:
clazz = ThreadPool if process_type == ProcessPool.THREAD else Pool
self.pool = clazz(n_pool)
def __enter__(self):
return self
def imap_unordered(self, func, args_iter):
if self.process_type != ProcessPool.SINGLE:
return self.pool.imap_unordered(func, args_iter)
else:
return map(func, args_iter)
def __exit__(self, exc_type, exc_value, traceback):
if self.process_type != ProcessPool.SINGLE:
self.pool.terminate()
def sha_str(sha):
"""The way we show git SHA-1 hashes in reports."""
return sha[:SHA_LEN]
def date_str(date):
"""The way we show dates in reports."""
return date.strftime('%Y-%m-%d')
DAY = pd.Timedelta('1 days') # 24 * 3600 * 1e9 in pandas nanosec time
# Max date accepted for commits. Clearly a sanity check
MAX_DATE = Timestamp('today').tz_localize(TIMEZONE) + DAY
def to_timestamp(date_s):
"""Convert string `date_s' to pandas Timestamp in `TIMEZONE`
NOTE: The idea is to get all times in one timezone.
"""
return Timestamp(date_s).tz_convert(TIMEZONE)
def delta_days(t0, t1):
"""Returns: time from `t0` to `t1' in days where t0 and t1 are Timestamps
Returned value is signed (+ve if t1 later than t0) and fractional
"""
return (t1 - t0).total_seconds() / 3600 / 24
concat = ''.join
path_join = os.path.join
def decode_to_str(bytes):
"""Decode byte list `bytes` to a unicode string trying utf-8 encoding first then latin-1.
"""
if bytes is None:
return None
try:
return bytes.decode('utf-8')
except:
return bytes.decode('latin-1')
def save_object(path, obj):
"""Save object `obj` to `path` after bzipping it
"""
# existing_pkl is for recovering from bad pickles
existing_pkl = '%s.old.pkl' % path
if os.path.exists(path) and not os.path.exists(existing_pkl):
os.rename(path, existing_pkl)
with bz2.BZ2File(path, 'w') as f:
# protocol=2 makes pickle usable by python 2.x
pickle.dump(obj, f, protocol=2)
# Delete existing_pkl if load_object succeeds
load_object(path)
if os.path.exists(path) and os.path.exists(existing_pkl):
os.remove(existing_pkl)
def load_object(path, default=None):
"""Load object from `path`
"""
if default is not None and not os.path.exists(path):
return default
try:
with bz2.BZ2File(path, 'r') as f:
return pickle.load(f)
except:
print('load_object(%s, %s) failed' % (path, default), file=sys.stderr)
raise
def mkdir(path):
"""Create directory `path` including all intermediate-level directories and ignore
"already exists" errors.
"""
try:
os.makedirs(path)
except OSError as e:
if not (e.errno == errno.EEXIST and os.path.isdir(path)):
raise
def df_append_totals(df_in):
"""Append row and column totals to Pandas DataFrame `df_in`, remove all zero columns and sort
rows and columns by total.
"""
assert 'Total' not in df_in.index
assert 'Total' not in df_in.columns
rows, columns = list(df_in.index), list(df_in.columns)
df = DataFrame(index=rows + ['Total'], columns=columns + ['Total'])
df.iloc[:-1, :-1] = df_in
df.iloc[:, -1] = df.iloc[:-1, :-1].sum(axis=1)
df.iloc[-1, :] = df.iloc[:-1, :].sum(axis=0)
row_order = ['Total'] + sorted(rows, key=lambda r: -df.loc[r, 'Total'])
column_order = ['Total'] + sorted(columns, key=lambda c: -df.loc['Total', c])
df = df.reindex_axis(row_order, axis=0)
df = df.reindex_axis(column_order, axis=1)
empties = [col for col in df.columns if df.loc['Total', col] == 0]
df.drop(empties, axis=1, inplace=True)
return df
def moving_average(series, window):
"""Returns: Weighted moving average of pandas Series `series` as a pandas Series.
Weights are a triangle of width `window`.
NOTE: If window is greater than the number of items in series then smoothing may not work
well. See first few lines of function code.
"""
if len(series) < 10:
return series
window = min(window, len(series))
weights = np.empty(window, dtype=np.float)
radius = (window - 1) / 2
for i in range(window):
weights[i] = radius + 1 - abs(i - radius)
ma = np.convolve(series, weights, mode='same')
assert ma.size == series.size, ([ma.size, ma.dtype], [series.size, series.dtype], window)
sum_raw = series.sum()
sum_ma = ma.sum()
if sum_ma:
ma *= sum_raw / sum_ma
return Series(ma, index=series.index)
def procrustes(s, width=100):
"""Returns: String `s` fitted `width` or fewer chars, removing middle characters if necessary.
"""
width = max(20, width)
if len(s) > width:
notch = int(round(width * 0.6)) - 5
end = width - 5 - notch
return '%s ... %s' % (s[:notch], s[-end:])
return s
RE_EXT = re.compile(r'^\.\w+$')
RE_EXT_NUMBER = re.compile(r'^\.\d+$')
def get_ext(path):
"""Returns: extension of file `path`
"""
parts = os.path.splitext(path)
if not parts:
ext = '[None]'
else:
ext = parts[-1]
if not RE_EXT.search(ext) or RE_EXT_NUMBER.search(ext):
ext = ''
return ext
def exec_output(command, require_output):
"""Executes `command` which is a list of strings. If `require_output` is True then raise an
exception is there is no stdout.
Returns: The stdout of the child process as a string.
"""
# TODO save stderr and print it on error
try:
output = subprocess.check_output(command)
except:
print('exec_output failed: command=%s' % ' '.join(command), file=sys.stderr)
raise
if require_output and not output:
raise RuntimeError('exec_output: command=%s' % command)
return decode_to_str(output)
def exec_output_lines(command, require_output, sep=None):
"""Executes `command` which is a list of strings. If `require_output` is True then raise an
exception is there is no stdout.
Returns: The stdout of the child process as a list of strings, one string per line.
"""
if sep is not None:
return exec_output(command, require_output).split(sep)
else:
return exec_output(command, require_output).splitlines()
def exec_headline(command):
"""Execute `command` which is a list of strings.
Returns: The first line stdout of the child process.
"""
return exec_output(command, True).splitlines()[0]
def git_file_list(path_patterns=()):
"""Returns: List of files in current git revision matching `path_patterns`.
This is basically git ls-files.
"""
# git ls-files -z returns a '\0' separated list of files terminated with '\0\0'
bin_list = exec_output_lines(['git', 'ls-files', '-z', '--exclude-standard'] + path_patterns,
False, '\0')
file_list = []
for path in bin_list:
if not path:
break
file_list.append(path)
return file_list
def git_pending_list(path_patterns=()):
"""Returns: List of git pending files matching `path_patterns`.
"""
return exec_output_lines(['git', 'diff', '--name-only'] + path_patterns, False)
def git_file_list_no_pending(path_patterns=()):
"""Returns: List of non-pending files in current git revision matching `path_patterns`.
"""
file_list = git_file_list(path_patterns)
pending = set(git_pending_list(path_patterns))
return [path for path in file_list if path not in pending]
def git_diff(rev1, rev2):
"""Returns: List of files that differ in git revisions `rev1` and `rev2`.
"""
return exec_output_lines(['git', 'diff', '--name-only', rev1, rev2], False)
def git_show_oneline(obj):
"""Returns: One-line description of a git object `obj`, which is typically a commit.
https://git-scm.com/docs/git-show
"""
return exec_headline(['git', 'show', '--oneline', '--quiet', obj])
def git_date(obj):
"""Returns: Date of a git object `obj`, which is typically a commit.
NOTE: The returned date is standardized to timezone TIMEZONE.
"""
date_s = exec_headline(['git', 'show', '--pretty=format:%ai', '--quiet', obj])
return to_timestamp(date_s)
RE_REMOTE_URL = re.compile(r'(https?://.*/[^/]+(?:\.git)?)\s+\(fetch\)')
RE_REMOTE_NAME = re.compile(r'https?://.*/(.+?)(\.git)?$')
def git_remote():
"""Returns: The remote URL and a short name for the current repository.
"""
# $ git remote -v
# origin https://github.com/FFTW/fftw3.git (fetch)
# origin https://github.com/FFTW/fftw3.git (push)
try:
output_lines = exec_output_lines(['git', 'remote', '-v'], True)
except Exception as e:
print('git_remote error: %s' % e)
return 'unknown', 'unknown'
for line in output_lines:
m = RE_REMOTE_URL.search(line)
if not m:
continue
remote_url = m.group(1)
remote_name = RE_REMOTE_NAME.search(remote_url).group(1)
return remote_url, remote_name
raise RuntimeError('No remote')
def git_describe():
"""Returns: git describe of current revision.
"""
return exec_headline(['git', 'describe', '--always'])
def git_name():
"""Returns: git name of current revision.
"""
return ' '.join(exec_headline(['git', 'name-rev', 'HEAD']).split()[1:])
def git_current_branch():
"""Returns: git name of current branch or None if there is no current branch (detached HEAD).
"""
branch = exec_headline(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
if branch == 'HEAD': # Detached HEAD?
branch = None
return branch
def git_current_revision():
"""Returns: SHA-1 of current revision.
"""
return exec_headline(['git', 'rev-parse', 'HEAD'])
def git_revision_description():
"""Returns: Our best guess at describing the current revision"""
description = git_current_branch()
if not description:
description = git_describe()
return description
RE_PATH = re.compile(r'''[^a-z^0-9^!@#$\-+=_\[\]\{\}\(\)^\x7f-\xffff]''', re.IGNORECASE)
RE_SLASH = re.compile(r'[\\/]+')
def normalize_path(path):
"""Returns: `path` without leading ./ and trailing / . \ is replaced by /
"""
path = RE_SLASH.sub('/', path)
if path.startswith('./'):
path = path[2:]
if path.endswith('/'):
path = path[:-1]
return path
def clean_path(path):
"""Returns: `path` with characters that are illegal in filenames replaced with '_'
"""
return RE_PATH.sub('_', normalize_path(path))
def git_blame_text(path):
"""Returns: git blame text for file `path`
"""
if PY2:
path = path.encode(sys.getfilesystemencoding())
return exec_output(['git', 'blame', '-l', '-f', '-w', '-M', path], False)
RE_BLAME = re.compile(r'''
\^*([0-9a-f]{4,})\s+
.+?\s+
\(
(.+?)\s+
(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\s+[+-]\d{4})
\s+(\d+)
\)''',
re.DOTALL | re.MULTILINE | re.VERBOSE)
def _debug_check_dates(max_date, sha_date_author, path_sha_loc):
"""Debug code to validate dates in `sha_date_author`, `path_sha_loc`
"""
if not STRICT_CHECKING:
return
assert max_date <= MAX_DATE, max_date
for path, sha_loc in path_sha_loc.items():
for sha, loc in sha_loc.items():
if loc <= 1:
continue
assert sha in sha_date_author, '%s not in sha_date_author' % [sha, path]
date, _ = sha_date_author[sha]
assert date <= max_date, ('date > max_date', sha, loc, [date, max_date], path)
class GitException(Exception):
def __init__(self, msg=None):
super(GitException, self).__init__(msg)
self.git_msg = msg
if IS_WINDOWS:
RE_LINE = re.compile(r'(?:\r\n|\n)+')
else:
RE_LINE = re.compile(r'[\n]+')
def _parse_blame(max_date, text, path):
"""Parses git blame output `text` and extracts LoC for each git hash found
max_date: Latest valid date for a commit
text: A string containing the git blame output of file `path`
path: Path of blamed file. Used only for constructing error messages in this function
Returns: line_sha_date_author {line_n: (sha, date, author)} over all lines in the file
"""
line_sha_date_author = {}
lines = RE_LINE.split(text)
while lines and not lines[-1]:
lines.pop()
if not lines:
raise GitException('is empty')
for i, ln in enumerate(lines):
if not ln:
continue
m = RE_BLAME.match(ln)
if not m:
raise GitException('bad line')
if m.group(2) == 'Not Committed Yet':
continue
sha = m.group(1)
author = m.group(2)
date_s = m.group(3)
line_n = int(m.group(4))
author = author.strip()
if author == '':
author = '<>'
assert line_n == i + 1, 'line_n=%d,i=%d\n%s\n%s' % (line_n, i, path, m.group(0))
assert author.strip() == author, 'author="%s\n%s:%d\n%s",' % (
author, path, i + 1, ln[:200])
date = to_timestamp(date_s)
if date > max_date:
raise GitException('bad date. sha=%s,date=%s' % (sha, date))
line_sha_date_author[line_n] = sha, date, author
if not line_sha_date_author:
raise GitException('is empty')
return line_sha_date_author
def _compute_author_sha_loc(line_sha_date_author, sloc_lines):
"""
line_sha_date_author: {line_n: (sha, date, author)}
sloc_lines: {line_n} for line_n in line_sha_date_author that are source code or None
Returns: sha_date_author, sha_aloc, sha_sloc
sha_date_author: {sha: (date, author)} over all SHA-1 hashes in
`line_sha_date_author`
sha_aloc: {sha: aloc} over all SHA-1 hashes found in `line_sha_date_author`. aloc
is "all lines of code"
sha_sloc: {sha: sloc} over SHA-1 hashes found in `line_sha_date_author` that are in
`sloc_lines`. sloc is "source lines of code". If sloc_lines is None then
sha_sloc is None.
"""
sha_date_author = {}
sha_aloc = Counter()
sha_sloc = None
for sha, date, author in line_sha_date_author.values():
sha_aloc[sha] += 1
sha_date_author[sha] = (date, author)
if not sha_aloc:
raise GitException('is empty')
if sloc_lines is not None:
sha_sloc = Counter()
counted_lines = set(line_sha_date_author.keys()) & sloc_lines
for line_n in counted_lines:
sha, _, _ = line_sha_date_author[line_n]
sha_sloc[sha] += 1
return sha_date_author, sha_aloc, sha_sloc
def get_ignored_files(gitstatsignore):
if gitstatsignore is None:
gitstatsignore = 'gitstatsignore'
else:
assert os.path.exists(gitstatsignore), 'gitstatsignore file "%s"' % gitstatsignore
if not gitstatsignore or not os.path.exists(gitstatsignore):
return set()
ignored_files = set()
with open(gitstatsignore, 'rt') as f:
for line in f:
line = line.strip('\n').strip()
if not line:
continue
ignored_files.update(git_file_list([line]))
return ignored_files
class Persistable(object):
"""Base class that
a) saves to disk,
catalog: a dict of objects
summary: a dict describing catalog
manifest: a dict of sizes of objects in a catalog
b) loads them from disk
Derived classes must contain a dict data member called `TEMPLATE` that gives the keys of the
data members to save / load and default constructors for each key.
"""
@staticmethod
def make_data_dir(path):
return path_join(path, 'data')
@staticmethod
def update_dict(base_dict, new_dict):
for k, v in new_dict.items():
if k in base_dict:
base_dict[k].update(v)
else:
base_dict[k] = v
return base_dict
def _make_path(self, name):
return path_join(self.base_dir, name)
def __init__(self, summary, base_dir):
"""Initialize the data based on TEMPLATE and set summary to `summary`.
summary: A dict giving a summary of the data to be saved
base_dir: Directory that summary, data and manifest are to be saved to
"""
assert 'TEMPLATE' in self.__class__.__dict__, 'No TEMPLATE in %s' % self.__class__.__dict__
self.base_dir = base_dir
self.data_dir = Persistable.make_data_dir(base_dir)
self.summary = summary.copy()
self.catalog = {k: v() for k, v in self.__class__.TEMPLATE.items()}
for k, v in self.catalog.items():
assert hasattr(v, 'update'), '%s.TEMPLATE[%s] does not have update(). type=%s' % (
self.__class__.__name__, k, type(v))
def _load_catalog(self):
catalog = load_object(self._make_path('data.pkl'), {})
if catalog.get('CACHE_FILE_VERSION', 0) != CACHE_FILE_VERSION:
return {}
del catalog['CACHE_FILE_VERSION']
return catalog
def load(self):
catalog = self._load_catalog()
if not catalog:
return False
Persistable.update_dict(self.catalog, catalog) # !@#$ Use toolz
path = self._make_path('summary')
if os.path.exists(path):
self.summary = eval(open(path, 'rt').read())
return True
def save(self):
# Load before saving in case another instance of this script is running
path = self._make_path('data.pkl')
if os.path.exists(path):
catalog = self._load_catalog()
self.catalog = Persistable.update_dict(catalog, self.catalog)
# Save the data, summary and manifest
mkdir(self.base_dir)
self.catalog['CACHE_FILE_VERSION'] = CACHE_FILE_VERSION
save_object(path, self.catalog)
open(self._make_path('summary'), 'wt').write(repr(self.summary))
manifest = {k: len(v) for k, v in self.catalog.items() if k != 'CACHE_FILE_VERSION'}
manifest['CACHE_FILE_VERSION'] = CACHE_FILE_VERSION
open(self._make_path('manifest'), 'wt').write(repr(manifest))
def __repr__(self):
return repr([self.base_dir, {k: len(v) for k, v in self.catalog.items()}])
class BlameRepoState(Persistable):
"""Repository level persisted data structures
Currently this is just sha_date_author.
"""
TEMPLATE = {'sha_date_author': lambda: {}}
class BlameRevState(Persistable):
"""Revision level persisted data structures
The main structures are path_sha_aloc and path_sha_sloc.
"""
TEMPLATE = {
'path_sha_aloc': lambda: {}, # aloc for all LoC
'path_sha_sloc': lambda: {}, # sloc for source LoC
'path_set': lambda: set(),
'bad_path_set': lambda: set(),
}
def get_lexer(path, text):
try:
return guess_lexer_for_filename(path, text[:1000])
except pygments.util.ClassNotFound:
return None
COMMMENTS = {
Comment,
Literal.String.Doc,
Comment.Multiline,
}
class LineState(object):
def __init__(self):
self.sloc = set()
self.tokens = []
self.lnum = 0
self.ltype = None
def tokens_to_lines(self, has_eol):
is_comment = self.ltype in COMMMENTS
is_blank = self.ltype == Text
text = concat(self.tokens)
if has_eol:
lines = text[:-1].split('\n')
else:
lines = text.spit('\n')
for line in lines:
self.lnum += 1
if not (is_comment or is_blank):
self.sloc.add(self.lnum)
self.tokens = []
self.ltype = None
def get_sloc_lines(path):
"""Determine the lines in file `path` that are source code. i.e. Not space or comments.
This requires a parser for this file type, which exists for most source code files in the
Pygment module.
Returns: If a Pygment lexer can be found for file `path`
{line_n} i.e. set of 1-offset line number for lines in `path` that are source.
Otherwise None
"""
with open(path, 'rb') as f:
text = decode_to_str(f.read())
lexer = get_lexer(path, text)
if lexer is None:
return None
line_state = LineState()
for ttype, value in lex(text, lexer):
if not line_state.ltype:
line_state.ltype = ttype
elif line_state.ltype == Text:
if ttype is not None:
line_state.ltype = ttype
elif line_state.ltype == Punctuation:
if ttype is not None and ttype != Text:
line_state.ltype = ttype
if value:
line_state.tokens.append(value)
if value.endswith('\n'):
line_state.tokens_to_lines(True)
return line_state.sloc
def _task_extract_author_sha_loc(args):
"""Wrapper around blame and comment detection code to allow it to be executed by a
multiprocessing Pool.
Runs git blame and parses output to extract LoC by sha for all the sha's (SHA-1 hashes) in
the blame output.
Runs a Pygment lexer over the file if there is a matching lexer and combines this with the
blame parse to extract SLoC for each git hash found
args: max_date, path
max_date: Latest valid date for a commit
path: path of file to analyze
Returns: path, sha_date_author, sha_loc, sha_sloc, exception
path: from `args`
sha_date_author: {sha: (date, author)} over all SHA-1 hashes found in `path`
sha_aloc: {sha: aloc} over all SHA-1 hashes found in `path`. aloc = all lines counts
sha_sloc: {sha: sloc} over all SHA-1 hashes found in `path`. sloc = source lines counts
"""
max_date, path = args
sha_date_author, sha_aloc, sha_sloc, exception = None, None, None, None
try:
text = git_blame_text(path)
line_sha_date_author = _parse_blame(max_date, text, path)
sloc_lines = get_sloc_lines(path)
sha_date_author, sha_aloc, sha_sloc = _compute_author_sha_loc(line_sha_date_author,
sloc_lines)
except Exception as e:
exception = e
if not DO_MULTIPROCESSING and not isinstance(e, (GitException, CalledProcessError,
IsADirectoryError)):
print('_task_extract_author_sha_loc: %s: %s' % (type(e), e), file=sys.stderr)
raise
return path, sha_date_author, sha_aloc, sha_sloc, exception
class BlameState(object):
"""A BlameState contains data from `git blame` that are used to compute reports.
This data can take a long time to generate so we allow it to be saved to and loaded from
disk so that it can be reused between runs.
Data members: (All are read-only)
repo_dir
sha_date_author
path_sha_aloc
path_sha_sloc
path_set
bad_path_set
Typical usage:
blame_state.load() # Load existing data from disk
changed = blame_state.update_data(file_set) # Blame files in file_set to update data
if changed:
blame_state.save() # Save updated data to disk
Internal members: 'repo_dir', '_repo_state', '_rev_state', '_repo_base_dir'
Disk storage
------------
<repo_base_dir> Defaults to ~/git.stats/<repository name>
└── cache
├── 241d0c54 Data for revision 241d0c54
│ ├── data.pkl The data in a bzipped pickle.
│ ├── manifest Python file with dict of data keys and lengths
│ └── summary Python file with dict of summary date
...
├
├── e7a3e5c4 Data for revision e7a3e5c4
│ ├── data.pkl
│ ├── manifest
│ └── summary
├── data.pkl Repository level data
├── manifest
└── summary
"""
def _debug_check(self):
"""Debugging code to check consistency of the data in a BlameState
"""
if not STRICT_CHECKING:
return
assert 'path_sha_aloc' in self._rev_state.catalog
path_sha_loc = self.path_sha_aloc
path_set = self.path_set
for path, sha_loc in path_sha_loc.items():
assert path in path_set, '%s not in self.path_set' % path
for sha, loc in sha_loc.items():
date, author = self.sha_date_author[sha]
if set(self.path_sha_aloc.keys()) | self.bad_path_set != self.path_set:
for path in sorted((set(self.path_sha_aloc.keys()) | self.bad_path_set) - self.path_set)[:20]:
print('!@!', path in self.path_sha_aloc, path in self.bad_path_set)
assert set(self.path_sha_aloc.keys()) | self.bad_path_set == self.path_set, (
'path sets wrong %d %d\n'
'(path_sha_aloc | bad_path_set) - path_set: %s\n'
'path_set - (path_sha_aloc | bad_path_set): %s\n' % (
len((set(self.path_sha_aloc.keys()) | self.bad_path_set) - self.path_set),
len(self.path_set - (set(self.path_sha_aloc.keys()) | self.bad_path_set)),
sorted((set(self.path_sha_aloc.keys()) | self.bad_path_set) - self.path_set)[:20],
sorted(self.path_set - (set(self.path_sha_aloc.keys()) | self.bad_path_set))[:20]
))
def __init__(self, repo_base_dir, repo_summary, rev_summary):
"""
repo_base_dir: Root of data saved for this repository. This is <repo_dir> in the storage
diagram. Typically ~/git.stats/<repository name>
repo_summary = {
'remote_url': remote_url,
'remote_name': remote_name,
}
rev_summary = {
'revision_sha': revision_sha,
'branch': git_current_branch(),
'description': description,
'name': git_name(),
'date': revision_date,
}
"""
self._repo_base_dir = repo_base_dir
self._repo_dir = path_join(repo_base_dir, 'cache')
self._repo_state = BlameRepoState(repo_summary, self.repo_dir)
rev_dir = path_join(self._repo_state.base_dir,
sha_str(rev_summary['revision_sha']))
self._rev_state = BlameRevState(rev_summary, rev_dir)
def copy(self, rev_dir):
"""Returns: A copy of self with its rev_dir member replaced by `rev_dir`
"""
blame_state = BlameState(self._repo_base_dir, self._repo_state.summary,
self._rev_state.summary)
blame_state._rev_state.base_dir = rev_dir
return blame_state
def load(self, max_date):
"""Loads a previously saved copy of it data from disk.
Returns: self
"""
valid_repo = self._repo_state.load()
valid_rev = self._rev_state.load()
if STRICT_CHECKING:
if max_date is not None:
_debug_check_dates(max_date, self.sha_date_author, self.path_sha_aloc)
assert 'path_sha_aloc' in self._rev_state.catalog, self._rev_state.catalog.keys()
assert 'path_sha_sloc' in self._rev_state.catalog, self._rev_state.catalog.keys()
self._debug_check()
return self, valid_repo and valid_rev
def save(self):
"""Saves a copy of its data to disk
"""
self._repo_state.save()
self._rev_state.save()
if STRICT_CHECKING:
self.load(None)
def __repr__(self):
return repr({k: repr(v) for k, v in self.__dict__.items()})
@property
def repo_dir(self):
"""Returns top directory for this repo's cached data.
Typically ~/git.stats/<repository name>/cache
"""
return self._repo_dir
@property
def sha_date_author(self):
"""Returns: {sha: (date, author)} for all commits that have been found in blaming this
repository. sha is SHA-1 hash of commit
This is a per-repository dict.
"""
return self._repo_state.catalog['sha_date_author']
@property