Last active
April 30, 2024 19:44
-
-
Save xpepper/6c194e87183550f54affef78acc8f638 to your computer and use it in GitHub Desktop.
An AI-driven git commit message generator. It needs a valid OpenAI key set as an env variable`OPENAI_API_KEY`. It works on macOS, needs curl and jq in order to work.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
OPENAI_API_KEY="${OPENAI_API_KEY}" | |
HOST="https://api.openai.com" | |
MODEL="gpt-3.5-turbo" | |
# Check if the API key is set | |
if [ -z "$OPENAI_API_KEY" ]; then | |
echo "OpenAI API key is not set. Please set the OPENAI_API_KEY environment variable." | |
exit 1 | |
fi | |
# Get the diff of staged changes | |
DIFF=$(git diff --staged) | |
# Check if there are any staged changes | |
if [ -z "$DIFF" ]; then | |
echo "No changes are staged for commit." | |
exit 1 | |
fi | |
# Escape special JSON characters in the diff output | |
# This uses Perl instead of sed for better cross-platform compatibility | |
ESCAPED_DIFF=$(echo "content: $DIFF" | perl -pe 's/\\/\\\\/g; s/"/\\"/g; s/\n/\\n/g; s/\r//g;') | |
# Prepare the data for the API request | |
read -r -d '' DATA <<EOF | |
{ | |
"model": "$MODEL", | |
"messages": [ | |
{"role": "system", "content": "You are a git message commit generator. You get a set of file changes and you generate a proper git commit message, following the Conventional Commits standard. Don't add any other info if not related to the changes themselves."}, | |
{"role": "user", "content": "$ESCAPED_DIFF"} | |
], | |
"max_tokens": 250, | |
"temperature": 0.3 | |
} | |
EOF | |
# Make the API request to OpenAI using the chat completions endpoint | |
RESPONSE=$(curl -s "$HOST/v1/chat/completions" \ | |
-H "Content-Type: application/json" \ | |
-H "Authorization: Bearer $OPENAI_API_KEY" \ | |
-d "$DATA") | |
# Extract the commit message from the response | |
COMMIT_MESSAGE=$(echo $RESPONSE | jq -r '.choices[0].message.content') | |
# Output the commit message | |
echo "Here's a commit message based on the diff:" | |
echo "$COMMIT_MESSAGE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another Python version using
openai
lib