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
4 changes: 3 additions & 1 deletion .github/actions/release-prep/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ workflow around it, ready to copy into a plugin repository.
Three tools run, in this order, from the root of the checkout:

1. `pup replace-version <version>` rewrites the version in every file `.puprc` lists under
`paths.versions`.
`paths.versions`. When the version has four parts, such as `5.30.3.1`, and `package.json` is one
of those files, `package.json` gets the first three parts, `5.30.3`: npm only takes semver. Every
other file gets all four.
2. `pup replace-tbd <version>` replaces the TBD placeholders (`@since TBD`, `@deprecated TBD`,
`_deprecated_function( __METHOD__, 'TBD' )` and the like) in the directories `.puprc` lists under
`checks.tbd.dirs`.
Expand Down
3 changes: 2 additions & 1 deletion .github/actions/release-prep/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ inputs:
changelogger configures: three or four numeric parts for `stellarwp`, a semver version for
`semver` or no configuration, no shape check for a custom strategy. An empty value and a
version lower than the one the branch already has are refused before anything is changed, and
so is a version the repository has already tagged.
so is a version the repository has already tagged. A four-part version is written to
`package.json` as its first three parts, when `.puprc` lists it as a version file.
required: true
date:
description: >-
Expand Down
60 changes: 56 additions & 4 deletions .github/actions/release-prep/release-prep.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
*/

const { execFileSync } = require('node:child_process')
const fs = require('node:fs')
const path = require('node:path')

// The three-or-four-parts pattern lives with the other version rules, shared with release-merge.
const { compareVersions, STELLARWP_VERSION_PATTERN } = require('../../lib/versions.js')
Expand Down Expand Up @@ -44,6 +46,15 @@ const SEMVER_PATTERN =
/** The numeric start of a version, which is what the branch-version comparison reads. */
const NUMERIC_PREFIX = /^\d+(\.\d+)*/

/** A version with a fourth numeric part, capturing the three parts before it. */
const FOUR_PART_PATTERN = /^(\d+\.\d+\.\d+)\.\d+$/

/**
* The first `"version"` key of a package.json, which is the package's own: the changelogger
* section can declare a `version` change type further down.
*/
const PACKAGE_VERSION_PATTERN = /("version"\s*:\s*")([^"]*)/

/** A calendar date as the changelog writing strategies expect it. */
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/

