medium.com 8 min read Original Source

How To Build a Local AI Commit Message Generator in Rust.

Every developer has a graveyard of commit messages they are not proud of. “fix”, “wip”, “changes”, “asdfgh”. The message that made sense at the time, at 11pm, when you just wanted to push and go to sleep.

The correct solution is discipline. The practical solution is to make writing a good commit message require less effort than writing a bad one.

This article is about building a CLI tool in Rust that reads your staged diff and generates a commit message using a local Ollama model. The entire pipeline runs on your machine. No API key, no internet connection, no cost per request, no sending your proprietary code to a third-party server.

It is also a practical Rust project that touches async HTTP, CLI argument parsing, streaming responses, and subprocess execution. Everything you would find in a real production tool.

What We Are Building

git add src/auth.rs
git-ai-commit
Generating commit message using model `llama3.2`...
feat(auth): add token expiry validation to JWT middleware
git add src/auth.rs
git-ai-commit
Generating commit message using model `llama3.2`...
feat(auth): add token expiry validation to JWT middleware

That is it. Stage your changes, run the tool, get a commit message that follows the Conventional Commits specification. If you disagree with it, change it. If you like it, use it. The model does the first draft, you do the review.

The full source is on GitHub: [link]

Prerequisites

You need Ollama installed and running, and at least one model pulled.

# Install Ollama from https://ollama.ai
# Then pull a model
ollama pull llama3.2
# Verify it works
ollama run llama3.2 "say hello"
# Install Ollama from https://ollama.ai
# Then pull a model
ollama pull llama3.2
# Verify it works
ollama run llama3.2 "say hello"

Ollama exposes a local HTTP API on port 11434. That is the only interface our tool uses. The model runs entirely on your hardware through llama.cpp under the hood. Ollama handles quantization, hardware acceleration on Apple Silicon and CUDA, and model management. We just make HTTP calls.

Project Structure

git-ai-commit/
  Cargo.toml
  src/
    main.rs      entry point
    cli.rs       argument definitions
    diff.rs      runs git diff --cached
    prompt.rs    builds the prompt
    ollama.rs    async HTTP client for Ollama
git-ai-commit/
  Cargo.toml
  src/
    main.rs      entry point
    cli.rs       argument definitions
    diff.rs      runs git diff --cached
    prompt.rs    builds the prompt
    ollama.rs    async HTTP client for Ollama

Each module has one job. main.rs wires them together. This is the structure from the Rust modules article: thin binary entry point, all logic in dedicated modules, each testable independently.

Cargo.toml

[package]
name        = "git-ai-commit"
version     = "0.1.0"
edition     = "2021"
description = "Generate Git commit messages from staged diffs using a local Ollama model."

[[bin]]
name = "git-ai-commit"
path = "src/main.rs"
[dependencies]
tokio        = { version = "1",    features = ["full"] }
reqwest      = { version = "0.12", features = ["json", "stream"] }
serde        = { version = "1",    features = ["derive"] }
serde_json   = "1"
clap         = { version = "4",    features = ["derive"] }
anyhow       = "1"
futures-util = "0.3"
[package]
name        = "git-ai-commit"
version     = "0.1.0"
edition     = "2021"
description = "Generate Git commit messages from staged diffs using a local Ollama model."

[[bin]]
name = "git-ai-commit"
path = "src/main.rs"
[dependencies]
tokio        = { version = "1",    features = ["full"] }
reqwest      = { version = "0.12", features = ["json", "stream"] }
serde        = { version = "1",    features = ["derive"] }
serde_json   = "1"
clap         = { version = "4",    features = ["derive"] }
anyhow       = "1"
futures-util = "0.3"

reqwest with the stream feature is what lets us receive the model output token by token rather than waiting for the entire response. anyhow handles errors without forcing us to define a custom error type for every function. clap with derive generates the CLI interface from struct annotations.

Getting the Staged Diff

The first step is running git diff --cached and capturing the output. Staged means only the changes you have added with git add, which is exactly the right scope. You do not want the model guessing about unstaged work in progress.

Result {
let output = Command::new("git")
.args([
"diff",
"–cached",
&format!("–unified={}", context_lines),
])
.output()
.context("Failed to run `git diff`. Is git installed and are you inside a repository?")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("git diff exited with error: {}", stderr.trim());
}
let diff = String::from_utf8(output.stdout)
.context("git diff output contained invalid UTF-8")?;
Ok(diff)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use anyhow::{Context, Result};
use std::process::Command;

pub fn staged(context_lines: &u8) -> Result<String> {
    let output = Command::new("git")
        .args([
            "diff",
            "--cached",
            &format!("--unified={}", context_lines),
        ])
        .output()
        .context("Failed to run `git diff`. Is git installed and are you inside a repository?")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git diff exited with error: {}", stderr.trim());
    }
    let diff = String::from_utf8(output.stdout)
        .context("git diff output contained invalid UTF-8")?;
    Ok(diff)
}
use anyhow::{Context, Result};
use std::process::Command;

pub fn staged(context_lines: &u8) -> Result<String> {
    let output = Command::new("git")
        .args([
            "diff",
            "--cached",
            &format!("--unified={}", context_lines),
        ])
        .output()
        .context("Failed to run `git diff`. Is git installed and are you inside a repository?")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git diff exited with error: {}", stderr.trim());
    }
    let diff = String::from_utf8(output.stdout)
        .context("git diff output contained invalid UTF-8")?;
    Ok(diff)
}

std::process::Command runs the subprocess synchronously and captures both stdout and stderr. We check the exit status explicitly. If git diff fails because we are not inside a repository, or because git is not installed, we get a meaningful error message rather than a panic.

The context_lines parameter controls the -U flag in git diff, which determines how many lines of surrounding code appear in the output. Five lines is enough for the model to understand what changed and why. Increase it if you are working with complex logic that needs more context.

The Prompt

The prompt is where most of the quality comes from. A vague prompt produces vague output. A precise prompt produces precise output.

<button data-code="pub fn build(diff: &str, hint: Option) -> String {
let hint_line = match hint {
Some(h) => format!("nAdditional context from the author: {}n", h),
None => String::new(),
};

format!(
r#"You are a senior software engineer reviewing a Git diff.
Your task is to write a concise, accurate Git commit message for the changes shown.
Rules:
– Follow the Conventional Commits specification.
– Format: ():
– Allowed types: feat, fix, refactor, test, docs, chore, perf, ci, build, style.
– The short description must be in the imperative mood and under 72 characters.
– Do not include bullet points, markdown, or any explanation.
– Output only the commit message. Nothing else.
{hint_line}
Git diff:
{diff}"#
)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

pub fn build(diff: &str, hint: Option<&str>) -> String {
    let hint_line = match hint {
        Some(h) => format!("nAdditional context from the author: {}n", h),
        None    => String::new(),
    };

format!(
        r#"You are a senior software engineer reviewing a Git diff.
Your task is to write a concise, accurate Git commit message for the changes shown.
Rules:
- Follow the Conventional Commits specification.
- Format: <type>(<optional scope>): <short description>
- Allowed types: feat, fix, refactor, test, docs, chore, perf, ci, build, style.
- The short description must be in the imperative mood and under 72 characters.
- Do not include bullet points, markdown, or any explanation.
- Output only the commit message. Nothing else.
{hint_line}
Git diff:
{diff}"#
    )
}
pub fn build(diff: &str, hint: Option<&str>) -> String {
    let hint_line = match hint {
        Some(h) => format!("nAdditional context from the author: {}n", h),
        None    => String::new(),
    };

format!(
        r#"You are a senior software engineer reviewing a Git diff.
Your task is to write a concise, accurate Git commit message for the changes shown.
Rules:
- Follow the Conventional Commits specification.
- Format: <type>(<optional scope>): <short description>
- Allowed types: feat, fix, refactor, test, docs, chore, perf, ci, build, style.
- The short description must be in the imperative mood and under 72 characters.
- Do not include bullet points, markdown, or any explanation.
- Output only the commit message. Nothing else.
{hint_line}
Git diff:
{diff}"#
    )
}

The key instructions are “output only the commit message, nothing else” and the format constraint. Without these, models will happily write three paragraphs explaining their reasoning before the actual message. The hint parameter lets you guide the model when the diff alone is ambiguous: --hint "breaking change" or --hint "performance fix".

The Ollama Client

Ollama exposes a REST API at /api/generate. The request body contains the model name, the prompt, and a stream boolean. The response is either a single JSON object or a stream of newline-delimited JSON objects depending on that flag.

<button data-code="#[derive(Debug, Serialize)]
struct GenerateRequest {
model: &'a str,
prompt: &'a str,
stream: bool,
}

#[derive(Debug, Deserialize)]
struct StreamChunk {
response: String,
done: bool,
}
#[derive(Debug, Deserialize)]
struct CompleteResponse {
response: String,
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#[derive(Debug, Serialize)]
struct GenerateRequest<'a> {
    model:  &'a str,
    prompt: &'a str,
    stream: bool,
}

#[derive(Debug, Deserialize)]
struct StreamChunk {
    response: String,
    done:     bool,
}
#[derive(Debug, Deserialize)]
struct CompleteResponse {
    response: String,
}
#[derive(Debug, Serialize)]
struct GenerateRequest<'a> {
    model:  &'a str,
    prompt: &'a str,
    stream: bool,
}

#[derive(Debug, Deserialize)]
struct StreamChunk {
    response: String,
    done:     bool,
}
#[derive(Debug, Deserialize)]
struct CompleteResponse {
    response: String,
}

The generate function handles both modes:

Result {
let url = format!("{}/api/generate", base_url.trim_end_matches('/'));
let client = Client::new();
let body = GenerateRequest { model, prompt, stream };

let response = client
.post(&url)
.json(&body)
.send()
.await
.with_context(|| {
format!(
"Could not reach Ollama at {}.
Ensure Ollama is running (`ollama serve`) and the URL is correct.",
base_url
)
})?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
anyhow::bail!("Ollama returned HTTP {}: {}", status, body.trim());
}
if stream {
collect_stream(response).await
} else {
collect_complete(response).await
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

pub async fn generate(
    base_url: &str,
    model:    &str,
    prompt:   &str,
    stream:   bool,
) -> Result<String> {
    let url    = format!("{}/api/generate", base_url.trim_end_matches('/'));
    let client = Client::new();
    let body   = GenerateRequest { model, prompt, stream };

let response = client
        .post(&url)
        .json(&body)
        .send()
        .await
        .with_context(|| {
            format!(
                "Could not reach Ollama at {}. 
                 Ensure Ollama is running (`ollama serve`) and the URL is correct.",
                base_url
            )
        })?;
    if !response.status().is_success() {
        let status = response.status();
        let body   = response.text().await.unwrap_or_default();
        anyhow::bail!("Ollama returned HTTP {}: {}", status, body.trim());
    }
    if stream {
        collect_stream(response).await
    } else {
        collect_complete(response).await
    }
}
pub async fn generate(
    base_url: &str,
    model:    &str,
    prompt:   &str,
    stream:   bool,
) -> Result<String> {
    let url    = format!("{}/api/generate", base_url.trim_end_matches('/'));
    let client = Client::new();
    let body   = GenerateRequest { model, prompt, stream };

let response = client
        .post(&url)
        .json(&body)
        .send()
        .await
        .with_context(|| {
            format!(
                "Could not reach Ollama at {}. 
                 Ensure Ollama is running (`ollama serve`) and the URL is correct.",
                base_url
            )
        })?;
    if !response.status().is_success() {
        let status = response.status();
        let body   = response.text().await.unwrap_or_default();
        anyhow::bail!("Ollama returned HTTP {}: {}", status, body.trim());
    }
    if stream {
        collect_stream(response).await
    } else {
        collect_complete(response).await
    }
}

The error message on connection failure is deliberate. reqwest would give you something like “connection refused”. We replace it with a message that tells you exactly what to do: check that Ollama is running.

Streaming Token by Token

The non-streaming path is straightforward: deserialize the complete JSON response and return the response field. The streaming path is where async Rust does real work.

Result {
use std::io::Write;

let mut stream = response.bytes_stream();
let mut buffer = String::new();
let mut output = String::new();
let stdout = std::io::stdout();
let mut handle = stdout.lock();
while let Some(chunk) = stream.next().await {
let bytes = chunk.context("Error reading stream chunk from Ollama")?;
buffer.push_str(
std::str::from_utf8(&bytes)
.context("Ollama stream chunk was not valid UTF-8")?
);
while let Some(newline_pos) = buffer.find('n') {
let line: String = buffer.drain(..=newline_pos).collect();
let line = line.trim();
if line.is_empty() {
continue;
}
let chunk: StreamChunk = serde_json::from_str(line)
.with_context(|| format!("Failed to parse stream chunk: {}", line))?;
if !chunk.response.is_empty() {
write!(handle, "{}", chunk.response)?;
handle.flush()?;
output.push_str(&chunk.response);
}
if chunk.done {
writeln!(handle)?;
return Ok(output);
}
}
}
Ok(output)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

async fn collect_stream(response: reqwest::Response) -> Result<String> {
    use std::io::Write;

  let mut stream = response.bytes_stream();
      let mut buffer = String::new();
      let mut output = String::new();
      let stdout     = std::io::stdout();
      let mut handle = stdout.lock();
      while let Some(chunk) = stream.next().await {
          let bytes = chunk.context("Error reading stream chunk from Ollama")?;
          buffer.push_str(
              std::str::from_utf8(&bytes)
                  .context("Ollama stream chunk was not valid UTF-8")?
          );
          while let Some(newline_pos) = buffer.find('n') {
              let line: String = buffer.drain(..=newline_pos).collect();
              let line = line.trim();
              if line.is_empty() {
                  continue;
              }
              let chunk: StreamChunk = serde_json::from_str(line)
                  .with_context(|| format!("Failed to parse stream chunk: {}", line))?;
              if !chunk.response.is_empty() {
                  write!(handle, "{}", chunk.response)?;
                  handle.flush()?;
                  output.push_str(&chunk.response);
              }
              if chunk.done {
                  writeln!(handle)?;
                  return Ok(output);
              }
          }
      }
      Ok(output)
}
async fn collect_stream(response: reqwest::Response) -> Result<String> {
    use std::io::Write;

  let mut stream = response.bytes_stream();
      let mut buffer = String::new();
      let mut output = String::new();
      let stdout     = std::io::stdout();
      let mut handle = stdout.lock();
      while let Some(chunk) = stream.next().await {
          let bytes = chunk.context("Error reading stream chunk from Ollama")?;
          buffer.push_str(
              std::str::from_utf8(&bytes)
                  .context("Ollama stream chunk was not valid UTF-8")?
          );
          while let Some(newline_pos) = buffer.find('n') {
              let line: String = buffer.drain(..=newline_pos).collect();
              let line = line.trim();
              if line.is_empty() {
                  continue;
              }
              let chunk: StreamChunk = serde_json::from_str(line)
                  .with_context(|| format!("Failed to parse stream chunk: {}", line))?;
              if !chunk.response.is_empty() {
                  write!(handle, "{}", chunk.response)?;
                  handle.flush()?;
                  output.push_str(&chunk.response);
              }
              if chunk.done {
                  writeln!(handle)?;
                  return Ok(output);
              }
          }
      }
      Ok(output)
}

response.bytes_stream() gives us a Stream<Item = Result<Bytes>>. We iterate it with stream.next().await from the futures_util crate. Each chunk of bytes may contain multiple partial JSON objects, or a single object may span multiple chunks. The buffer accumulates incoming bytes and processes complete lines as they become available.

stdout.lock() acquires the stdout lock once for the entire stream rather than once per token. For a stream that might deliver hundreds of tokens, acquiring and releasing the lock per token adds up. Locking once is cleaner and faster.

The flush() after each write is necessary. Stdout in Rust is line-buffered by default. Without flushing, tokens accumulate in the buffer and appear all at once at the end, which defeats the purpose of streaming.

The CLI Interface

clap with its derive feature generates the complete CLI from struct attributes:

<button data-code="#[derive(Parser, Debug)]
#[command(name = "git-ai-commit", version = "0.1.0", about = "Generate Git commit messages from staged diffs using a local Ollama model")]
pub struct Args {
#[arg(short = 'm', long = "model", default_value = "llama3.2", env = "GIT_AI_COMMIT_MODEL")]
pub model: String,
#[arg(short = 'u', long = "ollama-url", default_value = "http://localhost:11434", env = "OLLAMA_URL")]
pub ollama_url: String,
#[arg(short = 'H', long = "hint")]
pub hint: Option,
#[arg(short = 'c', long = "context-lines", default_value_t = 5)]
pub diff_context_lines: u8,
#[arg(long = "show-diff")]
pub show_diff: bool,
#[arg(short = 's', long = "stream")]
pub stream: bool,
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#[derive(Parser, Debug)]
#[command(name = "git-ai-commit", version = "0.1.0", about = "Generate Git commit messages from staged diffs using a local Ollama model")]
pub struct Args {
    #[arg(short = 'm', long = "model", default_value = "llama3.2", env = "GIT_AI_COMMIT_MODEL")]
    pub model: String,
#[arg(short = 'u', long = "ollama-url", default_value = "http://localhost:11434", env = "OLLAMA_URL")]
    pub ollama_url: String,
    #[arg(short = 'H', long = "hint")]
    pub hint: Option<String>,
    #[arg(short = 'c', long = "context-lines", default_value_t = 5)]
    pub diff_context_lines: u8,
    #[arg(long = "show-diff")]
    pub show_diff: bool,
    #[arg(short = 's', long = "stream")]
    pub stream: bool,
}
#[derive(Parser, Debug)]
#[command(name = "git-ai-commit", version = "0.1.0", about = "Generate Git commit messages from staged diffs using a local Ollama model")]
pub struct Args {
    #[arg(short = 'm', long = "model", default_value = "llama3.2", env = "GIT_AI_COMMIT_MODEL")]
    pub model: String,
#[arg(short = 'u', long = "ollama-url", default_value = "http://localhost:11434", env = "OLLAMA_URL")]
    pub ollama_url: String,
    #[arg(short = 'H', long = "hint")]
    pub hint: Option<String>,
    #[arg(short = 'c', long = "context-lines", default_value_t = 5)]
    pub diff_context_lines: u8,
    #[arg(long = "show-diff")]
    pub show_diff: bool,
    #[arg(short = 's', long = "stream")]
    pub stream: bool,
}

The env attribute on model and ollama_url means you can set GIT_AI_COMMIT_MODEL=mistral in your shell profile and skip the flag entirely on every invocation. Command-line flags override environment variables, environment variables override the compiled defaults.

Wiring it Together

main.rs is deliberately thin:

Result {
let args = Args::parse();
let diff = diff::staged(&args.diff_context_lines)?;
if diff.trim().is_empty() {
eprintln!("No staged changes found. Stage your changes with `git add` first.");
std::process::exit(1);
}
if args.show_diff {
println!("— Staged diff —n{}n—n", diff);
}
let prompt = prompt::build(&diff, args.hint.as_deref());
println!("Generating commit message using model `{}`…n", args.model);
let message = ollama::generate(&args.ollama_url, &args.model, &prompt, args.stream).await?;
println!("{}", message.trim());
Ok(())
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

mod cli;
mod diff;
mod ollama;
mod prompt;

use anyhow::Result;
use cli::Args;
use clap::Parser;
#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();
    let diff = diff::staged(&args.diff_context_lines)?;
    if diff.trim().is_empty() {
        eprintln!("No staged changes found. Stage your changes with `git add` first.");
        std::process::exit(1);
    }
    if args.show_diff {
        println!("--- Staged diff ---n{}n---n", diff);
    }
    let prompt = prompt::build(&diff, args.hint.as_deref());
    println!("Generating commit message using model `{}`...n", args.model);
    let message = ollama::generate(&args.ollama_url, &args.model, &prompt, args.stream).await?;
    println!("{}", message.trim());
    Ok(())
}
mod cli;
mod diff;
mod ollama;
mod prompt;

use anyhow::Result;
use cli::Args;
use clap::Parser;
#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();
    let diff = diff::staged(&args.diff_context_lines)?;
    if diff.trim().is_empty() {
        eprintln!("No staged changes found. Stage your changes with `git add` first.");
        std::process::exit(1);
    }
    if args.show_diff {
        println!("--- Staged diff ---n{}n---n", diff);
    }
    let prompt = prompt::build(&diff, args.hint.as_deref());
    println!("Generating commit message using model `{}`...n", args.model);
    let message = ollama::generate(&args.ollama_url, &args.model, &prompt, args.stream).await?;
    println!("{}", message.trim());
    Ok(())
}

#[tokio::main] sets up the async runtime. The ? operator propagates errors up to main, where anyhow::Result formats them and prints them to stderr before exiting with a non-zero code.

The empty diff check exits early with a clear message. This is the case where someone runs the tool before staging anything. Letting it proceed would send an empty prompt to the model and produce a useless response.

Installing and Using It

cargo install --path .
cargo install --path .

This compiles in release mode and copies the binary to ~/.cargo/bin, which should already be on your PATH if you have Rust installed.

# Basic usage
git add src/
git-ai-commit

# Use a larger model for complex changes
git-ai-commit --model llama3.1:70b
# Give the model a hint
git-ai-commit --hint "breaking change in the public API"
# See what the model is actually working with
git-ai-commit --show-diff
# Watch it generate token by token
git-ai-commit --stream
# Set a permanent default model
export GIT_AI_COMMIT_MODEL=mistral
# Basic usage
git add src/
git-ai-commit

# Use a larger model for complex changes
git-ai-commit --model llama3.1:70b
# Give the model a hint
git-ai-commit --hint "breaking change in the public API"
# See what the model is actually working with
git-ai-commit --show-diff
# Watch it generate token by token
git-ai-commit --stream
# Set a permanent default model
export GIT_AI_COMMIT_MODEL=mistral

What the Model Actually Sees

The prompt for a typical staged diff looks like this:

<button data-code="You are a senior software engineer reviewing a Git diff.
Your task is to write a concise, accurate Git commit message for the changes shown.
Rules:
– Follow the Conventional Commits specification.
– Format: ():
…
Git diff:
diff –git a/src/auth.rs b/src/auth.rs
index 3a4f2b1..8c1e4d9 100644
— a/src/auth.rs
+++ b/src/auth.rs
@@ -14,6 +14,15 @@ impl JwtValidator {
pub fn validate(&self, token: &str) -> Result {
let claims = decode::(token, &self.key, &self.validation)?;
+
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+
+ if claims.claims.exp

You are a senior software engineer reviewing a Git diff.
Your task is to write a concise, accurate Git commit message for the changes shown.
Rules:
- Follow the Conventional Commits specification.
- Format: <type>(<optional scope>): <short description>
...
Git diff:
diff --git a/src/auth.rs b/src/auth.rs
index 3a4f2b1..8c1e4d9 100644
--- a/src/auth.rs
+++ b/src/auth.rs
@@ -14,6 +14,15 @@ impl JwtValidator {
     pub fn validate(&self, token: &str) -> Result<Claims> {
         let claims = decode::<Claims>(token, &self.key, &self.validation)?;
+
+        let now = SystemTime::now()
+            .duration_since(UNIX_EPOCH)
+            .unwrap()
+            .as_secs();
+
+        if claims.claims.exp < now {
+            return Err(AuthError::TokenExpired);
+        }
+
         Ok(claims.claims)
     }
 }
You are a senior software engineer reviewing a Git diff.
Your task is to write a concise, accurate Git commit message for the changes shown.
Rules:
- Follow the Conventional Commits specification.
- Format: <type>(<optional scope>): <short description>
...
Git diff:
diff --git a/src/auth.rs b/src/auth.rs
index 3a4f2b1..8c1e4d9 100644
--- a/src/auth.rs
+++ b/src/auth.rs
@@ -14,6 +14,15 @@ impl JwtValidator {
     pub fn validate(&self, token: &str) -> Result<Claims> {
         let claims = decode::<Claims>(token, &self.key, &self.validation)?;
+
+        let now = SystemTime::now()
+            .duration_since(UNIX_EPOCH)
+            .unwrap()
+            .as_secs();
+
+        if claims.claims.exp < now {
+            return Err(AuthError::TokenExpired);
+        }
+
         Ok(claims.claims)
     }
 }

And the output:

feat(auth): add token expiry validation to JWT middleware
feat(auth): add token expiry validation to JWT middleware

The model reads the type annotation on AuthError::TokenExpired, understands that expiry checking was missing and has been added, and produces the right type prefix (feat) with the right scope (auth) and an imperative description.

Choosing a Model

llama3.2 (3B parameters) is fast on most hardware and produces solid commit messages for straightforward changes. For complex refactors or large diffs, mistral or llama3.1:8b produce more accurate descriptions at the cost of a few extra seconds.

The tool has no opinion about which model you use. If it is available in your Ollama installation and it responds to the generate API, it works.

What This Teaches You About Rust

The project covers four patterns that appear in nearly every real Rust CLI tool:

Subprocess execution. std::process::Command is the standard library’s interface to the operating system. Capturing stdout, checking exit codes, and converting bytes to strings is a pattern you will use constantly.

Async HTTP with streaming. reqwest plus tokio plus futures_util::StreamExt is the idiomatic stack for async network IO in Rust. The streaming pattern here, accumulating a byte buffer and parsing complete lines as they arrive, generalises to any newline-delimited protocol.

Error handling with context. anyhow::Context lets you attach human-readable messages to errors without defining custom error types. Every ? in this codebase has a .context() call that explains what the operation was trying to do, so the error message the user sees is always specific.

CLI design with clap. The derive feature means the argument parser is just a struct. Adding a new flag is adding a field. Environment variable support is one attribute. Help text comes from doc comments.

None of these are novel techniques. They are the standard Rust tools for this class of problem, used straightforwardly.

The full source with all files is on GitHub

GitHub – shan305/commit-generator: A CLI tool that reads your staged Git diff and generates a…
A CLI tool that reads your staged Git diff and generates a commit message using a local Ollama model. No API keys. No…

Published under Systems Engineering.

I spent six months writing about Rust and turned it into a 23-chapter field guide with a full Redis clone as the capstone. If you are working through this language seriously, it covers everything from ownership to production-level concurrency.

$7 — Zero to Rust: A Systems Programmer’s Field Guide
You can read the free sample here — Free 20-page sample