Skip to content

Instantly share code, notes, and snippets.

@PurpleBooth
Last active March 25, 2024 02:20
Show Gist options
  • Select an option

  • Save PurpleBooth/974e84f2801e42e81b3f07d80b321afd to your computer and use it in GitHub Desktop.

Select an option

Save PurpleBooth/974e84f2801e42e81b3f07d80b321afd to your computer and use it in GitHub Desktop.
I cba with writing my own commit messages anymore
#!/usr/bin/env python
import json
import os
import subprocess
import sys
from pprint import pprint
from urllib.request import Request, urlopen
api_key = "replaceme"
def ask_openai(summary: str, diff: str) -> str:
url = "https://api.openai.com/v1/chat/completions"
body = json.dumps(
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "system",
"content": "Write a well formatted commit message, without trailers, do not write a conventional commit",
},
{
"role": "assistant",
"content": "Sure, do you have any information other than the diff?",
},
{"role": "user", "content": summary},
{"role": "assistant", "content": "Can you provide me the diff?"},
{"role": "user", "content": diff},
{
"role": "assistant",
"content": "Thanks, the next message has the text you would put in your editor",
},
],
}
)
httprequest = Request(
url,
method="POST",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
},
)
with urlopen(httprequest, data=body.encode("utf-8")) as response:
body = response.read().decode()
return json.loads(body)["choices"][0]["message"]["content"]
hint = "No"
if len(sys.argv) > 1:
hint = " ".join(sys.argv[1:])
diff_output = subprocess.run(
["git", "diff", "--patch", "--cached"], capture_output=True
)
diff_output.check_returncode()
print(ask_openai(hint, diff_output.stdout.decode()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment