← Complete Projects

阅读中文版本

Build a Changelog Generator from Commit Messages

A CLI that reads conventional commit messages, groups them into features, fixes, and chores, and writes a Markdown changelog section for a version, from a git log or a file.

beginner~4 hnodejsgitchangelogcli

Project goal

Build a generator that parses conventional commit messages, groups them by type, links issue references, and writes a dated Markdown changelog section with sections for each commit type.

Final features

  • Parse conventional commit headers into type, scope, and description.
  • Group commits into features, fixes, and other change types.
  • Link issue references and skip merge and release commits.
  • Include breaking changes in a dedicated section.
  • Write a Markdown changelog section for a given version and date.

Architecture

A parser turns a commit subject into a structured change; a classifier groups changes by type and flags breaking ones; a renderer emits Markdown grouped by section; and the CLI reads from git log or a file. Parsing and rendering are pure so the whole pipeline tests without a repository.

Prerequisites

  • Node.js 20 LTS or later
  • Familiarity with conventional commit format
  • Basic Markdown authoring

Dependencies

  • node >=20 — child_process to read git log and the CLI entry point
  • vitest ^2.1.0 — Parser and renderer tests over fixtures

Directory structure

changelog/
├── src/
│   ├── parse.js
│   ├── classify.js
│   ├── render.js
│   └── cli.js
├── test/
│   ├── parse.test.js
│   └── render.test.js
└── package.json

Phases

1. Commit subject parser

Parse a conventional commit header into type, scope, description, and a breaking flag.

Files: src/parse.js

const HEADER = /^(?<type>\w+)(?:\((?<scope>[^)]+)\))?(?<breaking>!)?:\s*(?<description>.+)$/;

