Skip to content

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

<?php
/**
 * commit-message-generator — diff stats, prompt building, completion parsing.
 *
 * Language: PHP 7.4+ (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: PHP's preg_* functions run PCRE — the same engine
 * family as JavaScript's regex — so the canonical lib's patterns port almost
 * verbatim (/m and /i flags map one-to-one). The two traps: preg_replace
 * replaces ALL matches unless told otherwise (JS replace() without /g
 * replaces the first), and PHP strings are byte buffers, so the 8000-char
 * diff cap is measured with strlen() like the TS length check measures
 * UTF-16 units — identical for the ASCII diffs git produces.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** The commit types the island's picker offers (TS `CommitType`). */
const CMG_COMMIT_TYPES = ['feat', 'fix', 'docs', 'refactor', 'chore'];

/** Diffs larger than this are cut before they reach the model. */
const CMG_MAX_DIFF_CHARS = 8000;

const CMG_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.';

/** File / ±line / new-file counts extracted from one unified diff. */
final class CmgDiffStats
{
    public int $files = 0;
    public int $additions = 0;
    public int $deletions = 0;
    public int $newFiles = 0;
}

/** preg_match_all, normalised to int (PCRE errors count as "no matches"). */
function cmg_count_matches(string $pattern, string $subject): int
{
    return preg_match_all($pattern, $subject) ?: 0;
}

/** Count files / ±lines / new files from a unified diff; tolerant of
 * non-diff input. The /m flag gives JS's /gm line anchors; the [^+]/[^-]
 * guards skip the +++/--- file headers. */
function cmg_diff_stats(string $diff): CmgDiffStats
{
    $stats = new CmgDiffStats();
    if (trim($diff) === '') {
        return $stats;
    }
    $stats->files = cmg_count_matches('/^diff --git /m', $diff);
    $stats->additions = cmg_count_matches('/^\+[^+]/m', $diff);
    $stats->deletions = cmg_count_matches('/^-[^-]/m', $diff);
    $stats->newFiles = cmg_count_matches('/^new file mode /m', $diff);
    return $stats;
}

/** Build the [system, user] chat messages for the provider layer, each a
 * ['role' => …, 'content' => …] map. A diff over CMG_MAX_DIFF_CHARS is cut
 * with an explicit marker so a runaway `git diff` cannot blow the context. */
function cmg_build_prompt_messages(string $diff, string $type): array
{
    $stats = cmg_diff_stats($diff);
    $body = $diff;
    if (strlen($diff) > CMG_MAX_DIFF_CHARS) {
        $body = substr($diff, 0, CMG_MAX_DIFF_CHARS) . "\n… (diff truncated)";
    }
    return [
        ['role' => 'system', 'content' => CMG_SYSTEM_PROMPT],
        [
            'role' => 'user',
            'content' => "Commit type: {$type}\nDiff summary: {$stats->files} files changed, "
                . "{$stats->additions} additions, {$stats->deletions} deletions, "
                . "{$stats->newFiles} new files.\n\n{$body}",
        ],
    ];
}

/** Parse the model's reply into ['subject' => …, 'body' => …]; null when
 * unusable. Strips ``` fences, scans line by line for the first valid
 * conventional-commit subject; everything after it is the body, minus a bare
 * "here…:" / "sure…:" aside the model may have led with. */
function cmg_parse_completion(string $text): ?array
{
    $cleaned = trim((string) preg_replace('/```[a-z]*\n?/', '', $text));
    foreach (explode("\n", $cleaned) as $line) {
        $subject = trim($line);
        if (preg_match('/^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)(\([^)]+\))?!?: .+$/', $subject) !== 1) {
            continue;
        }
        $start = strpos($cleaned, $subject);
        if ($start === false) {
            return null;
        }
        $body = substr($cleaned, $start + strlen($subject));
        // limit = 1 mirrors JS replace() without the /g flag: first match only.
        $body = trim((string) preg_replace('/^\s*(here.*?:|sure.*?:)\s*$/im', '', $body, 1));
        return ['subject' => $subject, 'body' => $body];
    }
    return 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 →