AI Git Commit Messages with gcm Shell Function
Add this zshrc/bash script for `gcm`: it pipes staged diffs to LLM for concise commit messages, then lets you accept, edit, regenerate, or cancel—saving time on boilerplate commits.
Core gcm Function Workflow
Pipe staged changes via git diff --cached to the llm CLI (install from https://llm.datasette.io/) with this prompt: "Below is a diff of all staged changes... Please generate a concise, one-line commit message." The script displays the LLM output and loops until you choose: (a)ccept to run git commit -m "$message", (e)dit to input your own, (r)egenerate a new one, or (c)ancel. It uses a cross-shell read_input function for Bash/Zsh compatibility and handles commit failures gracefully.
To install: Copy the full script (starting with gcm() { ... }) into ~/.zshrc or ~/.bashrc, then source the file. Requires llm setup with OpenAI API key; defaults to a capable model like 4o-mini.
Trade-off: Relies on external llm tool and API costs (~$0.01-0.10 per commit depending on diff size); local models possible via forks.
Handling Conflicts and Custom Models
Oh My Zsh users often alias gcm to git checkout main—add unalias gcm 2>/dev/null before the function definition. To switch models, modify the llm call: e.g., llm -m "gpt-4o" for better quality or llm -m "gemini-1.5-flash" after llm install llm-gemini (free tier viable).
Local LLM forks: Use ollama run llama3.1:70b (405b needs massive RAM/GPU); one fork at https://gist.github.com/nikolaydubina/12e3c692eeb3a651579c9f6c25d024f8. Git config alias alternative: [alias] ai = "!f() { git add . && ... llm -m '4o-mini' ... }" preserves branch context better than zshrc in some cases.
Enhanced Alternatives and Extensions
For conventional commits: One-liner git commit -m "$(git diff --staged | sgpt 'Write a single conventional commits style... on branch $(git rev-parse --abbrev-ref HEAD)')".
Feature-rich tools:
- opencommit (npm i -g opencommit): Supports local/remote LLMs (Llama), conventional formats; run
ocoafteroco config set OCO_OPENAI_API_KEY=.... - gitpmoji: Git hook for message/emoji/rating/diff eval (OpenAI only).
- aicommit (coder/aicommit): Matches repo's existing commit style.
- gcop (github.com/Undertone0809/gcop): Git alias-compatible, multi-LLM.
Shell forks: Fish support (https://gist.github.com/knyazer/675e6eb945ae5ec64af2f9be4826b07e), Node.js no-API version (koisose/auto-commit-gaia with GaiaNet.ai/Llama), VSCode keybind (cmd+enter sends git ai). Add -m flag bypass: Check args before LLM call to use manual message directly.