-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokei.py
executable file
·77 lines (58 loc) · 1.69 KB
/
tokei.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
#!/bin/python3
# This file is intended to be used as a tokei cache
# it maps a directory (to be counted) to a git commit and the cached loc
import sys
import subprocess
import json
from pathlib import Path
CACHE_FILE: str = './tokei.cache.json'
def write_json(data: {}):
with open(CACHE_FILE, 'w') as file:
json.dump(data, file)
def read_json():
with open(CACHE_FILE, 'r') as file:
data = json.load(file)
return data
def get_commit(path: str):
res = subprocess.run(
f'git -C {path} rev-parse --short HEAD',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
res.check_returncode()
return res.stdout.decode('utf-8').rstrip()
def count(path: str, data: {}):
commit = get_commit(path)
if path in data:
if data[path]['commit'] == commit:
print('using cache', file=sys.stderr)
return data[path]['loc']
res = subprocess.run(
f'tokei {path} -o json',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
res.check_returncode()
print('using fresh data', file=sys.stderr)
tokei_data = json.loads(res.stdout)
loc = tokei_data['Total']['code']
data[path] = {
'commit': commit,
'loc': loc,
}
write_json(data)
return loc
if __name__ == '__main__':
cache_file = Path(CACHE_FILE)
if not cache_file.is_file():
write_json({})
if len(sys.argv) != 2:
print(f'Expected exactly one argument (path), found {len(sys.argv)}')
exit(1)
cache = read_json()
try:
sys.stdout.buffer.write(bytes(str(count(sys.argv[1], cache)), 'utf-8'))
except:
pass