-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit-gen.py
More file actions
executable file
·293 lines (240 loc) · 9.53 KB
/
Copy pathcommit-gen.py
File metadata and controls
executable file
·293 lines (240 loc) · 9.53 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
286
287
288
289
290
291
292
293
#!/usr/bin/env python3
"""
Commit Message Generator
Analyzes staged Git changes and generates conventional commit messages.
"""
import subprocess
import sys
import re
from pathlib import Path
from typing import List, Tuple, Optional
class CommitAnalyzer:
"""Analyzes git diff and generates commit messages."""
COMMIT_TYPES = {
'feat': 'New features',
'fix': 'Bug fixes',
'docs': 'Documentation changes',
'style': 'Code style changes',
'refactor': 'Code refactoring',
'test': 'Test changes',
'chore': 'Maintenance tasks',
'perf': 'Performance improvements',
'ci': 'CI/CD changes',
'build': 'Build system changes'
}
def __init__(self):
self.staged_files = []
self.diff_stats = {}
def check_git_repo(self) -> bool:
"""Check if we're in a git repository."""
try:
subprocess.run(
['git', 'rev-parse', '--git-dir'],
capture_output=True,
check=True,
text=True
)
return True
except subprocess.CalledProcessError:
return False
def get_staged_changes(self) -> bool:
"""Get list of staged files and their stats."""
try:
# Get staged files
result = subprocess.run(
['git', 'diff', '--staged', '--name-status'],
capture_output=True,
check=True,
text=True
)
if not result.stdout.strip():
return False
for line in result.stdout.strip().split('\n'):
parts = line.split('\t')
if len(parts) >= 2:
status = parts[0]
filepath = parts[1]
self.staged_files.append((status, filepath))
# Get diff stats
result = subprocess.run(
['git', 'diff', '--staged', '--stat'],
capture_output=True,
check=True,
text=True
)
self.diff_stats['summary'] = result.stdout
return True
except subprocess.CalledProcessError:
return False
def detect_commit_type(self) -> str:
"""Detect the most appropriate commit type."""
new_files = sum(1 for s, _ in self.staged_files if s == 'A')
modified_files = sum(1 for s, _ in self.staged_files if s == 'M')
deleted_files = sum(1 for s, _ in self.staged_files if s == 'D')
# Check file patterns
files = [f for _, f in self.staged_files]
# Documentation
if all(self._is_doc_file(f) for f in files):
return 'docs'
# Tests
if all(self._is_test_file(f) for f in files):
return 'test'
# CI/CD
if any(self._is_ci_file(f) for f in files):
return 'ci'
# Build files
if any(self._is_build_file(f) for f in files):
return 'build'
# Config/chore files
if any(self._is_config_file(f) for f in files):
return 'chore'
# New features (new files or significant additions)
if new_files > 0 and new_files >= modified_files:
return 'feat'
# Bug fixes (look for fix-related keywords in filenames)
if any('fix' in f.lower() or 'bug' in f.lower() for f in files):
return 'fix'
# Default to feat for new files, fix for modifications
if new_files > 0:
return 'feat'
elif modified_files > 0:
return 'fix'
return 'chore'
def detect_scope(self) -> Optional[str]:
"""Detect scope from file paths."""
files = [f for _, f in self.staged_files]
# Common scope patterns
common_dirs = {}
for filepath in files:
parts = Path(filepath).parts
if len(parts) > 1:
# Use first directory as scope
scope = parts[0]
common_dirs[scope] = common_dirs.get(scope, 0) + 1
if common_dirs:
# Return most common directory
return max(common_dirs, key=common_dirs.get)
return None
def generate_description(self) -> List[str]:
"""Generate bullet points describing changes."""
descriptions = []
for status, filepath in self.staged_files[:5]: # Limit to 5 files
filename = Path(filepath).name
if status == 'A':
descriptions.append(f"Add {filepath}")
elif status == 'M':
descriptions.append(f"Update {filepath}")
elif status == 'D':
descriptions.append(f"Remove {filepath}")
elif status.startswith('R'):
descriptions.append(f"Rename {filepath}")
if len(self.staged_files) > 5:
descriptions.append(f"... and {len(self.staged_files) - 5} more files")
return descriptions
def generate_commit_message(self) -> Tuple[str, List[str]]:
"""Generate the full commit message."""
commit_type = self.detect_commit_type()
scope = self.detect_scope()
descriptions = self.generate_description()
# Build subject line
if scope:
subject = f"{commit_type}({scope}): "
else:
subject = f"{commit_type}: "
# Generate subject description
if commit_type == 'feat':
subject += "add new functionality"
elif commit_type == 'fix':
subject += "resolve issues"
elif commit_type == 'docs':
subject += "update documentation"
elif commit_type == 'test':
subject += "add/update tests"
elif commit_type == 'chore':
subject += "update configuration"
else:
subject += "improve codebase"
return subject, descriptions
@staticmethod
def _is_doc_file(filepath: str) -> bool:
"""Check if file is documentation."""
doc_patterns = ['.md', '.txt', '.rst', 'README', 'CHANGELOG', 'LICENSE', 'docs/']
return any(pattern in filepath for pattern in doc_patterns)
@staticmethod
def _is_test_file(filepath: str) -> bool:
"""Check if file is a test."""
test_patterns = ['test_', '_test.', 'tests/', 'spec/', '__tests__/']
return any(pattern in filepath for pattern in test_patterns)
@staticmethod
def _is_ci_file(filepath: str) -> bool:
"""Check if file is CI/CD related."""
ci_patterns = ['.github/', '.gitlab-ci', 'Jenkinsfile', '.circleci/', '.travis.yml']
return any(pattern in filepath for pattern in ci_patterns)
@staticmethod
def _is_build_file(filepath: str) -> bool:
"""Check if file is build-related."""
build_patterns = ['package.json', 'Cargo.toml', 'setup.py', 'pom.xml', 'build.gradle', 'Makefile']
return any(pattern in filepath for pattern in build_patterns)
@staticmethod
def _is_config_file(filepath: str) -> bool:
"""Check if file is configuration."""
config_patterns = ['.env', 'config.', '.yml', '.yaml', '.toml', '.ini', '.conf']
return any(pattern in filepath for pattern in config_patterns)
def print_commit_message(subject: str, descriptions: List[str]):
"""Pretty print the commit message."""
print("\nSuggested commit message:")
print("━" * 80)
print(subject)
print()
for desc in descriptions:
print(f"- {desc}")
print("━" * 80)
def main():
"""Main entry point."""
analyzer = CommitAnalyzer()
# Check if in git repo
if not analyzer.check_git_repo():
print("❌ Error: Not in a git repository", file=sys.stderr)
sys.exit(1)
# Get staged changes
print("Analyzing staged changes...")
if not analyzer.get_staged_changes():
print("❌ No staged changes found. Use 'git add' to stage files first.", file=sys.stderr)
sys.exit(1)
# Generate commit message
subject, descriptions = analyzer.generate_commit_message()
# Display the message
print_commit_message(subject, descriptions)
# Ask for confirmation
print("\nUse this message? [Y/n/e(dit)]:", end=" ")
try:
response = input().strip().lower()
except (EOFError, KeyboardInterrupt):
print("\n\nAborted.")
sys.exit(0)
if response in ['', 'y', 'yes']:
# Commit with the generated message
full_message = subject + "\n\n" + "\n".join(f"- {d}" for d in descriptions)
try:
subprocess.run(
['git', 'commit', '-m', full_message],
check=True
)
print("✅ Committed successfully!")
except subprocess.CalledProcessError:
print("❌ Commit failed", file=sys.stderr)
sys.exit(1)
elif response in ['e', 'edit']:
print("\nOpening editor...")
full_message = subject + "\n\n" + "\n".join(f"- {d}" for d in descriptions)
try:
subprocess.run(['git', 'commit', '-e', '-m', full_message], check=True)
print("✅ Committed successfully!")
except subprocess.CalledProcessError:
print("❌ Commit failed", file=sys.stderr)
sys.exit(1)
else:
print("Aborted.")
sys.exit(0)
if __name__ == '__main__':
main()