AI Commit Message Generator — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// commit-message-generator — diff stats, prompt building, completion parsing.
//
// Language: Kotlin (JVM, stdlib only — kotlin.text.Regex over
// java.util.regex, 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: JVM strings are UTF-16 like JavaScript's, so
// length/substring/indexOf track the TS port exactly, and
// RegexOption.MULTILINE reproduces the /m anchors. One dialect trap:
// Regex.replace is global, but replaceFirst keeps the preamble strip
// first-match-only like the TS replace.
//
// Run: kotlinc kotlin.kt -include-runtime -d cmg.jar && java -jar cmg.jar
/** The commit types the island's picker offers (TS `CommitType`). */
val COMMIT_TYPES = listOf("feat", "fix", "docs", "refactor", "chore")
/** Diffs larger than this are cut before they reach the model. */
const val MAX_DIFF_CHARS = 8000
/** Provider-layer system message, verbatim from the TS lib. */
const val 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. */
val DIFF_FILE_RE = Regex("""^diff --git """, RegexOption.MULTILINE)
/** An added line: a `+` not followed by another `+` (skips the `+++` header). */
val ADD_RE = Regex("""^\+[^+]""", RegexOption.MULTILINE)
/** A deleted line: a `-` not followed by another `-` (skips the `---` header). */
val DEL_RE = Regex("""^-[^-]""", RegexOption.MULTILINE)
/** Git stamps brand-new files with a `new file mode` extended header. */
val NEW_FILE_RE = Regex("""^new file mode """, RegexOption.MULTILINE)
val FENCE_RE = Regex("```[a-z]*\n?")
val SUBJECT_RE = Regex(
"""^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)(\([^)]+\))?!?: .+$""",
)
val PREAMBLE_RE = Regex(
"""^\s*(here.*?:|sure.*?:)\s*$""",
setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE),
)
/** Counts extracted from one unified diff (TS `DiffStats`). */
data class DiffStats(val files: Int, val additions: Int, val deletions: Int, val newFiles: Int)
/** One message for the provider layer. */
data class ChatMessage(val role: String, val content: String)
/** The parsed model reply: subject line plus body. */
data class Completion(val subject: String, val body: String)
/**
* Count files / ±lines / new files from a unified diff; tolerant of
* non-diff input (mirrors diffStats() in the TS lib).
*/
fun diffStats(diff: String): DiffStats {
if (diff.isBlank()) return DiffStats(0, 0, 0, 0)
return DiffStats(
DIFF_FILE_RE.findAll(diff).count(),
ADD_RE.findAll(diff).count(),
DEL_RE.findAll(diff).count(),
NEW_FILE_RE.findAll(diff).count(),
)
}
/**
* 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 (mirrors buildPromptMessages()).
*/
fun buildPromptMessages(diff: String, commitType: String): List<ChatMessage> {
val stats = diffStats(diff)
val body =
if (diff.length > MAX_DIFF_CHARS) diff.substring(0, MAX_DIFF_CHARS) + "\n… (diff truncated)" else diff
val user = "Commit type: $commitType\nDiff summary: ${stats.files} files changed, " +
"${stats.additions} additions, ${stats.deletions} deletions, ${stats.newFiles} new files.\n\n$body"
return listOf(ChatMessage("system", SYSTEM_PROMPT), ChatMessage("user", user))
}
/**
* 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.
*/
fun parseCompletion(text: String): Completion? {
val cleaned = text.replace(FENCE_RE, "").trim()
for (line in cleaned.split("\n")) {
val t = line.trim()
if (!SUBJECT_RE.matches(t)) continue
val body = cleaned.substring(cleaned.indexOf(t) + t.length)
// replaceFirst = the TS port's non-global replace (first match only).
return Completion(t, PREAMBLE_RE.replaceFirst(body, "").trim())
}
return null
}
fun main() {
val diff = "diff --git a/x b/x\nnew file mode 100644\n--- a/x\n+++ b/x\n+hello\n-world\n"
val stats = diffStats(diff)
println("stats: ${stats.files} files, +${stats.additions} -${stats.deletions}, ${stats.newFiles} new")
val done = parseCompletion("```txt\nsure, here:\nfeat: add widget\n\nadds the widget\n```")
println("${done?.subject} | ${done?.body}")
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 →