AI Commit Message Generator — Rust source
Paste a git diff, get a conventional commit message from an LLM — bring your own free Groq key, called straight from your browser.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! commit-message-generator — diff stats, prompt building, completion parsing.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `commit-message-generator` tool,
//! ported from src/lib/commit-message.ts (the canonical TypeScript implementation).
//!
//! Why this file exists: the tool's non-LLM core is pure string work, so it
//! ports without any I/O or async surface. Rust std ships no regex engine, so
//! the canonical lib's four `/gm` diff counters become line predicates and the
//! subject / fence / preamble matchers become small hand-rolled scanners that
//! accept exactly the same language.
/// The commit types the island's picker offers (TS `CommitType`).
pub const COMMIT_TYPES: [&str; 5] = ["feat", "fix", "docs", "refactor", "chore"];
/// Diffs larger than this many characters are cut before reaching the model.
pub const MAX_DIFF_CHARS: usize = 8000;
/// The system prompt, verbatim from the TS lib.
pub const SYSTEM_PROMPT: &str = "You write one conventional commit message for the given diff. Reply with ONLY the message: a subject line \"type: imperative summary\" (max 72 chars, lowercase after the type), then a blank line, then a short body explaining what and why. No fences, no preamble.";
/// File / ±line / new-file counts extracted from one unified diff.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct DiffStats {
pub files: usize,
pub additions: usize,
pub deletions: usize,
pub new_files: usize,
}
/// One chat message for the provider layer.
#[derive(Debug, PartialEq, Eq)]
pub struct ChatMessage {
pub role: &'static str,
pub content: String,
}
/// The parsed model reply: a conventional-commit subject plus its body.
#[derive(Debug, PartialEq, Eq)]
pub struct Completion {
pub subject: String,
pub body: String,
}
/// Count files / ±lines / new files from a unified diff; tolerant of non-diff
/// input. Per-line predicates mirror `/^diff --git /gm`, `/^\+[^+]/gm`,
/// `/^-[^-]/gm` and `/^new file mode /gm`: a `+`/`-` only counts when a
/// non-`+`/non-`-` byte follows, which skips the `+++`/`---` file headers.
pub fn diff_stats(diff: &str) -> DiffStats {
let mut stats = DiffStats::default();
if diff.trim().is_empty() {
return stats;
}
for line in diff.lines() {
if line.starts_with("diff --git ") {
stats.files += 1;
}
if line.starts_with("new file mode ") {
stats.new_files += 1;
}
let mut chars = line.chars();
match (chars.next(), chars.next()) {
(Some('+'), Some(c)) if c != '+' => stats.additions += 1,
(Some('-'), Some(c)) if c != '-' => stats.deletions += 1,
_ => {}
}
}
stats
}
/// Build the [system, user] chat messages for the provider layer. A diff over
/// MAX_DIFF_CHARS is cut at the nearest UTF-8 boundary with an explicit
/// marker (JS slices by code unit; for the ASCII diffs git produces, and any
/// valid-UTF-8 input thanks to the boundary walk, the cut is equivalent).
pub fn build_prompt_messages(diff: &str, commit_type: &str) -> Vec<ChatMessage> {
let stats = diff_stats(diff);
let body = if diff.len() > MAX_DIFF_CHARS {
let mut end = MAX_DIFF_CHARS;
while end > 0 && !diff.is_char_boundary(end) {
end -= 1;
}
format!("{}\n… (diff truncated)", &diff[..end])
} else {
diff.to_string()
};
let user = format!(
"Commit type: {}\nDiff summary: {} files changed, {} additions, {} deletions, {} new files.\n\n{}",
commit_type, stats.files, stats.additions, stats.deletions, stats.new_files, body
);
vec![
ChatMessage { role: "system", content: SYSTEM_PROMPT.to_string() },
ChatMessage { role: "user", content: user },
]
}
/// Parse the model's reply into a `Completion`; `None` when unusable. Strips
/// ``` fences, scans line by line for the first valid conventional-commit
/// subject; everything after it is the body, minus a bare "here…:" /
/// "sure…:" aside the model may have led with.
pub fn parse_completion(text: &str) -> Option<Completion> {
let cleaned = strip_fences(text);
let cleaned = cleaned.trim();
for line in cleaned.lines() {
let subject = line.trim();
if !is_subject(subject) {
continue;
}
// indexOf semantics: first occurrence of the subject in the text.
let start = cleaned.find(subject)? + subject.len();
let body = strip_first_preamble(&cleaned[start..]).trim().to_string();
return Some(Completion { subject: subject.to_string(), body });
}
None
}
/// `/```[a-z]*\n?/g` — drop every fence (with optional language tag + newline).
fn strip_fences(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(pos) = rest.find("```") {
out.push_str(&rest[..pos]);
rest = &rest[pos + 3..];
let stop = rest.find(|c: char| !c.is_ascii_lowercase()).unwrap_or(rest.len());
rest = &rest[stop..];
rest = rest.strip_prefix('\n').unwrap_or(rest);
}
out.push_str(rest);
out
}
/// Subject alternatives, in the TS regex's literal order.
const SUBJECT_TYPES: [&str; 12] = [
"feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore",
"security", "audit",
];
/// `/^(feat|…|audit)(\([^)]+\))?!?: .+$/` on one line. No type in the list is
/// a prefix of another, so first-prefix-match equals regex alternation.
fn is_subject(line: &str) -> bool {
let rest = match SUBJECT_TYPES.iter().find_map(|t| line.strip_prefix(*t)) {
Some(rest) => rest,
None => return false,
};
let rest = match rest.strip_prefix('(') {
Some(after) => match after.find(')') {
Some(end) if end > 0 => &after[end + 1..], // scope needs 1+ chars, like [^)]+
_ => return false,
},
None => rest,
};
match rest.strip_prefix('!').unwrap_or(rest).strip_prefix(": ") {
Some(subject) => !subject.is_empty(),
None => false,
}
}
/// One line of `/^\s*(here.*?:|sure.*?:)\s*$/im`: optional surrounding
/// whitespace, a "here"/"sure" lead (case-insensitive), then a colon whose
/// tail is whitespace only.
fn is_preamble_line(line: &str) -> bool {
let t = line.trim();
let rest = match ci_strip_prefix(t, "here").or_else(|| ci_strip_prefix(t, "sure")) {
Some(rest) => rest,
None => return false,
};
match rest.rfind(':') {
Some(colon) => rest[colon + 1..].trim().is_empty(),
None => false,
}
}
fn ci_strip_prefix<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
if s.len() >= prefix.len() && s[..prefix.len()].eq_ignore_ascii_case(prefix) {
Some(&s[prefix.len()..])
} else {
None
}
}
/// JS `.replace(/…/im, '')` replaces only the FIRST match: drop the first
/// preamble line; the whitespace around it goes with the caller's trim().
fn strip_first_preamble(body: &str) -> String {
let lines: Vec<&str> = body.lines().collect();
match lines.iter().position(|l| is_preamble_line(l)) {
Some(i) => {
let mut kept: Vec<&str> = Vec::with_capacity(lines.len() - 1);
kept.extend_from_slice(&lines[..i]);
kept.extend_from_slice(&lines[i + 1..]);
kept.join("\n")
}
None => body.to_string(),
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →