automated git commit message

Recently discovered pretty nice project - opencommit

Idea is great, we are doing something similar for GitHub pull request description

But indeed, nice to have git commit automated as well

What I did not like about the tool is that it asks too much questions and there is no way to run it in quiet mode, at least until this issue not fixed

My very first though was - it is really cool idea for small go lang util but after almost fully complete it realized that it is so simple that even go not needed, everything can be done as simple bash script instead

Here is what I have ended up with:

#!/usr/bin/env bash

if git status | grep -q "nothing to commit, working tree clean"
then
    git status
    exit 0
fi

if git diff --cached --quiet
then
    git add .
fi

diff=$(git diff --staged -- $(git diff --staged --name-only --diff-filter=ACMRTU | egrep -v 'go.sum|package-lock.json|.terraform.lock.hcl|assets/.*\.(png|jpg)$|src/.*\.js$'))

body=$(jq --null-input --arg system "$system" --arg diff "$diff" '{
    "model": "gpt-3.5-turbo",
    "temperature": 0.7,
    "max_tokens": 320,
    "messages": [
        {
            "role": "system",
            "content": "Given \"git diff --staged\" command output your goal is to propose short single line commit title no longer than 80 chars"
        },
        {
            "role": "user",
            "content": $diff
        }
    ]
}')

summary=$(curl -s https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d "$body" | jq -r ".choices[0].message.content" | tr -d '"')

# echo $summary

body=$(jq --null-input --arg system "$system" --arg diff "$diff" '{
    "model": "gpt-3.5-turbo",
    "temperature": 0.7,
    "messages": [
        {
            "role": "system",
            "content": "Given \"git diff --staged\" command output your goal is to write an commit description"
        },
        {
            "role": "user",
            "content": $diff
        }
    ]
}')

description=$(curl -s https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d "$body" | jq -r ".choices[0].message.content")

# echo $description

git commit -m "$summary" -m "$description"

Notes:

  • it won't handle huge pull requests and will require you to filter files before sending them to GPT
  • it has some issues with tools where you commit changes programmatically