Skip to content

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++ (C++17, standard library only — std::regex speaks the
//           ECMAScript grammar, the same dialect as the TS port's RegExp)
// 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: because std::regex defaults to ECMAScript syntax,
// the five TS regexes carry over character for character — /m becomes the
// std::regex_constants::multiline flag (new in C++17). One dialect trap:
// std::regex_replace is always global, so the preamble strip uses
// regex_search + prefix/suffix splice to stay first-match-only.
//
// Build: c++ -std=c++17 cpp.cpp && ./a.out

#include <cstdio>
#include <optional>
#include <regex>
#include <string>
#include <vector>

namespace {

constexpr size_t kMaxDiffChars = 8000;

const char* kSystemPrompt =
    "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.";

const char* kCommitTypes[] = {"feat", "fix", "docs", "refactor", "chore"};

/** One match per `diff --git a/… b/…` file header. */
const std::regex kDiffFileRe("^diff --git ", std::regex_constants::multiline);
/** An added line: a `+` not followed by another `+` (skips the `+++` header). */
const std::regex kAddRe("^\\+[^+]", std::regex_constants::multiline);
/** A deleted line: a `-` not followed by another `-` (skips the `---` header). */
const std::regex kDelRe("^-[^-]", std::regex_constants::multiline);
/** Git stamps brand-new files with a `new file mode` extended header. */
const std::regex kNewFileRe("^new file mode ", std::regex_constants::multiline);
const std::regex kFenceRe("```[a-z]*\n?");
const std::regex kSubjectRe(
    "^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)(\\([^)]+\\))?!?: .+$");
const std::regex kPreambleRe("^\\s*(here.*?:|sure.*?:)\\s*$",
                             std::regex_constants::multiline | std::regex_constants::icase);

/** Counts extracted from one unified diff (TS `DiffStats`). */
struct DiffStats {
    size_t files = 0, additions = 0, deletions = 0, new_files = 0;
};

/** One message for the provider layer. */
struct ChatMessage {
    std::string role, content;
};

/** The parsed model reply: subject line plus body. */
struct Completion {
    std::string subject, body;
};

/** The six whitespace characters JS \s and C isspace share. */
bool is_space(char c) {
    return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
}

std::string trim_copy(const std::string& s) {
    size_t b = 0, e = s.size();
    while (b < e && is_space(s[b])) ++b;
    while (e > b && is_space(s[e - 1])) --e;
    return s.substr(b, e - b);
}

size_t count_matches(const std::string& s, const std::regex& re) {
    static const std::sregex_iterator kEnd;
    size_t n = 0;
    for (std::sregex_iterator it(s.begin(), s.end(), re); it != kEnd; ++it) ++n;
    return n;
}

}  // namespace

/**
 * Count files / ±lines / new files from a unified diff; tolerant of
 * non-diff input (mirrors diffStats() in the TS lib).
 */
DiffStats diff_stats(const std::string& diff) {
    DiffStats stats;
    bool blank = true;
    for (char c : diff) {
        if (!is_space(c)) { blank = false; break; }
    }
    if (blank) return stats;
    stats.files = count_matches(diff, kDiffFileRe);
    stats.additions = count_matches(diff, kAddRe);
    stats.deletions = count_matches(diff, kDelRe);
    stats.new_files = count_matches(diff, kNewFileRe);
    return stats;
}

/**
 * Build the [system, user] chat messages for the provider layer. A diff
 * over kMaxDiffChars is cut (at a UTF-8 boundary, like the go.go port)
 * with an explicit marker so a runaway `git diff` can never blow the
 * context window silently (mirrors buildPromptMessages() in the TS lib).
 */
std::vector<ChatMessage> build_prompt_messages(const std::string& diff,
                                               const std::string& commit_type) {
    const DiffStats stats = diff_stats(diff);
    std::string body = diff;
    if (diff.size() > kMaxDiffChars) {
        size_t end = kMaxDiffChars;
        while (end > 0 && (static_cast<unsigned char>(diff[end]) & 0xC0) == 0x80) end--;
        body = diff.substr(0, end) + "\n… (diff truncated)";
    }
    std::string user =
        "Commit type: " + commit_type + "\nDiff summary: " + std::to_string(stats.files) +
        " files changed, " + std::to_string(stats.additions) + " additions, " +
        std::to_string(stats.deletions) + " deletions, " + std::to_string(stats.new_files) +
        " new files.\n\n" + body;
    return {{"system", kSystemPrompt}, {"user", user}};
}

/**
 * Parse the model's reply into a Completion; nullopt 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.
 */
std::optional<Completion> parse_completion(const std::string& text) {
    const std::string cleaned = trim_copy(std::regex_replace(text, kFenceRe, ""));
    size_t pos = 0;
    while (pos <= cleaned.size()) {
        const size_t nl = cleaned.find('\n', pos);
        const size_t len = (nl == std::string::npos) ? cleaned.size() - pos : nl - pos;
        const std::string t = trim_copy(cleaned.substr(pos, len));
        if (!t.empty() && std::regex_match(t, kSubjectRe)) {
            // JS indexOf semantics: first occurrence of the trimmed subject.
            std::string body = cleaned.substr(cleaned.find(t) + t.size());
            std::smatch aside;
            if (std::regex_search(body, aside, kPreambleRe)) {
                body = aside.prefix().str() + aside.suffix().str();  // first match only
            }
            return Completion{t, trim_copy(body)};
        }
        if (nl == std::string::npos) break;
        pos = nl + 1;
    }
    return std::nullopt;
}

/* -------------------------------------------------------------------------
 * Demo
 * ------------------------------------------------------------------------- */

int main() {
    const std::string diff =
        "diff --git a/x b/x\nnew file mode 100644\n--- a/x\n+++ b/x\n+hello\n-world\n";
    const DiffStats stats = diff_stats(diff);
    std::printf("stats: %zu files, +%zu -%zu, %zu new\n", stats.files, stats.additions,
                stats.deletions, stats.new_files);

    const std::optional<Completion> done =
        parse_completion("```txt\nsure, here:\nfeat: add widget\n\nadds the widget\n```");
    if (done) {
        std::printf("%s | %s\n", done->subject.c_str(), done->body.c_str());
    }
    std::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 →