Expand Down Expand Up @@ -247,8 +258,9 @@ function validateBranch(branch, prefixes = []) {
*
* @throws {Error} When there is no .puprc, it is not JSON, or it declares no version files.
*
* @returns {{tbdDirs: string[]|null}} The directories the TBD check declares, or null when it
* declares none and pup falls back to its default.
* @returns {{tbdDirs: string[]|null, bumpsPackageJson: boolean}} The directories the TBD check
* declares, or null when it declares none and pup falls back to its default; and whether
* package.json is one of the version files.
*/
function readPuprc(text) {
if (text === null) {
Expand Down Expand Up @@ -278,7 +290,43 @@ function readPuprc(text) {

const dirs = config?.checks?.tbd?.dirs

return { tbdDirs: Array.isArray(dirs) ? dirs : null }
return {
tbdDirs: Array.isArray(dirs) ? dirs : null,
bumpsPackageJson: versions.some((entry) => path.normalize(String(entry?.file)) === 'package.json'),
}
}

/**
* Puts package.json back on three parts after pup wrote a four-part version into it.
*
* npm only takes semver, so a build fails on `"version": "5.30.3.1"`. The three parts, not
* `5.30.3+1`: `pup check:version-conflict` cuts a four-part version to its first three parts and
* needs package.json to equal them. Only the first `"version"` key is rewritten, and only when it
* holds the version pup just wrote, so any other package.json is left as it is.
*
* @param {object} options
* @param {object} options.core The @actions/core toolkit, for the log and the summary.
* @param {string} options.cwd The checkout.
* @param {string} options.version The version pup wrote, validated.
*
* @returns {Promise<void>} Resolves once package.json is rewritten, or found not to need it.
*/
async function keepPackageSemver({ core, cwd, version }) {
const semver = FOUR_PART_PATTERN.exec(version)?.[1]
const text = semver ? readCheckoutFile(cwd, 'package.json') : null

if (text === null || PACKAGE_VERSION_PATTERN.exec(text)?.[2] !== version) {
return
}

fs.writeFileSync(
path.join(cwd, 'package.json'),
text.replace(PACKAGE_VERSION_PATTERN, (match, key) => `${key}${semver}`)
)

const message = `package.json keeps ${semver}: npm does not take the four-part ${version}.`
core.info(message)
await core.summary.addRaw(message, true).write()
}

/**
Expand Down Expand Up @@ -488,7 +536,7 @@ async function runPrepare({ github, core, exec, env, cwd = process.cwd(), fetchI
const { owner, repo } = readRepository(env, 'Nothing was changed.')
await refuseTaggedVersion({ github, owner, repo, version })

const { tbdDirs } = readPuprc(readCheckoutFile(cwd, '.puprc'))
const { tbdDirs, bumpsPackageJson } = readPuprc(readCheckoutFile(cwd, '.puprc'))

if (!tbdDirs) {
core.warning(
Expand Down Expand Up @@ -525,6 +573,10 @@ async function runPrepare({ github, core, exec, env, cwd = process.cwd(), fetchI
throw noPharError(pupRelease, 'Nothing was changed.')
}

if (bumpsPackageJson) {
await keepPackageSemver({ core, cwd, version })
}

core.setOutput('version', version)
core.setOutput('date', date)
core.setOutput('branch', branch)
Expand Down
131 changes: 129 additions & 2 deletions tests/actions/release-prep/release-prep.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,38 @@ const PUPRC = {
/** A package.json with a changelogger config, as a repository using the stellarwp format has. */
const PACKAGE_JSON = { changelogger: { versioning: 'stellarwp', changesDir: 'changelog' } }

/** A .puprc that also bumps package.json, as a repository that builds with npm has. */
const PUPRC_WITH_PACKAGE = {
...PUPRC,
paths: { versions: [...PUPRC.paths.versions, { file: 'package.json', regex: '("version": ")([^"]+)' }] },
}

/**
* A package.json holding a version. The changelogger's `version` type comes after the package's own
* version, as it does in a repository that declares its change types.
*
* @param {string} version The package's version.
*
* @returns {string} The file's contents.
*/
function packageWith(version) {
return `{\n\t"name": "plugin",\n\t"version": "${version}",\n\t"changelogger": {\n\t\t"versioning": "stellarwp",\n\t\t"types": {\n\t\t\t"version": "Version"\n\t\t}\n\t}\n}\n`
}

/**
* A rule under which `pup replace-version` writes the version into package.json, as pup does for a
* file under paths.versions.
*
* @returns {object} A rule for recordingExec, to pass to allSucceed.
*/
function pupBumpsPackage() {
return {
command: 'php',
args: /replace-version/,
effect: (args, options) => fs.writeFileSync(path.join(options.cwd, 'package.json'), packageWith(args.at(-1))),
}
}

/** Today in UTC, the way the action resolves an empty or `today` date. */
const TODAY = new Date().toISOString().slice(0, 10)

Expand Down Expand Up @@ -400,13 +432,17 @@ describe('release-prep', () => {

describe('readPuprc', () => {
it('returns the TBD directories the file declares', () => {
assert.deepEqual(readPuprc(JSON.stringify(PUPRC)), { tbdDirs: ['src'] })
assert.deepEqual(readPuprc(JSON.stringify(PUPRC)), { tbdDirs: ['src'], bumpsPackageJson: false })
})

it('returns no TBD directories when the file declares none', () => {
const { checks, ...withoutChecks } = PUPRC

assert.deepEqual(readPuprc(JSON.stringify(withoutChecks)), { tbdDirs: null })
assert.deepEqual(readPuprc(JSON.stringify(withoutChecks)), { tbdDirs: null, bumpsPackageJson: false })
})

it('says whether package.json is one of the version files', () => {
assert.equal(readPuprc(JSON.stringify(PUPRC_WITH_PACKAGE)).bumpsPackageJson, true)
})

it('refuses a missing file, which pup would treat as an empty one', () => {
Expand Down Expand Up @@ -961,6 +997,66 @@ describe('release-prep', () => {
}
})

it('keeps package.json on three parts for a four-part version, and says so', async (t) => {
// npm only takes semver, so a build fails on "version": "5.30.3.1".
const { core, logged, summary } = await coreWithOutputs(t)
const { exec } = recordingExec(allSucceed([pupBumpsPackage()]))
const cwd = checkoutWith({ '.puprc': PUPRC_WITH_PACKAGE, 'package.json': packageWith('5.30.3') })

await prepareUntagged({ core, exec, env: prepareEnv({ INPUT_VERSION: '5.30.3.1' }), cwd })

// Only the first "version" key is the package's: the changelogger type is left alone.
assert.equal(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'), packageWith('5.30.3'))
assert.match(logged(), /package\.json keeps 5\.30\.3: npm does not take the four-part 5\.30\.3\.1/)
assert.match(summary(), /package\.json keeps 5\.30\.3: npm does not take the four-part 5\.30\.3\.1/)
})

it('puts back a package.json the branch already holds on four parts', async (t) => {
const { core } = await coreWithOutputs(t)
const { exec } = recordingExec(allSucceed([pupBumpsPackage()]))
const cwd = checkoutWith({ '.puprc': PUPRC_WITH_PACKAGE, 'package.json': packageWith('5.30.3.1') })

await prepareUntagged({ core, exec, env: prepareEnv({ INPUT_VERSION: '5.30.3.2' }), cwd })

assert.equal(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'), packageWith('5.30.3'))
})

it('leaves package.json to pup for a three-part version', async (t) => {
const { core, logged, summary } = await coreWithOutputs(t)
const { exec } = recordingExec(allSucceed([pupBumpsPackage()]))
const cwd = checkoutWith({ '.puprc': PUPRC_WITH_PACKAGE, 'package.json': packageWith('5.30.3') })

await prepareUntagged({ core, exec, env: prepareEnv({ INPUT_VERSION: '5.31.0' }), cwd })

assert.equal(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'), packageWith('5.31.0'))
assert.doesNotMatch(logged(), /package\.json keeps/)
assert.doesNotMatch(summary(), /package\.json keeps/)
})

it('leaves a package.json that .puprc does not list alone, whatever it holds', async (t) => {
const { core, logged } = await coreWithOutputs(t)
const { exec } = recordingExec(allSucceed())
const cwd = checkoutWith({ '.puprc': PUPRC, 'package.json': packageWith('5.30.3.1') })

await prepareUntagged({ core, exec, env: prepareEnv({ INPUT_VERSION: '5.30.3.1' }), cwd })

assert.equal(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'), packageWith('5.30.3.1'))
assert.doesNotMatch(logged(), /package\.json keeps/)
})

it('leaves a package.json alone when its first version key does not hold the version', async (t) => {
// A package.json with no version of its own: the first "version" key is the changelogger type.
const { core, logged } = await coreWithOutputs(t)
const { exec } = recordingExec(allSucceed())
const contents = JSON.stringify({ changelogger: { versioning: 'stellarwp', types: { version: 'Version' } } })
const cwd = checkoutWith({ '.puprc': PUPRC_WITH_PACKAGE, 'package.json': contents })

await prepareUntagged({ core, exec, env: prepareEnv({ INPUT_VERSION: '5.30.3.1' }), cwd })

assert.equal(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'), contents)
assert.doesNotMatch(logged(), /package\.json keeps/)
})

it('fails with pup output when pup fails, and stops there', async (t) => {
const { core, outputs } = await coreWithOutputs(t)
const { exec, calls } = recordingExec(
Expand Down Expand Up @@ -1232,6 +1328,37 @@ describe('release-prep', () => {
assert.equal(git(work, 'rev-parse', 'HEAD'), head, 'the checkout itself stays where it was')
})

it('commits package.json on three parts and every other version file on four', async (t) => {
const { core } = await coreWithOutputs(t)
const { github, requests } = await octokitFor(apiAccepts())
const work = checkoutOn('release/M26.jigglypuff')
fs.writeFileSync(path.join(work, '.puprc'), JSON.stringify(PUPRC_WITH_PACKAGE))
fs.writeFileSync(path.join(work, 'package.json'), packageWith('5.30.2'))
git(work, 'add', '-A')
git(work, 'commit', '--quiet', '-m', 'Add package.json')
// pup stands in: it writes the four-part version into both version files.
const pup = recordingExec(
allSucceed([
{
...pupBumpsPackage(),
effect: (args, options) => {
pupBumpsPackage().effect(args, options)
fs.writeFileSync(path.join(options.cwd, 'plugin.php'), `Version: ${args.at(-1)}\n`)
},
},
])
)

await runPrepare({ github, core, exec: pup.exec, env: prepareEnv({ INPUT_VERSION: '5.30.3.1' }), cwd: work })
const { exec } = await recordedRealExec()
await runCommit({ github, core, exec, env: commitEnv({ INPUT_VERSION: '5.30.3.1' }), cwd: work })

const uploaded = requests
.filter((request) => request.path === API.blobs)
.map((request) => Buffer.from(request.body.content, 'base64').toString())
assert.deepEqual(uploaded, [packageWith('5.30.3'), 'Version: 5.30.3.1\n'])
})

it('uploads the staged content, not the file on disk', async (t) => {
// .gitattributes normalization (here CRLF to LF) makes the staged blob differ from what is
// on the disk; the commit has to carry what git staged.
Expand Down
Loading