- Posted on
- • Artificial Intelligence
Artificial Intelligence Git Commit Messages
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Stop Writing Boring Git Messages: Use AI From Your Bash Shell
If you’ve ever stared at a blinking cursor trying to explain “what changed” for the tenth time today, you’re not alone. Writing clear, consistent commit messages is tedious—but it’s also essential for code review, debugging, and release notes. The good news: you can automate the grunt work with AI and still keep high-quality, Conventional Commit–style messages right from your Linux terminal.
This post shows you how to:
Understand why AI-generated commit messages are worth it
Install the minimal tooling with apt, dnf, or zypper
Add a Git hook that drafts messages using either a cloud model (OpenAI) or a local model (Ollama)
Tune prompts for your team’s style and add safety rails
Ship faster without sacrificing commit hygiene
Why AI Commit Messages Are Legit
Consistency beats chaos: Clean, predictable commit messages enable better
git logarchaeology, changelog generation, and release automation.Time back to code: Let AI summarize diffs while you focus on the work that matters.
Fewer nits in review: Clear commit reasoning reduces back-and-forth during PRs.
Works with your flow: A simple Git hook means no new app, no context-switching, and no IDE lock-in.
Prerequisites (Linux, Bash-first)
We’ll use standard Unix tools and Git hooks. Make sure you have Git, curl, and jq.
Debian/Ubuntu (apt):
sudo apt update sudo apt install -y git curl jqFedora/RHEL (dnf):
sudo dnf install -y git curl jqopenSUSE (zypper):
sudo zypper refresh sudo zypper install -y git curl jq
You’ll choose one of two AI backends:
Cloud: OpenAI API (fast to start; data leaves your machine).
Local: Ollama + a local model (private; runs on your hardware).
Option A: Cloud Model (OpenAI) Quickstart
1) Set your API key as an environment variable:
export OPENAI_API_KEY="sk-...your-key..."
Add that to your shell profile (e.g., ~/.bashrc) to persist.
2) Drop in a Git hook that drafts messages from your staged diff. Create .git/hooks/prepare-commit-msg and make it executable:
chmod +x .git/hooks/prepare-commit-msg
3) Paste this hook (OpenAI version) into .git/hooks/prepare-commit-msg:
#!/usr/bin/env bash
set -euo pipefail
# Git invokes this hook as: prepare-commit-msg <commit-msg-file> <commit-source> <sha1>
MSG_FILE="${1:-.git/COMMIT_EDITMSG}"
# Only run for normal commits (skip merges, rebases, etc.)
SOURCE="${2:-}"
[[ -n "${SOURCE}" ]] && exit 0
# Require OpenAI key
if [[ -z "${OPENAI_API_KEY:-}" ]]; then
echo "OpenAI key not set; skipping AI commit message." >&2
exit 0
fi
# Collect staged diff (ignore binary, limit size)
DIFF="$(git diff --staged --no-color --diff-algorithm=minimal -- . ':!*.lock' | sed 's/\x0//g')"
# Skip if nothing staged
[[ -z "$DIFF" ]] && exit 0
# Basic guardrail: skip on huge diffs
MAX_CHARS=50000
if (( ${#DIFF} > MAX_CHARS )); then
echo "Staged diff is large; skipping AI generation." >&2
exit 0
fi
# Prompt enforces Conventional Commits and 72-char wrap
read -r -d '' SYS <<'SYS'
You are a commit message assistant.
Rules:
- Output ONLY a Conventional Commit header and optional body.
- Header format: type(scope?): subject
- Use types like feat, fix, docs, style, refactor, perf, test, build, chore.
- Subject: imperative, <= 72 chars, no trailing period.
- Body: wrap at 72 chars; include rationale if helpful; bullet points allowed.
- Reference files/functions when useful, avoid leaking secrets.
SYS
read -r -d '' USER <<'USR'
Summarize the staged diff into a clear Conventional Commit message.
Emphasize why changes were made over what changed line-by-line.
If multiple logical changes exist, summarize them coherently.
USR
# Build JSON payload
PAYLOAD=$(jq -n \
--arg sys "$SYS" \
--arg usr "$USER" \
--arg diff "$DIFF" \
'{
model: "gpt-4o-mini",
messages: [
{role:"system", content:$sys},
{role:"user", content: ($usr + "\n\nDIFF START\n" + $diff + "\nDIFF END")}
],
temperature: 0.2
}')
# Call OpenAI Chat Completions API
RESP="$(curl -sS https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-H "Content-Type: application/json" \
-d "$PAYLOAD")"
# Extract content safely
CONTENT="$(printf '%s' "$RESP" | jq -r '.choices[0].message.content // empty')"
# Fallback if no content
if [[ -z "$CONTENT" ]]; then
echo "AI failed to produce content; leaving message empty to edit manually." >&2
exit 0
fi
# Write to commit message file (do not auto-commit; let user review)
printf '%s\n' "$CONTENT" > "$MSG_FILE"
4) Use it:
git add -A
git commit
Your editor opens with an AI-drafted message you can accept or tweak.
Note: API usage may incur cost; review your provider’s pricing and data-handling policy.
Option B: Local-Only With Ollama
Run models like Llama 3 locally—no data leaves your machine.
1) Install Ollama:
curl -fsSL https://ollama.com/install.sh | sh
2) Pull a model (example: Llama 3.1):
ollama pull llama3.1
3) Create the same Git hook, but using Ollama. Save as .git/hooks/prepare-commit-msg and make executable:
chmod +x .git/hooks/prepare-commit-msg
4) Paste this hook (Ollama version):
#!/usr/bin/env bash
set -euo pipefail
MSG_FILE="${1:-.git/COMMIT_EDITMSG}"
SOURCE="${2:-}"
[[ -n "${SOURCE}" ]] && exit 0
MODEL="${AI_COMMIT_MODEL:-llama3.1}"
DIFF="$(git diff --staged --no-color --diff-algorithm=minimal -- . ':!*.lock' | sed 's/\x0//g')"
[[ -z "$DIFF" ]] && exit 0
MAX_CHARS=50000
(( ${#DIFF} > MAX_CHARS )) && { echo "Large diff; skipping AI." >&2; exit 0; }
read -r -d '' PROMPT <<'P'
You are a commit message assistant.
Output ONLY:
- A Conventional Commit header: type(scope?): subject (<=72 chars)
- Optional body wrapped at 72 chars explaining rationale and impact.
Prefer: feat, fix, docs, style, refactor, perf, test, build, chore.
Use imperative mood. No trailing period in subject.
Staged DIFF:
P
OUT="$(ollama run "$MODEL" -p "${PROMPT}
${DIFF}
")"
# Simple cleanup (strip code fences if any)
OUT="$(printf '%s' "$OUT" | sed -E 's/^```[a-zA-Z]*$//; s/^```$//; s/```$//')"
[[ -z "$OUT" ]] && exit 0
printf '%s\n' "$OUT" > "$MSG_FILE"
5) Use it:
git add -A
git commit
You’ll get a locally generated message for review.
Optional: Install Node.js CLI “aicommits” (Plug-and-Play)
Prefer an off-the-shelf CLI that understands your diff and prints a commit message? You can use a popular Node.js-based tool.
First, install Node.js and npm:
Debian/Ubuntu (apt):
sudo apt update sudo apt install -y nodejs npmFedora/RHEL (dnf):
sudo dnf install -y nodejs npmopenSUSE (zypper):
sudo zypper refresh sudo zypper install -y nodejs npm
Then install the CLI globally:
npm install -g aicommits
Export your provider key (for example, OpenAI):
export OPENAI_API_KEY="sk-...your-key..."
Use it inside a Git repo after staging changes:
git add -A
aicommits
Tip: Some distros ship older Node.js. If you hit version issues, consider using nvm to install a recent LTS.
3–5 Actionable Tips To Make AI Commits Stick
1) Choose cloud vs local consciously:
Cloud: faster to try, broader model choices.
Local: better privacy, no per-token cost, needs CPU/GPU RAM.
2) Enforce a house style:
Nudge the model with a prompt that specifies Conventional Commits.
Keep subject lines ≤ 72 chars; wrap bodies at 72 for readable logs.
3) Keep a human in the loop:
Use prepare-commit-msg (preview) rather than commit-msg (auto-apply).
Make it easy to edit before saving the commit.
4) Add guardrails:
Skip AI for large diffs or vendored/binary paths.
Never include secrets; add patterns to exclude (e.g., .env, keys).
Fail open: if the model errors, just let Git continue with an empty message.
5) Iterate and version your prompt:
Store your prompt in the repo (e.g.,
.git-commit-prompt).Encourage PR feedback on commit quality; tune over time.
Real-World Example
Staged changes:
Updated README with a new “Quickstart”
Fixed an off-by-one in
pagination.go
A good AI-generated message might be:
feat(docs): add quickstart section and fix page indexing
Introduce a concise quickstart in the README to reduce setup time.
Also correct an off-by-one error in pagination.go that caused the last
page to be skipped when item counts were multiples of the page size.
Concise, imperative, and explains why—not a line-by-line diff recap.
Conclusion / Call To Action
Great commit messages shouldn’t slow you down. Add one of the hooks above, decide on cloud vs local, and start committing with consistent, Conventional Commit–style messages today.
If you want zero external dependencies: install Ollama and use the local hook.
If you want the quickest path to value: set OPENAI_API_KEY and use the OpenAI hook.
If you prefer a turnkey CLI: install Node.js with your package manager and try
aicommits.
Next step: pick an option, paste the hook, and git commit. Your future self (and your teammates) will thank you.