Skip to content

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

"""commit-message-generator — diff stats, prompt building, completion parsing.

Language: Python 3 (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: everything the AI Studio island does besides the LLM
call itself — counting a diff, shaping the chat prompt, parsing the model's
reply — is pure string work, so it ports losslessly. The porting subtlety is
regex flags: the TS lib's `m` (per-line anchors) and `g` (find all) become
re.MULTILINE and findall() here, and JS's first-match-only replace() becomes
sub(count=1).

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import re
from dataclasses import dataclass
from typing import List, Optional, Tuple

COMMIT_TYPES: Tuple[str, ...] = ("feat", "fix", "docs", "refactor", "chore")

MAX_DIFF_CHARS = 8000

# One match per `diff --git a/… b/…` file header.
_DIFF_FILE_RE = re.compile(r"^diff --git ", re.MULTILINE)
# An added line: a `+` not followed by another `+` (skips the `+++` header).
_ADD_RE = re.compile(r"^\+[^+]", re.MULTILINE)
# A deleted line: a `-` not followed by another `-` (skips the `---` header).
_DEL_RE = re.compile(r"^-[^-]", re.MULTILINE)
# Git stamps brand-new files with a `new file mode` extended header.
_NEW_FILE_RE = re.compile(r"^new file mode ", re.MULTILINE)
# Subject-line contract the model must satisfy: `type(scope)!: subject`.
# Tested per trimmed line, so fullmatch() reproduces the TS `^…$` test.
_SUBJECT_RE = re.compile(
    r"^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)"
    r"(\([^)]+\))?!?: .+$"
)
_FENCE_RE = re.compile(r"```[a-z]*\n?")
_PREAMBLE_RE = re.compile(r"^\s*(here.*?:|sure.*?:)\s*$", re.IGNORECASE | re.MULTILINE)

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.'
)


@dataclass
class DiffStats:
    """File / ±line / new-file counts extracted from one unified diff."""

    files: int = 0
    additions: int = 0
    deletions: int = 0
    new_files: int = 0


def diff_stats(diff: str) -> DiffStats:
    """Count files / ±lines / new files from a unified diff; tolerant of
    non-diff input (anything not shaped like a diff counts as zero)."""
    if not diff.strip():
        return DiffStats()
    return DiffStats(
        files=len(_DIFF_FILE_RE.findall(diff)),
        additions=len(_ADD_RE.findall(diff)),
        deletions=len(_DEL_RE.findall(diff)),
        new_files=len(_NEW_FILE_RE.findall(diff)),
    )


def build_prompt_messages(diff: str, commit_type: str) -> List[Tuple[str, str]]:
    """Build the [system, user] chat messages for the provider layer.

    Returns [(role, content), ...]. A diff over MAX_DIFF_CHARS is cut with an
    explicit marker so a runaway `git diff` cannot blow the context window.
    """
    stats = diff_stats(diff)
    body = f"{diff[:MAX_DIFF_CHARS]}\n… (diff truncated)" if len(diff) > MAX_DIFF_CHARS else diff
    user = (
        f"Commit type: {commit_type}\n"
        f"Diff summary: {stats.files} files changed, {stats.additions} additions, "
        f"{stats.deletions} deletions, {stats.new_files} new files.\n\n{body}"
    )
    return [("system", SYSTEM_PROMPT), ("user", user)]


def parse_completion(text: str) -> Optional[Tuple[str, str]]:
    """Parse the model's reply into (subject, body); None 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.
    """
    cleaned = _FENCE_RE.sub("", text).strip()
    for line in cleaned.split("\n"):
        subject = line.strip()
        if _SUBJECT_RE.fullmatch(subject):
            start = cleaned.find(subject) + len(subject)
            body = _PREAMBLE_RE.sub("", cleaned[start:], count=1).strip()
            return subject, body
    return None

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 →