AI Commit Message Generator — C# 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 C# implementation — the same logic the interactive tool runs, in a shareable, citable form.
// commit-message-generator — diff stats, prompt building, completion parsing.
//
// Language: C# (netstandard2.0 surface, no LINQ beyond basics —
// System.Text.RegularExpressions is the regex engine, the same
// role the re module plays in this tool's 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: .NET strings are UTF-16 like JavaScript's, so
// Length/Substring/IndexOf track the TS port's length/slice/indexOf exactly,
// and RegexOptions.Multiline reproduces the /m anchors. One dialect trap:
// Regex.Replace is always global, so the preamble strip does an explicit
// Match + Remove to stay first-match-only like the TS replace.
//
// Build: csc csharp.cs && csharp.exe (or drop into any .NET console)
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace CosmoDev.Polyglot;
/// <summary>Commit-message-generator core — pure logic, no I/O.</summary>
public static class CommitMessageTool
{
/// <summary>The commit types the island's picker offers (TS `CommitType`).</summary>
public static readonly string[] CommitTypes = { "feat", "fix", "docs", "refactor", "chore" };
/// <summary>Diffs larger than this are cut before they reach the model.</summary>
public const int MaxDiffChars = 8000;
/// <summary>Provider-layer system message, verbatim from the TS lib.</summary>
public const string 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.";
/// <summary>One match per `diff --git a/… b/…` file header.</summary>
private static readonly Regex DiffFileRe = new(@"^diff --git ", RegexOptions.Multiline | RegexOptions.Compiled);
/// <summary>An added line: a `+` not followed by another `+` (skips the `+++` header).</summary>
private static readonly Regex AddRe = new(@"^\+[^+]", RegexOptions.Multiline | RegexOptions.Compiled);
/// <summary>A deleted line: a `-` not followed by another `-` (skips the `---` header).</summary>
private static readonly Regex DelRe = new(@"^-[^-]", RegexOptions.Multiline | RegexOptions.Compiled);
/// <summary>Git stamps brand-new files with a `new file mode` extended header.</summary>
private static readonly Regex NewFileRe = new(@"^new file mode ", RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Regex FenceRe = new(@"```[a-z]*\n?", RegexOptions.Compiled);
private static readonly Regex SubjectRe = new(@"^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)(\([^)]+\))?!?: .+$", RegexOptions.Compiled);
private static readonly Regex PreambleRe = new(@"^\s*(here.*?:|sure.*?:)\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>Counts extracted from one unified diff (TS `DiffStats`).</summary>
public sealed class DiffStats
{
public int Files, Additions, Deletions, NewFiles;
}
public sealed class ChatMessage
{
public ChatMessage(string role, string content) { Role = role; Content = content; }
public string Role { get; } public string Content { get; }
}
/// <summary>The parsed model reply: subject line plus body.</summary>
public sealed class Completion
{
public Completion(string subject, string body) { Subject = subject; Body = body; }
public string Subject { get; } public string Body { get; }
}
/// <summary>
/// Count files / ±lines / new files from a unified diff; tolerant of
/// non-diff input. (Mirrors diffStats() in the TS lib; the Compute prefix
/// is the go.go port's dodge for the TS lib reusing one name for both.)
/// </summary>
public static DiffStats ComputeDiffStats(string diff)
{
var stats = new DiffStats();
if (string.IsNullOrWhiteSpace(diff)) return stats;
stats.Files = DiffFileRe.Matches(diff).Count;
stats.Additions = AddRe.Matches(diff).Count;
stats.Deletions = DelRe.Matches(diff).Count;
stats.NewFiles = NewFileRe.Matches(diff).Count;
return stats;
}
/// <summary>
/// Build the [system, user] chat messages for the provider layer. A diff
/// over MaxDiffChars is cut with an explicit marker so a runaway
/// `git diff` can never blow the context window silently.
/// </summary>
public static IReadOnlyList<ChatMessage> BuildPromptMessages(string diff, string commitType)
{
DiffStats stats = ComputeDiffStats(diff);
string body = diff.Length > MaxDiffChars
? diff.Substring(0, MaxDiffChars) + "\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 new ChatMessage[]
{
new ChatMessage("system", SystemPrompt),
new ChatMessage("user", user),
};
}
/// <summary>
/// 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 Match keeps it first-match-only).
/// </summary>
public static Completion ParseCompletion(string text)
{
string cleaned = FenceRe.Replace(text, "").Trim();
foreach (string line in cleaned.Split('\n'))
{
string t = line.Trim();
if (!SubjectRe.IsMatch(t)) continue;
string body = cleaned.Substring(cleaned.IndexOf(t, StringComparison.Ordinal) + t.Length);
Match aside = PreambleRe.Match(body);
if (aside.Success) body = body.Remove(aside.Index, aside.Length);
return new Completion(t, body.Trim());
}
return null;
}
private static void Main()
{
var diff = "diff --git a/x b/x\nnew file mode 100644\n--- a/x\n+++ b/x\n+hello\n-world\n";
DiffStats stats = ComputeDiffStats(diff);
Console.WriteLine($"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```");
Console.WriteLine($"{done.Subject} | {done.Body}");
Console.WriteLine(ParseCompletion("no commit subject here") ?? (object)"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 →