-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmagic_commit.py
More file actions
376 lines (306 loc) · 9.49 KB
/
Copy pathmagic_commit.py
File metadata and controls
376 lines (306 loc) · 9.49 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import itertools
import os
import subprocess
import sys
import threading
import time
from logging import Logger # Just so the linter doesn't complain
import openai
import requests
from jinja2 import Environment, PackageLoader
from .config import get_api_key, get_model, set_api_key, set_model
class GitRepositoryError(Exception):
"""Custom exception for Git repository errors."""
pass
class OpenAIKeyError(Exception):
"""Custom exception for OpenAI API key errors."""
class Llama2ServerError(Exception):
"""Custom exception for Llama2 server errors."""
pass
def is_git_repository(directory: str) -> bool:
"""
Check if a directory is a Git repository.
Parameters
----------
directory : str
The path to check.
Returns
-------
bool
True if the directory is a Git repository, False otherwise.
"""
print(directory)
return os.path.isdir(os.path.join(directory, ".git"))
def run_git_diff(directory: str) -> str:
"""
Run the `git diff --cached` command and return the result.
Parameters
----------
directory : str
The directory to run the command in.
Returns
-------
str
The output of the command.
"""
# TODO: Write unit tests for this function
return subprocess.run(
["git", "diff", "--cached"], cwd=directory, capture_output=True, text=True
).stdout
def run_git_log(directory: str) -> subprocess.CompletedProcess:
"""
Run 'git log' command in a specified directory.
Parameters
----------
directory : str
The directory to run the command in.
Returns
-------
subprocess.CompletedProcess
The result of the subprocess run command.
"""
return subprocess.run(
["git", "log", "--pretty=%B", "-n", "10"],
cwd=directory,
capture_output=True,
text=True,
)
def check_git_status(directory: str) -> bool:
"""
Check if there are changes staged for commit in the Git repository.
Parameters
----------
directory : str
The path to the Git repository.
Returns
-------
bool
True if there are changes staged for commit, False otherwise.
"""
result = subprocess.run(
["git", "status"], cwd=directory, capture_output=True, text=True
)
return "no changes added to commit" not in result.stdout
def get_commit_messages(directory: str) -> str:
"""
Fetch the last 10 commit messages from the Git repository.
Parameters
----------
directory : str
The path to the Git repository.
Returns
-------
str
The commit messages.
Raises
------
GitRepositoryError
If the specified directory is not a Git repository.
"""
if not is_git_repository(directory):
raise GitRepositoryError("The specified directory is not a Git repository.")
result = run_git_log(directory)
if result.returncode != 0:
raise GitRepositoryError("Unable to get commit messages.")
return result.stdout
def generate_commit_message(
diff: str, start: str, ticket: str, api_key: str, model: str, llama2_url: str = None
) -> str:
"""
Generate a commit message.
Parameters
----------
diff : str
The git diff to use.
start : str
The start of the commit message.
ticket : str
The GitHub issue to link in the commit message.
api_key : str
The OpenAI API key.
model : str
The OpenAI GPT model to use.
llama2_url: str
(Optional) The URL of the Llama2 server to use.
Returns
-------
str
The generated commit message.
Raises
------
OpenAIKeyError
If the OpenAI API key is not set.
"""
# Perform guard check for the OpenAI API key
if not api_key:
raise OpenAIKeyError("OpenAI API key not set.")
# Generate the prompt
system_msg = render_template("", "system")
user_msg = render_template(diff, "user")
# Generate the commit message
messages = [
{"role": "system", "content": system_msg},
{"role": "user", "content": user_msg},
]
# Determine which service to use
if llama2_url:
# Call the Llama2 server
response = call_llama2_server(llama2_url, messages)
print(response)
response = response["choices"][0]["message"]["content"].strip()
else:
# Use OpenAI's service
openai.api_key = api_key
response = openai.ChatCompletion.create(model=model, messages=messages)
response = response.choices[0].message.content.strip()
# Split the response by newline and store the result
split_response = response.split("\n", 1)
# Check if split_response contains at least 2 elements
if len(split_response) > 1:
response = split_response[1] if start else split_response[0]
else:
# If there is no newline, the whole response is either the start or the generated message
if not start:
start = response
# If start is already set, we leave response as is, or set it to an empty string
else:
response = ""
# Render and return the template
return render_final_template(start, response, ticket).strip()
def call_llama2_server(url: str, messages: list) -> dict:
"""
Call the Llama2 server.
Parameters
----------
url : str
The URL of the Llama2 server.
messages : list
The messages to send to the server.
Returns
-------
dict
The response from the server.
Raises
------
Llama2ServerError
If an error occurs while connecting to the server.
"""
try:
response = requests.post(url, json={"messages": messages})
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise Llama2ServerError(
f"An error occurred while connecting to the Llama2 server: {e}"
)
def render_template(message: str, template_name: str) -> str:
"""
Render the commit message template.
Parameters
----------
message : str
The commit message to render.
template_name : str
The name of the template to use.
Returns
-------
str
The rendered commit message.
"""
# TODO: Write unit tests for this function
# Render any escape sequences in the message
message.encode().decode("unicode_escape")
# Render and return the template
jinja = Environment(loader=PackageLoader("magic_commit", "templates")).get_template(
f"{template_name}.jinja"
)
return jinja.render(diff=message)
def render_final_template(start: str, generated_message: str, ticket: str) -> str:
"""
Render the final commit message template.
Parameters
----------
start : str
The start of the commit message.
generated_message : str
The generated commit message.
ticket : str
The GitHub issue to link in the commit message.
Returns
-------
str
The rendered commit message.
"""
# Render any escape sequences in the message
generated_message.encode().decode("unicode_escape")
# Render and return the template
jinja = Environment(loader=PackageLoader("magic_commit", "templates")).get_template(
"final.jinja"
)
return jinja.render(start=start, generated_message=generated_message, ticket=ticket)
def animate_loading(stop_event: threading.Event) -> None:
"""
Display a simple loading animation with dots until a stop_event is set.
Parameters
----------
stop_event : threading.Event
An event to signal when the animation should stop.
"""
for c in itertools.cycle([". ", ".. ", "..."]):
if stop_event.is_set():
sys.stdout.write("\r \r") # Clear the line
sys.stdout.flush()
break
sys.stdout.write("\rLoading" + c)
sys.stdout.flush()
time.sleep(0.5)
def run_magic_commit(
directory: str,
start: str,
ticket: str,
api_key: str,
model: str,
show_loading_message: bool,
llama2_url: str = None,
) -> str:
"""
Generate a commit message and return it.
Parameters
----------
directory : str
The path to the Git repository.
start : str
The start of the commit message.
ticket : str
The GitHub issue to link in the commit message.
api_key : str
The OpenAI API key.
model : str
The OpenAI GPT model to use.
show_loading_message : bool
Whether or not to show the loading animation.
llama2_url: str
(Optional) The URL of the Llama2 server to use.
Returns
-------
str
The generated commit message.
"""
# Create a threading event to signal when to stop the loading animation
if show_loading_message:
stop_loading = threading.Event()
loading_thread = threading.Thread(target=animate_loading, args=(stop_loading,))
loading_thread.start()
try:
diff = run_git_diff(directory)
if not check_git_status(directory): # Check if there are staged changes
return "⛔ Warning: No staged changes detected. Please stage some changes before running magic-commit."
commit_message = generate_commit_message(
diff, start, ticket, api_key, model, llama2_url
)
finally:
# Ensure the loading animation stops
if show_loading_message:
stop_loading.set()
loading_thread.join()
return commit_message