Created
March 29, 2025 21:14
-
-
Save anonrose/fc1926596a7c03c56843773d1dc4e7f2 to your computer and use it in GitHub Desktop.
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 | |
# source .env to get the OPENAI_API_KEY | |
# π Get only the diff of what has already been staged | |
git_diff_output=$(git diff --cached) | |
# π Check if there are any staged changes to commit | |
if [ -z "$git_diff_output" ]; then | |
echo "β οΈ No staged changes detected. Aborting." | |
exit 1 | |
fi | |
# ποΈ Limit the number of lines sent to AI to avoid overwhelming it | |
git_diff_output_limited=$(echo "$git_diff_output" | head -n 100) | |
# π¦ Prepare the AI prompt for the chat model | |
messages=$(jq -n --arg diff "$git_diff_output_limited" '[ | |
{"role": "system", "content": "You are an AI assistant that helps generate git commit messages based on code changes."}, | |
{"role": "user", "content": ("Suggest an informative commit message by summarizing code changes from the shared command output. The commit message should follow the conventional commit format and provide meaningful context for future readers.\n\nChanges:\n" + $diff)} | |
]') | |
# π Send the request to OpenAI API using the correct chat endpoint | |
response=$(curl -s -X POST https://api.openai.com/v1/chat/completions \ | |
-H "Content-Type: application/json" \ | |
-H "Authorization: Bearer OPENAI_KEY" \ | |
-d "$(jq -n \ | |
--argjson messages "$messages" \ | |
'{ | |
model: "gpt-4", | |
messages: $messages, | |
temperature: 0.5, | |
max_tokens: 300 | |
}' | |
)") | |
# π Extract the AI-generated commit message | |
commit_message=$(echo "$response" | jq -r '.choices[0].message.content' | sed 's/^ *//g') | |
# π Check if we got a valid commit message from the AI | |
if [ -z "$commit_message" ] || [[ "$commit_message" == "null" ]]; then | |
echo "π« Failed to generate a commit message from OpenAI." | |
echo "β οΈ API Response: $response" | |
exit 1 | |
fi | |
# π Show the suggested commit message and ask for confirmation | |
echo "π€ Suggested commit message:" | |
echo "$commit_message" | |
read -p "Do you want to use this message? (y/n) " choice | |
if [[ "$choice" != "y" ]]; then | |
echo "π Commit aborted by the user." | |
exit 1 | |
fi | |
# π Option to dry run | |
if [[ $1 == "--dry-run" ]]; then | |
echo "β Dry run: Commit message generated, but no commit was made." | |
exit 0 | |
fi | |
# π Commit only staged changes with the AI-generated message | |
if ! git commit -m "$commit_message"; then | |
echo "β Commit failed. Aborting." | |
exit 1 | |
fi | |
# π Success message | |
echo "β Committed with message: $commit_message" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment