Skip to content

Instantly share code, notes, and snippets.

@mmv08
Last active August 27, 2024 13:55
Show Gist options
  • Save mmv08/d967f3b6351fbcb5be9b3ce2af085093 to your computer and use it in GitHub Desktop.
Save mmv08/d967f3b6351fbcb5be9b3ce2af085093 to your computer and use it in GitHub Desktop.
# AI-powered Git Commit Function
# Copy paste this gist into your ~/.bashrc or ~/.zshrc to gain the `gcm` command. It:
# 1) gets the current staged changed diff
# 2) sends them to an LLM to write the git commit message
# 3) allows you to easily accept, edit, regenerate, cancel
# 4) also adds a global run_llm command that accepts a prompt
# based on https://gist.github.com/karpathy/1dd0294ef9567971c1e4348a90d69285
gcm-llm() {
# Function to generate commit message
run_llm() {
# ollama run llama3.1 "$1"
ollama run gemma2:27b "$1"
}
# Function to read user input compatibly with both Bash and Zsh
read_input() {
if [ -n "$ZSH_VERSION" ]; then
echo -n "$1"
read -r REPLY
else
read -p "$1" -r REPLY
fi
}
# Main script
echo "Generating..."
diff=$(git --no-pager diff --cached)
prompt="
Below is a diff of all staged changes, coming from the command:
$diff
Generate a concise, one-line commit message for these changes. Do not include anything else in the output."
commit_message=$(run_llm "$prompt")
while true; do
echo -e "\nProposed commit message:"
echo "$commit_message"
read_input "Do you want to (a)ccept, (e)dit, (r)egenerate, or (c)ancel? "
choice=$REPLY
case "$choice" in
a|A )
if git commit -m "$commit_message"; then
echo "Changes committed successfully!"
return 0
else
echo "Commit failed. Please check your changes and try again."
return 1
fi
;;
e|E )
read_input "Enter your commit message: "
commit_message=$REPLY
if [ -n "$commit_message" ] && git commit -m "$commit_message"; then
echo "Changes committed successfully with your message!"
return 0
else
echo "Commit failed. Please check your message and try again."
return 1
fi
;;
r|R )
echo "Regenerating commit message..."
commit_message=$(run_llm "$prompt")
;;
c|C )
echo "Commit cancelled."
return 1
;;
* )
echo "Invalid choice. Please try again."
;;
esac
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment