-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvoid_git.py
More file actions
executable file
·285 lines (230 loc) · 8.89 KB
/
Copy pathvoid_git.py
File metadata and controls
executable file
·285 lines (230 loc) · 8.89 KB
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
#!/usr/bin/env python3
"""
Git Analyzer
Tracks LOC (Lines of Code) changes via git diff
"""
import os
import subprocess
import re
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
@dataclass
class FileChange:
"""Per-file change statistics"""
path: str
loc_added: int
loc_deleted: int
loc_net: int # Net change (added - deleted)
@dataclass
class GitStats:
"""Git Statistics"""
total_loc_added: int
total_loc_deleted: int
total_loc_net: int
files_changed: int
file_changes: List[FileChange]
class GitAnalyzer:
"""
Git code change analyzer
Calculates LOC changes based on git diff
"""
def __init__(self, repo_path: Optional[str] = None):
"""
Initialize the Git analyzer
Args:
repo_path: Git repository path, defaults to current working directory
"""
self.repo_path = Path(repo_path or os.getcwd())
self._is_git_repo = self._check_git_repo()
def _check_git_repo(self) -> bool:
"""Return True if the path is a git repository"""
try:
result = subprocess.run(
['git', 'rev-parse', '--git-dir'],
cwd=self.repo_path,
capture_output=True,
text=True,
timeout=2
)
return result.returncode == 0
except (subprocess.TimeoutExpired, FileNotFoundError):
return False
def is_git_repository(self) -> bool:
"""Return True if the current directory is a git repository"""
return self._is_git_repo
def get_file_diff_stats(self, filepath: str) -> Optional[FileChange]:
"""
Get Git diff statistics for a single file
Args:
filepath: File path (relative to the repository root)
Returns:
FileChange object, or None if stats cannot be retrieved
"""
if not self._is_git_repo:
return None
try:
# Use git diff --numstat HEAD -- <file> to get line change stats
result = subprocess.run(
['git', 'diff', '--numstat', 'HEAD', '--', filepath],
cwd=self.repo_path,
capture_output=True,
text=True,
timeout=5
)
if result.returncode != 0:
return None
output = result.stdout.strip()
if not output:
# File is untracked or has no changes
return FileChange(
path=filepath,
loc_added=0,
loc_deleted=0,
loc_net=0
)
# Parse numstat output: added\tdeleted\tfilename
parts = output.split('\t')
if len(parts) >= 2:
added_str, deleted_str = parts[0], parts[1]
# Handle binary files (shown as '-')
if added_str == '-' or deleted_str == '-':
return FileChange(
path=filepath,
loc_added=0,
loc_deleted=0,
loc_net=0
)
loc_added = int(added_str)
loc_deleted = int(deleted_str)
return FileChange(
path=filepath,
loc_added=loc_added,
loc_deleted=loc_deleted,
loc_net=loc_added - loc_deleted
)
except (subprocess.TimeoutExpired, ValueError, subprocess.SubprocessError):
pass
return None
def get_files_diff_stats(self, filepaths: List[str]) -> GitStats:
"""
Get Git diff statistics for multiple files
Args:
filepaths: List of file paths
Returns:
GitStats object
"""
file_changes = []
total_added = 0
total_deleted = 0
for filepath in filepaths:
change = self.get_file_diff_stats(filepath)
if change:
file_changes.append(change)
total_added += change.loc_added
total_deleted += change.loc_deleted
return GitStats(
total_loc_added=total_added,
total_loc_deleted=total_deleted,
total_loc_net=total_added - total_deleted,
files_changed=len(file_changes),
file_changes=file_changes
)
def get_shortstat(self) -> Optional[Tuple[int, int, int]]:
"""
Get statistics from git diff --shortstat
Returns:
(files_changed, insertions, deletions) or None
"""
if not self._is_git_repo:
return None
try:
result = subprocess.run(
['git', 'diff', '--shortstat', 'HEAD'],
cwd=self.repo_path,
capture_output=True,
text=True,
timeout=5
)
if result.returncode != 0:
return None
output = result.stdout.strip()
if not output:
return (0, 0, 0)
# Parse output: "1 file changed, 2 insertions(+), 3 deletions(-)"
files_match = re.search(r'(\d+) files? changed', output)
insertions_match = re.search(r'(\d+) insertions?\(\+\)', output)
deletions_match = re.search(r'(\d+) deletions?\(-\)', output)
files_changed = int(files_match.group(1)) if files_match else 0
insertions = int(insertions_match.group(1)) if insertions_match else 0
deletions = int(deletions_match.group(1)) if deletions_match else 0
return (files_changed, insertions, deletions)
except (subprocess.TimeoutExpired, subprocess.SubprocessError):
return None
def stage_and_commit(self, message: str, files: Optional[List[str]] = None):
"""
Stage and commit files (test helper method)
Args:
message: Commit message
files: List of files to commit; None means all changes
"""
if not self._is_git_repo:
raise RuntimeError("Not a git repository")
try:
# Stage files
if files:
subprocess.run(['git', 'add'] + files, cwd=self.repo_path, check=True)
else:
subprocess.run(['git', 'add', '-A'], cwd=self.repo_path, check=True)
# Commit
subprocess.run(
['git', 'commit', '-m', message],
cwd=self.repo_path,
check=True,
capture_output=True
)
except subprocess.SubprocessError as e:
raise RuntimeError(f"Git commit failed: {e}")
if __name__ == "__main__":
# Test code
import tempfile
import shutil
print("Testing GitAnalyzer...")
# Create temporary git repository
test_dir = tempfile.mkdtemp(prefix="voidtally_git_")
print(f"Test directory: {test_dir}")
try:
# Initialize git repository
subprocess.run(['git', 'init'], cwd=test_dir, check=True, capture_output=True)
subprocess.run(['git', 'config', 'user.email', 'test@example.com'], cwd=test_dir, check=True)
subprocess.run(['git', 'config', 'user.name', 'Test User'], cwd=test_dir, check=True)
# Create initial file and commit
(Path(test_dir) / "README.md").write_text("# Test Project\n")
subprocess.run(['git', 'add', 'README.md'], cwd=test_dir, check=True)
subprocess.run(['git', 'commit', '-m', 'Initial commit'], cwd=test_dir, check=True, capture_output=True)
# Create GitAnalyzer
analyzer = GitAnalyzer(test_dir)
assert analyzer.is_git_repository(), "Should be a git repository"
print("✓ Git repository detected")
# Modify file (uncommitted)
(Path(test_dir) / "README.md").write_text("# Test Project\n\nNew content\nMore lines\n")
(Path(test_dir) / "new_file.py").write_text("def hello():\n print('world')\n")
# Test single-file stats
readme_stats = analyzer.get_file_diff_stats("README.md")
assert readme_stats is not None
assert readme_stats.loc_added >= 2 # at least 2 lines added
print(f"✓ README.md: +{readme_stats.loc_added} -{readme_stats.loc_deleted}")
# Test multi-file stats
stats = analyzer.get_files_diff_stats(["README.md", "new_file.py"])
assert stats.total_loc_added > 0
assert len(stats.file_changes) == 2
print(f"✓ Total: +{stats.total_loc_added} -{stats.total_loc_deleted}")
# Test shortstat
shortstat = analyzer.get_shortstat()
assert shortstat is not None
files, insertions, deletions = shortstat
print(f"✓ Shortstat: {files} files, +{insertions}, -{deletions}")
print("✅ GitAnalyzer test completed")
finally:
shutil.rmtree(test_dir)
print("Cleaned up test directory")