export function parseCommit(subject, body = '') {
  const match = HEADER.exec(subject.trim());
  if (!match) {
    return { type: 'other', scope: null, description: subject.trim(), breaking: false, refs: [] };
  }
  const { type, scope, breaking, description } = match.groups;
  return {
    type: type.toLowerCase(),
    scope: scope ?? null,
    description: description.trim(),
    breaking: Boolean(breaking) || /BREAKING CHANGE:/.test(body),
    refs: [...description.matchAll(/#(\d+)/g)].map((m) => Number(m[1])),
  };
}

Expected behavior: A scoped fix parses with its scope, a subject ending in ! is breaking, and a non-conventional subject becomes an other entry.

2. Classifier

Map commit types to changelog sections and collect breaking changes separately.

Files: src/classify.js

const SECTIONS = {
  feat: 'Features',
  fix: 'Fixes',
  perf: 'Performance',
  docs: 'Documentation',
  refactor: 'Refactors',
  test: 'Tests',
  chore: 'Chores',
  other: 'Other',
};

export function classify(commits) {
  const grouped = new Map();
  const breaking = [];
  for (const commit of commits) {
    if (/^chore\(release\)|^Merge /.test(commit.subject ?? '')) continue;
    if (commit.breaking) breaking.push(commit);
    const section = SECTIONS[commit.type] ?? 'Other';
    if (!grouped.has(section)) grouped.set(section, []);
    grouped.get(section).push(commit);
  }
  return { grouped, breaking };
}

export const SECTION_ORDER = ['Features', 'Fixes', 'Performance', 'Refactors', 'Documentation', 'Tests', 'Chores', 'Other'];

Expected behavior: Features and fixes land in their sections, a chore(release) subject is skipped, and breaking changes are collected in their own list.

3. Markdown renderer

Render the grouped changes as a Markdown section with a heading and per-type subheadings.

Files: src/render.js

import { SECTION_ORDER } from './classify.js';

export function renderSection(version, date, { grouped, breaking }) {
  const lines = ['## ' + version + ' - ' + date, ''];
  if (breaking.length) {
    lines.push('### Breaking changes', '');
    for (const b of breaking) lines.push('- ' + formatEntry(b));
    lines.push('');
  }
  for (const section of SECTION_ORDER) {
    const items = grouped.get(section);
    if (!items?.length) continue;
    lines.push('### ' + section, '');
    for (const item of items.sort((a, b) => a.description.localeCompare(b.description))) lines.push('- ' + formatEntry(item));
    lines.push('');
  }
  return lines.join('\n').trimEnd() + '\n';
}

function formatEntry(commit) {
  const scope = commit.scope ? '**' + commit.scope + ':** ' : '';
  return scope + commit.description;
}

Expected behavior: The rendered section lists breaking changes first, then sections in a fixed order, and entries are sorted within each section.

4. Git log reading

Read commit subjects and bodies from git with a parseable separator, or from a file for testing.

Files: src/git.js

import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { readFile } from 'node:fs/promises';

const run = promisify(execFile);

export async function readCommits({ from, file, cwd = process.cwd() } = {}) {
  if (file) {
    const text = await readFile(file, 'utf8');
    return parseBlocks(text);
  }
  const args = ['log', '--pretty=format:__C__%s%x1f%b%x1e'];
  if (from) args.push(from + '..HEAD');
  const { stdout } = await run('git', args, { cwd, maxBuffer: 16 * 1024 * 1024 });
  return parseBlocks(stdout);
}

function parseBlocks(text) {
  return text.split('__C__').filter(Boolean).map((block) => {
    const [subject, body = ''] = block.replace(/\x1e$/, '').split('\x1f');
    return { subject: subject.trim(), body };
  });
}

Expected behavior: Reading from a fixture file returns the same commit list as reading from git, and a range argument limits the set.

5. CLI

Parse commits, classify them, render a Markdown section, and print it or write it to a file.

Files: src/cli.js

import { readCommits } from './git.js';
import { parseCommit } from './parse.js';
import { classify } from './classify.js';
import { renderSection } from './render.js';

const args = parse(process.argv.slice(2));
if (!args.version) { console.error('usage: changelog --version 1.2.0 [--from v1.1.0] [--file commits.txt]'); process.exit(1); }
const raw = await readCommits({ from: args.from, file: args.file });
const commits = raw.map((c) => ({ ...parseCommit(c.subject, c.body), subject: c.subject }));
const section = renderSection(args.version, args.date ?? new Date().toISOString().slice(0, 10), classify(commits));
console.log(section);

Expected behavior: Running with a version prints a Markdown section, and committing a feat and a fix produces both a Features and a Fixes subheading.

6. Tests and hardening

Cover parsing, classification, and rendering, and add an end-to-end run over a fixture.

Files: test/render.test.js

import { parseCommit } from '../src/parse.js';
import { classify } from '../src/classify.js';
import { renderSection } from '../src/render.js';

function build(subjects) {
  return classify(subjects.map((s) => ({ ...parseCommit(s), subject: s })));
}

test('features and fixes render in order with scopes', () => {
  const md = renderSection('1.0.0', '2026-10-22', build([
    'feat(api): add pagination',
    'fix(cli): handle missing arg',
  ]));
  expect(md.indexOf('### Features')).toBeLessThan(md.indexOf('### Fixes'));
  expect(md).toContain('**api:** add pagination');
});

Expected behavior: The render suite passes, breaking changes appear before all other sections, and a commit without a type still appears under Other.

Testing

Run npx vitest. Parser tests cover a plain feat, a scoped fix, a breaking change marked by !, a breaking change noted in the body, and a non-conventional subject. Renderer tests assert section ordering and the presence of issue links, and a CLI test reads a fixture and produces a Markdown block.

Troubleshooting

Release or merge commits pollute the changelog

Skip subjects matching chore(release) or Merge during classification; release tooling should not appear as user-facing changes.

A breaking change is missed entirely

Check both the ! marker in the header and a BREAKING CHANGE footer in the body; the two signalling styles are both valid, and missing either hides a compatibility break.

Issue links render as plain numbers

Resolve references to full URLs using a repository base URL rather than emitting a bare number; a changelog is most useful when issues are one click away.

Deployment

Run in a release workflow to draft the changelog section, then let a human edit before publishing. Because it reads git or a file, it works the same in CI and on a developer machine.

Known limitations

  • It relies on the team following the conventional commit format; free-form history yields mostly Other entries.
  • Issue links use plain references unless a base URL is configured.

Project overview

A changelog is only as good as the discipline behind it, and conventional commits provide that discipline cheaply. This tool turns a stream of commit subjects into a grouped, human-readable section.

The parser handles the conventional commit header, the classifier maps types to sections and detects breaking changes, and the renderer produces Markdown you can paste into a release note.

Parsing a header into type, scope, and description is one regular expression with explicit optional parts:

const HEADER = /^(?<type>\w+)(?:\((?<scope>[^)]+)\))?(?<breaking>!)?:\s*(?<description>.+)$/;

export function parseCommit(subject, body = '') {
  const match = HEADER.exec(subject.trim());
  if (!match) return { type: 'other', scope: null, description: subject.trim(), breaking: false };
  const { type, scope, breaking, description } = match.groups;
  return {
    type: type.toLowerCase(),
    scope: scope ?? null,
    description: description.trim(),
    breaking: Boolean(breaking) || /BREAKING CHANGE:/.test(body),
  };
}

A non-conventional subject becomes an other entry rather than an error, so the changelog never drops a commit just because it did not follow the format.

Setup

Zero runtime dependencies; git is read through a child process and everything else is pure JavaScript.

Dependency Version Why it is here
node >=20 child_process to read git log and the CLI entry point
vitest ^2.1.0 Parser and renderer tests over fixtures

Create the project and install:

mkdir changelog && cd changelog
npm init -y
npm install -D vitest@^2.1.0

Configure the CLI and tests in package.json:

{
  "name": "changelog",
  "type": "module",
  "scripts": {
    "changelog": "node src/cli.js",
    "test": "vitest run"
  }
}

Commit a fixture file of commit subjects so parser and renderer tests run without reading the real repository.

Phase 1: Commit subject parser

Parse a conventional commit header into type, scope, description, and a breaking flag. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

const HEADER = /^(?<type>\w+)(?:\((?<scope>[^)]+)\))?(?<breaking>!)?:\s*(?<description>.+)$/;

