Skip to content
Open
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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ All subactions take a `node-version` input (default `24`; uppt needs `--experime
| `allow-forks` | `false` | By default the action skips on forks so they don't open release PRs of their own. |
| `prerelease` | _(unset)_ | One-shot prerelease identifier (`beta`, `rc`, or a bare number). See [Prereleases](#prereleases). |
| `title` | `v{version}` | Template for the release PR title and commit message, e.g. `chore(release): v{version}`. In [independent mode](#independent-versioning-experimental) the placeholders are `{count}` and `{packages}` (`package` or `packages`), and the default is `chore: release {count} {packages}`. |
| `sections` | _(unset)_ | Changelog section headings to override, one per line as `<type>: <title>`, e.g. `feat: 🚀 Features`. Listed commit types render first, in the order given; the rest keep their default heading and order. Lines starting with `#` are comments; a `#` later in a line is part of the title. See below for the accepted types. |
| `pr-notes` | _(unset)_ | Markdown to show in the release PR body below the timetable, such as links to preview builds. `{base}` is replaced with the base branch and, outside [independent mode](#independent-versioning-experimental), `{version}` with the next version (e.g. `1.3.0`). See below. |

uppt keeps `pr-notes` in a marked block of the release PR body, refreshes it on every run, and leaves it out of the GitHub release notes. For example, if [pkg.pr.new](https://github.com/stackblitz-labs/pkg.pr.new) runs on pushes to your base branches, you can point at the latest build of the base branch:
Expand All @@ -189,6 +190,26 @@ uppt keeps `pr-notes` in a marked block of the release PR body, refreshes it on
pr-notes: |
Try the latest `{base}` build: `npm i https://pkg.pr.new/<owner>/<repo>/<package>@{base}`
```

`sections` accepts these types, shown in their default order with their default headings. Any other type fails the run.

| Type | Default heading |
| --- | --- |
| `feat` | 🚀 Enhancements |
| `perf` | 🔥 Performance |
| `fix` | 🩹 Fixes |
| `refactor` | 💅 Refactors |
| `docs` | 📖 Documentation |
| `build` | 📦 Build |
| `types` | 🌊 Types |
| `chore` | 🏡 Chore |
| `examples` | 🏀 Examples |
| `test` | ✅ Tests |
| `style` | 🎨 Styles |
| `ci` | 🤖 CI |
| `revert` | ⏪ Reverts |
| `new-contributors` | 🎉 New Contributors |
| `contributors` | ❤️ Contributors |
</details>

<details>
Expand Down
5 changes: 5 additions & 0 deletions pr/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ inputs:
description: 'Template for the release PR title and the release branch''s commit message. Lockstep mode provides `{version}` (default `v{version}`); independent mode provides `{count}` and `{packages}`, which is `package` or `packages` to match the count (default `chore: release {count} {packages}`).'
required: false
default: ''
sections:
description: 'Optional changelog section headings, one per line as `<type>: <title>` (e.g. `feat: 🚀 Features`). `<type>` is one of `feat`, `perf`, `fix`, `refactor`, `docs`, `build`, `types`, `chore`, `examples`, `test`, `style`, `ci`, `revert` (the default order), `contributors` or `new-contributors`. Listed commit types render first, in the order given; the rest keep their default heading and order. Lines starting with `#` are comments; a `#` later in a line is part of the title.'
required: false
default: ''
prerelease:
description: 'One-shot prerelease identifier (e.g. `beta`, `rc`, or a bare number like `0`). When set, this run cuts or continues a prerelease: from a stable version the normal bump is applied and the identifier attached at counter 0 (`4.5.2` → `5.0.0-beta.0`); from a prerelease with the same identifier the counter increments (`5.0.0-beta.0` → `5.0.0-beta.1`). Omit for normal releases; a prerelease version with this unset graduates to its stable version. `uppt/publish` stages prereleases under a matching dist-tag (`beta`, `rc`, `next` for a bare number) so `latest` is never moved to them.'
required: false
Expand Down Expand Up @@ -111,5 +115,6 @@ runs:
MODE: ${{ inputs.mode }}
SCOPES: ${{ inputs.scopes }}
TITLE: ${{ inputs.title }}
SECTIONS: ${{ inputs.sections }}
PR_NOTES: ${{ inputs.pr-notes }}
run: node --experimental-strip-types ${{ github.action_path }}/../scripts/update-changelog.ts
108 changes: 77 additions & 31 deletions scripts/update-changelog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
// TITLE release PR title and commit message template, with
// `{version}` in lockstep mode and `{count}` /
// `{packages}` in independent mode
// SECTIONS newline-separated "<type>: <title>" overrides for
// the changelog section headings and order
// PR_NOTES Markdown kept in a marked block of the release PR
// preamble and refreshed on every run, with `{base}`
// and, in lockstep mode, `{version}`
Expand Down Expand Up @@ -81,6 +83,63 @@ const TYPE_TITLES: Record<string, string> = {

const KNOWN_TYPES = new Set(Object.keys(TYPE_TITLES))

const CONTRIBUTOR_TITLES = {
'new-contributors': '🎉 New Contributors',
'contributors': '❤️ Contributors',
}

const SECTION_KEYS = [...KNOWN_TYPES, ...Object.keys(CONTRIBUTOR_TITLES)]

/**
* Parse a newline-separated `sections:` input into section heading
* overrides, keyed by commit type or by `contributors` /
* `new-contributors`, in the order they are listed. Each non-blank line
* takes the shape `<type>: <title>`, split on the first colon so the title
* can hold colons of its own (`feat: :rocket: Features`). Lines starting
* with `#` are comments.
*/
export function parseSectionsInput (raw: string): Record<string, string> {
const titles: Record<string, string> = {}
const lines = raw.split(/\r?\n/)
for (let i = 0; i < lines.length; i++) {
const line = lines[i]!.trim()
if (!line || line.startsWith('#')) continue
const colon = line.indexOf(':')
if (colon === -1) {
throw new Error(`\`sections\` entry on line ${i + 1} is missing a colon. Expected "<type>: <title>", got "${line}".`)
}
const type = line.slice(0, colon).trim()
const title = line.slice(colon + 1).trim()
if (!SECTION_KEYS.includes(type)) {
throw new Error(`\`sections\` entry on line ${i + 1} names an unknown type \`${type}\`. Expected one of ${SECTION_KEYS.map(t => `\`${t}\``).join(', ')}.`)
}
if (!title) {
throw new Error(`\`sections\` entry for \`${type}\` has an empty title.`)
}
if (Object.hasOwn(titles, type)) {
throw new Error(`\`sections\` entry for \`${type}\` appears more than once.`)
}
titles[type] = title
}
return titles
}

function contributorLines (contributors: Contributor[], titles: Record<string, string> = {}): string[] {
const lines: string[] = []
const newContributors = contributors.filter(c => c.isFirstTime)
if (newContributors.length) {
lines.push(`### ${titles['new-contributors'] ?? CONTRIBUTOR_TITLES['new-contributors']}`, '', newContributors.map(c => `- ${c.name} (@${c.username})`).join('\n'), '')
}
lines.push(
`### ${titles.contributors ?? CONTRIBUTOR_TITLES.contributors}`,
'',
contributors.length
? contributors.map(c => `- ${c.name} (@${c.username})`).join('\n')
: '_no contributors yet_',
)
return lines
}

const isReleaseWorthy = (c: Commit) =>
KNOWN_TYPES.has(c.type) && !(c.type === 'chore' && c.scope === 'deps')

Expand Down Expand Up @@ -508,6 +567,12 @@ export function formatChangelog (
* rendered line: the section heading already names the package.
*/
packageScopes?: string[]
/**
* Section heading overrides by commit type, from `parseSectionsInput`.
* Listed types render first in their listed order; the rest keep their
* default heading and order.
*/
titles?: Record<string, string>
},
): string {
const grouped = new Map<string, Commit[]>()
Expand All @@ -527,10 +592,11 @@ export function formatChangelog (
const commitUrl = (sha: string) =>
`https://github.com/${opts.owner}/${opts.repo}/commit/${sha}`

for (const type of Object.keys(TYPE_TITLES)) {
const order = new Set([...Object.keys(opts.titles ?? {}), ...KNOWN_TYPES])
for (const type of order) {
const items = grouped.get(type)
if (!items?.length) continue
lines.push(`### ${TYPE_TITLES[type]}`, '')
lines.push(`### ${opts.titles?.[type] ?? TYPE_TITLES[type]}`, '')
for (const c of items) {
const ownScopes = c.scope.split(',').map(s => s.trim()).filter(Boolean)
const redundant = ownScopes.length === 1 && Boolean(opts.packageScopes?.includes(ownScopes[0]!))
Expand Down Expand Up @@ -1209,6 +1275,7 @@ export function buildIndependentBody (
repo: string
preamble: string
contributors?: Contributor[]
titles?: Record<string, string>
},
): string {
const releasedNames = new Set(plan.releases.map(r => r.name))
Expand All @@ -1223,6 +1290,7 @@ export function buildIndependentBody (
fromRef: release.fromTag,
toRef: `${release.name}@${release.newVersion}`,
packageScopes: release.scopes,
titles: opts.titles,
}), '')
} else {
const causes = propagationCauses(release, releasedNames)
Expand Down Expand Up @@ -1250,19 +1318,7 @@ export function buildIndependentBody (
lines.push('')
}

if (opts.contributors) {
const newContributors = opts.contributors.filter(c => c.isFirstTime)
if (newContributors.length) {
lines.push('### 🎉 New Contributors', '', newContributors.map(c => `- ${c.name} (@${c.username})`).join('\n'), '')
}
lines.push(
'### ❤️ Contributors',
'',
opts.contributors.length
? opts.contributors.map(c => `- ${c.name} (@${c.username})`).join('\n')
: '_no contributors yet_',
)
}
if (opts.contributors) lines.push(...contributorLines(opts.contributors, opts.titles))

return lines.join('\n').trimEnd()
}
Expand All @@ -1281,6 +1337,7 @@ export async function main () {
const dryRun = Boolean(process.env.DRY_RUN)
const repo = getRepo()
const baseBranch = getCurrentBranch()
const titles = parseSectionsInput(process.env.SECTIONS ?? '')

const headSha = git('rev-parse', 'HEAD')
if (await isReleaseMergeCommit(repo, headSha)) {
Expand All @@ -1299,7 +1356,7 @@ export async function main () {
if (!monorepo) {
throw new Error('`mode: independent` requires the `packages` input.')
}
await runIndependent(packagesInput)
await runIndependent(packagesInput, titles)
return
}

Expand Down Expand Up @@ -1359,6 +1416,7 @@ export async function main () {
repo: repo.repo,
fromRef: latestTag,
toRef: `v${newVersion}`,
titles,
})

console.log(`Current: ${currentVersion} -> ${newVersion} (${bump}${pinned ? `, pinned on #${pinned.pr.number}` : ''})`)
Expand Down Expand Up @@ -1410,7 +1468,6 @@ export async function main () {
// unauthenticated against public repos. We still benefit from a token
// (5000 req/h vs 60), but don't require one for previews.
const contributors = await getContributors(commits, repo, cutoff)
const newContributors = contributors.filter(c => c.isFirstTime)

const currentPR = await findOpenPR(repo, releaseBranch)
const intro = `> v${newVersion} is the next ${bump} release.`
Expand All @@ -1429,20 +1486,8 @@ export async function main () {
'## 👉 Changelog',
'',
changelog,
...(newContributors.length
? [
'',
'### 🎉 New Contributors',
'',
newContributors.map(c => `- ${c.name} (@${c.username})`).join('\n'),
]
: []),
'',
'### ❤️ Contributors',
'',
contributors.length
? contributors.map(c => `- ${c.name} (@${c.username})`).join('\n')
: '_no contributors yet_',
...contributorLines(contributors, titles),
].join('\n')

if (dryRun) {
Expand All @@ -1454,7 +1499,7 @@ export async function main () {
await upsertReleasePR(repo, { currentPR, title, head: releaseBranch, base: baseBranch, body })
}

async function runIndependent (packagesInput: string): Promise<void> {
async function runIndependent (packagesInput: string, titles: Record<string, string>): Promise<void> {
const workspaces = resolveWorkspaces(process.cwd(), packagesInput)
const scopeOverrides = parseScopesInput(process.env.SCOPES ?? '')
const tags = getAllTags()
Expand Down Expand Up @@ -1570,6 +1615,7 @@ async function runIndependent (packagesInput: string): Promise<void> {
repo: repo.repo,
preamble,
contributors,
titles,
})

if (dryRun) {
Expand Down
49 changes: 49 additions & 0 deletions test/update-changelog-main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const ENV_KEYS = [
'MODE',
'SCOPES',
'TITLE',
'SECTIONS',
'PR_NOTES',
] as const

Expand Down Expand Up @@ -286,6 +287,40 @@ describe('lockstep main', () => {
expect(prBody()).toContain('/compare/v1.2.3...v1.3.0)')
})

it('uses custom section headings in the PR body', async () => {
process.env.SECTIONS = 'feat: :rocket: Features'
await main()
expect(prBody()).toContain('### :rocket: Features')
expect(prBody()).not.toContain('### 🚀 Enhancements')
})

it('uses custom contributor headings in the PR body', async () => {
git.tags = []
process.env.SECTIONS = 'contributors: :green_heart: Contributors\nnew-contributors: :wave: New Contributors'
await main()
expect(prBody()).toContain('### :wave: New Contributors\n\n- Ada (@ada)')
expect(prBody()).toContain('### :green_heart: Contributors\n\n- Ada (@ada)')
expect(prBody()).not.toContain('❤️')
})

it('fails on an invalid sections input before writing anything', async () => {
process.env.SECTIONS = 'feature: Features'
await expect(main()).rejects.toThrow('unknown type `feature`')
expect(calls.some(c => c.method !== 'GET')).toBe(false)
})

it('fails on an invalid sections input on a release merge too', async () => {
process.env.SECTIONS = 'feature: Features'
api.prsForHead = [{ head: { ref: 'release/v1.2.3' }, merged_at: '2024-01-01T00:00:00Z' }]
await expect(main()).rejects.toThrow('unknown type `feature`')
})

it('fails on an invalid sections input even with nothing to release', async () => {
process.env.SECTIONS = 'feature: Features'
git.commits = [{ ...FEAT, subject: 'chore(deps): bump something' }]
await expect(main()).rejects.toThrow('unknown type `feature`')
})

it('uses a custom title for the PR and the release commit', async () => {
process.env.TITLE = 'chore(release): v{version}'
await main()
Expand Down Expand Up @@ -1113,6 +1148,20 @@ describe('independent main', () => {
expect(commit.body).toMatchObject({ message: 'chore(release): 2 packages' })
})

it('uses custom section headings in each package changelog', async () => {
process.env.SECTIONS = 'feat: :rocket: Features'
git.commits = [
{ ...FEAT, subject: 'feat(a): add a thing (#7)' },
{ ...FEAT, hash: 'd'.repeat(40), short: 'ddddddd', subject: 'feat(b): add another thing (#8)' },
]
git.revList = [FEAT.hash, 'd'.repeat(40)]
await main()
const [, a, b] = prBody().split(/^### [ab] \(/m)
expect(a).toContain('### :rocket: Features')
expect(b).toContain('### :rocket: Features')
expect(prBody()).not.toContain('🚀 Enhancements')
})

it('rejects a lockstep-only title placeholder', async () => {
process.env.TITLE = 'v{version}'
await expect(main()).rejects.toThrow('Unknown placeholder `{version}` in the `title` input; expected `{count}`, `{packages}`.')
Expand Down
Loading