Skip to content

AI Commit Message Generator — Zig 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 Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! commit-message-generator — diff stats, prompt building, completion parsing.
//!
//! Language: Zig (0.13, standard library only — std has no regex, so the
//!           TS port's five regexes become small scanners, like the base64
//!           tool's hand-rolled codec)
//! Source:   CosmoDev polyglot showcase port of the `commit-message-generator`
//!           tool, ported from src/lib/commit-message.ts (the canonical
//!           TypeScript implementation).
//! License:  display source — part of CosmoDev's polyglot tool pages.
//!
//! Why this file exists: the diff counters are plain prefix checks over
//! newline-split lines, the ``` fence strip is a skipping copy, and the
//! conventional-commit subject contract is a tiny hand-rolled matcher.
//! Everything is byte-based like the go.go port, with the truncation cut
//! pulled back to a UTF-8 boundary. (And no field is ever named `error`.)
//!
//! Test: zig test zig.zig

const std = @import("std");

/// Diffs larger than this are cut before they reach the model.
pub const max_diff_chars = 8000;

/// Provider-layer system message, verbatim from the TS lib.
pub const system_prompt =
    \\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.
;

/// The commit types the island's picker offers (TS `CommitType`).
pub const commit_types = [_][]const u8{ "feat", "fix", "docs", "refactor", "chore" };

/// The TS regex's leading (feat|…|audit) alternation.
const subject_types = [_][]const u8{
    "feat", "fix", "docs", "style", "refactor", "perf",
    "test", "build", "ci", "chore", "security", "audit",
};

/// Counts extracted from one unified diff (TS `DiffStats`).
pub const DiffStats = struct {
    files: usize = 0,
    additions: usize = 0,
    deletions: usize = 0,
    new_files: usize = 0,
};

/// One message for the provider layer.
pub const ChatMessage = struct { role: []const u8, content: []const u8 };

/// The parsed model reply: subject line plus body.
pub const Completion = struct { subject: []const u8, body: []const u8 };

/// JS \s: the six ASCII whitespace characters.
fn isSpace(c: u8) bool {
    return c == ' ' or c == '\t' or c == '\n' or c == '\r' or c == 0x0b or c == 0x0c;
}

/// Case-insensitive prefix test ("Here:" still counts as an aside).
fn ciStartsWith(s: []const u8, prefix: []const u8) bool {
    if (s.len < prefix.len) return false;
    for (prefix, 0..) |c, i| {
        if (std.ascii.toLower(s[i]) != c) return false;
    }
    return true;
}

/// JS: /^(feat|…|audit)(\([^)]+\))?!?: .+$/ — tested on a trimmed line.
fn isSubject(t: []const u8) bool {
    for (subject_types) |kind| {
        if (!std.mem.startsWith(u8, t, kind)) continue;
        var i = kind.len;
        if (i < t.len and t[i] == '(') { // optional (scope)
            var j = i + 1;
            while (j < t.len and t[j] != ')') j += 1;
            if (j == t.len or j == i + 1) continue; // unclosed or empty scope
            i = j + 1;
        }
        if (i < t.len and t[i] == '!') i += 1;
        // ": " then at least one more character (the .+).
        if (t.len > i + 2 and t[i] == ':' and t[i + 1] == ' ') return true;
    }
    return false;
}

/// Count files / ±lines / new files from a unified diff; tolerant of
/// non-diff input (mirrors diffStats() in the TS lib).
pub fn diffStats(diff: []const u8) DiffStats {
    var stats = DiffStats{};
    var blank = true;
    for (diff) |c| {
        if (!isSpace(c)) {
            blank = false;
            break;
        }
    }
    if (blank) return stats;
    var lines = std.mem.splitScalar(u8, diff, '\n');
    while (lines.next()) |line| {
        if (std.mem.startsWith(u8, line, "diff --git ")) stats.files += 1;
        if (line.len >= 2 and line[0] == '+' and line[1] != '+') stats.additions += 1;
        if (line.len >= 2 and line[0] == '-' and line[1] != '-') stats.deletions += 1;
        if (std.mem.startsWith(u8, line, "new file mode ")) stats.new_files += 1;
    }
    return stats;
}

/// JS: body.replace(/^\s*(here.*?:|sure.*?:)\s*$/im, "") — first match
/// only. Emits the body as [0, cut_start) ++ [cut_end, len): the earliest
/// line-start whose line is just a "here…:"/"sure…:" aside, plus the greedy
/// trailing \s* backtracked to just before a '\n' or the end of the body.
fn findPreamble(body: []const u8, cut_start: *usize, cut_end: *usize) void {
    cut_start.* = 0;
    cut_end.* = 0; // no match: body[0..0] ++ body[0..] is the whole body
    var p: usize = 0;
    while (p < body.len) : (p += 1) {
        if (!(p == 0 or body[p - 1] == '\n')) continue; // ^ anchors at line starts
        var q = p;
        while (q < body.len and isSpace(body[q])) q += 1; // ^\s*
        var e = q;
        while (e < body.len and body[e] != '\n') e += 1; // end of the line
        var ce = e;
        while (ce > q and isSpace(body[ce - 1])) ce -= 1; // minus trailing \s
        if (ce - q < 5 or body[ce - 1] != ':') continue;
        if (!(ciStartsWith(body[q..ce], "here") or ciStartsWith(body[q..ce], "sure"))) continue;
        var w = ce;
        while (w < body.len and isSpace(body[w])) w += 1; // \s* greedy...
        if (w == body.len) {
            cut_end.* = w; // ...and $ at the string end
            return;
        }
        var k = w;
        while (k > ce and body[k] != '\n') k -= 1; // ...backtracked to a '\n'
        if (k == ce and body[ce] != '\n') continue; // no '$' anchor on this line
        cut_start.* = p;
        cut_end.* = k;
        return;
    }
}

