Skip to content

Instantly share code, notes, and snippets.

@markusfisch
Created March 12, 2025 19:41
Show Gist options
  • Save markusfisch/1282a11d88f21703da5bc5be93e1459f to your computer and use it in GitHub Desktop.
Save markusfisch/1282a11d88f21703da5bc5be93e1459f to your computer and use it in GitHub Desktop.
Generate commit messages with OpenAI API

Generate commit messages with OpenAI API

This script automatically generates a commit message for staged changes in a git repository using OpenAI's API.

It tries to enforce the contributing guidelines for a good commit message.

Unfortunately, this doesn't always work. If you have ideas for a better prompt, please let me know!

Prerequisites

  • OPENAI_API_KEY environment variable with a valid OpenAI API key
  • jq
  • curl

Usage

Put this script into your PATH and run it inside a git repository with staged changes:

$ gcm
#!/usr/bin/env bash
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
echo 'error: not inside a git repository' >&2
exit 1
}
STAGED_DIFF=$(git diff --cached)
[ "$STAGED_DIFF" ] || {
echo 'no staged changes found' >&2
exit 0
}
(( $(echo "$STAGED_DIFF" | wc -l) > 1000 )) && {
echo 'error: too many changes to upload' >&2
exit 1
}
PROMPT=$(cat << EOF
Please generate a concise commit message using the following staged changes. The commit message must follow these strict formatting rules:
1. The first line MUST:
- Be 50 characters or less.
- Use the imperative mood.
- NOT end with a period.
2. After the first line, there MUST be a blank line.
3. If further explanation is needed, include additional lines:
- Each line MUST wrap at exactly 72 characters.
- Do NOT exceed 72 characters per line.
- Break sentences appropriately to ensure readability.
Now, analyze the following staged changes and generate a commit message that strictly adheres to these rules.
Staged changes:
${STAGED_DIFF}
IMPORTANT: Do not ignore these rules. The commit message must strictly follow them.
EOF
)
RESPONSE=$(curl -s -X POST 'https://api.openai.com/v1/chat/completions' \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-d "$(jq -n \
--arg model 'gpt-3.5-turbo' \
--arg prompt "$PROMPT" \
'{
"model": $model,
"messages": [
{
"role": "user",
"content": $prompt
}
],
"temperature": 0.7
}'
)"
) || exit $?
COMMIT_MESSAGE=$(echo "$RESPONSE" | \
jq -r '.choices[0].message.content // empty' \
)
if [ -z "$COMMIT_MESSAGE" ] || [ "$COMMIT_MESSAGE" == 'null' ]; then
echo "error: $RESPONSE" >&2
exit 1
fi
git commit -e -m "$COMMIT_MESSAGE" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment