-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit_gen.py
More file actions
executable file
·223 lines (179 loc) · 7.08 KB
/
Copy pathcommit_gen.py
File metadata and controls
executable file
·223 lines (179 loc) · 7.08 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
#!/usr/bin/env python3
"""
Git Commit Message Generator
Analyzes staged changes and suggests conventional commit messages.
"""
import subprocess
import sys
import re
from pathlib import Path
from typing import Tuple, List, Dict
def run_git_command(args: List[str]) -> str:
"""Run a git command and return output."""
try:
result = subprocess.run(
['git'] + args,
capture_output=True,
text=True,
check=True
)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
print(f"Error running git command: {e}", file=sys.stderr)
sys.exit(1)
def get_staged_files() -> Dict[str, List[str]]:
"""Get lists of staged files by change type."""
output = run_git_command(['diff', '--cached', '--name-status'])
if not output:
print("No staged changes found. Stage some changes with 'git add' first.")
sys.exit(0)
changes = {
'added': [],
'modified': [],
'deleted': [],
'renamed': []
}
for line in output.split('\n'):
if not line:
continue
parts = line.split('\t')
status = parts[0]
filename = parts[1] if len(parts) > 1 else ''
if status.startswith('A'):
changes['added'].append(filename)
elif status.startswith('M'):
changes['modified'].append(filename)
elif status.startswith('D'):
changes['deleted'].append(filename)
elif status.startswith('R'):
changes['renamed'].append(filename)
return changes
def detect_commit_type(changes: Dict[str, List[str]]) -> str:
"""Detect the appropriate commit type based on changes."""
all_files = (changes['added'] + changes['modified'] +
changes['deleted'] + changes['renamed'])
# Check for documentation changes
doc_patterns = ['.md', '.txt', '.rst', 'docs/', 'README']
if any(any(pattern in f for pattern in doc_patterns) for f in all_files):
if all(any(pattern in f for pattern in doc_patterns) for f in all_files):
return 'docs'
# Check for test files
test_patterns = ['test_', '_test.', 'tests/', 'spec/', '.test.', '.spec.']
if any(any(pattern in f for pattern in test_patterns) for f in all_files):
if all(any(pattern in f for pattern in test_patterns) for f in all_files):
return 'test'
# Check for config/build files
config_patterns = ['.json', '.yaml', '.yml', '.toml', '.ini',
'Makefile', 'Dockerfile', '.config', 'package.json',
'requirements.txt', 'setup.py', 'pyproject.toml']
if any(any(pattern in f for pattern in config_patterns) for f in all_files):
if len(changes['added']) == 0 and len(changes['deleted']) == 0:
return 'chore'
# Check for style-only changes (css, formatting)
style_patterns = ['.css', '.scss', '.sass', '.less', '.style']
if any(any(pattern in f for pattern in style_patterns) for f in all_files):
return 'style'
# New files suggest a feature
if len(changes['added']) > 0:
return 'feat'
# Deletions might be refactoring or chore
if len(changes['deleted']) > 0 and len(changes['modified']) > 0:
return 'refactor'
# Default to fix for modifications
if len(changes['modified']) > 0:
return 'fix'
return 'chore'
def detect_scope(changes: Dict[str, List[str]]) -> str:
"""Detect the scope based on file paths."""
all_files = (changes['added'] + changes['modified'] +
changes['deleted'] + changes['renamed'])
if not all_files:
return ''
# Extract common directory or component
paths = [Path(f) for f in all_files]
# Get first-level directories
dirs = set()
for p in paths:
if len(p.parts) > 1:
dirs.add(p.parts[0])
# If all changes in one directory, use it as scope
if len(dirs) == 1:
scope = list(dirs)[0]
# Clean up common directory names
if scope in ['src', 'lib', 'app']:
if len(paths[0].parts) > 1:
scope = paths[0].parts[1]
return scope
# Check for common patterns
if any('auth' in f.lower() for f in all_files):
return 'auth'
if any('api' in f.lower() for f in all_files):
return 'api'
if any('ui' in f.lower() or 'component' in f.lower() for f in all_files):
return 'ui'
if any('db' in f.lower() or 'database' in f.lower() for f in all_files):
return 'db'
return ''
def generate_description(changes: Dict[str, List[str]], commit_type: str) -> str:
"""Generate a commit message description."""
added = len(changes['added'])
modified = len(changes['modified'])
deleted = len(changes['deleted'])
# Get primary file for context
primary_file = ''
if changes['added']:
primary_file = Path(changes['added'][0]).stem
elif changes['modified']:
primary_file = Path(changes['modified'][0]).stem
descriptions = {
'feat': f"add {primary_file} functionality" if primary_file else "add new feature",
'fix': f"resolve issue in {primary_file}" if primary_file else "fix bug",
'docs': "update documentation",
'style': "improve code formatting",
'refactor': f"restructure {primary_file}" if primary_file else "refactor code",
'test': "add test coverage",
'chore': "update dependencies" if any('requirements' in f or 'package.json' in f
for f in changes['modified']) else "update configuration",
'perf': "optimize performance"
}
return descriptions.get(commit_type, "update code")
def main():
"""Main entry point."""
print("🔍 Analyzing staged changes...\n")
# Check if we're in a git repository
try:
run_git_command(['rev-parse', '--git-dir'])
except SystemExit:
print("Error: Not a git repository")
sys.exit(1)
# Get staged changes
changes = get_staged_files()
# Detect commit type and scope
commit_type = detect_commit_type(changes)
scope = detect_scope(changes)
description = generate_description(changes, commit_type)
# Build commit message
if scope:
commit_msg = f"{commit_type}({scope}): {description}"
else:
commit_msg = f"{commit_type}: {description}"
# Display results
print("📝 Suggested commit message:")
print(f"\n {commit_msg}\n")
print("Changes detected:")
if changes['added']:
for f in changes['added']:
print(f" + Added: {f}")
if changes['modified']:
for f in changes['modified']:
print(f" ~ Modified: {f}")
if changes['deleted']:
for f in changes['deleted']:
print(f" - Deleted: {f}")
if changes['renamed']:
for f in changes['renamed']:
print(f" → Renamed: {f}")
print("\n💡 To use this message:")
print(f' git commit -m "{commit_msg}"')
if __name__ == '__main__':
main()