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 (C11, standard library only — C has no regex in its standard
* library, so the TS port's five regexes become small scanners)
* 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: the diff counters are plain prefix checks over
* newline-split lines, the ``` fence strip is a skipping copy, and the
* conventional-commit subject contract is a tiny hand-rolled matcher.
* Everything is byte-based like the go.go port, with the truncation cut
* pulled back to a UTF-8 boundary.
*
* Build: cc -std=c11 c.c && ./a.out
*/
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** Diffs larger than this are cut before they reach the model. */
#define MAX_DIFF_CHARS 8000
/** Provider-layer system message, verbatim from the TS lib. */
static const char *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.";
/** The commit types the island's picker offers (TS CommitType). */
static const char *const COMMIT_TYPES[] = {"feat", "fix", "docs", "refactor", "chore", NULL};
/** The TS regex's leading (feat|…|audit) alternation. */
static const char *const SUBJECT_TYPES[] = {
"feat", "fix", "docs", "style", "refactor", "perf",
"test", "build", "ci", "chore", "security", "audit",
};
/** Counts extracted from one unified diff (TS DiffStats). */
typedef struct {
long files, additions, deletions, new_files;
} DiffStats;
/** One message for the provider layer; the caller frees content. */
typedef struct {
const char *role;
char *content;
} ChatMessage;
/** The parsed model reply: subject line plus body; the caller frees both. */
typedef struct {
char *subject, *body;
} Completion;
/** The six whitespace characters JavaScript's \s recognizes. */
static bool is_space(char c)
{
return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
}
static char *xstrdup(const char *s) { return strcpy(malloc(strlen(s) + 1), s); }
static char *xstrndup(const char *s, size_t n)
{
char *out = malloc(n + 1);
memcpy(out, s, n);
out[n] = '\0';
return out;
}
/** JS trim() over the ASCII whitespace set. */
static char *trim_dup(const char *s)
{
while (*s && is_space(*s)) s++;
size_t n = strlen(s);
while (n > 0 && is_space(s[n - 1])) n--;
return xstrndup(s, n);
}
/** Case-insensitive prefix test ("Here:" still counts as an aside). */
static bool ci_prefix(const char *s, const char *prefix)
{
for (size_t i = 0; prefix[i]; i++) {
if (tolower((unsigned char)s[i]) != prefix[i]) return false;
}
return true;
}
/** JS: /^(feat|…|audit)(\([^)]+\))?!?: .+$/ — tested on a trimmed line. */
static bool is_subject(const char *t, size_t n)
{
for (size_t k = 0; k < sizeof SUBJECT_TYPES / sizeof *SUBJECT_TYPES; k++) {
const size_t tl = strlen(SUBJECT_TYPES[k]);
if (n < tl || memcmp(t, SUBJECT_TYPES[k], tl) != 0) continue;
size_t i = tl;
if (i < n && t[i] == '(') { /* optional (scope) */
size_t j = i + 1;
while (j < n && t[j] != ')') j++;
if (j == n || j == i + 1) continue; /* unclosed or empty scope */
i = j + 1;
}
if (i < n && t[i] == '!') i++; /* optional breaking mark */
if (i + 2 < n && t[i] == ':' && t[i + 1] == ' ') return true; /* .+ */
}
return false;
}
/** Count files / ±lines / new files from a unified diff; tolerant of
* non-diff input (mirrors diffStats() in the TS lib). */
static void diff_stats(const char *diff, DiffStats *stats)
{
memset(stats, 0, sizeof *stats);
bool blank = true;
for (const char *p = diff; *p; p++) {
if (!is_space(*p)) { blank = false; break; }
}
if (blank) return;
for (const char *line = diff; line;) {
const char *nl = strchr(line, '\n');
const size_t len = nl ? (size_t)(nl - line) : strlen(line);
if (len >= 11 && memcmp(line, "diff --git ", 11) == 0) stats->files++;
if (len >= 2 && line[0] == '+' && line[1] != '+') stats->additions++;
if (len >= 2 && line[0] == '-' && line[1] != '-') stats->deletions++;
if (len >= 14 && memcmp(line, "new file mode ", 14) == 0) stats->new_files++;
line = nl ? nl + 1 : NULL;
}
}
/** Does the JS regex ^\s*(here.*?:|sure.*?:)\s*$ match at line start p?
* Writes the match end (greedy \s* backtracked to just before a '\n' or
* the end of the body) into *end. */
static bool preamble_at(const char *body, size_t n, size_t p, size_t *end)
{
size_t q = p;
while (q < n && is_space(body[q])) q++; /* ^\s* */
size_t e = q;
while (e < n && body[e] != '\n') e++; /* end of the line */
size_t ce = e;
while (ce > q && is_space(body[ce - 1])) ce--; /* minus trailing \s */
if (ce - q < 5 || body[ce - 1] != ':') return false;
if (!ci_prefix(body + q, "here") && !ci_prefix(body + q, "sure")) return false;
size_t w = ce;
while (w < n && is_space(body[w])) w++;
if (w == n) { *end = n; return true; }
size_t k = w; /* $ = just before a */
while (k > ce && body[k] != '\n') k--; /* '\n' or string end */
if (k == ce && body[ce] != '\n') return false;
*end = k;
return true;
}
/** JS: body.replace(/^\s*(here.*?:|sure.*?:)\s*$/im, "") — first match
* only, spliced out of the buffer in place. */
static void strip_preamble(char *body)
{
const size_t n = strlen(body);
size_t p = 0;
while (p < n) {
size_t end = n;
if ((p == 0 || body[p - 1] == '\n') && preamble_at(body, n, p, &end)) {
memmove(body + p, body + end, n - end);
body[n - (end - p)] = '\0';
return;
}
const char *nl = strchr(body + p, '\n');
if (!nl) break;
p = (size_t)(nl - body) + 1;
}
}
/** JS: text.replace(/```[a-z]*\n?/g, "") — a skipping copy that drops each
* ``` run, any lowercase info string after it, and one following newline. */
static char *strip_fences(const char *s)
{
const size_t n = strlen(s);
char *out = malloc(n + 1);
size_t o = 0, i = 0;
while (i < n) {
if (i + 2 < n && s[i] == '`' && s[i + 1] == '`' && s[i + 2] == '`') {
i += 3;
while (i < n && s[i] >= 'a' && s[i] <= 'z') i++;
if (i < n && s[i] == '\n') i++;
} else {
out[o++] = s[i++];
}
}
out[o] = '\0';
return out;
}
/** Build the [system, user] chat messages for the provider layer (mirrors
* buildPromptMessages() in the TS lib). A diff over MAX_DIFF_CHARS is cut
* at a UTF-8 boundary with an explicit marker. */
static void build_prompt_messages(const char *diff, const char *commit_type, ChatMessage out[2])
{
DiffStats stats;
diff_stats(diff, &stats);
const size_t n = strlen(diff);
char *body;
if (n > MAX_DIFF_CHARS) {
size_t end = MAX_DIFF_CHARS;
while (end > 0 && ((unsigned char)diff[end] & 0xC0) == 0x80) end--;
body = malloc(end + 32);
memcpy(body, diff, end);
strcpy(body + end, "\n… (diff truncated)");
} else {
body = xstrdup(diff);
}
char *user = malloc(strlen(commit_type) + n + 160);
sprintf(user,
"Commit type: %s\nDiff summary: %ld files changed, %ld additions, "
"%ld deletions, %ld new files.\n\n%s",
commit_type, stats.files, stats.additions, stats.deletions, stats.new_files, body);
free(body);
out[0].role = "system";
out[0].content = xstrdup(SYSTEM_PROMPT);
out[1].role = "user";
out[1].content = 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. */
static Completion *parse_completion(const char *text)
{
char *cleaned = strip_fences(text);
char *t_all = trim_dup(cleaned);
Completion *result = NULL;
for (const char *cur = t_all; *cur;) {
const char *nl = strchr(cur, '\n');
const char *le = nl ? nl : cur + strlen(cur);
const char *ls = cur;
while (ls < le && is_space(*ls)) ls++;
while (le > ls && is_space(le[-1])) le--;
const size_t tlen = (size_t)(le - ls);
if (tlen > 0 && is_subject(ls, tlen)) {
const char *at = strstr(cleaned, xstrndup(ls, tlen)); /* JS indexOf */
if (at) {
char *body = xstrdup(at + tlen);
strip_preamble(body);
result = malloc(sizeof *result);
result->subject = xstrndup(ls, tlen);
result->body = trim_dup(body);
free(body);
}
break;
}
if (!nl) break;
cur = nl + 1;
}
free(t_all);
free(cleaned);
return result;
}
/* -------------------------------------------------------------------------
* Demo
* ------------------------------------------------------------------------- */
int main(void)
{
DiffStats stats;
diff_stats("diff --git a/x b/x\nnew file mode 100644\n--- a/x\n+++ b/x\n+hello\n-world\n",
&stats);
printf("stats: %ld files, +%ld -%ld, %ld new\n", stats.files, stats.additions,
stats.deletions, stats.new_files);
ChatMessage msgs[2];
build_prompt_messages("tiny diff", "feat", msgs);
printf("user: %.40s\n", msgs[1].content);
free(msgs[0].content);
free(msgs[1].content);
Completion *done =
parse_completion("```txt\nsure, here:\nfeat: add widget\n\nadds the widget\n```");
if (done) printf("parsed: %s | %s\n", done->subject, done->body);
free(done->subject);
free(done->body);
free(done);
printf("%s\n", parse_completion("no commit subject here") ? "parsed" : "null");
return 0;
}
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 →