/// Build the [system, user] chat messages for the provider layer (mirrors
/// buildPromptMessages() in the TS lib). A diff over max_diff_chars is cut
/// at a UTF-8 boundary with an explicit marker. The caller owns the result.
pub fn buildPromptMessages(
    allocator: std.mem.Allocator,
    diff: []const u8,
    commit_type: []const u8,
) ![]ChatMessage {
    const stats = diffStats(diff);
    var body: []const u8 = diff;
    if (diff.len > max_diff_chars) {
        var end: usize = max_diff_chars;
        while (end > 0 and (diff[end] & 0xC0) == 0x80) end -= 1;
        body = try std.mem.concat(allocator, u8, &[_][]const u8{
            diff[0..end],
            "\n… (diff truncated)",
        });
    }
    const user = try std.fmt.allocPrint(
        allocator,
        "Commit type: {s}\nDiff summary: {d} files changed, {d} additions, {d} deletions, {d} new files.\n\n{s}",
        .{ commit_type, stats.files, stats.additions, stats.deletions, stats.new_files, body },
    );
    const messages = try allocator.alloc(ChatMessage, 2);
    messages[0] = .{ .role = "system", .content = system_prompt };
    messages[1] = .{ .role = "user", .content = user };
    return messages;
}

/// Parse the model's reply into a Completion; null when unusable (mirrors
/// parseCompletion() in the TS lib). Strips ``` fences, scans line by line
/// for the first valid conventional-commit subject, and takes everything
/// after it as the body, minus a bare "here…:"/"sure…:" aside. The caller
/// owns the returned slices.
pub fn parseCompletion(allocator: std.mem.Allocator, text: []const u8) !?Completion {
    // Strip ``` fences: after "```", drop [a-z]* and one following newline.
    const buf = try allocator.alloc(u8, text.len);
    defer allocator.free(buf);
    var n: usize = 0;
    var i: usize = 0;
    while (i < text.len) {
        if (i + 2 < text.len and std.mem.startsWith(u8, text[i..], "```")) {
            i += 3;
            while (i < text.len and text[i] >= 'a' and text[i] <= 'z') i += 1;
            if (i < text.len and text[i] == '\n') i += 1;
        } else {
            buf[n] = text[i];
            n += 1;
            i += 1;
        }
    }
    const cleaned = buf[0..n];

    // JS trim() over the whole reply, then line-by-line subject scanning.
    var b: usize = 0;
    while (b < n and isSpace(cleaned[b])) b += 1;
    var e = n;
    while (e > b and isSpace(cleaned[e - 1])) e -= 1;
    const t_all = cleaned[b..e];

    var lines = std.mem.splitScalar(u8, t_all, '\n');
    while (lines.next()) |raw_line| {
        var ls: usize = 0;
        while (ls < raw_line.len and isSpace(raw_line[ls])) ls += 1;
        var le = raw_line.len;
        while (le > ls and isSpace(raw_line[le - 1])) le -= 1;
        const subject = raw_line[ls..le];
        if (!isSubject(subject)) continue;
        // JS indexOf: first occurrence of the subject anywhere in the reply.
        const at = std.mem.indexOf(u8, t_all, subject).?;
        const body = t_all[at + subject.len ..];
        var cut_start: usize = 0;
        var cut_end: usize = body.len;
        findPreamble(body, &cut_start, &cut_end);
        const joined = try std.mem.concat(allocator, u8, &[_][]const u8{
            body[0..cut_start],
            body[cut_end..],
        });
        defer allocator.free(joined);
        const out_subject = try allocator.dupe(u8, subject);
        const out_body = try allocator.dupe(u8, std.mem.trim(u8, joined, " \t\n\r\x0b\x0c"));
        return Completion{ .subject = out_subject, .body = out_body };
    }
    return null;
}

test "diff stats, prompt building and reply parsing mirror the TS lib" {
    const t = std.testing;
    const a = t.allocator;

    const diff = "diff --git a/x b/x\nnew file mode 100644\n--- a/x\n+++ b/x\n+hello\n-world\n";
    const stats = diffStats(diff);
    try t.expectEqual(@as(usize, 1), stats.files);
    try t.expectEqual(@as(usize, 1), stats.additions);
    try t.expectEqual(@as(usize, 1), stats.deletions);
    try t.expectEqual(@as(usize, 1), stats.new_files);

    const messages = try buildPromptMessages(a, diff, "feat");
    defer a.free(messages);
    defer a.free(messages[1].content);
    try t.expectEqualStrings("system", messages[0].role);
    try t.expect(std.mem.startsWith(
        u8,
        messages[1].content,
        "Commit type: feat\nDiff summary: 1 files changed, 1 additions, 1 deletions, 1 new files.",
    ));

    const done = (try parseCompletion(
        a,
        "```txt\nsure, here:\nfeat: add widget\n\nadds the widget\n```",
    )).?;
    try t.expectEqualStrings("feat: add widget", done.subject);
    try t.expectEqualStrings("adds the widget", done.body);
    a.free(done.subject);
    a.free(done.body);

    const none = try parseCompletion(a, "no commit subject here");
    try t.expect(none == null);
}

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 →