-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-activity.py
executable file
·182 lines (149 loc) · 4.47 KB
/
git-activity.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
#!/usr/bin/env python3
import argparse
import contextlib
from dataclasses import dataclass
import os
from pathlib import Path
from pprint import pprint as pp
import re
import subprocess
import sys
from typing import Iterable, Optional
@contextlib.contextmanager
def chdir(folder: Path) -> None:
"""
Context manager to temporarily change the current working directory.
"""
curdir = os.getcwd()
os.chdir(folder)
try:
yield
finally:
os.chdir(curdir)
def existing_folder(string: str) -> Path:
"""
An `argparse` type to convert string to a `Path` object.
Raises:
argparse.ArgumentTypeError:
If path is not an existing folder.
Returns:
Path to an existing folder.
"""
path = Path(string).expanduser().resolve()
error = None
if not path.exists():
error = f"Folder does not exist: {path}"
if not path.is_dir():
error = f"Path is not a folder: {path}"
if error is not None:
raise argparse.ArgumentTypeError(error)
return path
def find_repos(parent: Path, *, find_hidden=False) -> Iterable[Path]:
"""
Yield folders containing git repos.
This is any regular folder containing in turn the folder '.git'.
Args:
parent:
Folder to look under.
find_hidden:
Look inside folders starting with a full-stop.
Returns:
Generator over folder Path objects
"""
parent = Path(parent)
examined = 0
found = 0
for root, dirs, files in os.walk(parent, topdown=True):
# Skip hidden folders
if os.path.basename(root).startswith('.'):
dirs.clear()
continue
examined += 1
dirs.sort()
if '.git' in dirs:
found += 1
yield Path(root)
# Don't look any further inside repo
dirs.clear()
pp(examined)
@dataclass
class Commit:
timestamp: int # Unix timestamp
author: str # eg. "Name <email>"
project: str # Top-level folder name, eg. "lost.co.nz"
message: str # First line only
@classmethod
def from_log(cls, line: str):
"""
Construct object from git log line.
"""
# TODO
class GitLog:
def __init__(self):
"""
Run 'git log' in a project folder and parse its output.
"""
self.regex = re.compile(
r"(\d+) " # Unix Epoch
r"(.*>) " # Name <email>
r"(.*)" # Commit message
)
def run(self, folder: Path, since: Optional[int] = None) -> str:
"""
Run `git log` in current directory and capture its output.
Args:
folder:
Top-level git project folder.
since:
Optionally exclude commits before this Unix timestamp.
Returns:
Multiline unicode string, one-line per commit.
"""
args = [
'git',
'log',
'--pretty=%at %aN <%aE> %s',
]
if since is not None:
args.append(f"--since={since}")
with chdir(folder):
process = subprocess.run(args, capture_output=True, text=True, timeout=5.0)
return process.stdout
def parse(self, line) -> list[str]:
"""
Break log line into parts.
"""
match = self.regex.match(line)
if match is None:
raise ValueError(f"Could not parse git log: {line!r}")
pp(self.regex.match(line).groups())
def main(options: argparse.Namespace) -> int:
log = GitLog()
for project in find_repos(options.folder):
output = log.run(project, since=1_695_000_000)
if output:
pp(project)
pp(output)
pp('')
return 0
print(output)
print(repr(output))
for line in output.splitlines():
print(repr(line))
print(log.parse(line))
return 0
def parse(args: list[str]) -> argparse.Namespace:
description = "Summarise recent Git project activity"
parser = argparse.ArgumentParser(description=description)
parser.add_argument(
'folder',
default='~',
metavar='FOLDER',
nargs='?',
type=existing_folder,
help='folder to look under',
)
return parser.parse_args()
if __name__ == '__main__':
options = parse(sys.argv[1:])
sys.exit(main(options))