export function parseCommit(subject, body = '') {
  const match = HEADER.exec(subject.trim());
  if (!match) {
    return { type: 'other', scope: null, description: subject.trim(), breaking: false, refs: [] };
  }
  const { type, scope, breaking, description } = match.groups;
  return {
    type: type.toLowerCase(),
    scope: scope ?? null,
    description: description.trim(),
    breaking: Boolean(breaking) || /BREAKING CHANGE:/.test(body),
    refs: [...description.matchAll(/#(\d+)/g)].map((m) => Number(m[1])),
  };
}

Acceptance for this phase: A scoped fix parses with its scope, a subject ending in ! is breaking, and a non-conventional subject becomes an other entry.

Phase 2: Classifier

Map commit types to changelog sections and collect breaking changes separately. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

const SECTIONS = {
  feat: 'Features',
  fix: 'Fixes',
  perf: 'Performance',
  docs: 'Documentation',
  refactor: 'Refactors',
  test: 'Tests',
  chore: 'Chores',
  other: 'Other',
};

export function classify(commits) {
  const grouped = new Map();
  const breaking = [];
  for (const commit of commits) {
    if (/^chore\(release\)|^Merge /.test(commit.subject ?? '')) continue;
    if (commit.breaking) breaking.push(commit);
    const section = SECTIONS[commit.type] ?? 'Other';
    if (!grouped.has(section)) grouped.set(section, []);
    grouped.get(section).push(commit);
  }
  return { grouped, breaking };
}

export const SECTION_ORDER = ['Features', 'Fixes', 'Performance', 'Refactors', 'Documentation', 'Tests', 'Chores', 'Other'];

Acceptance for this phase: Features and fixes land in their sections, a chore(release) subject is skipped, and breaking changes are collected in their own list.

Phase 3: Markdown renderer

Render the grouped changes as a Markdown section with a heading and per-type subheadings. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

import { SECTION_ORDER } from './classify.js';

export function renderSection(version, date, { grouped, breaking }) {
  const lines = ['## ' + version + ' - ' + date, ''];
  if (breaking.length) {
    lines.push('### Breaking changes', '');
    for (const b of breaking) lines.push('- ' + formatEntry(b));
    lines.push('');
  }
  for (const section of SECTION_ORDER) {
    const items = grouped.get(section);
    if (!items?.length) continue;
    lines.push('### ' + section, '');
    for (const item of items.sort((a, b) => a.description.localeCompare(b.description))) lines.push('- ' + formatEntry(item));
    lines.push('');
  }
  return lines.join('\n').trimEnd() + '\n';
}

function formatEntry(commit) {
  const scope = commit.scope ? '**' + commit.scope + ':** ' : '';
  return scope + commit.description;
}

Acceptance for this phase: The rendered section lists breaking changes first, then sections in a fixed order, and entries are sorted within each section.

Phase 4: Git log reading

Read commit subjects and bodies from git with a parseable separator, or from a file for testing. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { readFile } from 'node:fs/promises';

const run = promisify(execFile);

export async function readCommits({ from, file, cwd = process.cwd() } = {}) {
  if (file) {
    const text = await readFile(file, 'utf8');
    return parseBlocks(text);
  }
  const args = ['log', '--pretty=format:__C__%s%x1f%b%x1e'];
  if (from) args.push(from + '..HEAD');
  const { stdout } = await run('git', args, { cwd, maxBuffer: 16 * 1024 * 1024 });
  return parseBlocks(stdout);
}

function parseBlocks(text) {
  return text.split('__C__').filter(Boolean).map((block) => {
    const [subject, body = ''] = block.replace(/\x1e$/, '').split('\x1f');
    return { subject: subject.trim(), body };
  });
}

Acceptance for this phase: Reading from a fixture file returns the same commit list as reading from git, and a range argument limits the set.

Phase 5: CLI

Parse commits, classify them, render a Markdown section, and print it or write it to a file. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

import { readCommits } from './git.js';
import { parseCommit } from './parse.js';
import { classify } from './classify.js';
import { renderSection } from './render.js';

const args = parse(process.argv.slice(2));
if (!args.version) { console.error('usage: changelog --version 1.2.0 [--from v1.1.0] [--file commits.txt]'); process.exit(1); }
const raw = await readCommits({ from: args.from, file: args.file });
const commits = raw.map((c) => ({ ...parseCommit(c.subject, c.body), subject: c.subject }));
const section = renderSection(args.version, args.date ?? new Date().toISOString().slice(0, 10), classify(commits));
console.log(section);

Acceptance for this phase: Running with a version prints a Markdown section, and committing a feat and a fix produces both a Features and a Fixes subheading.

Phase 6: Tests and hardening

Cover parsing, classification, and rendering, and add an end-to-end run over a fixture. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

import { parseCommit } from '../src/parse.js';
import { classify } from '../src/classify.js';
import { renderSection } from '../src/render.js';

function build(subjects) {
  return classify(subjects.map((s) => ({ ...parseCommit(s), subject: s })));
}

test('features and fixes render in order with scopes', () => {
  const md = renderSection('1.0.0', '2026-10-22', build([
    'feat(api): add pagination',
    'fix(cli): handle missing arg',
  ]));
  expect(md.indexOf('### Features')).toBeLessThan(md.indexOf('### Fixes'));
  expect(md).toContain('**api:** add pagination');
});

Acceptance for this phase: The render suite passes, breaking changes appear before all other sections, and a commit without a type still appears under Other.

Testing strategy

Run npx vitest. Parser tests cover a plain feat, a scoped fix, a breaking change marked by !, a breaking change noted in the body, and a non-conventional subject. Renderer tests assert section ordering and the presence of issue links, and a CLI test reads a fixture and produces a Markdown block.

The breaking-change test is the one that matters most for release safety: a missed breaking change is the failure mode a changelog exists to prevent.

Extending the project

Reading from a range, filtering by scope, and emitting release notes in another format are additions around the pure parser and renderer. A config file can map custom types to sections without code changes.