Skip to content

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

// commit-message-generator — diff stats, prompt building, completion parsing.
//
// Language: Java (17, standard library only — java.util.regex is the regex
//           engine, the same role the re module plays in python.py)
// 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: Java strings are UTF-16 like JavaScript's, so
// length()/substring()/indexOf() track the TS port exactly, and
// Pattern.MULTILINE reproduces the /m anchors. One dialect trap:
// Matcher.replaceAll is always global, so the preamble strip does an
// explicit find() + splice to stay first-match-only like the TS replace.
//
// Run: java java.java   (single-file source launch)

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Commit-message-generator core — pure logic, no I/O. */
final class CommitMessageTool {

    /** The commit types the island's picker offers (TS `CommitType`). */
    static final List<String> COMMIT_TYPES = List.of("feat", "fix", "docs", "refactor", "chore");

    /** Diffs larger than this are cut before they reach the model. */
    static final int MAX_DIFF_CHARS = 8000;

    /** Provider-layer system message, verbatim from the TS lib. */
    static final String 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.";

    /** One match per `diff --git a/… b/…` file header. */
    static final Pattern DIFF_FILE_RE = Pattern.compile("^diff --git ", Pattern.MULTILINE);
    /** An added line: a `+` not followed by another `+` (skips the `+++` header). */
    static final Pattern ADD_RE = Pattern.compile("^\\+[^+]", Pattern.MULTILINE);
    /** A deleted line: a `-` not followed by another `-` (skips the `---` header). */
    static final Pattern DEL_RE = Pattern.compile("^-[^-]", Pattern.MULTILINE);
    /** Git stamps brand-new files with a `new file mode` extended header. */
    static final Pattern NEW_FILE_RE = Pattern.compile("^new file mode ", Pattern.MULTILINE);
    static final Pattern FENCE_RE = Pattern.compile("```[a-z]*\n?");
    static final Pattern SUBJECT_RE = Pattern.compile(
            "^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)(\\([^)]+\\))?!?: .+$");
    static final Pattern PREAMBLE_RE = Pattern.compile(
            "^\\s*(here.*?:|sure.*?:)\\s*$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);

    /** Counts extracted from one unified diff (TS `DiffStats`). */
    record DiffStats(int files, int additions, int deletions, int newFiles) {}

    /** One message for the provider layer. */
    record ChatMessage(String role, String content) {}

    /** The parsed model reply: subject line plus body. */
    record Completion(String subject, String body) {}

    /**
     * Count files / ±lines / new files from a unified diff; tolerant of
     * non-diff input (mirrors diffStats() in the TS lib).
     */
    static DiffStats diffStats(String diff) {
        if (diff.strip().isEmpty()) return new DiffStats(0, 0, 0, 0);
        return new DiffStats(count(diff, DIFF_FILE_RE), count(diff, ADD_RE),
                count(diff, DEL_RE), count(diff, NEW_FILE_RE));
    }

    private static int count(String s, Pattern pattern) {
        Matcher m = pattern.matcher(s);
        int n = 0;
        while (m.find()) n++;
        return n;
    }

    /**
     * Build the [system, user] chat messages for the provider layer. A diff
     * over MAX_DIFF_CHARS is cut with an explicit marker so a runaway
     * `git diff` can never blow the context window silently.
     */
    static List<ChatMessage> buildPromptMessages(String diff, String commitType) {
        DiffStats stats = diffStats(diff);
        String body = diff.length() > MAX_DIFF_CHARS
                ? diff.substring(0, MAX_DIFF_CHARS) + "\n… (diff truncated)"
                : diff;
        String user = "Commit type: " + commitType
                + "\nDiff summary: " + stats.files() + " files changed, " + stats.additions()
                + " additions, " + stats.deletions() + " deletions, " + stats.newFiles()
                + " new files.\n\n" + body;
        return List.of(new ChatMessage("system", SYSTEM_PROMPT), new ChatMessage("user", user));
    }

    /**
     * Parse the model's reply into a Completion; null when unusable. 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 (explicit find() keeps it first-match-only).
     */
    static Completion parseCompletion(String text) {
        String cleaned = text.replaceAll("```[a-z]*\n?", "").strip();
        for (String line : cleaned.split("\n", -1)) {
            String t = line.strip();
            if (!SUBJECT_RE.matcher(t).matches()) continue;
            String body = cleaned.substring(cleaned.indexOf(t) + t.length());
            Matcher aside = PREAMBLE_RE.matcher(body);
            if (aside.find()) {
                body = body.substring(0, aside.start()) + body.substring(aside.end());
            }
            return new Completion(t, body.strip());
        }
        return null;
    }

    public static void main(String[] args) {
        String diff = "diff --git a/x b/x\nnew file mode 100644\n--- a/x\n+++ b/x\n+hello\n-world\n";
        DiffStats stats = diffStats(diff);
        System.out.println("stats: " + stats.files() + " files, +" + stats.additions()
                + " -" + stats.deletions() + ", " + stats.newFiles() + " new");

        Completion done = parseCompletion("```txt\nsure, here:\nfeat: add widget\n\nadds the widget\n```");
        System.out.println(done.subject() + " | " + done.body());
        System.out.println(parseCompletion("no commit subject here"));
    }
}

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 →