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

The project is deliberately sized so that every stage ships something you can run: the first phase produces a working command or endpoint, and each later phase adds one capability without forcing a rewrite of what came before. That property — always runnable, never half-migrated — is what makes the tutorial usable as a weekend build rather than a sketch that only works once the final commit lands.

The finished tool carries no hidden services and no hosted dependencies. Everything it needs lives in the repository and a machine with the stated runtime, so a reader can clone, install, run the tests, and trust that the behaviour they see locally is the behaviour the tutorial promised. Where a real deployment needs an external system, that seam is called out explicitly rather than smuggled in through a default.

It is written for a working developer who wants the whole shape of a real tool in one readable pass rather than a tour of a framework. Each phase states the decision it makes and why, then shows the code that encodes it, so the reader can stop after any phase with something that runs and resume later without relearning the whole design. The prose is deliberately honest about trade-offs: where a simpler approach would break at scale, that ceiling is named instead of hidden behind a benchmark.

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.

Set up the workspace before writing any logic. The table below pins every dependency to a version so the behaviour you observe matches the tutorial; floating versions are the most common reason a reader’s output diverges from the text. Install exactly what the table lists, then confirm the toolchain reports the expected version before continuing.

Two configuration choices deserve attention up front. First, the project keeps its runtime entry and its test entry as separate scripts so that running tests never starts a server or writes to a data directory. Second, all tunables are read from one place — a small config module or environment variables — so that nothing depends on the working directory a command happens to be launched from.

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.

The first hard decision is where the boundary between parsing and doing sits. Input arrives as raw text — argv, environment variables, a file on disk — and this phase converts it exactly once into a typed object that the rest of the program trusts. Confining that conversion to a single module means every later layer receives clean, already-validated input and never re-checks a string, which removes a whole class of bugs where two modules quietly disagree about what a flag or a field means. The second decision is failure visibility: invalid input must produce an actionable message and a non-zero exit rather than a stack trace surfacing from three layers down. Getting these two boundaries right early is what lets the remaining phases stay small.

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.

This phase defines the data model that every other module speaks. The choice of shape matters more than it looks: flat records are easy to serialize and diff, nested structures model relationships but complicate equality checks, and identifiers must be stable across edits so that references never silently rebind. The code here stays pure — functions take data and return data, with no clocks, no disk, and no printing — because pure functions are the only kind that can be tested exhaustively without a fixture harness. When the model is right the surrounding code almost writes itself; when it is wrong every later phase pays interest.

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.

The core operation is where the project delivers its value, and the temptation is to cram every option into one function. Resist it. The main path should read as a short, obvious sequence — load, transform, emit — with the branching behaviour factored into small decisions that can be tested on their own. This phase also fixes the error contract: which failures are fatal, which are recoverable, and how a partial result is reported. A tool that can explain what it did and why it stopped is far easier to trust in a pipeline than one that only signals success or silence.

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.

Integration is where the project stops being a toy. Input may arrive in a format an external system produced, output may need to match a contract another system consumes, and the two rarely line up without adjustment. This phase owns the adapters — the small translation functions between the outside world’s shape and the internal model — and it owns the boundary decisions about what to do when the two disagree: coerce, reject, or warn and continue. Keeping adapters thin and explicit means a change to an external format touches one file, and the internal model stays stable as the ecosystem around it moves.

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.

The user-facing surface determines whether the project feels finished. A command-line tool owes its caller predictable stdout, meaningful stderr, and honest exit codes; a service owes a stable request and response schema plus consistent status handling. This phase wires the internal modules to that surface and nothing else — it contains no business logic of its own, only translation between the outside contract and the internal calls. That separation is what lets the same core serve a CLI today and an HTTP endpoint tomorrow without duplication, and it is why the tests for this layer assert process-level behaviour rather than poking at internals.

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.

The final phase turns a working program into a dependable one. Tests are the visible part, but the discipline behind them is deeper: every claim the earlier phases made is pinned by an executable check, and every failure mode the tutorial mentioned has a test that reproduces it before the fix. Edge cases — empty input, malformed records, concurrent invocations, interrupted writes — are enumerated and asserted rather than assumed away. The payoff is a suite that fails loudly and precisely when someone changes a decision, which is exactly the signal a maintainer wants the moment they touch the code.

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.

Design trade-offs

Minimal dependencies over framework convenience. A framework would hand over plumbing for free, but it would also own the interesting decisions this project exists to teach. Keeping the dependency surface small means the lifecycle is visible end to end, the install is instant, and the tool runs anywhere the stated runtime does. The cost is owning the edge cases yourself — which is precisely why each of them gets a test.

Explicit contracts over clever conventions. Where a convention would infer behaviour from a filename or a folder, the project asks for a named export or a declared field instead. It reads as slightly more verbose and is far easier to review: a reader sees the intent on the line that owns it rather than reconstructing it from directory layout. Debugging also gets cheaper, because the failure points at the declaration instead of the convention that silently produced it.

Deterministic behaviour over convenience defaults. Anything that could vary between machines — time, ordering, encoding, locale — is injected or pinned rather than read from the ambient environment. That choice costs a little ceremony and buys reproducible output, which is the property that makes the output diffable in review and the tests trustworthy across the team’s machines.

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.

Tests are organised by layer so a failure points at the decision that broke. Pure unit tests cover the transformation logic without touching disk or network and run in milliseconds; integration tests exercise the real entry point against a temporary working directory and assert the observable contract; a small end-to-end tier proves the whole path produces the documented output. Keeping the fast tiers large and the slow tier thin is what lets the suite run on every save while still catching integration mistakes.

Every test asserts a specific promise from the phases above rather than merely covering lines. A passing suite therefore means the tool kept its word: filters compose, identifiers stay stable, failures exit non-zero with a readable message, and the output matches the format a downstream consumer expects. When someone changes a contract the matching test fails with an exact diff, turning a silent regression into a line in the pull request.

Running the suite in CI is the last line of defence, but the same command runs locally before every commit, which is what keeps the feedback loop short. A green run means the documented behaviour still holds; a red run names the exact promise that broke. Treat the suite as executable documentation and it stays current, because a stale assertion fails the moment the code and the text disagree.

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.

The structure leaves obvious seams for growth. Each capability that could be added — a new output format, an extra filter, an interactive mode — lands in one layer because the boundaries between parsing, logic, and presentation are already drawn. Extensions that would break the current design are equally visible: the moment a feature needs cross-process coordination or a database, the storage interface is where the change belongs, and its tests tell you immediately whether the surrounding code survives the swap.