How to generate git commit messages using GPT-4

In this tutorial, you'll be given a bash script to help you generate git commit messages using ChatGPT / GPT-4 API based on your git diff message

Share:

Apr 1, 2023 286 Words

Read Time: 2 Minutes

A mockup of the blog post named "How to generate git commit messages using GPT-4" by TnvMadhav.

Setup & Requirments

🧠 I’ve built this on the macOS and I’ve written this guide for linux based operating system

Install jq using Home Brew

brew install jq

Generate OpenAPI Key

  • Go to the OpenAI website and signup if you don’t already have an account
  • From the OpenAI dashboard, click the “API keys” link in the top menu
  • Click the “Create” button to generate your API key and copy it
  • Store key in an environment variable called OPENAI_API_KEY for use while running bash script later

Get Bash Script

#!/bin/bash

# Replace double quotes with Unicode character
function replace_double_quotes {
  echo "${1//\"/\u201C}"
}

# Replace single quotes with Unicode character
function replace_single_quotes {
  echo "${1//\'/\u2018}"
}

# Get the Git diff and save it to a file
STRING_WITH_BREAKS=$(git diff)

# Read the API key from an environment variable
API_KEY=$OPENAI_API_KEY

echo "With breaks $STRING_WITH_BREAKS \n"

STRING_NO_BREAKS=$( echo "Generate a commit message based on this Git diff: $STRING_WITH_BREAKS" | tr -d '\n')

# Solves convoluted escape issues:  spent 2 hours on this problem :(
STRING_NO_BREAKS=$(replace_double_quotes "$(replace_single_quotes "$STRING_NO_BREAKS")")

echo "No breaks $STRING_NO_BREAKS \n"

# URL Encode the string
STRING_URL_ENCODE=$(echo "$STRING_NO_BREAKS" | jq -sRr @uri)

echo "Url encode $STRING_URL_ENCODE \n"

if [ -z "$API_KEY" ]; then
  echo "ERROR: OPENAI_API_KEY environment variable is not set"
  exit 1
fi

# Call the ChatGPT API to generate a commit message based on the diff
CURL_COMMAND="curl --location 'https://api.openai.com/v1/chat/completions' \
 --header 'Content-Type: application/json' \
 --header 'Authorization: Bearer $API_KEY' \
 --data-raw '{\"model\": \"gpt-4\", \"messages\": [{\"role\": \"user\", \"content\": \"$STRING_URL_ENCODE\" }]}'"

echo "Curl command is $CURL_COMMAND"

COMMIT_MSG=$(eval "$CURL_COMMAND" | jq -r ".choices[].message.content")

# Add and commit the changes with the generated commit message
git add .
git commit -m "$COMMIT_MSG"

echo "Changes committed with message: $COMMIT_MSG"

πŸ‘‹ – @TnvMadhav