Last active
February 25, 2024 00:52
-
-
Save sullrich/d67ec64a20543753862a5747cd42478f to your computer and use it in GitHub Desktop.
This file contains 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 | |
# gitcommit - Script to summarize git changes using OpenAI and commit with a custom message leading the AI summary | |
# Ensure OPENAI_API_KEY is set | |
if [[ -z "${OPENAI_API_KEY}" ]]; then | |
echo "OPENAI_API_KEY is not set. Please export it before running this script." | |
exit 1 | |
fi | |
# Check for custom commit message argument | |
if [[ -z "$1" ]]; then | |
echo "No custom commit message provided. Please provide a commit message as the first argument." | |
exit 1 | |
fi | |
CUSTOM_MSG="$1" | |
# Perform git diff and save output, then JSON-encode it | |
GIT_DIFF=$(git diff) | |
# Check if there are changes to commit | |
if [[ -z "${GIT_DIFF}" ]]; then | |
echo "No changes to commit." | |
exit 0 | |
fi | |
# Prepare the JSON payload using jq | |
PAYLOAD=$(jq -n --arg content "Summarize this commit: $GIT_DIFF" \ | |
'{model: "gpt-3.5-turbo", messages: [{role: "user", content: $content}], temperature: 0.7}') | |
# Call OpenAI to summarize the git diff, using the JSON-encoded diff | |
SUMMARY_RESPONSE=$(curl -s -H "Content-Type: application/json" \ | |
-H "Authorization: Bearer $OPENAI_API_KEY" \ | |
-d "$PAYLOAD" \ | |
"https://api.openai.com/v1/chat/completions") | |
# Debug: Uncomment to inspect the raw response | |
# echo "$SUMMARY_RESPONSE" | |
# Extract summary from response | |
OPENAISUMMARY=$(echo "$SUMMARY_RESPONSE" | jq -r '.choices[0].message.content' | tr -d '\n') | |
# Check if summary is empty, null, or failed to be obtained | |
if [[ -z "${OPENAISUMMARY}" ]] || [[ "${OPENAISUMMARY}" == "null" ]]; then | |
echo "Failed to obtain a valid summary from OpenAI. Exiting script." | |
exit 1 | |
fi | |
COMMIT_MSG="${CUSTOM_MSG}: ${OPENAISUMMARY}" | |
# Perform git commit | |
git commit -a -m "$COMMIT_MSG" | |
# Output success message | |
echo "Changes committed with summary: '$COMMIT_MSG'" | |
git push | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment