-
Install
llm -
Create a new directory for your global Git hooks. For example, you can create a directory named
git_hooksin your home directory:
mkdir -p ~/.git_hooks
-
Create a new file named
prepare-commit-msg(without any extension) in the~/.git_hooksdirectory. -
Open the
prepare-commit-msgfile in a text editor and add the same content as before:
#!/bin/sh
# ANSI color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Function to display a spinning animation
spin_animation() {
spinner=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
while true; do
for i in "${spinner[@]}"; do
tput civis # Hide the cursor
tput el1 # Clear the line from the cursor to the beginning
printf "\r${YELLOW}%s${NC} Generating LLM commit message..." "$i"
sleep 0.1
tput cub 32 # Move the cursor back 32 columns
done
done
}
# Check if the commit is a merge commit
if [ -n "$2" ]; then
exit 0
fi
# Start the spinning animation
spin_animation &
spin_pid=$!
# Generate the commit message using git diff and llm
commit_msg=$(git diff --cached | llm -s "$(cat ~/.config/prompts/commit-system-prompt.txt)")
# Stop the spinning animation
kill $spin_pid
wait $spin_pid 2>/dev/null
# Move the cursor to the next line and show the cursor
tput cnorm
echo
# Display the generated commit message with colors and formatting
echo "${BLUE}=== Generated Commit Message ===${NC}"
echo "${GREEN}$commit_msg${NC}"
echo "${BLUE}=================================${NC}"
echo
# Write the generated commit message to the commit message file
echo "$commit_msg" > "$1"
- Make the
prepare-commit-msgfile executable by running the following command in your terminal:
chmod +x ~/.git_hooks/prepare-commit-msg
- Configure Git to use your global hooks directory by running the following command:
git config --global core.hooksPath ~/.git_hooks
This command sets the core.hooksPath configuration option to your global hooks directory (~/.git_hooks).
Now, whenever you run git commit in any of your repositories, Git will execute the global prepare-commit-msg hook located in ~/.git_hooks/prepare-commit-msg. The hook will generate the commit message based on the staged changes using the llm command and the system prompt from ~/.config/prompts/commit-system-prompt.txt.
By setting up a global prepare-commit-msg hook, you can have the commit message generation functionality available in all your repositories without the need to set it up individually for each repository.
Remember to have the llm command and the ~/.config/prompts/commit-system-prompt.txt file set up correctly for the global hook to work as expected.
With this global hook in place, you can simply stage your changes using git add or git add -p, and then run git commit. The global prepare-commit-msg hook will automatically generate the commit message for you, ready for review and editing before finalizing the commit.