Skip to content

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

# commit-message-generator — diff stats, prompt building, completion parsing.
#
# Language: Ruby (3.x, standard library only — Regexp is built into the
#           language, the same role the re module plays in 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: the tool's non-LLM core is pure string work, and
# Ruby's regexps translate the TS port almost literally — with two dialect
# traps: ^ is ALWAYS line-anchored in Ruby (no /m flag for the diff counters;
# Ruby's /m means dot-matches-newline), and `sub` (not `gsub`) keeps the
# preamble strip first-match-only like the TS port's non-global replace.

# frozen_string_literal: true

module CommitMessageGenerator
  COMMIT_TYPES = %w[feat fix docs refactor chore].freeze

  MAX_DIFF_CHARS = 8000

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

  # One match per `diff --git a/… b/…` file header (^ is line-anchored already).
  DIFF_FILE_RE = /^diff --git /
  # An added line: a `+` not followed by another `+` (skips the `+++` header).
  ADD_RE = /^\+[^+]/
  # A deleted line: a `-` not followed by another `-` (skips the `---` header).
  DEL_RE = /^-[^-]/
  # Git stamps brand-new files with a `new file mode` extended header.
  NEW_FILE_RE = /^new file mode /
  FENCE_RE = /```[a-z]*\n?/
  SUBJECT_RE = /\A(feat|fix|docs|style|refactor|perf|test|build|ci|chore|security|audit)(\([^)]+\))?!?: .+\z/
  PREAMBLE_RE = /^\s*(here.*?:|sure.*?:)\s*$/

  DiffStats = Struct.new(:files, :additions, :deletions, :new_files)
  Completion = Struct.new(:subject, :body)

  module_function

  # Count files / ±lines / new files from a unified diff; tolerant of
  # non-diff input (mirrors diffStats() in the TS lib).
  def diff_stats(diff)
    return DiffStats.new(0, 0, 0, 0) if diff.strip.empty?

    DiffStats.new(diff.scan(DIFF_FILE_RE).count, diff.scan(ADD_RE).count,
                  diff.scan(DEL_RE).count, diff.scan(NEW_FILE_RE).count)
  end

  # Build the [system, user] chat messages for the provider layer. A diff
  # over MAX_DIFF_CHARS is cut with an explicit marker so a runaway
  # `git diff` can never blow the context window silently (mirrors
  # buildPromptMessages() in the TS lib).
  def build_prompt_messages(diff, type:)
    stats = diff_stats(diff)
    body = diff.length > MAX_DIFF_CHARS ? diff[0, MAX_DIFF_CHARS] + "\n… (diff truncated)" : diff
    [
      { role: 'system', content: SYSTEM_PROMPT },
      { role: 'user', content: "Commit type: #{type}\nDiff summary: #{stats.files} files changed, " \
                               "#{stats.additions} additions, #{stats.deletions} deletions, " \
                               "#{stats.new_files} new files.\n\n#{body}" },
    ]
  end

  # Parse the model's reply into a Completion; nil 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.
  def parse_completion(text)
    cleaned = text.gsub(FENCE_RE, '').strip
    cleaned.split("\n", -1).each do |line|
      t = line.strip
      next unless t.match?(SUBJECT_RE)

      body = cleaned[cleaned.index(t) + t.length..]
      return Completion.new(t, body.sub(PREAMBLE_RE, '').strip)
    end
    nil
  end
end

if $PROGRAM_NAME == __FILE__
  include CommitMessageGenerator
  diff = "diff --git a/x b/x\nnew file mode 100644\n--- a/x\n+++ b/x\n+hello\n-world\n"
  p diff_stats(diff)
  p build_prompt_messages(diff, type: 'feat')[1][:content][0, 96]
  p parse_completion("```txt\nsure, here:\nfeat: add widget\n\nadds the widget\n```")
  p parse_completion('no commit subject here')
end

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 →