-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_gencommit.py
More file actions
217 lines (173 loc) · 6.95 KB
/
git_gencommit.py
File metadata and controls
217 lines (173 loc) · 6.95 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
#!/usr/bin/env python3
"""
git-gencommit: AI-powered git commit message generator using OpenAI
"""
import sys
import os
import subprocess
import argparse
import json
from typing import Optional
from openai import OpenAI
from pydantic import BaseModel
class CommitMessage(BaseModel):
"""Structured output schema for commit messages"""
summary: str
body: Optional[str] = None
def check_openai_key() -> str:
"""Check if OPENAI_API_KEY is set in environment"""
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("Error: OPENAI_API_KEY environment variable is not set.", file=sys.stderr)
print("Please set it with: export OPENAI_API_KEY='your-api-key'", file=sys.stderr)
sys.exit(1)
return api_key
def get_staged_diff() -> str:
"""Get the diff of staged changes"""
try:
result = subprocess.run(
["git", "diff", "--cached"],
capture_output=True,
text=True,
check=True
)
if not result.stdout.strip():
print("Error: No staged changes found.", file=sys.stderr)
print("Please stage your changes with 'git add' first.", file=sys.stderr)
sys.exit(1)
return result.stdout
except subprocess.CalledProcessError as e:
print(f"Error: Failed to get git diff: {e}", file=sys.stderr)
sys.exit(1)
except FileNotFoundError:
print("Error: git command not found. Make sure git is installed.", file=sys.stderr)
sys.exit(1)
def generate_commit_message(diff: str, model: str, format_type: str) -> CommitMessage:
"""Generate commit message using OpenAI with structured outputs"""
api_key = check_openai_key()
client = OpenAI(api_key=api_key)
# Build prompt based on format type
format_instructions = {
"detailed": "Generate a multi-line commit message with a concise summary line and a detailed body explaining the changes and why they were made.",
"conventional": "Generate a commit message following Conventional Commits format (type(scope): description). The summary should use the format like 'feat(auth): add login validation' or 'fix(api): resolve null pointer exception'. The body should provide additional context.",
"simple": "Generate a single-line descriptive commit message that clearly summarizes the changes."
}
prompt = f"""You are an expert at writing clear, informative git commit messages.
Analyze the following git diff and generate an appropriate commit message.
{format_instructions[format_type]}
The summary line should be clear, concise, and written in imperative mood (e.g., "Add feature" not "Added feature" or "Adds feature").
{f"The body should provide context about why the changes were made and any important details." if format_type != "simple" else ""}
Git diff:
{diff}
"""
try:
response = client.beta.chat.completions.parse(
model=model,
messages=[
{"role": "system", "content": "You are a helpful assistant that generates git commit messages."},
{"role": "user", "content": prompt}
],
response_format=CommitMessage,
)
return response.choices[0].message.parsed
except Exception as e:
print(f"Error: Failed to generate commit message: {e}", file=sys.stderr)
sys.exit(1)
def format_commit_message(commit_msg: CommitMessage, format_type: str) -> str:
"""Format commit message for display and use"""
if format_type == "simple" or not commit_msg.body:
return commit_msg.summary
else:
return f"{commit_msg.summary}\n\n{commit_msg.body}"
def edit_message_inline(message: str) -> str:
"""Allow user to edit the message in their preferred editor"""
import tempfile
# Get the user's preferred editor from environment, default to vim
editor = os.getenv("EDITOR", "vim")
# Create a temporary file with the current message
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tf:
tf.write(message)
temp_path = tf.name
try:
# Open the editor with the temp file
subprocess.run([editor, temp_path], check=True)
# Read the edited message
with open(temp_path, 'r') as f:
edited_message = f.read().strip()
if not edited_message:
print("\nError: Empty commit message. Commit cancelled.")
sys.exit(0)
return edited_message
except subprocess.CalledProcessError:
print(f"\nError: Failed to open editor '{editor}'.")
print("You can set a different editor with: export EDITOR='nano'")
sys.exit(1)
except KeyboardInterrupt:
print("\n\nCommit cancelled.")
sys.exit(0)
finally:
# Clean up the temporary file
if os.path.exists(temp_path):
os.remove(temp_path)
def prompt_user(message: str) -> str:
"""Show message and prompt user to accept, reject, or edit"""
while True:
print("\n" + "=" * 60)
print("Generated commit message:")
print("=" * 60)
print(message)
print("=" * 60)
response = input("\nAccept (a), Edit (e), or Reject (r)? [a/e/r]: ").strip().lower()
if response == "a":
return message
elif response == "e":
return edit_message_inline(message)
elif response == "r":
print("\nCommit cancelled.")
sys.exit(0)
else:
print("Invalid input. Please enter 'a', 'e', or 'r'.")
def commit_changes(message: str):
"""Commit the staged changes with the given message"""
try:
result = subprocess.run(
["git", "commit", "-m", message],
capture_output=True,
text=True,
check=True
)
print(result.stdout)
print("Commit successful!")
except subprocess.CalledProcessError as e:
print(f"Error: Failed to commit changes: {e}", file=sys.stderr)
print(e.stderr, file=sys.stderr)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(
description="AI-powered git commit message generator using OpenAI"
)
parser.add_argument(
"--model",
default="gpt-4o",
help="OpenAI model to use (default: gpt-4o)"
)
parser.add_argument(
"--format",
choices=["detailed", "conventional", "simple"],
default="detailed",
help="Commit message format (default: detailed)"
)
args = parser.parse_args()
# Get staged diff
print("Analyzing staged changes...")
diff = get_staged_diff()
# Generate commit message
print(f"Generating commit message using {args.model}...")
commit_msg = generate_commit_message(diff, args.model, args.format)
formatted_message = format_commit_message(commit_msg, args.format)
# Prompt user for approval/editing
final_message = prompt_user(formatted_message)
# Commit the changes
commit_changes(final_message)
if __name__ == "__main__":
main()