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
# Add to your profile the following bash function | |
# Use it with this command: git commit -m "$(summarize_git_diff)" | |
# To confirm how the commit message will look like: git log -1 | |
export OPENAI_API_KEY='your openai api key' | |
summarize_git_diff() { | |
# Capture the full git diff (staged changes) without using a pager | |
local diff_file chunk_dir chunk_prefix final_summary chunk payload response chunk_summary | |
diff_file=$(mktemp) | |
git --no-pager diff --cached > "$diff_file" | |
# Create a temporary directory for the chunk files | |
chunk_dir=$(mktemp -d) | |
chunk_prefix="${chunk_dir}/chunk_" | |
# Split the diff file into chunks of 200 lines (adjust as needed) | |
split -l 200 "$diff_file" "$chunk_prefix" | |
# Initialize the final summary | |
final_summary="" | |
# Process each chunk | |
for chunk in "${chunk_dir}"/chunk_*; do | |
# Build the JSON payload safely using jq's --rawfile to avoid issues with quotes or newlines | |
payload=$(jq -n --rawfile chunk "$chunk" \ | |
--arg preface "Summarize concisely without losing preciseness the following git diff output to produce a git commit message:\n" \ | |
'{ | |
model: "gpt-3.5-turbo", | |
messages: [{role: "user", content: ($preface + $chunk)}], | |
max_tokens: 150, | |
temperature: 0.3 | |
}') | |
# Call the OpenAI API | |
response=$(curl -sS https://api.openai.com/v1/chat/completions \ | |
-H "Content-Type: application/json" \ | |
-H "Authorization: Bearer ${OPENAI_API_KEY}" \ | |
-d "$payload") | |
# Extract the summary for this chunk | |
chunk_summary=$(echo "$response" | jq -r '.choices[0].message.content') | |
# Append the chunk summary to the final summary | |
final_summary="${final_summary}\n\n${chunk_summary}" | |
done | |
# Clean up temporary files and directory | |
rm "$diff_file" | |
rm -r "$chunk_dir" | |
# Output the combined summary | |
echo -e "$final_summary" | |
} |