Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
<!--
Title: (<type>) <Sentence-case summary>, for example "(feat) Add the Warp tool for closing gaps".
Types: feat (new feature, minor version), fix (bug fix), perf (performance), docs (documentation),
refactor, test, build, ci, chore. Every type except feat is a patch version. Add ! after the
type, as in "(feat!)", for a breaking change and a major version.
-->

## Summary

-
Expand All @@ -9,4 +16,4 @@
## Release notes

- [ ] Added a release to `src/docs/changelog.ts` describing what changed for users
- [ ] Bumped the version with `npm version minor --no-git-tag-version` (features) or `patch` (fixes), matching the new release
- [ ] Bumped the version to match the title type with `npm version <minor|patch> --no-git-tag-version`
17 changes: 0 additions & 17 deletions .github/workflows/changelog.yml

This file was deleted.

32 changes: 32 additions & 0 deletions .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Pull request

on:
pull_request:
branches: [main]
types: [opened, edited, reopened, synchronize]

jobs:
format:
name: Title and description
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: node scripts/check-pull-request.mjs

changelog:
name: Changelog and version
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 22
- run: node scripts/check-changelog.mjs "origin/$BASE_REF"
env:
BASE_REF: ${{ github.base_ref }}
PR_TITLE: ${{ github.event.pull_request.title }}
63 changes: 63 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Contributing

Pull requests to `main` must pass the **Pull request** checks. They verify the title,
the description, and the release notes.

## Title

Start the title with a type in parentheses, then a space and a sentence-case summary
with no period:

```text
(feat) Add the Warp tool for closing gaps in scanned parts
(fix) Keep Drive connected after a reload
```

| Type | Use for | Version |
| ---------- | ----------------------------------- | ------- |
| `feat` | A new feature | minor |
| `fix` | A bug fix | patch |
| `perf` | A performance improvement | patch |
| `docs` | Documentation only | patch |
| `refactor` | Code changes with the same behavior | patch |
| `test` | Tests only | patch |
| `build` | Build, dependencies, or tooling | patch |
| `ci` | Continuous integration | patch |
| `chore` | Other maintenance | patch |

Add `!` after the type, as in `(feat!)`, for a breaking change; that is a major
version.

## Description

Use the [pull request template](.github/pull_request_template.md). The description
starts with these sections, in this order:

1. `## Summary`: bullets describing what changed and why.
2. `## Testing`: what you ran and what passed, plus anything not tested.
3. `## Release notes`: the template's checklist, with every item checked.

You can add other sections, such as a review log, after the summary.

## Release notes and version

Every pull request adds a release to the documentation's What's new page:

1. Bump the version to match the title type, for example
`npm version minor --no-git-tag-version` for `feat`. This updates `package.json`
and `package-lock.json`.
2. Add a release with the same version at the top of `src/docs/changelog.ts`,
describing what changed for people using Kitbasher.

