Skip to content

Instantly share code, notes, and snippets.

@crazy4pi314
Last active February 15, 2023 18:27
Show Gist options
  • Save crazy4pi314/4f64dd1fd43cee299e82278fef6d9f7a to your computer and use it in GitHub Desktop.
Save crazy4pi314/4f64dd1fd43cee299e82278fef6d9f7a to your computer and use it in GitHub Desktop.
OpenAI assisted git commit msg

How to use:

  1. Make sure you have your OpenAI API key set as an environment variable (OPENAI_API_KEY)
  2. Set up the pre-commit message prep hook bu adding the other two files here in the ./git/hooksdirectory.

Test using it by staging some changes to commit and then running git commit in the command line. The file it pops up for you to edit now should have the suggested summary of the changes from the OpenAI api commented out like this:

# Here is a suggested commit message from code-davinci-002.
# ---
# * Added ipynb to the dependencies
# 
# ### Question 2
# 
# What is the purpose of the `environment.yml` file?
# 
# * It is a file that contains the dependencies for the project.
# 
# ### Question 3
# 
# What is the purpose of the `.gitignore`
# ---
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch main
# Changes to be committed:
#	modified:   test.json
#
# Changes not staged for commit:
#	modified:   environment.yml
#
# Untracked files:
#	.env
#	Untitled-1.ipynb
#	commit-helper.code-workspace
#	foo.py
#	testmsg
#	view
#

TODO:

  • Need better prompt and model engineering work to get better message formats and contents. Easy to adjust with the globals in the Python script.
#!/bin/sh
python .git/hooks/prepare-commit-msg.py $1
#!/usr/bin/env python
import sys
import os
from subprocess import check_output
import openai
MODEL = "code-davinci-002"
PROMPT = '\nExplain the changes from the git diff output in plain English. Use past tense third person, for example "Modified the code":\n'
print("Starting prepare-commit-msg hook")
def parse_response(response, query):
return response["choices"][0]["text"].replace(query, "").strip()
commit_msg_filepath = sys.argv[1]
diff_text = check_output(["git", "diff"]).decode("utf-8").strip()
openai.api_key = os.getenv("OPENAI_API_KEY")
stop_sequence = '\"\"\"'
query = diff_text + stop_sequence + PROMPT
response = openai.Completion.create(
model=MODEL,
prompt=query,
temperature=0,
max_tokens=64,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
stop=[stop_sequence],
echo=True,
)
commented_suggestion = [f"\n# Here is a suggested commit message from {MODEL}.\n# ---"] + [
f"# {line}" for line in parse_response(response, query).splitlines()
] + ["# ---"]
with open(commit_msg_filepath, "r+") as f:
commit_msg = f.read()
f.seek(0, 0)
f.write('\n'.join(commented_suggestion)+ f"{commit_msg}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment