Skip to content

Instantly share code, notes, and snippets.

@kenchopa
Last active June 16, 2025 21:12
Show Gist options
  • Select an option

  • Save kenchopa/d46c940f2bc28ef5959b381f2d02dd0b to your computer and use it in GitHub Desktop.

Select an option

Save kenchopa/d46c940f2bc28ef5959b381f2d02dd0b to your computer and use it in GitHub Desktop.
openai generated auto commit
#!/bin/bash
set -euo pipefail
exec > /tmp/prepare-commit-msg.log 2>&1
echo "βš™οΈ prepare-commit-msg hook starting..."
COMMIT_MSG_FILE="${1:-}"
COMMIT_SOURCE="${2:-}"
COMMIT_SHA="${3:-}"
echo "πŸ“ COMMIT_MSG_FILE: $COMMIT_MSG_FILE"
echo "πŸ“„ COMMIT_SOURCE: $COMMIT_SOURCE"
echo "πŸ”’ COMMIT_SHA: $COMMIT_SHA"
# Skip for merge, squash, rebase, etc.
if [[ -n "$COMMIT_SOURCE" ]]; then
echo "ℹ️ Commit source provided ($COMMIT_SOURCE). Skipping hook."
exit 0
fi
# Check if jq is installed
if ! command -v jq > /dev/null; then
echo "❌ jq is not installed. Please install jq to continue."
exit 1
fi
# Check for OpenAI key
if [[ -z "${OPENAI_API_KEY:-}" ]]; then
echo "❌ OPENAI_API_KEY is not set. Skipping AI commit message."
exit 0
fi
echo "πŸ”‘ OPENAI_API_KEY detected"
# Get staged changes
echo "πŸ” Checking for staged diff..."
GIT_DIFF=$(git diff --cached)
if [[ -z "$GIT_DIFF" ]]; then
echo "❌ No staged changes to describe."
exit 0
fi
echo "βœ… Staged diff found"
# Build OpenAI prompt
echo "πŸ“ Preparing OpenAI prompt..."
PROMPT=$(cat <<EOF
Generate a concise, conventional commit message based on the following git diff.
Use the Conventional Commits format (e.g., feat:, fix:, chore:, docs:, refactor:, test:).
Summarize the intent clearly. Do not include file paths or code snippets.
Git diff:
$GIT_DIFF
EOF
)
# Escape prompt using jq to ensure valid JSON
ESCAPED_PROMPT=$(jq -Rs . <<< "$PROMPT")
# Send to OpenAI
echo "πŸ“‘ Sending request to OpenAI..."
RAW_RESPONSE=$(curl -sS -w "\n%{http_code}" https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{
"model": "gpt-4",
"messages": [
{
"role": "user",
"content": $ESCAPED_PROMPT
}
],
"temperature": 0.3
}
EOF
)
# Split response and status
HTTP_BODY=$(echo "$RAW_RESPONSE" | sed '$d')
HTTP_STATUS=$(echo "$RAW_RESPONSE" | tail -n1)
echo "πŸ“¨ Raw response (HTTP $HTTP_STATUS):"
echo "$HTTP_BODY"
# Check status code
if [[ "$HTTP_STATUS" != "200" ]]; then
echo "❌ OpenAI API returned HTTP $HTTP_STATUS"
echo "⚠️ Commit aborted."
exit 1
fi
# Check for OpenAI error message
OPENAI_ERROR=$(echo "$HTTP_BODY" | jq -r '.error.message // empty')
if [[ -n "$OPENAI_ERROR" ]]; then
echo "❌ OpenAI error: $OPENAI_ERROR"
exit 1
fi
# Parse message content
COMMIT_MESSAGE=$(echo "$HTTP_BODY" | jq -r '.choices[0].message.content // empty')
if [[ -z "$COMMIT_MESSAGE" ]]; then
echo "❌ Failed to parse commit message from response."
exit 1
fi
echo "βœ… Commit message received"
# Prompt user (supports non-interactive fallback)
echo ""
echo "πŸ€– Suggested commit message:"
echo "----------------------------------"
echo "$COMMIT_MESSAGE"
echo "----------------------------------"
echo ""
if [[ -t 0 ]]; then
echo "Options:"
echo "[a] Accept"
echo "[e] Edit"
echo "[c] Cancel commit"
read -p "Your choice [a/e/c]: " choice
else
echo "⚠️ Non-interactive shell detected. Auto-accepting commit message."
choice="a"
fi
case "$choice" in
a|A)
echo "$COMMIT_MESSAGE" > "$COMMIT_MSG_FILE"
echo "πŸ’Ύ Message accepted and written"
;;
e|E)
TMPFILE=$(mktemp)
echo "$COMMIT_MESSAGE" > "$TMPFILE"
echo "πŸ“ Opening editor: ${EDITOR:-vim}"
${EDITOR:-vim} "$TMPFILE"
cat "$TMPFILE" > "$COMMIT_MSG_FILE"
rm "$TMPFILE"
echo "✏️ Message edited and written"
;;
c|C)
echo "❌ Commit cancelled by user."
exit 1
;;
*)
echo "⚠️ Invalid option. Commit cancelled."
exit 1
;;
esac
@kenchopa
Copy link
Author

πŸ€– prepare-commit-msg: AI-Powered Git Commit Messages

This Git hook automatically generates commit messages using the OpenAI GPT-4 API, based on your staged changes. It follows the Conventional Commits specification to keep your commit history consistent and meaningful.


✨ Features

  • Generates commit messages using OpenAI GPT-4
  • Follows Conventional Commits format (feat:, fix:, chore:, etc.)
  • Skips for merge/rebase/squash commits
  • Allows manual approval/editing/canceling before finalizing
  • Automatically logs execution to /tmp/prepare-commit-msg.log

πŸ› οΈ Installation

1. Save the script as a Git hook

curl -o .git/hooks/prepare-commit-msg https://gist.githubusercontent.com/kenchopa/d46c940f2bc28ef5959b381f2d02dd0b/raw/prepare-commit-msg
chmod +x .git/hooks/prepare-commit-msg

Alternatively, copy the script manually into .git/hooks/prepare-commit-msg and make it executable.


2. Install dependencies

Make sure both jq and curl are installed on your system:

  • macOS (Homebrew):

    brew install jq
  • Ubuntu/Debian:

    sudo apt install jq
  • Arch Linux:

    sudo pacman -S jq
  • Windows (via Chocolatey):

    choco install jq

3. Set your OpenAI API key

You must provide your OpenAI API key to allow the hook to send requests to the GPT-4 API.

πŸ”‘ Option 1: Export manually (for current session)

export OPENAI_API_KEY="sk-..."

πŸ” Option 2: Persist the key in your shell configuration

To automatically load your OPENAI_API_KEY every time you open a terminal, add it to your shell config file.

  • For Bash (~/.bashrc or ~/.bash_profile):

    echo 'export OPENAI_API_KEY="sk-..."' >> ~/.bashrc
    source ~/.bashrc
  • For Zsh (~/.zshrc):

    echo 'export OPENAI_API_KEY="sk-..."' >> ~/.zshrc
    source ~/.zshrc
  • For Fish shell:

    set -Ux OPENAI_API_KEY "sk-..."

Replace "sk-..." with your actual OpenAI API key from your OpenAI account dashboard.


πŸš€ Usage

  1. Stage your changes:

    git add .
  2. Commit as usual:

    git commit
  3. The hook will:

    • Detect staged changes
    • Send them to OpenAI GPT-4
    • Suggest a Conventional Commit message
    • Ask you to:
      • [a] Accept
      • [e] Edit
      • [c] Cancel

If you're in a non-interactive shell (like CI), the message will be auto-accepted.


πŸ”’ Environment Requirements

  • OPENAI_API_KEY must be set
  • jq must be installed
  • Internet connection to access the OpenAI API

❗ Skipping the Hook

To skip the hook (e.g., for merge commits or CI):

git commit --no-verify

πŸ“„ License

MIT β€” free to use and modify. Credit is appreciated but not required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment