Last active
December 11, 2024 17:13
-
-
Save valmat/44822e1b7c6884bebb25b3ff005117fe to your computer and use it in GitHub Desktop.
AI git commit filler
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/env bash | |
set -e | |
model="gpt-4o"; | |
temperature=0.8; | |
prompt="Below is the output of \`git diff HEAD\`."` | |
`"\nPlease provide a perfect git commit message."` | |
`"\nAlways use an emoji as the first character. Use emojis in the message text when appropriate."` | |
`"\nUse past tense in the message title."` | |
`"\nIt would be nice to list the modified files in the commit message." | |
# checking whether the argument was passed to the script | |
if ! [[ $# -eq 0 ]]; then | |
prompt="${prompt}\n\nUse the following hint to generate the commit message: \`$1\`."` | |
`"\nThe commit message language is strictly English." | |
fi | |
prompt="${prompt}\n\n(# If there is an error in the code, please report it in the comments to the commit)." | |
git add . --all | |
message=$(git diff HEAD) | |
if [ -z "$message" ]; then | |
echo "Nothing to commit, working tree clean" >&2 | |
exit 1 | |
fi | |
json_payload=$(jq -n \ | |
--arg model "$model" \ | |
--arg temperature "$temperature" \ | |
--arg prompt "$prompt" \ | |
--arg message "$message" \ | |
'{ | |
model: $model, | |
temperature: ($temperature | tonumber), | |
messages: [ | |
{ | |
role: "system", | |
content: $prompt | |
}, | |
{ | |
role: "user", | |
content: $message | |
} | |
] | |
}') | |
response=$(curl -s https://api.openai.com/v1/chat/completions \ | |
-H "Content-Type: application/json" \ | |
-H "Authorization: Bearer $OPENAI_API_KEY" \ | |
-d "$json_payload") | |
# Checking if the "error" key is in the response | |
if echo "$response" | jq -e '.error' > /dev/null; then | |
echo "Error: $(echo "$response" | jq -r '.error.message')" >&2 | |
exit 2 | |
else | |
# If there is no error, trying to extract the desired message | |
content=$(echo "$response" | jq -e -r '.choices[0].message.content') | |
# Checking if the message was extracted | |
if ! [[ $? -eq 0 ]]; then | |
# If the message could not be extracted, | |
# output the original text of the response to stderr | |
echo "Failed to extract the message. Response was:" >&2 | |
echo "$response" >&2 | |
exit 3 | |
fi | |
fi | |
description_file=$(mktemp) | |
echo "$content" > "$description_file" | |
nano "$description_file" | |
cat "$description_file" | |
cat "$description_file" | sed '/^#/d' > "${description_file}.tmp" | |
mv "${description_file}.tmp" "$description_file" | |
git commit -a --file "$description_file" | |
rm "$description_file" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment