
Rust Tutorial: How to Build a CLI Tool that Writes Your Git Commit Messages
Walk through how to build an open source Rust CLI tool that turns staged Git changes into AI-written commits messages.
Start readingIn this guide I'm going to walk through how I built and published si-git-commit, an open source Rust CLI that writes my Git commit messages for me. The binary is called ghsi, and it reads your staged changes, asks an AI model for a Conventional Commits message, shows you the result, and commits and pushes after you confirm.
Here's a full run in a real repository. Watch how one command stages two files, generates the message, asks for confirmation, and then commits and pushes.
Short answer: Install it with
cargo install si-git-commit, runghsi config init, pick a model withghsi config model, and then runghsiinside any Git repository. ghsi sends a compact version of your staged diff to OpenAI, Anthropic, or any OpenAI-compatible endpoint, prints the message it gets back, and commits and pushes after you approve it.
A quick note on the recordings in this guide. Every line of terminal output comes from the published ghsi 0.1.0 binary. To make the demo repeatable without a live API key, I pointed base_url at a small local server that logs each request and replays one reply. That reply was written by gpt-6-luna from ghsi's exact prompt. Everything below was checked against version 0.1.0 as it's published on crates.io.
Why I built a replacement #
For a while I generated my commit messages with ghit, an MIT-licensed Rust CLI by Evis Drenova. Its last release is 0.1.1 from July 2025, and its repository now hosts Helix, a new version control system from the same author. si-git-commit keeps ghit's workflow and a good part of its structure, so it's fair to call it a rebuild of that tool.
In October 2026 my setup stopped working, and the reason was a model retirement. OpenAI's deprecations page lists October 23, 2026 as the shutdown date for gpt-4.1-nano, which was the model in my config, so every request failed:
"message": "The model `gpt-4.1-nano` has been deprecated, learn more here: https://platform.openai.com/docs/deprecations",
"code": "model_not_found"
Changing the model in ~/.ghit.toml didn't fix it. ghit 0.1.1 always sends max_tokens: 200 and temperature: 0.3, and the newer model I switched to rejected the request:
"message": "Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead.",
I opened a pull request upstream with that fix, and it's still open as I write this. However, my needs went beyond one parameter. I wanted a tool that works in every kind of project I work on, including Rust apps, and that survives model retirements. I also wanted settings that are easy to find and messages that pass in repositories that enforce Conventional Commits with Husky.
Here's what changed between the two tools:
| ghit 0.1.1 | si-git-commit 0.1.0 | |
|---|---|---|
| Token limit | max_tokens: 200 | max_completion_tokens: 800, configurable |
| Temperature | always 0.3 | not sent, so each model uses its default |
| Providers | OpenAI, with a hard-coded URL | OpenAI, Anthropic, and any OpenAI-compatible base_url |
| Settings | a hand-edited ~/.ghit.toml | ghsi config commands that find your environment keys |
| New files | missed by git diff --quiet | caught by git status --porcelain |
| Long diffs | a 4,000-byte slice that can panic | a 12,000-byte budget cut on a character boundary |
| Tests | none in the crate | 26 passing tests |
That 4,000-byte slice deserves a closer look. ghit truncates with &formatted[..4000], and Rust panics when a byte index lands inside a multi-byte character. When I ran ghit's own formatting function on a diff full of arrows, it crashed with this message:
end byte index 4000 is not a char boundary; it is inside '→' (bytes 3999..4002 of string)
Install ghsi and make your first commit #
You'll need a Rust toolchain and an API key for your provider. Let's install the crate:
cargo install si-git-commit
That one command installs two binaries, ghsi and si-git-commit, which run the same code. If you'd rather skip the compile, the v0.1.0 GitHub release has prebuilt binaries for Linux, Windows, and macOS on both Intel and Apple silicon.
Next on the list is the settings file. In the animation below, watch for the line where ghsi finds the OPENAI_API_KEY that's already exported in my shell, and then watch the model picker save a new model without opening an editor.
These are the commands from that recording:
ghsi config init
ghsi config model
cat ~/.config/si-git-commit/config.toml
Pick a current model first. Version 0.1.0 defaults to
gpt-5-mini, and its suggestion list also includesgpt-5andgpt-4.1-mini. OpenAI's deprecations page gives shutdown dates for all three: December 11, 2026 forgpt-5andgpt-5-mini, and January 14, 2027 forgpt-4.1-mini. Runghsi config model gpt-5.6-luna, or pick another current model, so you don't hit the same wall I did.
Now make a change in any repository and run:
ghsi
ghsi will stage everything, print the message, and ask Create this commit? [Y/n] before it touches your history. If you want to see a message without committing, use ghsi --dry-run. Keep in mind that a dry run still stages your files, so run git restore --staged . afterward if you want them unstaged again.
How the code is organized #
The crate is a library with a thin binary on top. src/bin/ghsi.rs is nine lines long and calls si_git_commit::cli::run(), so the integration tests can import the same modules that the binary uses.

Before we look at each module, here's what happens to one real change as it moves through them. Watch the diff shrink to 776 bytes, the two request fields that ghsi no longer sends, and the reply turning into two -m arguments.
Step 1: Define the command line with clap #
Let's start with the binary names. I wanted ghsi with no arguments to run the whole workflow, and I wanted the long crate name to work as a command too, so the two [[bin]] entries in Cargo.toml point at the same file:
[[bin]]
name = "ghsi"
path = "src/bin/ghsi.rs"
# Alias so `cargo install si-git-commit` also provides the long name.
[[bin]]
name = "si-git-commit"
path = "src/bin/ghsi.rs"
Cargo accepts this, but every build prints a warning that the file is "found to be present in multiple build targets." A cleaner option for the next release is a second small file in src/bin/ that calls the same run() function.
The subcommands use clap's derive API, and each one gets a short alias, so ghsi c, ghsi g, and ghsi s all work:
#[derive(Subcommand, Debug)]
pub enum Commands {
/// Stage, generate, commit, and push (default workflow) [alias: c]
#[command(visible_alias = "c")]
Commit(CommitArgs),
/// Generate a message for already-staged changes [aliases: gen, g]
#[command(visible_aliases = ["gen", "g"])]
Generate(ModelArgs),
/// Stage files (or all changes), then generate — no commit [alias: s]
#[command(visible_alias = "s")]
Stage(StageArgs),
/// View and edit your settings TOML (model, provider, keys)
Config(ConfigArgs),
}
There's one small bug in that snippet. clap already prints visible aliases in the help output, as the clap documentation describes, so the alias text in each doc comment shows up twice:
commit Stage, generate, commit, and push (default workflow) [alias: c] [alias: c]
Deleting the bracketed text from the doc comments fixes it. The top-level Cli struct also accepts ghit's old --auto, --generate, and --stage-and-generate flags, which means existing ghit aliases and scripts keep working.
Step 2: Talk to Git through the git binary #
Next, we need a way to talk to Git. ghsi doesn't link a Git library, and every Git operation goes through one helper that runs the git binary with std::process::Command:
fn run_git(args: &[&str]) -> Result<std::process::Output> {
Command::new("git")
.args(args)
.output()
.map_err(|e| SiError::Git(format!("failed to execute `git {}`: {e}", args.join(" "))))
}
Running the real binary means your hooks, credential helpers, signing settings, and .gitconfig behave the same way they do in your terminal. The arguments go straight to git with no shell in between, so quotes or backticks inside a generated message can't break the command.
The dirty-tree check is the second change from ghit. ghit asked git diff --quiet, which ignores untracked files, so a change that only added new files stopped with "No changes found to commit." ghsi reads git status --porcelain instead:
pub fn has_unstaged_changes() -> Result<bool> {
let output = run_git(&["status", "--porcelain"])?;
ensure_success(&["status", "--porcelain"], &output)?;
let text = String::from_utf8_lossy(&output.stdout);
// Porcelain lines starting with a space or `?` in the worktree
// column mean unstaged/untracked work exists. Any line at all
// without staged content is also fine to treat via staged check;
// here we report "worktree dirty" when any line has worktree state.
Ok(text.lines().any(|line| {
let bytes = line.as_bytes();
bytes.len() >= 2 && (bytes[1] != b' ' || line.starts_with("??"))
}))
}
Step 3: Compact the diff before it leaves your machine #
Now that we can read the staged diff, we need to shrink it, because a raw unified diff carries a number of lines that a model doesn't need. format_diff_for_llm keeps the file names, hunk headers, added and removed lines, and a limited amount of context, and it drops the index, ---, and +++ headers:
for line in raw_diff.lines() {
if let Some(rest) = line.strip_prefix("diff --git ") {
flush(&mut formatted, ¤t_file, &changes);
// `diff --git a/path b/path` — take the b/ side.
current_file = rest
.split_whitespace()
.nth(1)
.unwrap_or("unknown")
.trim_start_matches("b/")
.to_string();
changes.clear();
} else if line.starts_with("+++") || line.starts_with("---") {
continue;
} else if line.starts_with("@@") {
changes.push(format!("Changes at {line}"));
} else if let Some(content) = line.strip_prefix('+') {
changes.push(format!(" Added: {content}"));
} else if let Some(content) = line.strip_prefix('-') {
changes.push(format!(" Removed: {content}"));
} else if let Some(content) = line.strip_prefix(' ') {
if !content.trim().is_empty() && changes.len() < 40 {
changes.push(format!(" Context: {content}"));
}
}
}
The demo change compacts to 776 bytes, well under the 12,000-byte budget. When a diff is larger, truncate_str walks back to the nearest character boundary before it cuts, which is the fix for the ghit panic from earlier:
pub fn truncate_str(s: &str, limit: usize) -> String {
if s.len() <= limit {
return s.to_string();
}
let mut end = limit;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
format!("{}\n\n[... diff truncated for brevity ...]", &s[..end])
}
Keep in mind that this compacted diff, along with the output of git diff --cached --stat, is exactly what will go to your provider. There's also one edge case left in that loop. The +++ and --- check matches content lines too, so a removed SQL comment such as -- old note or an added C statement such as ++i; never reaches the model. I confirmed both cases with a test against the 0.1.0 library, and skipping those lines only between a diff --git line and the first @@ would close the gap.
Step 4: Write the prompt and parse the reply #
Now that we've compacted the diff, we can build the prompt. The system prompt asks for Conventional Commits and spells out the rules:
pub const SYSTEM_PROMPT: &str = "You are an expert engineer who writes clear, precise Git commit messages \
following Conventional Commits (feat:, fix:, docs:, style:, refactor:, perf:, test:, build:, ci:, chore:). \
Rules: keep the subject line at most 72 characters, imperative mood, no trailing period, \
no markdown fences, no extra commentary. Output only the commit message.";
The user prompt adds the stat summary and the compacted diff. The message_level setting picks one of three styles: quiet for a subject line only, normal for a subject plus two to five bullets, and verbose for a longer body.
Parsing the reply is deliberately simple. ghsi strips a code fence if the model adds one anyway, and then it splits the reply at the first blank line:
pub fn parse_commit_message(response: &str) -> (String, Option<String>) {
let trimmed = response.trim();
let cleaned = strip_code_fence(trimmed);
if let Some((subject, body)) = cleaned.split_once("\n\n") {
let subject = subject.lines().next().unwrap_or(subject).trim().to_string();
let body = body.trim();
if body.is_empty() {
(subject, None)
} else {
(subject, Some(body.to_string()))
}
} else {
let subject = cleaned.lines().next().unwrap_or("").trim().to_string();
(subject, None)
}
}
ghsi doesn't validate the format itself. That still works for repositories with a Husky commit-msg hook, because ghsi runs git commit without --no-verify, so the hook will reject a bad subject the same way it would for a message you typed.
Step 5: Send requests that current models accept #
This is the part that broke ghit for me, so the request types are small and explicit. The OpenAI request has no temperature field and no max_tokens field at all:
#[derive(Serialize)]
struct OpenAiChatRequest {
model: String,
messages: Vec<ChatMessage>,
max_completion_tokens: u32,
}
OpenAI's API specification describes max_tokens as "now deprecated in favor of max_completion_tokens, and is not compatible with o-series models." Anthropic's Messages API still names its limit max_tokens, so the Anthropic request keeps that name and maps the same setting onto it:
#[derive(Serialize)]
struct AnthropicRequest {
model: String,
max_tokens: u32,
system: String,
messages: Vec<ChatMessage>,
}
Here are both request shapes side by side, taken from the requests the local server captured during the demo:

A unit test locks the OpenAI shape in place for three model ids, so a future refactor can't quietly bring the old fields back:
let body = serde_json::to_value(&request).expect("request should serialize");
assert_eq!(body["model"].as_str(), Some(model));
assert_eq!(body["max_completion_tokens"].as_u64(), Some(800));
assert!(
body.get("max_tokens").is_none(),
"legacy max_tokens must never be sent to OpenAI for {model}"
);
assert!(
body.get("temperature").is_none(),
"temperature must use the model default for {model}"
);
Reasoning models need one more bit of planning. The same specification says max_completion_tokens includes "visible output tokens and reasoning tokens," and OpenAI's reasoning guide recommends reserving at least 25,000 tokens for reasoning and outputs when you start experimenting. ghsi's default budget is 800 tokens, which is a small fraction of that. When I simulated a reply that had used up its budget, with empty content and a finish_reason of length, ghsi printed this:
Error: OpenAI API error: empty response (no choices returned)
Hint: check your model with `ghsi config model` (settings: /tmp/empty.toml). Deprecated model ids are the most common cause.
The hint points at the model, but the fix in that case is a larger budget, for example ghsi config set max_completion_tokens 4000. Checking finish_reason and naming the budget in that error would make the problem much easier to spot.
Step 6: Make the settings file easy to find #
The biggest usability change from ghit is that you never have to guess where the settings live. Config::config_path checks an environment variable first and then falls back to the platform's config directory:
pub fn config_path() -> PathBuf {
if let Ok(p) = env::var("SI_GIT_COMMIT_CONFIG") {
if !p.trim().is_empty() {
return PathBuf::from(p);
}
}
let base = dirs::config_dir().unwrap_or_else(|| {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".config")
});
base.join("si-git-commit").join("config.toml")
}
On Linux that's ~/.config/si-git-commit/config.toml, and on macOS it's ~/Library/Application Support/si-git-commit/config.toml, which matches the dirs crate documentation. ghsi config path prints the location any time, and ghsi config shows every setting along with where the API key came from.
API keys follow a simple order: a key saved in the file wins, then SI_GIT_COMMIT_API_KEY, then the provider's own variable, OPENAI_API_KEY or ANTHROPIC_API_KEY. In other words, if you've already exported your key in your shell profile, ghsi simply picks it up and there's nothing to configure.
That convenience created a bug that I fixed before publishing. Loading the settings copies an environment key into memory, and the first version of ghsi config model wrote that key into the TOML file when it saved a new model. Commit c6e7933 fixed it by saving only the key that was already stored in the file:
let mut to_save = config.clone();
to_save.api_key = Config::stored_api_key().unwrap_or_default();
An integration test runs the real binary with a fake key in the environment and then checks the file:
// Changing the model must not copy the environment key into the file.
let set = run_ghsi_with_openai_key(
&config,
&["config", "model", "gpt-5.6-luna"],
Some("sk-test-1234567890"),
);
assert!(set.status.success(), "stderr: {}", stderr(&set));
let saved = std::fs::read_to_string(&config).expect("read saved config");
assert!(
!saved.contains("sk-test-1234567890"),
"env key must not be persisted, file was: {saved}"
);
On Unix systems, save_to also sets the file's permissions to 0600, so only your user can read a key you do store there.
Step 7: Choose a workflow for each run #
The default command covers the full workflow, and flags such as -y and --no-push change it for a single run:
| Command | What it does |
|---|---|
ghsi | Stage all changes, generate, confirm, commit, and push |
ghsi -y | Run the same workflow without the confirmation prompt |
ghsi src/lib.rs README.md | Stage and commit only the listed files |
ghsi commit --no-push | Commit locally and skip the push |
ghsi commit --edit | Open the message in $EDITOR before committing |
ghsi stage | Stage and generate without committing |
ghsi generate | Generate a message for changes you've already staged |
ghsi --model <id> --level verbose | Override the model and message style for one run |
Step 8: Test the real binary #
Cargo sets an environment variable for every binary target when it compiles integration tests, which the Cargo reference documents as CARGO_BIN_EXE_<name>. The tests use it to run the compiled ghsi against a temporary settings file:
fn ghsi_bin() -> &'static str {
env!("CARGO_BIN_EXE_ghsi")
}
On a clean machine, cargo test on the published 0.1.0 sources passed 14 unit tests, 11 integration tests, and 1 doctest, and both cargo fmt --check and cargo clippy --all-targets -- -D warnings came back clean. CI runs the same three checks on Ubuntu and macOS for every push and pull request.
There's a catch in 0.1.0, however. The tests point SI_GIT_COMMIT_CONFIG at a file that doesn't exist yet, and Config::candidate_paths still searches the default locations in that case. On a Linux machine that already had ~/.config/si-git-commit/config.toml, 4 of the 11 integration tests failed, and the run changed the model saved in that real file. The same thing happens outside the tests, where ghsi config init with the override set reported this instead of creating a new file:
Settings file already exists: /home/user/.config/si-git-commit/config.toml
When the override is set, the search should stop at that one path. This patch is my proposed fix rather than published code, and with it all 11 integration tests pass and the real file stays untouched:
pub fn candidate_paths() -> Vec<PathBuf> {
if env::var("SI_GIT_COMMIT_CONFIG").map(|p| !p.trim().is_empty()).unwrap_or(false) {
return vec![Self::config_path()];
}
let mut paths = vec![Self::config_path()];
Step 9: Publish to crates.io and GitHub Releases #
Before publishing, I filled in the metadata that crates.io and docs.rs display. Cargo allows at most five keywords, according to the manifest reference, so the list is short:
keywords = ["git", "ai", "cli", "llm", "commit"]
categories = ["command-line-utilities", "development-tools"]
The publish itself is one command, and the Cargo book recommends running it with --dry-run first, which packages and builds the crate without uploading anything:
cargo publish --dry-run
cargo publish
Take that dry run seriously, because the same page is clear that a release is permanent: "The version can never be overwritten, and the code cannot be deleted." That's also why the deprecated default model needs a 0.1.1 release rather than an edit to 0.1.0.
The GitHub release didn't go as smoothly as the crate did, so here's the timeline from that afternoon in UTC. Watch for the red failure at 20:51 and the two-line fix that turned the release green.
The release workflow builds four binaries and uploads them with softprops/action-gh-release. On the first tag, every upload ended with the same error:
⚠️ GitHub release failed with status: 403
undefined
retrying... (0 retries remaining)
❌ Too many retries. Aborting...
The problem was the token's scope. According to GitHub's documentation, new repositories in a personal account give GITHUB_TOKEN read-only access to contents, and repositories in an organization inherit the organization's setting. The action's README asks for contents: write, so commit ce91fe9 added it at the top of the workflow:
# Creating a GitHub Release and uploading assets requires write access.
# Some repositories default the Actions GITHUB_TOKEN to read-only, which
# causes softprops/action-gh-release to fail with HTTP 403.
permissions:
contents: write
After I moved the v0.1.0 tag to that commit, the release run passed and attached binaries for Linux, Windows, and both Mac architectures, each between 2.7 and 3.5 MB. The crate itself had already shipped at 20:55 from commit c6e7933, which is fine because ce91fe9 only touched the workflow file. The same log also warned that softprops/action-gh-release@v1 and actions/checkout@v4 target Node.js 20, which is deprecated on GitHub's runners, and the release action's current major version is v3.
Known limits in 0.1.0 #
Each of these was confirmed against the published binary or its source:
- The default model and two of the suggested models are on OpenAI's deprecation list, so 0.1.1 should change them, along with the README and changelog lines that promise no deprecated defaults.
- Setting
SI_GIT_COMMIT_CONFIGto a file that doesn't exist yet falls back to an existing file in a default location, as described in Step 8. - ghsi doesn't check the message format, so your
commit-msghook is the place to enforce it. - Removed lines that start with
--and added lines that start with++are dropped from the compacted diff. - A staged file that isn't valid UTF-8 stops the run with "invalid UTF-8 in git diff output."
- A reasoning model that runs out of budget produces an error that blames the model instead of the budget.
--dry-runstill stages files, and the help output prints each subcommand alias twice.- Diffs over 12,000 bytes are cut, so the model will only see the first part of a large change.
Frequently asked questions #
Does ghsi work with Claude models? #
Yes. Run ghsi config model claude-sonnet-4-6 --provider anthropic and export ANTHROPIC_API_KEY. ghsi then sends Anthropic's Messages format with the x-api-key and anthropic-version headers.
Can I use a local or self-hosted model? #
Yes, as long as the server accepts OpenAI's Chat Completions request, including the max_completion_tokens field. Run ghsi config set provider openai-compatible and point base_url at your server, for example ghsi config set base_url http://localhost:8080/v1.
What does ghsi send to the AI provider? #
It sends the system prompt, the git diff --cached --stat summary, and the compacted staged diff, up to 12,000 bytes. Running ghsi with no arguments calls git add ., which stages every change under your current directory that .gitignore doesn't exclude. Check git status first if your working tree holds anything you don't want to share.
Will ghsi skip my Git hooks? #
No. It runs git commit without --no-verify, so your pre-commit and commit-msg hooks run exactly as they do when you commit by hand.
I hope that this has been a helpful guide to building, testing, and publishing a Rust CLI that writes your commit messages for you. The full source is on GitHub, and you can install the tool from crates.io.