The check compares against `main`: a `feat` pull request on 1.18.0 must be 1.19.0,
and a `fix` must be 1.18.1. If another pull request merges first, merge `main` and
bump again. See [maintaining the documentation](docs/documentation.md#whats-new)
for the release fields.

## Check locally

```sh
npm test
PR_TITLE="(feat) Add pins" PR_BODY_FILE=body.md node scripts/check-pull-request.mjs
PR_TITLE="(feat) Add pins" node scripts/check-changelog.mjs origin/main
```
11 changes: 5 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -951,12 +951,11 @@ See [design specification](docs/design.md) and [verification notes](docs/verific

## Contributing

Every pull request must add a release to the documentation's **What's new** page.
Bump the version with `npm version minor --no-git-tag-version` for features or
`patch` for fixes, then add a release with the same version at the top of
`src/docs/changelog.ts` describing what changed for users. The Changelog check on
pull requests fails until both are done. See
[maintaining the documentation](docs/documentation.md#whats-new).
Pull request titles start with a type in parentheses, such as `(feat)` or `(fix)`,
descriptions follow the template's Summary, Testing, and Release notes sections, and
every pull request adds a release to the documentation's **What's new** page with a
matching version bump. Checks on pull requests enforce all three. See
[CONTRIBUTING.md](CONTRIBUTING.md).

## License

Expand Down
22 changes: 9 additions & 13 deletions docs/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,17 @@ client-side navigation enhancement.
workbench header's What's new button shows the three newest releases and marks
one the visitor hasn't opened yet.

Every pull request adds one release at the top of the list:

1. Run `npm version minor --no-git-tag-version` for a new feature, or `patch` for
a fix or small improvement. This updates `package.json` and `package-lock.json`.
2. Add a release with the same `version`, today's `date`, a short `title`, and one
entry per user-visible change. Mark each `new`, `improved`, or `fixed`, and set
`guide` to an article ID to link to it.
Every pull request adds one release at the top of the list, with the version
bump its title type calls for (see [CONTRIBUTING.md](../CONTRIBUTING.md)). Give the
release the same `version` as `package.json`, today's `date`, a short `title`, and
one entry per user-visible change. Mark each `new`, `improved`, or `fixed`, and set
`guide` to an article ID to link to it.

Write for people using Kitbasher, not for reviewers: what they can now do, or what
works differently. The Changelog workflow runs `scripts/check-changelog.mjs`, which
fails a pull request that leaves the changelog untouched, does not raise the
version above `main`, or lets `package.json`, `package-lock.json`, and the newest
release disagree. `tests/unit/changelog.test.ts` checks ordering, dates, and guide
links. If two open pull requests take the same version, the one merged second must
move to the next version.
works differently. `scripts/check-changelog.mjs` fails a pull request that leaves the
changelog untouched, sets a version other than the one its title type calls for, or
lets `package.json`, `package-lock.json`, and the newest release disagree.
`tests/unit/changelog.test.ts` checks ordering, dates, and guide links.

## Images

Expand Down
28 changes: 17 additions & 11 deletions scripts/check-changelog.mjs
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { bumpVersion, expectedBump, isNewer, parseTitle } from './pull-request-rules.mjs';

const changelogPath = 'src/docs/changelog.ts';
const base = process.argv[2] ?? process.env.CHANGELOG_BASE ?? 'origin/main';
const title = process.env.PR_TITLE;
const git = (...args) =>
execFileSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const failures = [];

const parse = (version) => version.split('.').map(Number);
const newer = (a, b) => {
const [x, y] = [parse(a), parse(b)];
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
return false;
};
const latestIn = (source) => source.match(/version:\s*'(\d+\.\d+\.\d+)'/)?.[1];
const show = (path) => {
try {
Expand All @@ -31,23 +27,33 @@ const version = JSON.parse(readFileSync('package.json', 'utf8')).version;
const lockVersion = JSON.parse(readFileSync('package-lock.json', 'utf8')).version;
const latest = latestIn(readFileSync(changelogPath, 'utf8'));
const baseVersion = JSON.parse(show('package.json') ?? '{"version":"0.0.0"}').version;
const baseLatest = latestIn(show(changelogPath) ?? '') ?? '0.0.0';
const baseChangelog = show(changelogPath);
const baseLatest = latestIn(baseChangelog ?? '') ?? '0.0.0';

if (latest !== version)
failures.push(
`The newest release in ${changelogPath} is ${latest}, but package.json is ${version}.`,
);
if (lockVersion !== version)
failures.push(`package-lock.json is ${lockVersion}, but package.json is ${version}.`);
if (!newer(version, baseVersion))
failures.push(`Bump package.json above ${baseVersion}, the version on ${base}.`);
if (!newer(latest ?? '0.0.0', baseLatest))
if (!isNewer(latest ?? '0.0.0', baseLatest))
failures.push(`Add a release newer than ${baseLatest} at the top of ${changelogPath}.`);

// The pull request that introduces the changelog also backfills earlier versions.
const level = title && baseChangelog ? expectedBump(title) : undefined;
if (level) {
const expected = bumpVersion(baseVersion, level);
if (version !== expected)
failures.push(
`A "(${parseTitle(title).type})" pull request is a ${level} release: set the version to ${expected}, not ${version}.`,
);
} else if (!isNewer(version, baseVersion))
failures.push(`Bump package.json above ${baseVersion}, the version on ${base}.`);

if (failures.length) {
console.error(`Changelog check failed against ${base}:\n- ${failures.join('\n- ')}`);
console.error(
'\nRun `npm version minor --no-git-tag-version` (or patch for fixes) and add a matching release to src/docs/changelog.ts.',
`\nRun \`npm version ${level ?? 'minor'} --no-git-tag-version\` and add a matching release to ${changelogPath}.`,
);
process.exit(1);
}
Expand Down
22 changes: 22 additions & 0 deletions scripts/check-pull-request.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { readFileSync } from 'node:fs';
import { checkBody, checkTitle, pullRequestTypes } from './pull-request-rules.mjs';

const event = process.env.GITHUB_EVENT_PATH
? JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')).pull_request
: undefined;
const title = process.env.PR_TITLE ?? event?.title ?? '';
const body = process.env.PR_BODY_FILE
? readFileSync(process.env.PR_BODY_FILE, 'utf8')
: (process.env.PR_BODY ?? event?.body ?? '');

const failures = [...checkTitle(title), ...checkBody(body)];
if (failures.length) {
console.error(`Pull request format check failed:\n- ${failures.join('\n- ')}`);
console.error(
`\nTitle types:\n${Object.entries(pullRequestTypes)
.map(([type, { label }]) => ` ${type}: ${label}`)
.join('\n')}\nSee CONTRIBUTING.md and .github/pull_request_template.md.`,
);
process.exit(1);
}
console.log(`Pull request format is valid: ${title}`);
11 changes: 11 additions & 0 deletions scripts/pull-request-rules.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export type VersionBump = 'major' | 'minor' | 'patch';
export const pullRequestTypes: Record<string, { label: string; bump: VersionBump }>;
export const requiredSections: string[];
export function parseTitle(
title: string,
): { type: string; breaking: boolean; subject: string } | undefined;
export function checkTitle(title: string): string[];
export function checkBody(body: string | null | undefined): string[];
export function bumpVersion(version: string, level: VersionBump): string;
export function isNewer(a: string, b: string): boolean;
export function expectedBump(title: string): VersionBump | undefined;
96 changes: 96 additions & 0 deletions scripts/pull-request-rules.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
export const pullRequestTypes = {
feat: { label: 'New feature', bump: 'minor' },
fix: { label: 'Bug fix', bump: 'patch' },
perf: { label: 'Performance', bump: 'patch' },
docs: { label: 'Documentation', bump: 'patch' },
refactor: { label: 'Refactor with no change in behavior', bump: 'patch' },
test: { label: 'Tests only', bump: 'patch' },
build: { label: 'Build, dependencies, or tooling', bump: 'patch' },
ci: { label: 'Continuous integration', bump: 'patch' },
chore: { label: 'Maintenance', bump: 'patch' },
};

export const requiredSections = ['Summary', 'Testing', 'Release notes'];

const titlePattern = new RegExp(`^\\((${Object.keys(pullRequestTypes).join('|')})(!)?\\) (.+)$`);

export function parseTitle(title) {
const match = title.trim().match(titlePattern);
return match ? { type: match[1], breaking: !!match[2], subject: match[3] } : undefined;
}

export function checkTitle(title) {
const parsed = parseTitle(title);
if (!parsed)
return [
`Start the title with a type in parentheses, such as "(feat) Add the Warp tool". Types: ${Object.keys(pullRequestTypes).join(', ')}.`,
];
const failures = [];
if (!/^[A-Z]/.test(parsed.subject))
failures.push('Start the title after the type with a capital letter.');
if (/[.\s]$/.test(parsed.subject)) failures.push('End the title without a period or space.');
if (title.trim().length > 80) failures.push('Keep the title to 80 characters or fewer.');
return failures;
}

const meaningful = (text) =>
text
.split('\n')
.map((line) => line.replace(/^\s*(?:[-*]|\d+\.)\s*/, '').trim())
.some(Boolean);

export function checkBody(body) {
const text = (body ?? '').replace(/<!--[\s\S]*?-->/g, '').replace(/\r\n/g, '\n');
const sections = [...text.matchAll(/^## +(.+?)\s*$/gm)].map((match, i, all) => ({
title: match[1],
content: text.slice(match.index + match[0].length, all[i + 1]?.index ?? text.length),
}));
const found = sections.map((section) => section.title);
const failures = [];
const positions = requiredSections.map((title) => found.indexOf(title));
for (const [i, title] of requiredSections.entries())
if (positions[i] < 0) failures.push(`Add a "## ${title}" section.`);
if (
positions.every((position) => position >= 0) &&
positions.some((p, i) => i && p < positions[i - 1])
)
failures.push(
`Order the sections ${requiredSections.map((title) => `"${title}"`).join(', ')}.`,
);
if (found[0] !== undefined && found[0] !== 'Summary')
failures.push('Start the description with the "## Summary" section.');
const content = (title) => sections.find((section) => section.title === title)?.content ?? '';
for (const title of ['Summary', 'Testing'])
if (found.includes(title) && !meaningful(content(title)))
failures.push(`Fill in the "${title}" section.`);
if (found.includes('Release notes')) {
const notes = content('Release notes');
if (/^\s*[-*] \[ \]/m.test(notes)) failures.push('Check every item under "Release notes".');
else if (!/^\s*[-*] \[[xX]\]/m.test(notes))
failures.push('Keep the checklist from the template under "Release notes".');
}
return failures;
}

const parseVersion = (version) => version.split('.').map(Number);

export function bumpVersion(version, level) {
const [major, minor, patch] = parseVersion(version);
return level === 'major'
? `${major + 1}.0.0`
: level === 'minor'
? `${major}.${minor + 1}.0`
: `${major}.${minor}.${patch + 1}`;
}

export function isNewer(a, b) {
const [x, y] = [parseVersion(a), parseVersion(b)];
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
return false;
}

export function expectedBump(title) {
const parsed = parseTitle(title);
if (!parsed) return undefined;
return parsed.breaking ? 'major' : pullRequestTypes[parsed.type].bump;
}
Loading
Loading