In this guide, I'll show you how to create a Bash script that generates a short poem based on the changes made in your Git repository and uses it as a commit message. We'll integrate the OpenAI API to generate the poems and override the git commit -m
command to use our custom script.
Create a file called poetic_commit.sh
and paste the following code:
#!/bin/bash
# Save your OpenAI API Key in the OPENAI_API_KEY variable
export OPENAI_API_KEY="your_openai_api_key_here"
# Get a list of changed files
files_changed=$(git diff --name-only)
# Create a brief description of the changes
description="Changed files: $files_changed"
# Call OpenAI API using the 'description' to generate a short poem
commit_poem=$(curl -s -H "Content-Type: application/json" -H "Authorization: Bearer $OPENAI_API_KEY" -d "{\"model\": \"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\", \"content\": \"Write a short poem about the following changes: $description\"}], \"max_tokens\": 30, \"temperature\": 0.7, \"n\": 1, \"stop\": null}" "https://api.openai.com/v1/chat/completions" | jq -r '.choices[0].message.text' | tr -d '\n')
# Commit with the generated poem as the commit message
git commit -m "$commit_poem"
Replace your_openai_api_key_here
with your actual OpenAI API key.
Make sure you have curl
and jq
installed on your system. If not, install them using your package manager, e.g.:
sudo apt-get install curl jq
Make the script executable by running the following command:
chmod +x poetic_commit.sh
Create a shell function called git
that will override the git
command and call the custom script when you use git commit -m
. Add the following function to your ~/.bashrc
or ~/.bash_aliases
file:
# Save the original git command in a variable
_git=$(which git)
# Create a custom git function to override the git command
git() {
if [[ "$1" == "commit" ]] && [[ "$2" == "-m" ]]; then
# Call the custom script
path/to/your/script/poetic_commit.sh
else
# Call the original git command with the passed arguments
$_git "$@"
fi
}
Replace path/to/your/script/poetic_commit.sh
with the actual path to the poetic_commit.sh
script that you created earlier.
After adding the function to your ~/.bashrc
or ~/.bash_aliases
, save the file and restart your terminal or run source ~/.bashrc
or source ~/.bash_aliases
to apply the changes.
Now, when you use git commit -m
, it will run the poetic_commit.sh
script instead of the regular commit command. All other git
commands will work as usual.
Please note that using the OpenAI API may have associated costs, and the script above assumes you have the necessary permissions and quota to use the