Skip to content

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

// commit-message-generator — diff stats, prompt building, completion parsing.
//
// Language: Go (standard library only).
// 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 the
// std regexp package covers it 1:1 — JS's /m (line anchors) and /g (find all)
// flags become Go's (?m) and FindAllString(-1), and JS's first-match-only
// replace becomes an explicit FindStringIndex splice.
package commitmessagegenerator

import (
	"fmt"
	"regexp"
	"strings"
	"unicode/utf8"
)

// CommitTypes lists the commit types the island's picker offers (TS CommitType).
var CommitTypes = []string{"feat", "fix", "docs", "refactor", "chore"}

// MaxDiffChars caps how much of a diff is sent to the model.
const MaxDiffChars = 8000

// SystemPrompt is the provider-layer system message, verbatim from the TS lib.
const 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.`

var (
	diffFileRe = regexp.MustCompile(`(?m)^diff --git `)  // one per file header
	addRe      = regexp.MustCompile(`(?m)^\+[^+]`)       // + not followed by +: skips +++
	delRe      = regexp.MustCompile(`(?m)^-[^-]`)        // - not followed by -: skips ---
	newFileRe  = regexp.MustCompile(`(?m)^new file mode `)
	fenceRe    = regexp.MustCompile("```[a-z]*\n?")
	subjectRe  = regexp.MustCompile(`^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)(\([^)]+\))?!?: .+$`)
	preambleRe = regexp.MustCompile(`(?im)^\s*(here.*?:|sure.*?:)\s*$`)
)

// DiffStats holds the counts ComputeDiffStats extracts from one unified diff.
// (The TS lib's diffStats() shares its name with its result type; Go cannot,
// so the function takes the Compute prefix.)
type DiffStats struct {
	Files     int
	Additions int
	Deletions int
	NewFiles  int
}

// ChatMessage is one message for the provider layer.
type ChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

// Completion is the parsed model reply: subject line plus body.
type Completion struct {
	Subject string `json:"subject"`
	Body    string `json:"body"`
}

// ComputeDiffStats counts files / ±lines / new files from a unified diff;
// tolerant of non-diff input (mirrors diffStats() in the TS lib).
func ComputeDiffStats(diff string) DiffStats {
	if strings.TrimSpace(diff) == "" {
		return DiffStats{}
	}
	return DiffStats{
		Files:     len(diffFileRe.FindAllString(diff, -1)),
		Additions: len(addRe.FindAllString(diff, -1)),
		Deletions: len(delRe.FindAllString(diff, -1)),
		NewFiles:  len(newFileRe.FindAllString(diff, -1)),
	}
}

// BuildPromptMessages builds the [system, user] chat messages for the
// provider layer (mirrors buildPromptMessages() in the TS lib). A diff over
// MaxDiffChars is cut at the nearest UTF-8 boundary with an explicit marker.
func BuildPromptMessages(diff, commitType string) []ChatMessage {
	stats := ComputeDiffStats(diff)
	body := diff
	if len(diff) > MaxDiffChars {
		end := MaxDiffChars
		for end > 0 && !utf8.RuneStart(diff[end]) {
			end--
		}
		body = diff[:end] + "\n… (diff truncated)"
	}
	user := fmt.Sprintf(
		"Commit type: %s\nDiff summary: %d files changed, %d additions, %d deletions, %d new files.\n\n%s",
		commitType, stats.Files, stats.Additions, stats.Deletions, stats.NewFiles, body)
	return []ChatMessage{
		{Role: "system", Content: SystemPrompt},
		{Role: "user", Content: user},
	}
}

// ParseCompletion parses 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 {
	cleaned := strings.TrimSpace(fenceRe.ReplaceAllString(text, ""))
	for _, line := range strings.Split(cleaned, "\n") {
		subject := strings.TrimSpace(line)
		if !subjectRe.MatchString(subject) {
			continue
		}
		// strings.Index reproduces JS indexOf semantics (first occurrence).
		start := strings.Index(cleaned, subject) + len(subject)
		body := cleaned[start:]
		if loc := preambleRe.FindStringIndex(body); loc != nil {
			body = body[:loc[0]] + body[loc[1]:]
		}
		return &Completion{Subject: subject, Body: strings.TrimSpace(body)}
	}
	return 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 →