Skip to content

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

// commit-message-generator — diff stats, prompt building, completion parsing.
//
// Language: Swift (5, Foundation allowed — NSRegularExpression is ICU, the
//           regex engine family JavaScript's RegExp descends from)
// 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: NSString ranges are UTF-16 offsets, so the
// indexOf/substring bookkeeping matches the TS port exactly, and
// .anchorsMatchLines reproduces the /m anchors. One dialect trap:
// replaceMatches is global, so the preamble strip uses firstMatch +
// deleteCharacters to stay first-match-only like the TS replace.
//
// Run: swift swift.swift

import Foundation

func regex(_ pattern: String, _ options: NSRegularExpression.Options = []) -> NSRegularExpression {
    try! NSRegularExpression(pattern: pattern, options: options)
}

/// One match per `diff --git a/… b/…` file header.
let diffFileRe = regex("^diff --git ", .anchorsMatchLines)
/// An added line: a `+` not followed by another `+` (skips the `+++` header).
let addRe = regex("^\\+[^+]", .anchorsMatchLines)
/// A deleted line: a `-` not followed by another `-` (skips the `---` header).
let delRe = regex("^-[^-]", .anchorsMatchLines)
/// Git stamps brand-new files with a `new file mode` extended header.
let newFileRe = regex("^new file mode ", .anchorsMatchLines)
let fenceRe = regex("```[a-z]*\n?")
let subjectRe = regex("^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)(\\([^)]+\\))?!?: .+$")
let preambleRe = regex("^\\s*(here.*?:|sure.*?:)\\s*$", [.anchorsMatchLines, .caseInsensitive])

/// The commit types the island's picker offers (TS `CommitType`).
let commitTypes = ["feat", "fix", "docs", "refactor", "chore"]

/// Diffs larger than this are cut before they reach the model.
let maxDiffChars = 8000

/// Provider-layer system message, verbatim from the TS lib.
let systemPrompt = "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."

/// Counts extracted from one unified diff (TS `DiffStats`).
struct DiffStats {
    var files = 0, additions = 0, deletions = 0, newFiles = 0
}

/// One message for the provider layer.
struct ChatMessage {
    let role: String
    let content: String
}

/// The parsed model reply: subject line plus body.
struct Completion {
    let subject: String
    let body: String
}

/// Count files / ±lines / new files from a unified diff; tolerant of
/// non-diff input (mirrors diffStats() in the TS lib).
func diffStats(_ diff: String) -> DiffStats {
    guard !diff.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return DiffStats() }
    return DiffStats(
        files: countMatches(diffFileRe, diff),
        additions: countMatches(addRe, diff),
        deletions: countMatches(delRe, diff),
        newFiles: countMatches(newFileRe, diff))
}

private func countMatches(_ re: NSRegularExpression, _ s: String) -> Int {
    re.numberOfMatches(in: s, range: NSRange(s.startIndex..., in: s))
}

/// Build the [system, user] chat messages for the provider layer. A diff
/// over maxDiffChars is cut (in UTF-16 units, like the TS slice) with an
/// explicit marker so a runaway `git diff` can never blow the context
/// window silently (mirrors buildPromptMessages() in the TS lib).
func buildPromptMessages(_ diff: String, type commitType: String) -> [ChatMessage] {
    let stats = diffStats(diff)
    let body = diff.utf16.count > maxDiffChars
        ? String(decoding: diff.utf16.prefix(maxDiffChars), as: UTF16.self) + "\n… (diff truncated)"
        : diff
    let user = "Commit type: \(commitType)\nDiff summary: \(stats.files) files changed, " +
        "\(stats.additions) additions, \(stats.deletions) deletions, \(stats.newFiles) new files.\n\n\(body)"
    return [ChatMessage(role: "system", content: systemPrompt),
            ChatMessage(role: "user", content: user)]
}

/// Parse the model's reply into a Completion; nil 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.
func parseCompletion(_ text: String) -> Completion? {
    // Strip ``` fences globally — replaceMatches is the JS /g here.
    let stripped = NSMutableString(string: text)
    fenceRe.replaceMatches(
        in: stripped, range: NSRange(location: 0, length: stripped.length), withTemplate: "")
    let cleaned = stripped as String
    let ns = cleaned as NSString

    for line in cleaned.components(separatedBy: "\n") {
        let t = line.trimmingCharacters(in: .whitespacesAndNewlines)
        guard subjectRe.firstMatch(in: t, range: NSRange(t.startIndex..., in: t)) != nil else { continue }

        // JS indexOf semantics over UTF-16 offsets.
        let start = ns.range(of: t).location + (t as NSString).length
        let body = NSMutableString(string: ns.substring(from: start))
        if let aside = preambleRe.firstMatch(
            in: body as String, range: NSRange(location: 0, length: body.length))
        {
            body.deleteCharacters(in: aside.range)  // first match only
        }
        return Completion(
            subject: t,
            body: (body as String).trimmingCharacters(in: .whitespacesAndNewlines))
    }
    return nil
}

// Demo — `swift swift.swift`
let sample = "diff --git a/x b/x\nnew file mode 100644\n--- a/x\n+++ b/x\n+hello\n-world\n"
let stats = diffStats(sample)
print("stats: \(stats.files) files, +\(stats.additions) -\(stats.deletions), \(stats.newFiles) new")

let done = parseCompletion("```txt\nsure, here:\nfeat: add widget\n\nadds the widget\n```")
print("\(done?.subject ?? "nil") | \(done?.body ?? "nil")")
print(parseCompletion("no commit subject here")?.subject ?? "nil")

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 →