From 7961108cca8d5d2d778c469f4a816dc6ce1b91a0 Mon Sep 17 00:00:00 2001 From: Dominic Saadi Date: Fri, 8 Mar 2024 01:30:42 -0800 Subject: [PATCH] chore(release): try changesets instead of changelog (#10138) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The newish changelog workflow has personally saved me a lot of time and is half the reason we were able to release so many times on a moment's notice last week. But it's prone to merge conflicts, both in this repo and in the release tooling (most cherry picks from the main branch to the next branch had merge conflicts because of the changelog) so it's not going to scale out much more. But it's proved it's usefulness. I tried Changesets properโ€”seemed like the obvious choice and @ahaywood even independently came up with the ideaโ€”but it's overkill. I don't want to have to associate a semver with a PR (we use milestones for that). I also don't want to have to pick which packages we're versioning. Right now it's always all of them. And without the tooling or without using git, there's no obvious way to tie a changeset back to the PR that made it. (Maybe one of the changeset changelog packages do this, but config.) All I really want is what we're doing right now without the merge conflicts, so I spiked on a small script to generate a minimal changeset: ``` yarn changesets 10116 yarn changesets https://github.com/redwoodjs/redwood/pull/10116 ``` The idea is that we'll do what we've been doing, but just via that command. It'll write a file to `.changesets/three-random-words.md`, and we'll put our release notes for the PR there. The release tooling can aggregate them into release notes at the time of release. The main con is that we can't see all the unreleased changes in linear order in one file. But tradeoffs. It's definitely worth not having to put up with merge conflicts. --- .github/actions/check_changelog/action.yml | 10 -- .../check_changelog/check_changelog.mjs | 68 -------- .github/actions/check_changesets/action.yml | 10 ++ .../check_changesets/check_changesets.mjs | 47 ++++++ .../package.json | 2 +- .../yarn.lock | 4 +- .github/workflows/check-changelog.yml | 12 +- package.json | 2 + tasks/changesets/changesets.mts | 50 ++++++ tasks/changesets/changesetsHelpers.mts | 148 ++++++++++++++++++ tasks/changesets/placeholder.md | 7 + yarn.lock | 10 ++ 12 files changed, 283 insertions(+), 87 deletions(-) delete mode 100644 .github/actions/check_changelog/action.yml delete mode 100644 .github/actions/check_changelog/check_changelog.mjs create mode 100644 .github/actions/check_changesets/action.yml create mode 100644 .github/actions/check_changesets/check_changesets.mjs rename .github/actions/{check_changelog => check_changesets}/package.json (85%) rename .github/actions/{check_changelog => check_changesets}/yarn.lock (99%) create mode 100755 tasks/changesets/changesets.mts create mode 100644 tasks/changesets/changesetsHelpers.mts create mode 100644 tasks/changesets/placeholder.md diff --git a/.github/actions/check_changelog/action.yml b/.github/actions/check_changelog/action.yml deleted file mode 100644 index 8364b63124fb..000000000000 --- a/.github/actions/check_changelog/action.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: Check CHANGELOG.md -description: Checks if CHANGELOG.md has been updated - -runs: - using: node20 - main: check_changelog.mjs - -inputs: - labels: - required: true diff --git a/.github/actions/check_changelog/check_changelog.mjs b/.github/actions/check_changelog/check_changelog.mjs deleted file mode 100644 index e971928c5171..000000000000 --- a/.github/actions/check_changelog/check_changelog.mjs +++ /dev/null @@ -1,68 +0,0 @@ -import { getInput } from '@actions/core' -import { exec, getExecOutput } from '@actions/exec' -import github from '@actions/github' - -async function main() { - // If the PR has the "changelog-ok" label, just pass. - const { labels } = JSON.parse(getInput('labels')) - const hasChangelogOkLabel = labels.some((label) => label.name === 'changelog-ok') - if (hasChangelogOkLabel) { - console.log('Skipping check because of the "changelog-ok" label') - return - } - - // Check if the PR updates the Changelog. - await exec('git fetch origin main', [], { silent: true }) - const { stdout } = await getExecOutput('git diff origin/main --name-only', [], { silent: true }) - const changedFiles = stdout.toString().trim().split('\n').filter(Boolean) - const didUpdateChangelog = changedFiles.some((file) => file === 'CHANGELOG.md') - if (didUpdateChangelog) { - // Empty space here (and in subsequent `console.log`s) for formatting in the action. - console.log( - [ - '', - "CHANGELOG.md was updated", - ].join('\n') - ) - - return - } - - const pr = github.context.payload.pull_request - - // The lines here are long but it's about how they look in GitHub actions, not here. - // So if you make changes, cross check them with how they actually look in the action. - console.log( - [ - '', - '๐Ÿ“ Update the Changelog', - '=======================', - '', - 'Before this PR can be merged, you need to update the Changelog at CHANGELOG.md. Add a bullet point to the Unreleased section at the top of the file in the following format', - '', - '```', - "## Unreleased", - '', - " - PR title (#PR number) by @PR author", - '', - " Body...", - '```', - '', - `"PR title" and "PR number" should be the title and number of the PR you're working on verbatim. But "Body" shouldn't necessarily be the same. Feel free to use it as a starting point though.`, - '', - 'In writing the body, explain what this PR means for Redwood users. The more detail the better. E.g., is it a new feature? How do they use it? Code examples go a long way!', - '', - "Here are your PR's title, number, and body as a starting point:", - '', - '```', - `- ${pr.title} (#${pr.number}) by @${pr.user.login}`, - '', - ` ${pr.body}`, - '```', - ].join('\n') - ) - - process.exitCode = 1 -} - -main() diff --git a/.github/actions/check_changesets/action.yml b/.github/actions/check_changesets/action.yml new file mode 100644 index 000000000000..9218183da162 --- /dev/null +++ b/.github/actions/check_changesets/action.yml @@ -0,0 +1,10 @@ +name: Check changesets +description: Checks if changeset was added to the PR + +runs: + using: node20 + main: check_changesets.mjs + +inputs: + labels: + required: true diff --git a/.github/actions/check_changesets/check_changesets.mjs b/.github/actions/check_changesets/check_changesets.mjs new file mode 100644 index 000000000000..d012b019f0d3 --- /dev/null +++ b/.github/actions/check_changesets/check_changesets.mjs @@ -0,0 +1,47 @@ +import { getInput } from '@actions/core' +import { exec, getExecOutput } from '@actions/exec' +import github from '@actions/github' + +async function main() { + // If the PR has the "changesets-ok" label, just pass. + const { labels } = JSON.parse(getInput('labels')) + const hasChangesetsOkLabel = labels.some((label) => label.name === 'changesets-ok') + if (hasChangesetsOkLabel) { + console.log('Skipping check because of the "changesets-ok" label') + return + } + + // Check if the PR adds a changeset. + await exec('git fetch origin main', [], { silent: true }) + const { stdout } = await getExecOutput('git diff origin/main --name-only', [], { silent: true }) + const changedFiles = stdout.toString().trim().split('\n').filter(Boolean) + const addedChangeset = changedFiles.some((file) => file.startsWith('.changesets/')) + if (addedChangeset) { + // Empty space here (and in subsequent `console.log`s) for formatting in the action. + console.log( + [ + '', + "Added a changeset", + ].join('\n') + ) + + return + } + + const pr = github.context.payload.pull_request + console.log( + [ + '', + '๐Ÿ“ Consider adding a changeset', + '==============================', + '', + 'If this is a user-facing PR (a feature or a fix), it should probably have a changeset.', + `Run \`yarn changesets ${pr.number}\` to create a changeset for this PR.`, + "If it doesn't need one (it's a chore), you can add the 'changesets-ok' label.", + ].join('\n') + ) + + process.exitCode = 1 +} + +main() diff --git a/.github/actions/check_changelog/package.json b/.github/actions/check_changesets/package.json similarity index 85% rename from .github/actions/check_changelog/package.json rename to .github/actions/check_changesets/package.json index cd086b5097a7..a57b28c2956f 100644 --- a/.github/actions/check_changelog/package.json +++ b/.github/actions/check_changesets/package.json @@ -1,5 +1,5 @@ { - "name": "check_changelog", + "name": "check_changesets", "private": true, "dependencies": { "@actions/core": "1.10.1", diff --git a/.github/actions/check_changelog/yarn.lock b/.github/actions/check_changesets/yarn.lock similarity index 99% rename from .github/actions/check_changelog/yarn.lock rename to .github/actions/check_changesets/yarn.lock index 08e54ab4edcb..d89dca47afe7 100644 --- a/.github/actions/check_changelog/yarn.lock +++ b/.github/actions/check_changesets/yarn.lock @@ -171,9 +171,9 @@ __metadata: languageName: node linkType: hard -"check_changelog@workspace:.": +"check_changesets@workspace:.": version: 0.0.0-use.local - resolution: "check_changelog@workspace:." + resolution: "check_changesets@workspace:." dependencies: "@actions/core": "npm:1.10.1" "@actions/exec": "npm:1.1.1" diff --git a/.github/workflows/check-changelog.yml b/.github/workflows/check-changelog.yml index eabf6b71b921..de48c3b134db 100644 --- a/.github/workflows/check-changelog.yml +++ b/.github/workflows/check-changelog.yml @@ -1,4 +1,4 @@ -name: ๐Ÿ“ Check CHANGELOG.md +name: ๐Ÿ“ Check changesets on: pull_request: @@ -11,8 +11,8 @@ concurrency: cancel-in-progress: true jobs: - check-changelog: - name: ๐Ÿ“ Check CHANGELOG.md + check-changesets: + name: ๐Ÿ“ Check changesets runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -25,9 +25,9 @@ jobs: node-version: 20 - run: yarn install - working-directory: ./.github/actions/check_changelog + working-directory: ./.github/actions/check_changesets - - name: Check CHANGELOG.md - uses: ./.github/actions/check_changelog + - name: Check changesets + uses: ./.github/actions/check_changesets with: labels: '{ "labels": ${{ toJSON(github.event.pull_request.labels) }} }' diff --git a/package.json b/package.json index 175388812f0d..ece0abb155b0 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "build:pack": "nx run-many -t build:pack", "build:test-project": "node ./tasks/test-project/test-project", "build:watch": "lerna run build:watch --parallel; tsc --build", + "changesets": "tsx ./tasks/changesets/changesets.mts", "check": "node ./tasks/check/check.mjs", "clean:prisma": "rimraf node_modules/.prisma/client && node node_modules/@prisma/client/scripts/postinstall.js", "e2e": "node ./tasks/run-e2e", @@ -89,6 +90,7 @@ "execa": "5.1.1", "fast-glob": "3.3.2", "fs-extra": "11.2.0", + "human-id": "^4.1.1", "jest": "29.7.0", "jscodeshift": "0.15.0", "lerna": "8.0.2", diff --git a/tasks/changesets/changesets.mts b/tasks/changesets/changesets.mts new file mode 100755 index 000000000000..a4203826773a --- /dev/null +++ b/tasks/changesets/changesets.mts @@ -0,0 +1,50 @@ +import { chalk, fs } from 'zx' + +import { + getChangesetFilePath, + getPlaceholder, + resolveArgv, + shouldShowHelp, + showHelp, +} from './changesetsHelpers.mjs' + +async function main() { + if (shouldShowHelp()) { + showHelp() + return + } + + const { prNumber } = resolveArgv() + + const changesetFilePath = getChangesetFilePath(prNumber) + const placeholder = await getPlaceholder(prNumber) + await fs.outputFile(changesetFilePath, placeholder) + console.log( + [ + `๐Ÿ“ Created a changeset at ${chalk.magenta(changesetFilePath)}`, + " Commit it when you're done and push your branch up to GitHub. Thank you! ๐Ÿ™", + ].join('\n') + ) +} + +try { + await main() +} catch (error) { + console.error(`${error.message}\n`) + showHelp() + process.exitCode = 1 +} + +// Test suite +// +// - should be the placeholder at ./placeholder.md +// - yarn changesets +// +// - should be the title and body of PR 10075 +// - yarn changesets 10075 +// - yarn changesets '#10075' +// +// - should throw and show help +// - yarn changesets abcd +// - yarn changesets 10075000 +// - yarn changesets https://github.com/redwoodjs/redwood/pull/10075 diff --git a/tasks/changesets/changesetsHelpers.mts b/tasks/changesets/changesetsHelpers.mts new file mode 100644 index 000000000000..0f59ad69583e --- /dev/null +++ b/tasks/changesets/changesetsHelpers.mts @@ -0,0 +1,148 @@ +import { fileURLToPath } from 'node:url' + +import { humanId } from 'human-id' +import { argv, path, fs } from 'zx' + +const ROOT_DIR_PATH = fileURLToPath(new URL('../../', import.meta.url)) +const DIRNAME = path.dirname(fileURLToPath(new URL(import.meta.url))) +const CHANGESETS_DIR = path.join(ROOT_DIR_PATH, '.changesets') + +export function showHelp() { + console.log(`\ +Usage: yarn changesets [prNumber] + + prNumber: A PR number. If provided, the changeset will use the PR's title and body as its placeholder. + + Examples: + yarn changesets # Create a changeset with the default placeholder + yarn changesets 10075 # Create a changeset with PR 10075's title and body +`) +} + +export function getChangesetFilePath(prNumber?: number) { + let changesetId + + if (prNumber) { + changesetId = prNumber + } else { + changesetId = humanId({ + separator: '-', + capitalize: false, + }) + } + + return path.join(CHANGESETS_DIR, `${changesetId}.md`) +} + +export async function getPlaceholder(prNumber?: number) { + if (prNumber) { + return getPrPlaceholderByNumber(prNumber) + } + + return getDefaultPlaceholder() +} + +export function resolveArgv() { + const maybePrNumber = argv._[0] + if (!maybePrNumber) { + return { prNumber: undefined } + } + if (typeof maybePrNumber === 'string' && maybePrNumber.startsWith('#')) { + return { prNumber: +maybePrNumber.replace('#', '') } + } + if (typeof maybePrNumber === 'number') { + return { prNumber: maybePrNumber } + } + + throw new Error(`Invalid PR number: ${maybePrNumber}`) +} + +export function shouldShowHelp() { + return argv.help || argv.h +} + +async function getPrPlaceholderByNumber(prNumber: number) { + const { data, errors } = await fetchFromGitHub({ + query: getPrByNumberQuery, + variables: { prNumber }, + }) + + if (errors) { + throw new Error(`Failed to fetch PR #${prNumber}: ${errors[0].message}`) + } + + const pr = data.repository.pullRequest + return getPlaceholderForPr(pr) +} + +function getDefaultPlaceholder() { + return fs.readFile(path.join(DIRNAME, 'placeholder.md')) +} + +async function fetchFromGitHub({ query, variables }: { query: string; variables: Record }) { + const headers: Record = { + 'Content-Type': 'application/json', + } + if (process.env.GITHUB_TOKEN) { + headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}` + } + if (process.env.REDWOOD_GITHUB_TOKEN) { + headers.Authorization = `Bearer ${process.env.REDWOOD_GITHUB_TOKEN}` + } + + const res = await fetch('https://api.github.com/graphql', { + method: 'POST', + headers, + body: JSON.stringify({ + query, + variables, + }), + }) + + return res.json() +} + +type PR = { + id: string + title: string + number: number + author: { + login: string + } + body: string +} + +const pullRequestFragment = `\ +fragment PullRequestDetails on PullRequest { + id + title + number + author { + login + } + body +} +` + +const getPrByNumberQuery = `\ +${pullRequestFragment} +query ($prNumber: Int!) { + repository(owner: "redwoodjs", name: "redwood") { + pullRequest(number: $prNumber) { + ...PullRequestDetails + } + } +} +` + +function getPlaceholderForPr(pr: PR) { + return [ + "(Delete this help paragraph when you're done.) Thanks for writing a changeset! Here's a place to start.", + "Don't edit the title, but in editing the body, try to explain what this PR means for Redwood users.", + "The more detail the better. E.g., is it a new feature? How do they use it? Code examples go a long way!", + '', + `- ${pr.title} (#${pr.number}) by @${pr.author.login}`, + '', + pr.body, + ].join('\n') +} diff --git a/tasks/changesets/placeholder.md b/tasks/changesets/placeholder.md new file mode 100644 index 000000000000..537da262f025 --- /dev/null +++ b/tasks/changesets/placeholder.md @@ -0,0 +1,7 @@ +- PR title (#PR number) by @PR author + + In writing the body, explain what this PR means for Redwood users. The more detail the better. E.g., is it a new feature? How do they use it? + + ``` + Code examples go a long way! + ``` diff --git a/yarn.lock b/yarn.lock index 569714c45dc9..a5ec8f43ec46 100644 --- a/yarn.lock +++ b/yarn.lock @@ -20843,6 +20843,15 @@ __metadata: languageName: node linkType: hard +"human-id@npm:^4.1.1": + version: 4.1.1 + resolution: "human-id@npm:4.1.1" + bin: + human-id: dist/cli.js + checksum: 10c0/9a9a18130fb7d6bc707054bacc32cb328289be0de47ba5669fd04995435e7e59931b87c644a223d68473c450221d104175a5fefe93d77f3522822ead8945def8 + languageName: node + linkType: hard + "human-signals@npm:^1.1.1": version: 1.1.1 resolution: "human-signals@npm:1.1.1" @@ -29654,6 +29663,7 @@ __metadata: execa: "npm:5.1.1" fast-glob: "npm:3.3.2" fs-extra: "npm:11.2.0" + human-id: "npm:^4.1.1" jest: "npm:29.7.0" jscodeshift: "npm:0.15.0" lerna: "npm:8.0.2"