Skip to content
Merged
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
8 changes: 6 additions & 2 deletions packages/release/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ Private workspace package, not published. The release tooling of the monorepo, r

## Releasing

1. `pnpm release:prepare` bumps the changed packages and opens the `chore(release)` pull request, with the release notes of each package in its description.
2. A reviewer approves it, and it is merged.
1. `pnpm release:prepare` bumps the changed packages, with the release notes of each package in the pull request description:
- on the branch of the changes (the usual way), it commits the bumps there and adds the release to its pull request, opened if there is none: the changes and their release get one review. Run it before requesting the review: a new commit dismisses an approval (it asks first);
- on `main`, it opens a `chore(release)` pull request of its own, for changes already merged.
2. A reviewer approves the pull request, and it is merged.
3. publish.yml, on the push to main, publishes the versions not on npm (`cl-release ship`): it builds and tests them from the commit that set them, then, dependencies first, tags each version, publishes it to npm (OIDC, provenance) and publishes its GitHub release. Each package published to npm gets its own Slack message, with the link to its release notes.

Nothing is run after the merge. `release:prepare` stops while a merged release is not on npm yet, and on a branch whose release is already prepared.

A release that stopped halfway resumes by running publish.yml by hand: what is on npm is skipped.

## Commands
Expand Down
104 changes: 94 additions & 10 deletions packages/release/src/commands/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@
* By default it prints the plan and asks for a single confirmation;
* --interactive lets you change or skip each package's version.
*
* Nothing is committed to the base branch: the bumps go on a `release/…`
* branch and a pull request, whose description has the release notes of
* each package. Once it is approved and merged, publish.yml publishes the
* versions (`cl-release ship`): tags, npm, GitHub releases.
* Nothing is committed to the base branch. Run on the base branch, the
* bumps go on a `release/…` branch and a pull request of their own. Run on
* another branch (the changes to release), the bumps are committed on it and
* pushed: its pull request, opened if there is none, then holds the changes
* and their release, approved with one review. Either way the description
* has the release notes of each package, and once the pull request is
* approved and merged publish.yml publishes the versions (`cl-release ship`):
* tags, npm, GitHub releases.
*/
import { execFileSync } from 'node:child_process'
import { join } from 'node:path'
Expand All @@ -35,7 +39,10 @@ const USAGE = `Usage: cl-release version [--interactive | --yes] [--base <branch
--interactive confirm, change or skip each package's version
--yes no confirmation at all
--base <b> branch the release PR targets (default: main)
--no-pr commit on a local release branch only, do not push or open a PR
--no-pr commit only, do not push or open (or update) a PR

On the base branch it opens a release PR of its own; on another branch it
commits the bumps there and opens or updates that branch's PR.
--dry-run show what would happen and change nothing`

type Level = 'major' | 'minor' | 'patch'
Expand Down Expand Up @@ -122,6 +129,42 @@ export const releasePrBody = (entries: ReleaseEntry[], repository = 'https://git
)
}

const RELEASE_START = '<!-- cl-release -->'
const RELEASE_END = '<!-- /cl-release -->'

/**
* A pull request description with the release section added, or replaced
* when there is one already: the rest of the description is kept.
*/
export const withReleaseSection = (body: string, release: string): string => {
const section = `${RELEASE_START}\n## Release\n\n${release}\n${RELEASE_END}`
const start = body.indexOf(RELEASE_START)
const end = body.indexOf(RELEASE_END)
if (start > -1 && end > start) return `${body.slice(0, start)}${section}${body.slice(end + RELEASE_END.length)}`
return body.trim() ? `${body.trimEnd()}\n\n${section}` : section
}

type BranchPr = { number: number; url: string; body: string; reviewDecision: string; isDraft: boolean }

/** The open pull request of a branch, if any */
const branchPr = (branch: string): BranchPr | undefined => {
try {
const pr = JSON.parse(execFileSync('gh', ['pr', 'view', branch, '--json', 'number,url,body,reviewDecision,isDraft,state'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }))
return pr.state === 'OPEN' ? pr : undefined
} catch {
return undefined
}
}

/** The version of a package on a ref, if the package exists there */
const versionAt = (ref: string, pkg: Package): string | undefined => {
try {
return JSON.parse(git('show', `${ref}:${pkg.path}/package.json`)).version
} catch {
return undefined
}
}

export const run = async (args: string[]): Promise<void> => {
const { values } = parse(
args,
Expand All @@ -135,8 +178,24 @@ export const run = async (args: string[]): Promise<void> => {
USAGE,
)
const base = values.base
const current = git('branch', '--show-current')
// On another branch than the base: the release goes in that branch's PR
const onBranch = current !== '' && current !== base

requireUpToDate(base)
let pr: BranchPr | undefined
if (onBranch) {
if (git('status', '--porcelain')) fail('Working tree is not clean.')
git('fetch', '--quiet', 'origin', base, '--tags')
try {
git('merge-base', '--is-ancestor', `origin/${base}`, 'HEAD')
} catch {
fail(`${current} doesn't have the latest ${base}: merge origin/${base} into it first.`)
}
const bumped = publicPackages().filter((p) => versionAt(`origin/${base}`, p) !== undefined && versionAt(`origin/${base}`, p) !== p.version)
if (bumped.length > 0)
fail(`The release is already prepared on ${current}: ${bumped.map((p) => `${p.name}@${p.version}`).join(', ')}. To prepare it again, revert its chore(release) commit first.`)
pr = branchPr(current)
} else requireUpToDate(base)

// A merged release not on npm yet (publish.yml still running, or failed):
// its tags don't exist yet, so its changes would be released a second time
Expand Down Expand Up @@ -220,16 +279,27 @@ export const run = async (args: string[]): Promise<void> => {
}

const tags = selected.map((s) => tagOf(s.pkg, s.version))
const branch = `release/${tags.length === 1 ? tags[0] : new Date().toISOString().slice(0, 16).replace(/[-:T]/g, '')}`
const branch = onBranch ? current : `release/${tags.length === 1 ? tags[0] : new Date().toISOString().slice(0, 16).replace(/[-:T]/g, '')}`
const subject = `chore(release): ${tags.join(', ')}`

console.log(`\n${subject}\n branch: ${branch}`)
console.log(`\n${subject}\n branch: ${branch}${pr ? `, pull request #${pr.number}` : ''}`)
if (values['dry-run']) {
console.log(' (dry run: nothing changed)')
return
}

git('switch', '--quiet', '-c', branch)
// A new commit on an approved PR dismisses its approval
if (pr?.reviewDecision === 'APPROVED' && !values.yes) {
const confirm = createInterface({ input: process.stdin, output: process.stdout })
const answer = (await confirm.question(`\n#${pr.number} is approved: the release commit dismisses its approval, and it needs a new review. Go on? [y/N] `)).trim().toLowerCase()
confirm.close()
if (answer !== 'y' && answer !== 'yes') {
console.log('Aborted: nothing changed.')
process.exit(0)
}
}

if (!onBranch) git('switch', '--quiet', '-c', branch)
for (const s of selected) {
const file = join(s.pkg.path, 'package.json')
const manifest = readJson(file)
Expand All @@ -241,7 +311,7 @@ export const run = async (args: string[]): Promise<void> => {
console.log(`✓ Committed on ${branch}`)

if (values['no-pr']) {
console.log(`\nPush it and open a PR to ${base}: once approved and merged, publish.yml publishes the versions.`)
console.log(`\nPush it and open (or update) a PR to ${base}: once approved and merged, publish.yml publishes the versions.`)
return
}

Expand All @@ -254,6 +324,20 @@ export const run = async (args: string[]): Promise<void> => {
entries.push({ name: s.pkg.name, path: s.pkg.path, from: s.pkg.version, to: s.version, tag, notes })
}
const body = releasePrBody(entries)

if (onBranch) {
if (pr) {
execFileSync('gh', ['pr', 'edit', String(pr.number), '--body', withReleaseSection(pr.body, body)], { stdio: 'ignore' })
console.log(`✓ Release added to #${pr.number}: ${pr.url}`)
console.log(pr.isDraft ? ' It is a draft: mark it ready and request the reviews.' : ' Request the reviews if not done yet.')
} else {
// Titled after the branch's first change, the message of its merge commit on the base branch
const [first] = git('log', '--reverse', '--format=%s', `origin/${base}..HEAD`).split('\n').filter((c) => !c.startsWith('chore(release)'))
execFileSync('gh', ['pr', 'create', '--base', base, '--head', branch, '--title', first ?? subject, '--body', withReleaseSection('', body)], { stdio: 'inherit' })
}
return
}

// The release PR itself has no place in the release notes
execFileSync('gh', ['label', 'create', 'ignore-for-release', '--force', '--color', 'ededed', '--description', 'Excluded from release notes'], {
stdio: 'ignore',
Expand Down
21 changes: 20 additions & 1 deletion packages/release/test/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { withMaintenanceNote } from '../src/commands/notes.ts'
import { dependenciesToPublish, isConcurrentPublish } from '../src/commands/publish.ts'
import { planShip } from '../src/commands/ship.ts'
import { withWorkspaceDeps } from '../src/commands/try.ts'
import { addChangedDependencies, bump, releasePrBody } from '../src/commands/version.ts'
import { addChangedDependencies, bump, releasePrBody, withReleaseSection } from '../src/commands/version.ts'
import { pkg } from './helpers.ts'

describe('version', () => {
Expand Down Expand Up @@ -139,3 +139,22 @@ describe('release PR body', () => {
expect(body).to.contain('… [all the changes](https://github.com/commercelayer/commercelayer-cli/commits/main/plugins/p0)')
})
})

describe('release section of a pull request', () => {
it('adds the release to the description of the changes', () => {
const body = withReleaseSection('## Changes\n\n- a fix\n', 'notes v1')
expect(body).to.match(/^## Changes\n\n- a fix\n\n<!-- cl-release -->\n## Release\n\nnotes v1\n<!-- \/cl-release -->$/)
})

it('replaces the release section, keeping the rest', () => {
const once = withReleaseSection('intro', 'notes v1')
const twice = withReleaseSection(`${once}\n\nfooter`, 'notes v2')
expect(twice).to.contain('intro').and.to.contain('notes v2').and.to.contain('footer')
expect(twice).not.to.contain('notes v1')
expect(twice.match(/<!-- cl-release -->/g)).to.have.length(1)
})

it('is the whole description of a new pull request', () => {
expect(withReleaseSection('', 'notes')).to.equal('<!-- cl-release -->\n## Release\n\nnotes\n<!-- /cl-release -->')
})
})
2 changes: 1 addition & 1 deletion plugins/tags/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@commercelayer/cli-plugin-tags",
"description": "Commerce Layer CLI Tags plugin",
"version": "3.0.0",
"version": "3.0.1",
"author": "Pierluigi Viti <pierluigi@commercelayer.io>",
"homepage": "https://github.com/commercelayer/commercelayer-cli/tree/main/plugins/tags",
"repository": {
Expand Down
Loading