Verify releases on isolated release branches and harden shipping (#10396)
* chore(release): verify releases on isolated release branches and harden shipping High-traffic merges on main cancel more than half of main CI runs, so waiting on main CI repeatedly stalls releases. Releases also ran duplicate post-tag CI, lacked a release-branch Desktop Packages trigger, hit unretried Apple notarytool polling errors and a finalize-rollout directory bug on macOS retries, and relied on a non-idempotent npm publish chain and conflict-prone reconcile cherry-picks. This splits release execution into release:prep:* (reversible version commit without tagging, pushed once to release/** for isolated CI + Desktop Packages) and release:ship[:beta] (idempotent npm publishing with retry, propagation checks, automatic beta dist-tag sync on stable, and release/*-only tag push), adds conflict-free main reconciliation, and extends macOS xcrun retries to notarytool submit and wait. * fix(release): address review findings on Docker retries, tag push, and reconciliation Isolate manual Docker publish dispatches in their own non-cancelling concurrency group, verify HEAD matches origin/<release-branch> before release:ship publishes or tags (and remove one-shot combined scripts that bypassed release-branch checks), drop --refs from peeled annotated-tag lookups in push-current-release-tag.mjs, retry lockfile sync in reconcile-release.mjs when package-lock.json version lags package.json, and document cutting from pre-existing tags. * fix(release): preserve TTY OTP prompts in npm publish and keep newer beta changelogs Inherit TTY stdin/stdout for interactive npm publish and dist-tag add (plus --otp passthrough) while keeping stderr piped for retry classification, and keep newer beta or promoted stable changelog entries intact when an older beta tag is reconciled.
This commit is contained in:
1 parent
d816b94c54
commit
01aa8b3406
18 files changed
+1960
-265
No files matched your search
+267
-63
@@ -7,6 +7,8 @@ import { relative as relativePath } from "node:path";
|
||||
import test from "node:test";
|
||||
import { runInNewContext } from "node:vm";
|
||||
|
||||
import { PUBLISH_WORKSPACES } from "./publish-release-packages.mjs";
|
||||
|
||||
const repoRoot = new URL("../", import.meta.url);
|
||||
const ciWorkflowPath = new URL(".github/workflows/ci.yml", repoRoot);
|
||||
const dockerWorkflowPath = new URL(".github/workflows/docker.yml", repoRoot);
|
||||
@@ -142,8 +144,8 @@ test("change gating allows superseded workflow runs to cancel", () => {
|
||||
|
||||
test("published npm packages declare and ship the repository license", () => {
|
||||
const rootManifest = JSON.parse(readFileSync(new URL("package.json", repoRoot), "utf8"));
|
||||
const workspaceArgs = rootManifest.scripts["release:publish"].match(/--workspace=\S+/g);
|
||||
assert.notEqual(workspaceArgs, null, "release:publish must select public packages");
|
||||
assert.match(rootManifest.scripts["release:publish"], /scripts\/publish-release-packages\.mjs/);
|
||||
const workspaceArgs = PUBLISH_WORKSPACES.map((workspace) => `--workspace=${workspace}`);
|
||||
const packed = JSON.parse(
|
||||
execFileSync("npm", ["pack", "--dry-run", "--ignore-scripts", "--json", ...workspaceArgs], {
|
||||
cwd: repoRoot,
|
||||
@@ -164,8 +166,8 @@ test("published npm packages declare and ship the repository license", () => {
|
||||
}));
|
||||
assert.deepEqual(
|
||||
licenses,
|
||||
workspaceArgs.map((workspace) => ({
|
||||
name: workspace.slice("--workspace=".length),
|
||||
PUBLISH_WORKSPACES.map((workspace) => ({
|
||||
name: workspace,
|
||||
license: "Apache-2.0",
|
||||
files: ["LICENSE"],
|
||||
})),
|
||||
@@ -365,14 +367,32 @@ test("packaging runs on main without allocating pull-request runners", () => {
|
||||
assert.doesNotMatch(trigger, /pull_request/);
|
||||
assert.doesNotMatch(source, /dorny\/paths-filter/);
|
||||
}
|
||||
const docker = readFileSync(dockerWorkflowPath, "utf8");
|
||||
assert.match(
|
||||
docker,
|
||||
/group: docker-\$\{\{ github\.workflow \}\}-\$\{\{ github\.event_name == 'workflow_dispatch' && inputs\.publish == 'true' && format\('publish-\{0\}', inputs\.paseo_version \|\| github\.run_id\) \|\| github\.ref \}\}/,
|
||||
"manual Docker release retries use their own concurrency group so main pushes never cancel them",
|
||||
);
|
||||
assert.match(
|
||||
docker,
|
||||
/cancel-in-progress: \$\{\{ !startsWith\(github\.ref, 'refs\/tags\/'\) && !\(github\.event_name == 'workflow_dispatch' && inputs\.publish == 'true'\) \}\}/,
|
||||
"Docker cancels superseded non-tag main checks while preserving tag and manual publish runs",
|
||||
);
|
||||
const nix = readFileSync(nixWorkflowPath, "utf8");
|
||||
assert.match(nix.split("jobs:", 1)[0], /^\s+workflow_dispatch:/m);
|
||||
});
|
||||
|
||||
test("desktop packaging smokes main pushes and only the pull requests that touch packaging", () => {
|
||||
test("CI and desktop packaging verify release branches isolated from main traffic", () => {
|
||||
const ciTrigger = readFileSync(ciWorkflowPath, "utf8").split("jobs:", 1)[0];
|
||||
assert.match(ciTrigger, /push:\s*\n\s+branches: \[main, "release\/\*\*"\]/);
|
||||
|
||||
const source = readFileSync(new URL(".github/workflows/desktop-packages.yml", repoRoot), "utf8");
|
||||
const trigger = source.split("jobs:", 1)[0];
|
||||
assert.match(trigger, /push:\s*\n\s+branches: \[main\]/);
|
||||
assert.match(trigger, /push:\s*\n\s+branches: \[main, "release\/\*\*"\]/);
|
||||
assert.match(trigger, /^\s+workflow_dispatch:/m);
|
||||
assert.match(trigger, /pull_request:\s*\n\s+paths:/);
|
||||
assert.match(trigger, /- "packages\/desktop\/\*\*"/);
|
||||
assert.match(trigger, /^\s+cancel-in-progress: true$/m);
|
||||
assert.doesNotMatch(source, /dorny\/paths-filter/);
|
||||
for (const action of ["actions/checkout", "actions/setup-node", "actions/upload-artifact"]) {
|
||||
assert.match(source, new RegExp(`${action}@[0-9a-f]{40} # v\\d+\\.\\d+\\.\\d+`));
|
||||
@@ -582,107 +602,291 @@ test("Windows units and integration run independently with complete routed cover
|
||||
}
|
||||
});
|
||||
|
||||
test("macOS release retries only transient stapling failures without rebuilding the signed app", async (t) => {
|
||||
test("desktop release creates release-manifests before entering it and uses the xcrun retry script", () => {
|
||||
const workflow = readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8");
|
||||
const wrapper = workflow
|
||||
.match(/<<'STAPLER'\n([\s\S]*?)\n STAPLER/)[1]
|
||||
.replace(/^ /gm, "");
|
||||
const networkError =
|
||||
assert.match(workflow, /scripts\/macos-xcrun-retry\.sh/);
|
||||
assert.match(workflow, /mkdir -p release-manifests\s*\n\s+cd release-manifests/);
|
||||
});
|
||||
|
||||
test("macOS release xcrun wrapper retries transient stapling and notarization failures without rebuilding", async (t) => {
|
||||
const wrapperSource = readFileSync(new URL("scripts/macos-xcrun-retry.sh", repoRoot), "utf8");
|
||||
const networkLostError =
|
||||
'Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."';
|
||||
const notaryTimeoutWithId =
|
||||
'Error: HTTPError(statusCode: nil, error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=https://appstoreconnect.apple.com/notary/v2/submissions/ee2872f3-65d9-49f7-b2b5-adcdfe2db6ba?})';
|
||||
const notaryOfflineWithId =
|
||||
'Error: HTTPError(statusCode: nil, error: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSErrorFailingURLStringKey=https://appstoreconnect.apple.com/notary/v2/submissions/ee2872f3-65d9-49f7-b2b5-adcdfe2db6ba?})';
|
||||
const notaryUploadTimeout =
|
||||
'Error: HTTPError(statusCode: nil, error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out.")';
|
||||
const acceptedJson = JSON.stringify({
|
||||
id: "ee2872f3-65d9-49f7-b2b5-adcdfe2db6ba",
|
||||
message: "Successfully received submission info",
|
||||
status: "Accepted",
|
||||
});
|
||||
const invalidJson = JSON.stringify({
|
||||
id: "ee2872f3-65d9-49f7-b2b5-adcdfe2db6ba",
|
||||
message: "Submission invalid",
|
||||
status: "Invalid",
|
||||
});
|
||||
|
||||
const cases = [
|
||||
{
|
||||
name: "success",
|
||||
outcomes: [0],
|
||||
output: "stapled",
|
||||
command: "stapler",
|
||||
name: "stapler success",
|
||||
steps: [{ code: 0, output: "stapled" }],
|
||||
args: ["stapler", "staple", "-v", "Paseo signed.app"],
|
||||
expected: 0,
|
||||
attempts: 1,
|
||||
expectedCalls: [["stapler", "staple", "-v", "Paseo signed.app"]],
|
||||
expectPattern: /stapled/,
|
||||
},
|
||||
{
|
||||
name: "transient then success",
|
||||
outcomes: [68, 0],
|
||||
output: networkError,
|
||||
command: "stapler",
|
||||
name: "stapler transient then success",
|
||||
steps: [
|
||||
{ code: 68, output: networkLostError },
|
||||
{ code: 0, output: "stapled" },
|
||||
],
|
||||
args: ["stapler", "staple", "-v", "Paseo signed.app"],
|
||||
expected: 0,
|
||||
attempts: 2,
|
||||
expectedCalls: [
|
||||
["stapler", "staple", "-v", "Paseo signed.app"],
|
||||
["stapler", "staple", "-v", "Paseo signed.app"],
|
||||
],
|
||||
expectPattern: /stapled/,
|
||||
},
|
||||
{
|
||||
name: "exhausted network retries",
|
||||
outcomes: [68, 68, 68, 68, 0],
|
||||
output: networkError,
|
||||
command: "stapler",
|
||||
name: "stapler exhausted network retries",
|
||||
steps: [
|
||||
{ code: 68, output: networkLostError },
|
||||
{ code: 68, output: networkLostError },
|
||||
{ code: 68, output: networkLostError },
|
||||
{ code: 68, output: networkLostError },
|
||||
],
|
||||
args: ["stapler", "staple", "-v", "Paseo signed.app"],
|
||||
expected: 68,
|
||||
attempts: 4,
|
||||
expectedCalls: Array.from({ length: 4 }, () => [
|
||||
"stapler",
|
||||
"staple",
|
||||
"-v",
|
||||
"Paseo signed.app",
|
||||
]),
|
||||
expectPattern: /network connection was lost/,
|
||||
},
|
||||
{
|
||||
name: "non-network staple error",
|
||||
outcomes: [68, 0],
|
||||
output: "ticket not found",
|
||||
command: "stapler",
|
||||
name: "stapler non-network error is not retried",
|
||||
steps: [{ code: 68, output: "ticket not found" }],
|
||||
args: ["stapler", "staple", "-v", "Paseo signed.app"],
|
||||
expected: 68,
|
||||
attempts: 1,
|
||||
expectedCalls: [["stapler", "staple", "-v", "Paseo signed.app"]],
|
||||
expectPattern: /ticket not found/,
|
||||
},
|
||||
{
|
||||
name: "different exit code",
|
||||
outcomes: [1, 0],
|
||||
output: networkError,
|
||||
command: "stapler",
|
||||
name: "notarytool switches to wait when polling fails after upload and emits clean JSON",
|
||||
steps: [
|
||||
{ code: 1, output: notaryTimeoutWithId },
|
||||
{ code: 1, output: notaryOfflineWithId },
|
||||
{ code: 0, output: acceptedJson },
|
||||
],
|
||||
args: [
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--password",
|
||||
"pw",
|
||||
"--team-id",
|
||||
"team",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
expected: 0,
|
||||
expectedCalls: [
|
||||
[
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--password",
|
||||
"pw",
|
||||
"--team-id",
|
||||
"team",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
[
|
||||
"notarytool",
|
||||
"wait",
|
||||
"ee2872f3-65d9-49f7-b2b5-adcdfe2db6ba",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--password",
|
||||
"pw",
|
||||
"--team-id",
|
||||
"team",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
[
|
||||
"notarytool",
|
||||
"wait",
|
||||
"ee2872f3-65d9-49f7-b2b5-adcdfe2db6ba",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--password",
|
||||
"pw",
|
||||
"--team-id",
|
||||
"team",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
],
|
||||
expectCleanJson: true,
|
||||
},
|
||||
{
|
||||
name: "notarytool retries submit when upload fails before submission ID exists",
|
||||
steps: [
|
||||
{ code: 1, output: notaryUploadTimeout },
|
||||
{ code: 0, output: acceptedJson },
|
||||
],
|
||||
args: [
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
expected: 0,
|
||||
expectedCalls: [
|
||||
[
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
[
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
],
|
||||
expectCleanJson: true,
|
||||
},
|
||||
{
|
||||
name: "notarytool deterministic Invalid rejection is never retried",
|
||||
steps: [{ code: 0, output: invalidJson }],
|
||||
args: [
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
expected: 0,
|
||||
expectedCalls: [
|
||||
[
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
],
|
||||
expectCleanJson: true,
|
||||
},
|
||||
{
|
||||
name: "notarytool bad credentials error is never retried",
|
||||
steps: [{ code: 1, output: "Error: HTTP status code: 401. Invalid credentials." }],
|
||||
args: [
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
expected: 1,
|
||||
attempts: 1,
|
||||
},
|
||||
{
|
||||
name: "notary submission is not retried",
|
||||
outcomes: [68, 0],
|
||||
output: networkError,
|
||||
command: "notarytool",
|
||||
expected: 68,
|
||||
attempts: 1,
|
||||
expectedCalls: [
|
||||
[
|
||||
"notarytool",
|
||||
"submit",
|
||||
"/tmp/Paseo.zip",
|
||||
"--apple-id",
|
||||
"id",
|
||||
"--wait",
|
||||
"--output-format",
|
||||
"json",
|
||||
],
|
||||
],
|
||||
expectPattern: /Invalid credentials/,
|
||||
},
|
||||
];
|
||||
for (const scenario of cases) {
|
||||
await t.test(scenario.name, () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "stapler-retry-"));
|
||||
const directory = mkdtempSync(join(tmpdir(), "xcrun-retry-"));
|
||||
try {
|
||||
const statePath = join(directory, "state.json");
|
||||
const realXcrun = join(directory, "real-xcrun");
|
||||
const wrapperPath = join(directory, "xcrun");
|
||||
writeFileSync(wrapperPath, wrapper, { mode: 0o755 });
|
||||
writeFileSync(wrapperPath, wrapperSource, { mode: 0o755 });
|
||||
writeFileSync(join(directory, "sleep"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
|
||||
writeFileSync(
|
||||
statePath,
|
||||
JSON.stringify({ outcomes: scenario.outcomes, output: scenario.output, calls: [] }),
|
||||
);
|
||||
writeFileSync(statePath, JSON.stringify({ steps: scenario.steps, calls: [] }));
|
||||
writeFileSync(
|
||||
realXcrun,
|
||||
`#!/usr/bin/env node
|
||||
const fs = require("node:fs");
|
||||
const state = JSON.parse(fs.readFileSync(process.env.STAPLER_STATE, "utf8"));
|
||||
const state = JSON.parse(fs.readFileSync(process.env.XCRUN_STATE, "utf8"));
|
||||
state.calls.push(process.argv.slice(2));
|
||||
const code = state.outcomes.shift();
|
||||
fs.writeFileSync(process.env.STAPLER_STATE, JSON.stringify(state));
|
||||
console.log(state.output);
|
||||
process.exit(code);
|
||||
const next = state.steps.shift();
|
||||
fs.writeFileSync(process.env.XCRUN_STATE, JSON.stringify(state));
|
||||
if (!next) process.exit(99);
|
||||
process.stdout.write(next.output + "\\n");
|
||||
process.exit(next.code);
|
||||
`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
const args = [scenario.command, "staple", "-v", "Paseo signed.app"];
|
||||
const result = spawnSync("bash", [wrapperPath, ...args], {
|
||||
const result = spawnSync("bash", [wrapperPath, ...scenario.args], {
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
PASEO_REAL_XCRUN: realXcrun,
|
||||
STAPLER_STATE: statePath,
|
||||
XCRUN_STATE: statePath,
|
||||
PATH: `${directory}:${process.env.PATH}`,
|
||||
},
|
||||
timeout: 5000,
|
||||
});
|
||||
assert.equal(result.status, scenario.expected, result.stdout + result.stderr);
|
||||
const state = JSON.parse(readFileSync(statePath, "utf8"));
|
||||
assert.deepEqual(
|
||||
state.calls,
|
||||
Array.from({ length: scenario.attempts }, () => args),
|
||||
);
|
||||
assert.match(result.stdout, /stapled|network connection was lost|ticket not found/);
|
||||
assert.deepEqual(state.calls, scenario.expectedCalls);
|
||||
if (scenario.expectCleanJson) {
|
||||
// @electron/notarize merges stdout and stderr before calling JSON.parse.
|
||||
const parsed = JSON.parse((result.stdout + result.stderr).trim());
|
||||
assert.equal(parsed.id, "ee2872f3-65d9-49f7-b2b5-adcdfe2db6ba");
|
||||
}
|
||||
if (scenario.expectPattern) {
|
||||
assert.match(result.stdout + result.stderr, scenario.expectPattern);
|
||||
}
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
Executable
+139
@@ -0,0 +1,139 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
# Retries transient Apple network errors for `xcrun stapler staple` and
|
||||
# `xcrun notarytool submit` without rebuilding the signed macOS app.
|
||||
# Compatible with macOS's default bash 3.2.
|
||||
|
||||
real_xcrun="${PASEO_REAL_XCRUN:?PASEO_REAL_XCRUN must point to the real xcrun binary}"
|
||||
|
||||
is_transient_apple_network_error() {
|
||||
local file="$1"
|
||||
grep -Eq \
|
||||
'NSURLErrorDomain|HTTPError\(statusCode: nil|HTTPError\(statusCode: Optional\(5[0-9][0-9]\)|HTTP status code: 5[0-9][0-9]' \
|
||||
"$file"
|
||||
}
|
||||
|
||||
extract_submission_id() {
|
||||
local file="$1"
|
||||
local match
|
||||
match="$(grep -Eo '/notary/v2/submissions/[0-9a-fA-F-]{36}' "$file" | head -n 1 || true)"
|
||||
if [[ -n "$match" ]]; then
|
||||
printf '%s\n' "${match##*/}"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
run_stapler_with_retry() {
|
||||
local output
|
||||
output="$(mktemp)"
|
||||
trap 'rm -f "$output"' RETURN
|
||||
|
||||
local attempt status
|
||||
for attempt in 1 2 3 4; do
|
||||
if "$real_xcrun" "$@" >"$output" 2>&1; then
|
||||
cat "$output"
|
||||
return 0
|
||||
else
|
||||
status=$?
|
||||
fi
|
||||
cat "$output"
|
||||
if [[ "$status" != 68 || "$attempt" == 4 ]] || ! is_transient_apple_network_error "$output"; then
|
||||
return "$status"
|
||||
fi
|
||||
echo "::warning::Apple staple connection lost; retrying the same signed app ($attempt/4)" >&2
|
||||
sleep 30
|
||||
done
|
||||
}
|
||||
|
||||
run_notarytool_submit_with_retry() {
|
||||
# @electron/notarize merges stdout and stderr before calling JSON.parse, so
|
||||
# keep retry attempts silent and emit only the final attempt's output.
|
||||
local output
|
||||
output="$(mktemp)"
|
||||
trap 'rm -f "$output"' RETURN
|
||||
|
||||
local has_wait=false
|
||||
local skipped_file=false
|
||||
local wait_args=()
|
||||
local arg
|
||||
local idx=0
|
||||
for arg in "$@"; do
|
||||
idx=$((idx + 1))
|
||||
if (( idx <= 2 )); then
|
||||
continue
|
||||
fi
|
||||
if [[ "$arg" == "--wait" ]]; then
|
||||
has_wait=true
|
||||
continue
|
||||
fi
|
||||
if [[ "$skipped_file" == false && "$arg" != -* ]]; then
|
||||
skipped_file=true
|
||||
continue
|
||||
fi
|
||||
wait_args+=("$arg")
|
||||
done
|
||||
|
||||
local attempt status submission_id=""
|
||||
for attempt in 1 2 3; do
|
||||
if "$real_xcrun" "$@" >"$output" 2>&1; then
|
||||
cat "$output"
|
||||
return 0
|
||||
else
|
||||
status=$?
|
||||
fi
|
||||
|
||||
if ! is_transient_apple_network_error "$output"; then
|
||||
cat "$output"
|
||||
return "$status"
|
||||
fi
|
||||
|
||||
if [[ "$has_wait" == true ]]; then
|
||||
submission_id="$(extract_submission_id "$output" || true)"
|
||||
if [[ -n "$submission_id" ]]; then
|
||||
break
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "$attempt" == 3 ]]; then
|
||||
cat "$output"
|
||||
return "$status"
|
||||
fi
|
||||
|
||||
sleep 30
|
||||
done
|
||||
|
||||
if [[ -n "$submission_id" ]]; then
|
||||
local wait_attempt
|
||||
for wait_attempt in 1 2 3 4 5 6; do
|
||||
sleep 30
|
||||
if "$real_xcrun" notarytool wait "$submission_id" "${wait_args[@]}" >"$output" 2>&1; then
|
||||
cat "$output"
|
||||
return 0
|
||||
else
|
||||
status=$?
|
||||
fi
|
||||
|
||||
if [[ "$wait_attempt" == 6 ]] || ! is_transient_apple_network_error "$output"; then
|
||||
cat "$output"
|
||||
return "$status"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
cat "$output"
|
||||
return "${status:-1}"
|
||||
}
|
||||
|
||||
if [[ "${1:-}" == "stapler" && "${2:-}" == "staple" ]]; then
|
||||
run_stapler_with_retry "$@"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
if [[ "${1:-}" == "notarytool" && "${2:-}" == "submit" ]]; then
|
||||
run_notarytool_submit_with_retry "$@"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
exec "$real_xcrun" "$@"
|
||||
@@ -0,0 +1,287 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { isMainModule } from "./is-main-module.mjs";
|
||||
import { compareReleaseVersions, parseReleaseVersion } from "./release-version-utils.mjs";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = path.resolve(__dirname, "..");
|
||||
|
||||
export const PUBLISH_WORKSPACES = [
|
||||
"@getpaseo/highlight",
|
||||
"@getpaseo/relay",
|
||||
"@getpaseo/protocol",
|
||||
"@getpaseo/client",
|
||||
"@getpaseo/plugin",
|
||||
"@getpaseo/server",
|
||||
"@getpaseo/cli",
|
||||
];
|
||||
|
||||
const PUBLISH_ATTEMPTS = 4;
|
||||
const PUBLISH_BACKOFF_MS = 15_000;
|
||||
const VISIBILITY_ATTEMPTS = 12;
|
||||
const VISIBILITY_POLL_MS = 5_000;
|
||||
const VIEW_ATTEMPTS = 3;
|
||||
|
||||
function usageAndExit(code = 1) {
|
||||
process.stderr.write(
|
||||
"Usage: node scripts/publish-release-packages.mjs [--beta] [--dry-run] [--otp <code>]\n",
|
||||
);
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = { beta: false, dryRun: false, otp: "" };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--beta") {
|
||||
args.beta = true;
|
||||
} else if (arg === "--dry-run") {
|
||||
args.dryRun = true;
|
||||
} else if (arg === "--otp") {
|
||||
args.otp = argv[index + 1] ?? "";
|
||||
if (!args.otp) {
|
||||
usageAndExit(1);
|
||||
}
|
||||
index += 1;
|
||||
} else if (arg === "--help" || arg === "-h") {
|
||||
usageAndExit(0);
|
||||
} else {
|
||||
usageAndExit(1);
|
||||
}
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
export function getNpmStdio({
|
||||
interactive = false,
|
||||
stdinIsTTY = Boolean(process.stdin.isTTY),
|
||||
stdoutIsTTY = Boolean(process.stdout.isTTY),
|
||||
} = {}) {
|
||||
// npm's OTP helper prompts only when both stdin and stdout are TTYs; keep
|
||||
// stderr piped so transient registry errors can still be classified for retry.
|
||||
if (interactive && stdinIsTTY && stdoutIsTTY) {
|
||||
return ["inherit", "inherit", "pipe"];
|
||||
}
|
||||
return ["ignore", "pipe", "pipe"];
|
||||
}
|
||||
|
||||
function defaultRunNpm(args, options = {}) {
|
||||
const command = process.platform === "win32" ? "npm.cmd" : "npm";
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: rootDir,
|
||||
encoding: "utf8",
|
||||
shell: process.platform === "win32",
|
||||
stdio: getNpmStdio(options),
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
return { status: 1, stdout: "", stderr: result.error.message };
|
||||
}
|
||||
|
||||
return {
|
||||
status: result.status ?? 1,
|
||||
stdout: result.stdout ?? "",
|
||||
stderr: result.stderr ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function defaultSleep(delayMs) {
|
||||
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
|
||||
function outputOf(result) {
|
||||
return `${result.stdout ?? ""}\n${result.stderr ?? ""}`.trim();
|
||||
}
|
||||
|
||||
function isNotFoundOutput(text) {
|
||||
return /\bE404\b|404 Not Found|is not in this registry/i.test(text);
|
||||
}
|
||||
|
||||
function isAlreadyPublishedConflict(text) {
|
||||
return /EPUBLISHCONFLICT|cannot publish over the previously published versions/i.test(text);
|
||||
}
|
||||
|
||||
function isTransientNpmError(text) {
|
||||
return /\b(E429|E500|E502|E503|E504|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENOTFOUND|ESOCKETTIMEDOUT|FETCH_ERROR)\b|\b(429|500|502|503|504)\b|socket hang up|network timeout/i.test(
|
||||
text,
|
||||
);
|
||||
}
|
||||
|
||||
async function isPackageVersionPublished(pkg, version, { runNpm, sleep }) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
for (let attempt = 1; attempt <= VIEW_ATTEMPTS; attempt += 1) {
|
||||
const result = runNpm(["view", spec, "version", "--json"]);
|
||||
if (result.status === 0) {
|
||||
try {
|
||||
const parsed = JSON.parse(result.stdout.trim());
|
||||
if (parsed === version || (Array.isArray(parsed) && parsed.includes(version))) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
if (result.stdout.trim() === version) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const combined = outputOf(result);
|
||||
if (isNotFoundOutput(combined)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (attempt < VIEW_ATTEMPTS && isTransientNpmError(combined)) {
|
||||
await sleep(attempt * 5_000);
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new Error(`Failed checking whether ${spec} is published:\n${combined}`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function waitForPackageVisibility(pkg, version, { runNpm, sleep }) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
for (let attempt = 1; attempt <= VISIBILITY_ATTEMPTS; attempt += 1) {
|
||||
if (await isPackageVersionPublished(pkg, version, { runNpm, sleep })) {
|
||||
return;
|
||||
}
|
||||
if (attempt < VISIBILITY_ATTEMPTS) {
|
||||
console.log(`Waiting for ${spec} to appear on npm (${attempt}/${VISIBILITY_ATTEMPTS})...`);
|
||||
await sleep(VISIBILITY_POLL_MS);
|
||||
}
|
||||
}
|
||||
throw new Error(`${spec} did not become visible on npm after ${VISIBILITY_ATTEMPTS} checks.`);
|
||||
}
|
||||
|
||||
async function publishOnePackage(pkg, version, { beta, dryRun, otp }, { runNpm, sleep }) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
if (!dryRun && (await isPackageVersionPublished(pkg, version, { runNpm, sleep }))) {
|
||||
console.log(`Already published ${spec}; skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const args = ["publish", `--workspace=${pkg}`, "--access", "public"];
|
||||
if (beta) {
|
||||
args.push("--tag", "beta");
|
||||
}
|
||||
if (dryRun) {
|
||||
args.push("--dry-run");
|
||||
}
|
||||
if (otp) {
|
||||
args.push(`--otp=${otp}`);
|
||||
}
|
||||
|
||||
for (let attempt = 1; attempt <= PUBLISH_ATTEMPTS; attempt += 1) {
|
||||
const result = runNpm(args, { interactive: !dryRun });
|
||||
if (result.status === 0) {
|
||||
if (result.stdout) {
|
||||
process.stdout.write(result.stdout);
|
||||
}
|
||||
if (!dryRun) {
|
||||
await waitForPackageVisibility(pkg, version, { runNpm, sleep });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const combined = outputOf(result);
|
||||
if (!dryRun && isAlreadyPublishedConflict(combined)) {
|
||||
await waitForPackageVisibility(pkg, version, { runNpm, sleep });
|
||||
console.log(`Confirmed ${spec} is published after conflict response.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempt < PUBLISH_ATTEMPTS && isTransientNpmError(combined)) {
|
||||
const delayMs = attempt * PUBLISH_BACKOFF_MS;
|
||||
console.warn(
|
||||
`Publishing ${spec} failed transiently; retrying in ${delayMs / 1000}s (${attempt + 1}/${PUBLISH_ATTEMPTS})`,
|
||||
);
|
||||
await sleep(delayMs);
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new Error(`Failed to publish ${spec}:\n${combined}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function syncBetaDistTags(version, { otp }, { runNpm, sleep }) {
|
||||
let distTags = {};
|
||||
for (let attempt = 1; attempt <= VIEW_ATTEMPTS; attempt += 1) {
|
||||
const result = runNpm(["view", "@getpaseo/cli", "dist-tags", "--json"]);
|
||||
if (result.status === 0) {
|
||||
distTags = JSON.parse(result.stdout.trim());
|
||||
break;
|
||||
}
|
||||
const combined = outputOf(result);
|
||||
if (attempt < VIEW_ATTEMPTS && isTransientNpmError(combined)) {
|
||||
await sleep(attempt * 5_000);
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Failed to read @getpaseo/cli dist-tags:\n${combined}`);
|
||||
}
|
||||
|
||||
const currentBeta = typeof distTags.beta === "string" ? distTags.beta.trim() : "";
|
||||
if (currentBeta && compareReleaseVersions(version, currentBeta) <= 0) {
|
||||
console.log(`Leaving npm beta dist-tag at ${currentBeta} (newer than or equal to ${version}).`);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const pkg of PUBLISH_WORKSPACES) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
const distTagArgs = ["dist-tag", "add", spec, "beta"];
|
||||
if (otp) {
|
||||
distTagArgs.push(`--otp=${otp}`);
|
||||
}
|
||||
for (let attempt = 1; attempt <= PUBLISH_ATTEMPTS; attempt += 1) {
|
||||
const result = runNpm(distTagArgs, { interactive: true });
|
||||
if (result.status === 0) {
|
||||
break;
|
||||
}
|
||||
const combined = outputOf(result);
|
||||
if (attempt < PUBLISH_ATTEMPTS && isTransientNpmError(combined)) {
|
||||
await sleep(attempt * PUBLISH_BACKOFF_MS);
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Failed to move beta dist-tag for ${spec}:\n${combined}`);
|
||||
}
|
||||
}
|
||||
console.log(`Moved npm beta dist-tag to ${version} across all published packages.`);
|
||||
}
|
||||
|
||||
export async function publishReleasePackages(options = {}, deps = {}) {
|
||||
const runNpm = deps.runNpm ?? defaultRunNpm;
|
||||
const sleep = deps.sleep ?? defaultSleep;
|
||||
const beta = Boolean(options.beta);
|
||||
const dryRun = Boolean(options.dryRun);
|
||||
const otp = typeof options.otp === "string" ? options.otp.trim() : "";
|
||||
const version =
|
||||
options.version ?? JSON.parse(readFileSync(path.join(rootDir, "package.json"), "utf8")).version;
|
||||
|
||||
const parsed = parseReleaseVersion(version);
|
||||
if (parsed.isPrerelease && !beta) {
|
||||
throw new Error(
|
||||
`Refusing to publish prerelease version ${version} to latest. Pass --beta instead.`,
|
||||
);
|
||||
}
|
||||
if (!parsed.isPrerelease && beta) {
|
||||
throw new Error(
|
||||
`Refusing to publish stable version ${version} with --beta. Omit --beta for stable releases.`,
|
||||
);
|
||||
}
|
||||
|
||||
for (const pkg of PUBLISH_WORKSPACES) {
|
||||
await publishOnePackage(pkg, version, { beta, dryRun, otp }, { runNpm, sleep });
|
||||
}
|
||||
|
||||
if (!beta && !dryRun) {
|
||||
await syncBetaDistTags(version, { otp }, { runNpm, sleep });
|
||||
}
|
||||
}
|
||||
|
||||
if (isMainModule(import.meta.url)) {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
await publishReleasePackages(args);
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
PUBLISH_WORKSPACES,
|
||||
getNpmStdio,
|
||||
publishReleasePackages,
|
||||
} from "./publish-release-packages.mjs";
|
||||
|
||||
const noSleep = () => Promise.resolve();
|
||||
|
||||
function ok(stdout = "") {
|
||||
return { status: 0, stdout, stderr: "" };
|
||||
}
|
||||
|
||||
function fail(stderr = "", status = 1, stdout = "") {
|
||||
return { status, stdout, stderr };
|
||||
}
|
||||
|
||||
test("publishes all workspaces in dependency order, waits for propagation, and advances beta dist-tag on stable", async () => {
|
||||
const calls = [];
|
||||
const published = new Set();
|
||||
|
||||
await publishReleasePackages(
|
||||
{ version: "0.17.0", beta: false, dryRun: false },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
calls.push(args);
|
||||
if (args[0] === "view" && args[2] === "version") {
|
||||
const spec = args[1];
|
||||
return published.has(spec) ? ok(JSON.stringify("0.17.0")) : fail("npm error code E404");
|
||||
}
|
||||
if (args[0] === "publish") {
|
||||
const pkg = args
|
||||
.find((arg) => arg.startsWith("--workspace="))
|
||||
.slice("--workspace=".length);
|
||||
published.add(`${pkg}@0.17.0`);
|
||||
return ok();
|
||||
}
|
||||
if (args[0] === "view" && args[2] === "dist-tags") {
|
||||
return ok(JSON.stringify({ latest: "0.16.2", beta: "0.17.0-beta.2" }));
|
||||
}
|
||||
if (args[0] === "dist-tag" && args[1] === "add") {
|
||||
return ok();
|
||||
}
|
||||
throw new Error(`Unexpected npm args: ${args.join(" ")}`);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const publishOrder = calls
|
||||
.filter((args) => args[0] === "publish")
|
||||
.map((args) => args.find((arg) => arg.startsWith("--workspace=")).slice("--workspace=".length));
|
||||
assert.deepEqual(publishOrder, PUBLISH_WORKSPACES);
|
||||
|
||||
const betaTagUpdates = calls
|
||||
.filter((args) => args[0] === "dist-tag" && args[1] === "add")
|
||||
.map((args) => [args[2], args[3]]);
|
||||
assert.deepEqual(
|
||||
betaTagUpdates,
|
||||
PUBLISH_WORKSPACES.map((pkg) => [`${pkg}@0.17.0`, "beta"]),
|
||||
);
|
||||
});
|
||||
|
||||
test("skips already-published packages cleanly so partial failures can be rerun", async () => {
|
||||
const published = new Set([
|
||||
"@getpaseo/highlight@0.17.0-beta.2",
|
||||
"@getpaseo/relay@0.17.0-beta.2",
|
||||
"@getpaseo/protocol@0.17.0-beta.2",
|
||||
]);
|
||||
const publishTargets = [];
|
||||
|
||||
await publishReleasePackages(
|
||||
{ version: "0.17.0-beta.2", beta: true, dryRun: false },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
if (args[0] === "view" && args[2] === "version") {
|
||||
return published.has(args[1])
|
||||
? ok(JSON.stringify("0.17.0-beta.2"))
|
||||
: fail("npm error code E404");
|
||||
}
|
||||
if (args[0] === "publish") {
|
||||
assert.ok(args.includes("--tag") && args.includes("beta"));
|
||||
const pkg = args
|
||||
.find((arg) => arg.startsWith("--workspace="))
|
||||
.slice("--workspace=".length);
|
||||
publishTargets.push(pkg);
|
||||
published.add(`${pkg}@0.17.0-beta.2`);
|
||||
return ok();
|
||||
}
|
||||
throw new Error(`Unexpected npm args: ${args.join(" ")}`);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
assert.deepEqual(publishTargets, [
|
||||
"@getpaseo/client",
|
||||
"@getpaseo/plugin",
|
||||
"@getpaseo/server",
|
||||
"@getpaseo/cli",
|
||||
]);
|
||||
});
|
||||
|
||||
test("retries transient publish errors, waits for delayed registry propagation, and recovers EPUBLISHCONFLICT after timeout", async () => {
|
||||
const attempts = new Map();
|
||||
const visibilityChecks = new Map();
|
||||
const published = new Set();
|
||||
|
||||
await publishReleasePackages(
|
||||
{ version: "0.17.0-beta.2", beta: true, dryRun: false },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
if (args[0] === "view" && args[2] === "version") {
|
||||
const spec = args[1];
|
||||
if (!published.has(spec)) {
|
||||
return fail("npm error code E404");
|
||||
}
|
||||
const count = (visibilityChecks.get(spec) ?? 0) + 1;
|
||||
visibilityChecks.set(spec, count);
|
||||
// Simulate npm CDN lag on @getpaseo/server for 2 polls before becoming visible.
|
||||
if (spec === "@getpaseo/server@0.17.0-beta.2" && count < 3) {
|
||||
return fail("npm error code E404");
|
||||
}
|
||||
return ok(JSON.stringify("0.17.0-beta.2"));
|
||||
}
|
||||
if (args[0] === "publish") {
|
||||
const pkg = args
|
||||
.find((arg) => arg.startsWith("--workspace="))
|
||||
.slice("--workspace=".length);
|
||||
const count = (attempts.get(pkg) ?? 0) + 1;
|
||||
attempts.set(pkg, count);
|
||||
if (pkg === "@getpaseo/client" && count === 1) {
|
||||
return fail("npm error code E503\n503 Service Unavailable");
|
||||
}
|
||||
if (pkg === "@getpaseo/server" && count === 1) {
|
||||
// Timed out after npm accepted the tarball.
|
||||
published.add(`${pkg}@0.17.0-beta.2`);
|
||||
return fail("npm error code ETIMEDOUT");
|
||||
}
|
||||
if (pkg === "@getpaseo/server" && count === 2) {
|
||||
return fail(
|
||||
"npm error code E403\nYou cannot publish over the previously published versions: 0.17.0-beta.2.",
|
||||
);
|
||||
}
|
||||
published.add(`${pkg}@0.17.0-beta.2`);
|
||||
return ok();
|
||||
}
|
||||
throw new Error(`Unexpected npm args: ${args.join(" ")}`);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(attempts.get("@getpaseo/client"), 2);
|
||||
assert.equal(attempts.get("@getpaseo/server"), 2);
|
||||
assert.equal(visibilityChecks.get("@getpaseo/server@0.17.0-beta.2"), 3);
|
||||
});
|
||||
|
||||
test("does not retry deterministic npm auth errors", async () => {
|
||||
let publishAttempts = 0;
|
||||
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0-beta.2", beta: true, dryRun: false },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
if (args[0] === "view") {
|
||||
return fail("npm error code E404");
|
||||
}
|
||||
publishAttempts += 1;
|
||||
return fail("npm error code ENEEDAUTH\nYou must be logged in to publish packages.");
|
||||
},
|
||||
},
|
||||
),
|
||||
/ENEEDAUTH|logged in/,
|
||||
);
|
||||
|
||||
assert.equal(publishAttempts, 1);
|
||||
});
|
||||
|
||||
test("leaves beta dist-tag untouched when a stable hotfix is older than the active beta", async () => {
|
||||
const calls = [];
|
||||
const published = new Set();
|
||||
|
||||
await publishReleasePackages(
|
||||
{ version: "0.16.3", beta: false, dryRun: false },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
calls.push(args);
|
||||
if (args[0] === "view" && args[2] === "version") {
|
||||
return published.has(args[1])
|
||||
? ok(JSON.stringify("0.16.3"))
|
||||
: fail("npm error code E404");
|
||||
}
|
||||
if (args[0] === "publish") {
|
||||
const pkg = args
|
||||
.find((arg) => arg.startsWith("--workspace="))
|
||||
.slice("--workspace=".length);
|
||||
published.add(`${pkg}@0.16.3`);
|
||||
return ok();
|
||||
}
|
||||
if (args[0] === "view" && args[2] === "dist-tags") {
|
||||
return ok(JSON.stringify({ latest: "0.16.2", beta: "0.17.0-beta.1" }));
|
||||
}
|
||||
throw new Error(`Unexpected npm args: ${args.join(" ")}`);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
calls.some((args) => args[0] === "dist-tag"),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects channel and version mismatches", async () => {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0-beta.2", beta: false, dryRun: true },
|
||||
{ runNpm: () => ok(), sleep: noSleep },
|
||||
),
|
||||
/prerelease.*--beta/i,
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0", beta: true, dryRun: true },
|
||||
{ runNpm: () => ok(), sleep: noSleep },
|
||||
),
|
||||
/stable.*--beta/i,
|
||||
);
|
||||
});
|
||||
|
||||
test("dry-run skips registry queries, propagation polling, and dist-tag sync", async () => {
|
||||
const calls = [];
|
||||
|
||||
await publishReleasePackages(
|
||||
{ version: "0.17.0", beta: false, dryRun: true },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
calls.push(args);
|
||||
return ok();
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(calls.length, PUBLISH_WORKSPACES.length);
|
||||
for (const args of calls) {
|
||||
assert.equal(args[0], "publish");
|
||||
assert.ok(args.includes("--dry-run"));
|
||||
}
|
||||
});
|
||||
|
||||
test("inherits TTY stdin/stdout for interactive publish and dist-tag OTP prompts while keeping stderr piped", () => {
|
||||
assert.deepEqual(getNpmStdio({ interactive: true, stdinIsTTY: true, stdoutIsTTY: true }), [
|
||||
"inherit",
|
||||
"inherit",
|
||||
"pipe",
|
||||
]);
|
||||
assert.deepEqual(getNpmStdio({ interactive: false, stdinIsTTY: true, stdoutIsTTY: true }), [
|
||||
"ignore",
|
||||
"pipe",
|
||||
"pipe",
|
||||
]);
|
||||
assert.deepEqual(getNpmStdio({ interactive: true, stdinIsTTY: false, stdoutIsTTY: true }), [
|
||||
"ignore",
|
||||
"pipe",
|
||||
"pipe",
|
||||
]);
|
||||
});
|
||||
|
||||
test("marks publish and dist-tag invocations interactive and forwards --otp when supplied", async () => {
|
||||
const recorded = [];
|
||||
const published = new Set();
|
||||
|
||||
await publishReleasePackages(
|
||||
{ version: "0.17.0", beta: false, dryRun: false, otp: "123456" },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args, options) {
|
||||
recorded.push({ args, interactive: Boolean(options?.interactive) });
|
||||
if (args[0] === "view" && args[2] === "version") {
|
||||
return published.has(args[1])
|
||||
? ok(JSON.stringify("0.17.0"))
|
||||
: fail("npm error code E404");
|
||||
}
|
||||
if (args[0] === "publish") {
|
||||
const pkg = args
|
||||
.find((arg) => arg.startsWith("--workspace="))
|
||||
.slice("--workspace=".length);
|
||||
published.add(`${pkg}@0.17.0`);
|
||||
return ok();
|
||||
}
|
||||
if (args[0] === "view" && args[2] === "dist-tags") {
|
||||
return ok(JSON.stringify({ latest: "0.16.2", beta: "0.17.0-beta.2" }));
|
||||
}
|
||||
return ok();
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
for (const entry of recorded) {
|
||||
if (entry.args[0] === "view") {
|
||||
assert.equal(entry.interactive, false);
|
||||
} else {
|
||||
assert.equal(entry.interactive, true);
|
||||
assert.ok(entry.args.includes("--otp=123456"));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -3,42 +3,57 @@ import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { isMainModule } from "./is-main-module.mjs";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = path.resolve(__dirname, "..");
|
||||
const rootPackagePath = path.join(rootDir, "package.json");
|
||||
|
||||
function usageAndExit(code = 0) {
|
||||
process.stderr.write(`Usage: node scripts/push-current-release-tag.mjs [--branch <name>]\n`);
|
||||
process.stderr.write(
|
||||
`Usage: node scripts/push-current-release-tag.mjs [--branch <name>] [--check]\n`,
|
||||
);
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
function run(cmd, args) {
|
||||
execFileSync(cmd, args, { cwd: rootDir, stdio: "inherit" });
|
||||
function defaultRun(cmd, args, cwd) {
|
||||
execFileSync(cmd, args, { cwd, stdio: "inherit" });
|
||||
}
|
||||
|
||||
function runQuiet(cmd, args) {
|
||||
return execFileSync(cmd, args, { cwd: rootDir, encoding: "utf8" }).trim();
|
||||
function defaultRunQuiet(cmd, args, cwd) {
|
||||
return execFileSync(cmd, args, { cwd, encoding: "utf8" }).trim();
|
||||
}
|
||||
|
||||
function getRemoteTagCommit(tag) {
|
||||
function getRemoteRefCommit(ref, runQuiet) {
|
||||
try {
|
||||
return runQuiet("git", ["ls-remote", "--exit-code", "--refs", "origin", `refs/tags/${tag}^{}`])
|
||||
.split(/\s+/)[0]
|
||||
.trim();
|
||||
return runQuiet("git", ["ls-remote", "--exit-code", "origin", ref]).split(/\s+/)[0].trim();
|
||||
} catch {
|
||||
try {
|
||||
return runQuiet("git", ["ls-remote", "--exit-code", "--refs", "origin", `refs/tags/${tag}`])
|
||||
.split(/\s+/)[0]
|
||||
.trim();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function getRemoteTagCommit(tag, runQuiet) {
|
||||
// Do not pass --refs: it suppresses the peeled `^{}` commit entry for annotated tags.
|
||||
return (
|
||||
getRemoteRefCommit(`refs/tags/${tag}^{}`, runQuiet) ||
|
||||
getRemoteRefCommit(`refs/tags/${tag}`, runQuiet)
|
||||
);
|
||||
}
|
||||
|
||||
export function assertReleaseBranch(branchRef) {
|
||||
const trimmed = typeof branchRef === "string" ? branchRef.trim() : "";
|
||||
if (!trimmed || !trimmed.startsWith("release/") || trimmed === "release/") {
|
||||
throw new Error(
|
||||
`Refusing to push release from branch "${trimmed || "<detached>"}". ` +
|
||||
"Releases must be cut from a release/* branch (for example release/vX.Y.Z or release/vX.Y.Z-beta.N).",
|
||||
);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {
|
||||
branch: "",
|
||||
check: false,
|
||||
};
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
@@ -48,6 +63,10 @@ function parseArgs(argv) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--check") {
|
||||
args.check = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--help" || arg === "-h") {
|
||||
usageAndExit(0);
|
||||
}
|
||||
@@ -57,50 +76,79 @@ function parseArgs(argv) {
|
||||
return args;
|
||||
}
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const rootPackage = JSON.parse(readFileSync(rootPackagePath, "utf8"));
|
||||
const version = typeof rootPackage.version === "string" ? rootPackage.version.trim() : "";
|
||||
if (!version) {
|
||||
throw new Error('Root package.json must contain a valid "version"');
|
||||
}
|
||||
export function pushCurrentReleaseTag(argv = process.argv.slice(2), deps = {}) {
|
||||
const cwd = deps.cwd ?? rootDir;
|
||||
const run = deps.run ?? ((cmd, args) => defaultRun(cmd, args, cwd));
|
||||
const runQuiet = deps.runQuiet ?? ((cmd, args) => defaultRunQuiet(cmd, args, cwd));
|
||||
|
||||
const tag = `v${version}`;
|
||||
const headCommit = runQuiet("git", ["rev-parse", "HEAD"]);
|
||||
const args = parseArgs(argv);
|
||||
const rootPackagePath = path.join(cwd, "package.json");
|
||||
const rootPackage = JSON.parse(readFileSync(rootPackagePath, "utf8"));
|
||||
const version = typeof rootPackage.version === "string" ? rootPackage.version.trim() : "";
|
||||
if (!version) {
|
||||
throw new Error('Root package.json must contain a valid "version"');
|
||||
}
|
||||
|
||||
let localTagCommit = "";
|
||||
try {
|
||||
localTagCommit = runQuiet("git", ["rev-list", "-n", "1", tag]);
|
||||
} catch {
|
||||
run("git", ["tag", "-a", tag, "-m", tag]);
|
||||
localTagCommit = runQuiet("git", ["rev-list", "-n", "1", tag]);
|
||||
}
|
||||
|
||||
if (localTagCommit !== headCommit) {
|
||||
throw new Error(
|
||||
`Local tag ${tag} points to ${localTagCommit}, but HEAD is ${headCommit}. ` +
|
||||
"Create a new release commit before pushing this tag.",
|
||||
);
|
||||
}
|
||||
|
||||
const currentBranch = runQuiet("git", ["branch", "--show-current"]);
|
||||
const branchRef = args.branch || currentBranch;
|
||||
if (!branchRef) {
|
||||
throw new Error("Cannot determine branch to push. Pass --branch <name>.");
|
||||
}
|
||||
run("git", ["push", "origin", `HEAD:${branchRef}`]);
|
||||
|
||||
const remoteTagCommit = getRemoteTagCommit(tag);
|
||||
|
||||
if (remoteTagCommit) {
|
||||
if (remoteTagCommit !== localTagCommit) {
|
||||
const dirty = runQuiet("git", ["status", "--porcelain"]);
|
||||
if (dirty) {
|
||||
throw new Error(
|
||||
`Remote tag ${tag} points to ${remoteTagCommit}, but local tag points to ${localTagCommit}. ` +
|
||||
"Refusing to reuse an existing release tag for a different commit.",
|
||||
"Git working directory is not clean. Commit and verify changes on the release branch before shipping.",
|
||||
);
|
||||
}
|
||||
console.log(`Tag ${tag} already exists on origin`);
|
||||
} else {
|
||||
run("git", ["push", "origin", tag]);
|
||||
|
||||
const currentBranch = runQuiet("git", ["branch", "--show-current"]);
|
||||
const branchRef = assertReleaseBranch(args.branch || currentBranch);
|
||||
const headCommit = runQuiet("git", ["rev-parse", "HEAD"]);
|
||||
|
||||
// Require HEAD to match origin/<branchRef> so release:ship never publishes or
|
||||
// tags an unpushed commit whose release-branch CI and Desktop Packages have not run.
|
||||
const remoteBranchCommit = getRemoteRefCommit(`refs/heads/${branchRef}`, runQuiet);
|
||||
if (remoteBranchCommit !== headCommit) {
|
||||
throw new Error(
|
||||
`HEAD (${headCommit.slice(0, 9)}) does not match origin/${branchRef} (${remoteBranchCommit ? remoteBranchCommit.slice(0, 9) : "not pushed"}). ` +
|
||||
`Push ${branchRef} and confirm CI and Desktop Packages pass before shipping.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (args.check) {
|
||||
return { branchRef, headCommit, tag: `v${version}` };
|
||||
}
|
||||
|
||||
const tag = `v${version}`;
|
||||
|
||||
let localTagCommit = "";
|
||||
try {
|
||||
localTagCommit = runQuiet("git", ["rev-list", "-n", "1", tag]);
|
||||
} catch {
|
||||
run("git", ["tag", "-a", tag, "-m", tag]);
|
||||
localTagCommit = runQuiet("git", ["rev-list", "-n", "1", tag]);
|
||||
}
|
||||
|
||||
if (localTagCommit !== headCommit) {
|
||||
throw new Error(
|
||||
`Local tag ${tag} points to ${localTagCommit}, but HEAD is ${headCommit}. ` +
|
||||
"Create a new release commit before pushing this tag.",
|
||||
);
|
||||
}
|
||||
|
||||
const remoteTagCommit = getRemoteTagCommit(tag, runQuiet);
|
||||
|
||||
if (remoteTagCommit) {
|
||||
if (remoteTagCommit !== localTagCommit) {
|
||||
throw new Error(
|
||||
`Remote tag ${tag} points to ${remoteTagCommit}, but local tag points to ${localTagCommit}. ` +
|
||||
"Refusing to reuse an existing release tag for a different commit.",
|
||||
);
|
||||
}
|
||||
console.log(`Tag ${tag} already exists on origin at ${localTagCommit.slice(0, 9)}`);
|
||||
} else {
|
||||
run("git", ["push", "origin", tag]);
|
||||
}
|
||||
|
||||
console.log(`Release push complete: branch ${branchRef} and tag ${tag}`);
|
||||
return { branchRef, headCommit, tag };
|
||||
}
|
||||
|
||||
console.log(`Release push complete: branch HEAD and tag ${tag}`);
|
||||
if (isMainModule(import.meta.url)) {
|
||||
pushCurrentReleaseTag();
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
|
||||
import { assertReleaseBranch, pushCurrentReleaseTag } from "./push-current-release-tag.mjs";
|
||||
|
||||
function git(cwd, args) {
|
||||
return execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
|
||||
}
|
||||
|
||||
function createReleaseRepoWithBareRemote(version = "0.17.0-beta.2") {
|
||||
const root = mkdtempSync(path.join(tmpdir(), "push-release-tag-"));
|
||||
const remote = path.join(root, "origin.git");
|
||||
const repo = path.join(root, "work");
|
||||
execFileSync("git", ["init", "--bare", "-q", remote]);
|
||||
execFileSync("git", ["init", "-q", repo]);
|
||||
git(repo, ["config", "user.name", "Test"]);
|
||||
git(repo, ["config", "user.email", "test@example.com"]);
|
||||
git(repo, ["remote", "add", "origin", remote]);
|
||||
git(repo, ["checkout", "-b", `release/v${version}`]);
|
||||
writeFileSync(
|
||||
path.join(repo, "package.json"),
|
||||
`${JSON.stringify({ name: "paseo", version }, null, 2)}\n`,
|
||||
);
|
||||
git(repo, ["add", "package.json"]);
|
||||
git(repo, ["commit", "-q", "-m", `chore(release): cut ${version}`]);
|
||||
return { root, remote, repo };
|
||||
}
|
||||
|
||||
test("accepts release/* branches for release pushes", () => {
|
||||
assert.doesNotThrow(() => assertReleaseBranch("release/v0.17.0-beta.2"));
|
||||
assert.doesNotThrow(() => assertReleaseBranch("release/v0.17.0"));
|
||||
assert.doesNotThrow(() => assertReleaseBranch("release/0.17.1-hotfix"));
|
||||
});
|
||||
|
||||
test("refuses main and non-release branches for release pushes", () => {
|
||||
assert.throws(() => assertReleaseBranch("main"), /release\/\*/);
|
||||
assert.throws(() => assertReleaseBranch("feat/something"), /release\/\*/);
|
||||
assert.throws(() => assertReleaseBranch("release/"), /release\/\*/);
|
||||
assert.throws(() => assertReleaseBranch(""), /release\/\*/);
|
||||
});
|
||||
|
||||
test("refuses to ship when HEAD has not been pushed to the remote release branch", () => {
|
||||
const { root, repo } = createReleaseRepoWithBareRemote("0.17.0-beta.2");
|
||||
try {
|
||||
// Never pushed yet: --check and full push both fail before publishing or tagging.
|
||||
assert.throws(() => pushCurrentReleaseTag(["--check"], { cwd: repo }), /does not match origin/);
|
||||
assert.throws(() => pushCurrentReleaseTag([], { cwd: repo }), /does not match origin/);
|
||||
|
||||
// Push the verified commit, then add an unpushed local commit on top.
|
||||
git(repo, ["push", "-q", "-u", "origin", "HEAD"]);
|
||||
assert.doesNotThrow(() => pushCurrentReleaseTag(["--check"], { cwd: repo }));
|
||||
|
||||
writeFileSync(path.join(repo, "extra.txt"), "unverified\n");
|
||||
git(repo, ["add", "extra.txt"]);
|
||||
git(repo, ["commit", "-q", "-m", "extra local commit"]);
|
||||
|
||||
assert.throws(() => pushCurrentReleaseTag(["--check"], { cwd: repo }), /does not match origin/);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("retrying release:push succeeds cleanly when the annotated tag already points at HEAD on origin", () => {
|
||||
const { root, repo } = createReleaseRepoWithBareRemote("0.17.0-beta.2");
|
||||
try {
|
||||
git(repo, ["push", "-q", "-u", "origin", "HEAD"]);
|
||||
const first = pushCurrentReleaseTag([], { cwd: repo });
|
||||
assert.equal(first.tag, "v0.17.0-beta.2");
|
||||
|
||||
// Re-running after the annotated tag already exists on origin must not report a false SHA mismatch.
|
||||
const second = pushCurrentReleaseTag([], { cwd: repo });
|
||||
assert.equal(second.tag, "v0.17.0-beta.2");
|
||||
assert.equal(second.headCommit, first.headCommit);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { getFdroidVersionCodes as defaultGetFdroidVersionCodes } from "../packages/app/native-release-version.js";
|
||||
import { parseChangelogEntries } from "./changelog-utils.mjs";
|
||||
import { isMainModule } from "./is-main-module.mjs";
|
||||
import {
|
||||
compareReleaseVersions,
|
||||
normalizeReleaseTag,
|
||||
parseReleaseVersion,
|
||||
} from "./release-version-utils.mjs";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = path.resolve(__dirname, "..");
|
||||
|
||||
function usageAndExit(code = 1) {
|
||||
process.stderr.write("Usage: node scripts/reconcile-release.mjs --tag <vX.Y.Z[-beta.N]>\n");
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
let tag = "";
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--tag") {
|
||||
tag = argv[index + 1] ?? "";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--help" || arg === "-h") {
|
||||
usageAndExit(0);
|
||||
}
|
||||
usageAndExit(1);
|
||||
}
|
||||
if (!tag) {
|
||||
usageAndExit(1);
|
||||
}
|
||||
return { tag };
|
||||
}
|
||||
|
||||
function splitRawEntries(content) {
|
||||
const lines = content.split(/\r?\n/);
|
||||
const entries = parseChangelogEntries(content);
|
||||
const preamble = lines.slice(0, entries[0].headingLineIndex).join("\n").trimEnd();
|
||||
const blocks = entries.map((entry, index) => {
|
||||
const nextStart = entries[index + 1]?.headingLineIndex ?? lines.length;
|
||||
const raw = lines.slice(entry.headingLineIndex, nextStart).join("\n").trim();
|
||||
return { version: entry.version, raw };
|
||||
});
|
||||
return { preamble, blocks };
|
||||
}
|
||||
|
||||
function safeParseVersion(version) {
|
||||
try {
|
||||
return parseReleaseVersion(version);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function mergeChangelogEntry(mainContent, tagContent, targetVersion) {
|
||||
const target = parseReleaseVersion(targetVersion);
|
||||
const tagParsed = splitRawEntries(tagContent);
|
||||
const taggedBlock = tagParsed.blocks.find((block) => block.version === target.version);
|
||||
if (!taggedBlock) {
|
||||
throw new Error(`No changelog entry found for ${target.version} in tagged changelog.`);
|
||||
}
|
||||
|
||||
const mainParsed = splitRawEntries(mainContent);
|
||||
|
||||
// Never downgrade an already-reconciled newer entry in the same beta series
|
||||
// (e.g. a retried beta.1 reconciliation after beta.2 or stable promotion landed).
|
||||
if (
|
||||
target.isBeta &&
|
||||
mainParsed.blocks.some((block) => {
|
||||
const existing = safeParseVersion(block.version);
|
||||
return (
|
||||
existing &&
|
||||
existing.baseVersion === target.baseVersion &&
|
||||
compareReleaseVersions(existing.version, target.version) > 0
|
||||
);
|
||||
})
|
||||
) {
|
||||
return mainContent;
|
||||
}
|
||||
|
||||
const kept = mainParsed.blocks.filter((block) => {
|
||||
if (block.version === target.version) {
|
||||
return false;
|
||||
}
|
||||
const existing = safeParseVersion(block.version);
|
||||
if (
|
||||
existing &&
|
||||
existing.isBeta &&
|
||||
existing.baseVersion === target.baseVersion &&
|
||||
compareReleaseVersions(existing.version, target.version) < 0
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
let insertIndex = kept.findIndex((block) => {
|
||||
const existing = safeParseVersion(block.version);
|
||||
if (!existing) {
|
||||
return true;
|
||||
}
|
||||
return compareReleaseVersions(target.version, existing.version) > 0;
|
||||
});
|
||||
|
||||
if (insertIndex === -1) {
|
||||
insertIndex = kept.length;
|
||||
}
|
||||
|
||||
kept.splice(insertIndex, 0, taggedBlock);
|
||||
|
||||
const parts = [];
|
||||
if (mainParsed.preamble.length > 0) {
|
||||
parts.push(mainParsed.preamble);
|
||||
}
|
||||
for (const block of kept) {
|
||||
parts.push(block.raw);
|
||||
}
|
||||
return `${parts.join("\n\n")}\n`;
|
||||
}
|
||||
|
||||
function defaultVerifyTag(tag, cwd) {
|
||||
execFileSync("git", ["rev-parse", "--verify", `refs/tags/${tag}^{commit}`], {
|
||||
cwd,
|
||||
stdio: "ignore",
|
||||
});
|
||||
}
|
||||
|
||||
function defaultReadTagFile(tag, filePath, cwd) {
|
||||
return execFileSync("git", ["show", `${tag}:${filePath}`], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
function defaultRunNpm(args, cwd) {
|
||||
const command = process.platform === "win32" ? "npm.cmd" : "npm";
|
||||
execFileSync(command, args, {
|
||||
cwd,
|
||||
stdio: "inherit",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
}
|
||||
|
||||
function lockfileMatchesVersion(cwd, rootPackage, version) {
|
||||
const lockfilePath = path.join(cwd, "package-lock.json");
|
||||
if (!existsSync(lockfilePath)) {
|
||||
return true;
|
||||
}
|
||||
const lockfile = JSON.parse(readFileSync(lockfilePath, "utf8"));
|
||||
if (lockfile.version !== version || lockfile.packages?.[""]?.version !== version) {
|
||||
return false;
|
||||
}
|
||||
const workspaces = Array.isArray(rootPackage.workspaces) ? rootPackage.workspaces : [];
|
||||
for (const workspace of workspaces) {
|
||||
if (lockfile.packages?.[workspace] && lockfile.packages[workspace].version !== version) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function reconcileRelease(options, deps = {}) {
|
||||
const cwd = options.cwd ?? rootDir;
|
||||
const tag = normalizeReleaseTag(options.tag);
|
||||
const version = tag.slice(1);
|
||||
const parsed = parseReleaseVersion(version);
|
||||
|
||||
const verifyTag = deps.verifyTag ?? ((targetTag) => defaultVerifyTag(targetTag, cwd));
|
||||
const readTagFile =
|
||||
deps.readTagFile ?? ((targetTag, filePath) => defaultReadTagFile(targetTag, filePath, cwd));
|
||||
const runNpm = deps.runNpm ?? ((args) => defaultRunNpm(args, cwd));
|
||||
const getFdroidVersionCodes = deps.getFdroidVersionCodes ?? defaultGetFdroidVersionCodes;
|
||||
|
||||
verifyTag(tag);
|
||||
|
||||
for (const changelogFile of ["CHANGELOG.md", "CHANGELOG.zh-CN.md"]) {
|
||||
const targetPath = path.join(cwd, changelogFile);
|
||||
const mainContent = readFileSync(targetPath, "utf8");
|
||||
const tagContent = readTagFile(tag, changelogFile);
|
||||
const merged = mergeChangelogEntry(mainContent, tagContent, version);
|
||||
writeFileSync(targetPath, merged);
|
||||
}
|
||||
|
||||
const fdroidFiles = [];
|
||||
if (!parsed.isPrerelease) {
|
||||
for (const { versionCode } of getFdroidVersionCodes(version)) {
|
||||
const relativePath = path.join(
|
||||
"fastlane",
|
||||
"metadata",
|
||||
"android",
|
||||
"en-US",
|
||||
"changelogs",
|
||||
`${versionCode}.txt`,
|
||||
);
|
||||
const content = readTagFile(tag, relativePath.replaceAll("\\", "/"));
|
||||
const destination = path.join(cwd, relativePath);
|
||||
mkdirSync(path.dirname(destination), { recursive: true });
|
||||
writeFileSync(destination, content);
|
||||
fdroidFiles.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
const rootPackagePath = path.join(cwd, "package.json");
|
||||
const rootPackage = JSON.parse(readFileSync(rootPackagePath, "utf8"));
|
||||
const currentMainVersion = rootPackage.version;
|
||||
const versionComparison = compareReleaseVersions(version, currentMainVersion);
|
||||
|
||||
let versionUpdated = false;
|
||||
if (
|
||||
versionComparison > 0 ||
|
||||
(versionComparison === 0 && !lockfileMatchesVersion(cwd, rootPackage, version))
|
||||
) {
|
||||
if (rootPackage.version !== version) {
|
||||
rootPackage.version = version;
|
||||
writeFileSync(rootPackagePath, `${JSON.stringify(rootPackage, null, 2)}\n`);
|
||||
}
|
||||
runNpm(["run", "version:sync-internal"]);
|
||||
runNpm(["run", "release:prepare"]);
|
||||
versionUpdated = true;
|
||||
console.log(
|
||||
`Updated workspace versions and lockfile from ${currentMainVersion} to ${version}.`,
|
||||
);
|
||||
} else {
|
||||
console.log(`Kept main version at ${currentMainVersion} (newer than or equal to ${version}).`);
|
||||
}
|
||||
|
||||
return { tag, version, versionUpdated, fdroidFiles };
|
||||
}
|
||||
|
||||
if (isMainModule(import.meta.url)) {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
reconcileRelease(args);
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
|
||||
import { mergeChangelogEntry, reconcileRelease } from "./reconcile-release.mjs";
|
||||
|
||||
const MAIN_CHANGELOG_WITH_BETA = `# Changelog
|
||||
|
||||
## 0.17.0-beta.1 - 2026-11-19
|
||||
|
||||
- **Beta 1 highlight:** Initial beta. ([#101](https://github.com/getpaseo/paseo/pull/101))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed beta 1 bug ([#101](https://github.com/getpaseo/paseo/pull/101))
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed 0.16.2 bug ([#99](https://github.com/getpaseo/paseo/pull/99))
|
||||
`;
|
||||
|
||||
test("replaces an earlier beta entry in place for follow-up betas and promotions", () => {
|
||||
const tagBeta2 = `# Changelog
|
||||
|
||||
## 0.17.0-beta.2 - 2026-11-21
|
||||
|
||||
- **Beta 2 highlight:** Updated beta. ([#105](https://github.com/getpaseo/paseo/pull/105))
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed 0.16.2 bug ([#99](https://github.com/getpaseo/paseo/pull/99))
|
||||
`;
|
||||
|
||||
const mergedBeta2 = mergeChangelogEntry(MAIN_CHANGELOG_WITH_BETA, tagBeta2, "0.17.0-beta.2");
|
||||
assert.doesNotMatch(mergedBeta2, /## 0\.17\.0-beta\.1/);
|
||||
assert.match(mergedBeta2, /^# Changelog\n\n## 0\.17\.0-beta\.2 - 2026-11-21\n/);
|
||||
assert.match(mergedBeta2, /## 0\.16\.2 - 2026-11-18/);
|
||||
|
||||
const tagStable = `# Changelog
|
||||
|
||||
## 0.17.0 - 2026-11-22
|
||||
|
||||
- **Stable highlight:** Shipped stable. ([#105](https://github.com/getpaseo/paseo/pull/105))
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
`;
|
||||
|
||||
const mergedStable = mergeChangelogEntry(mergedBeta2, tagStable, "0.17.0");
|
||||
assert.doesNotMatch(mergedStable, /## 0\.17\.0-beta\.2/);
|
||||
assert.match(mergedStable, /^# Changelog\n\n## 0\.17\.0 - 2026-11-22\n/);
|
||||
assert.match(mergedStable, /## 0\.16\.2 - 2026-11-18/);
|
||||
});
|
||||
|
||||
test("inserts a stable hotfix below a newer active beta entry", () => {
|
||||
const tagHotfix = `# Changelog
|
||||
|
||||
## 0.16.3 - 2026-11-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed urgent 0.16.3 regression ([#103](https://github.com/getpaseo/paseo/pull/103))
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed 0.16.2 bug ([#99](https://github.com/getpaseo/paseo/pull/99))
|
||||
`;
|
||||
|
||||
const merged = mergeChangelogEntry(MAIN_CHANGELOG_WITH_BETA, tagHotfix, "0.16.3");
|
||||
const betaIndex = merged.indexOf("## 0.17.0-beta.1 - 2026-11-19");
|
||||
const hotfixIndex = merged.indexOf("## 0.16.3 - 2026-11-20");
|
||||
const prevStableIndex = merged.indexOf("## 0.16.2 - 2026-11-18");
|
||||
|
||||
assert.ok(betaIndex >= 0 && hotfixIndex > betaIndex && prevStableIndex > hotfixIndex);
|
||||
});
|
||||
|
||||
test("keeps newer beta or promoted stable changelog entries when reconciling an older beta", () => {
|
||||
const mainWithBeta2 = `# Changelog
|
||||
|
||||
## 0.17.0-beta.2 - 2026-11-21
|
||||
|
||||
- **Beta 2 highlight:** Newer beta. ([#105](https://github.com/getpaseo/paseo/pull/105))
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
`;
|
||||
|
||||
const mainWithStable = `# Changelog
|
||||
|
||||
## 0.17.0 - 2026-11-22
|
||||
|
||||
- **Stable highlight:** Shipped stable. ([#105](https://github.com/getpaseo/paseo/pull/105))
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
`;
|
||||
|
||||
assert.equal(
|
||||
mergeChangelogEntry(mainWithBeta2, MAIN_CHANGELOG_WITH_BETA, "0.17.0-beta.1"),
|
||||
mainWithBeta2,
|
||||
);
|
||||
assert.equal(
|
||||
mergeChangelogEntry(mainWithStable, MAIN_CHANGELOG_WITH_BETA, "0.17.0-beta.1"),
|
||||
mainWithStable,
|
||||
);
|
||||
});
|
||||
|
||||
test("reconcileRelease updates changelogs, F-Droid files, and versions only when tag is newer", () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "reconcile-release-"));
|
||||
try {
|
||||
writeFileSync(path.join(dir, "CHANGELOG.md"), MAIN_CHANGELOG_WITH_BETA);
|
||||
writeFileSync(
|
||||
path.join(dir, "CHANGELOG.zh-CN.md"),
|
||||
"# Changelog\n\n## 0.17.0-beta.1 - 2026-11-19\n\n- 旧内容\n\n## 0.16.2 - 2026-11-18\n\n- 0.16.2\n",
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(dir, "package.json"),
|
||||
`${JSON.stringify({ name: "paseo", version: "0.17.0-beta.1" }, null, 2)}\n`,
|
||||
);
|
||||
|
||||
const tagFiles = new Map([
|
||||
[
|
||||
"CHANGELOG.md",
|
||||
"# Changelog\n\n## 0.16.3 - 2026-11-20\n\n### Fixed\n\n- Hotfix ([#103](https://github.com/getpaseo/paseo/pull/103))\n\n## 0.16.2 - 2026-11-18\n",
|
||||
],
|
||||
[
|
||||
"CHANGELOG.zh-CN.md",
|
||||
"# Changelog\n\n## 0.16.3 - 2026-11-20\n\n### 修复\n\n- 热修复 ([#103](https://github.com/getpaseo/paseo/pull/103))\n\n## 0.16.2 - 2026-11-18\n",
|
||||
],
|
||||
["fastlane/metadata/android/en-US/changelogs/160031.txt", "Hotfix notes\n"],
|
||||
["fastlane/metadata/android/en-US/changelogs/160032.txt", "Hotfix notes\n"],
|
||||
]);
|
||||
|
||||
const ranCommands = [];
|
||||
const hotfixResult = reconcileRelease(
|
||||
{ tag: "v0.16.3", cwd: dir },
|
||||
{
|
||||
getFdroidVersionCodes: () => [
|
||||
{ abi: "armeabi-v7a", versionCode: 160031 },
|
||||
{ abi: "arm64-v8a", versionCode: 160032 },
|
||||
],
|
||||
readTagFile(_tag, filePath) {
|
||||
if (!tagFiles.has(filePath)) {
|
||||
throw new Error(`Missing ${filePath}`);
|
||||
}
|
||||
return tagFiles.get(filePath);
|
||||
},
|
||||
verifyTag: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// Hotfix 0.16.3 is older than main's 0.17.0-beta.1: keep main's version untouched.
|
||||
assert.equal(hotfixResult.versionUpdated, false);
|
||||
assert.deepEqual(ranCommands, []);
|
||||
assert.equal(
|
||||
JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")).version,
|
||||
"0.17.0-beta.1",
|
||||
);
|
||||
assert.equal(
|
||||
readFileSync(path.join(dir, "fastlane/metadata/android/en-US/changelogs/160031.txt"), "utf8"),
|
||||
"Hotfix notes\n",
|
||||
);
|
||||
assert.match(
|
||||
readFileSync(path.join(dir, "CHANGELOG.md"), "utf8"),
|
||||
/## 0\.17\.0-beta\.1[\s\S]*## 0\.16\.3[\s\S]*## 0\.16\.2/,
|
||||
);
|
||||
|
||||
// Now reconcile 0.17.0 promotion (newer than 0.17.0-beta.1): updates root version and runs sync + prepare.
|
||||
mkdirSync(path.join(dir, "fastlane/metadata/android/en-US/changelogs"), { recursive: true });
|
||||
tagFiles.set(
|
||||
"CHANGELOG.md",
|
||||
"# Changelog\n\n## 0.17.0 - 2026-11-22\n\n- **Shipped:** Ready. ([#105](https://github.com/getpaseo/paseo/pull/105))\n",
|
||||
);
|
||||
tagFiles.set(
|
||||
"CHANGELOG.zh-CN.md",
|
||||
"# Changelog\n\n## 0.17.0 - 2026-11-22\n\n- **已发布**:就绪。([#105](https://github.com/getpaseo/paseo/pull/105))\n",
|
||||
);
|
||||
tagFiles.set("fastlane/metadata/android/en-US/changelogs/170001.txt", "0.17.0 notes\n");
|
||||
|
||||
const promoResult = reconcileRelease(
|
||||
{ tag: "v0.17.0", cwd: dir },
|
||||
{
|
||||
getFdroidVersionCodes: () => [{ abi: "armeabi-v7a", versionCode: 170001 }],
|
||||
readTagFile(_tag, filePath) {
|
||||
return tagFiles.get(filePath);
|
||||
},
|
||||
verifyTag: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(promoResult.versionUpdated, true);
|
||||
assert.equal(
|
||||
JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")).version,
|
||||
"0.17.0",
|
||||
);
|
||||
assert.deepEqual(ranCommands, [
|
||||
["run", "version:sync-internal"],
|
||||
["run", "release:prepare"],
|
||||
]);
|
||||
assert.doesNotMatch(
|
||||
readFileSync(path.join(dir, "CHANGELOG.md"), "utf8"),
|
||||
/## 0\.17\.0-beta\.1/,
|
||||
);
|
||||
assert.match(
|
||||
readFileSync(path.join(dir, "CHANGELOG.md"), "utf8"),
|
||||
/## 0\.17\.0 - 2026-11-22[\s\S]*## 0\.16\.3 - 2026-11-20/,
|
||||
);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("reconcileRelease retries version sync and lockfile install when a prior run failed before updating package-lock.json", () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "reconcile-retry-"));
|
||||
try {
|
||||
writeFileSync(path.join(dir, "CHANGELOG.md"), MAIN_CHANGELOG_WITH_BETA);
|
||||
writeFileSync(
|
||||
path.join(dir, "CHANGELOG.zh-CN.md"),
|
||||
"# Changelog\n\n## 0.17.0-beta.1 - 2026-11-19\n\n- 旧内容\n",
|
||||
);
|
||||
// Simulate a previous reconcile attempt where package.json was bumped to 0.17.0-beta.2
|
||||
// before `npm run release:prepare` failed, leaving package-lock.json at 0.17.0-beta.1.
|
||||
writeFileSync(
|
||||
path.join(dir, "package.json"),
|
||||
`${JSON.stringify({ name: "paseo", version: "0.17.0-beta.2" }, null, 2)}\n`,
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(dir, "package-lock.json"),
|
||||
`${JSON.stringify({ name: "paseo", version: "0.17.0-beta.1", packages: { "": { version: "0.17.0-beta.1" } } }, null, 2)}\n`,
|
||||
);
|
||||
|
||||
const tagFiles = new Map([
|
||||
["CHANGELOG.md", "# Changelog\n\n## 0.17.0-beta.2 - 2026-11-21\n\n- Beta 2\n"],
|
||||
["CHANGELOG.zh-CN.md", "# Changelog\n\n## 0.17.0-beta.2 - 2026-11-21\n\n- Beta 2\n"],
|
||||
]);
|
||||
|
||||
const ranCommands = [];
|
||||
const result = reconcileRelease(
|
||||
{ tag: "v0.17.0-beta.2", cwd: dir },
|
||||
{
|
||||
readTagFile: (_tag, filePath) => tagFiles.get(filePath),
|
||||
verifyTag: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
if (args[1] === "release:prepare") {
|
||||
writeFileSync(
|
||||
path.join(dir, "package-lock.json"),
|
||||
`${JSON.stringify({ name: "paseo", version: "0.17.0-beta.2", packages: { "": { version: "0.17.0-beta.2" } } }, null, 2)}\n`,
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(result.versionUpdated, true);
|
||||
assert.deepEqual(ranCommands, [
|
||||
["run", "version:sync-internal"],
|
||||
["run", "release:prepare"],
|
||||
]);
|
||||
|
||||
// A third run once package-lock.json matches is a no-op for version/lockfile sync.
|
||||
ranCommands.length = 0;
|
||||
const idempotent = reconcileRelease(
|
||||
{ tag: "v0.17.0-beta.2", cwd: dir },
|
||||
{
|
||||
readTagFile: (_tag, filePath) => tagFiles.get(filePath),
|
||||
verifyTag: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(idempotent.versionUpdated, false);
|
||||
assert.deepEqual(ranCommands, []);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -51,6 +51,31 @@ export function parseReleaseVersion(version) {
|
||||
};
|
||||
}
|
||||
|
||||
export function compareReleaseVersions(leftVersion, rightVersion) {
|
||||
const left = parseReleaseVersion(leftVersion);
|
||||
const right = parseReleaseVersion(rightVersion);
|
||||
|
||||
for (const field of ["major", "minor", "patch"]) {
|
||||
if (left[field] !== right[field]) {
|
||||
return left[field] > right[field] ? 1 : -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!left.isPrerelease && !right.isPrerelease) {
|
||||
return 0;
|
||||
}
|
||||
if (!left.isPrerelease) {
|
||||
return 1;
|
||||
}
|
||||
if (!right.isPrerelease) {
|
||||
return -1;
|
||||
}
|
||||
if (left.betaNumber === right.betaNumber) {
|
||||
return 0;
|
||||
}
|
||||
return left.betaNumber > right.betaNumber ? 1 : -1;
|
||||
}
|
||||
|
||||
export function formatReleaseVersion({ major, minor, patch, prerelease = null }) {
|
||||
assertInteger(major, "major version");
|
||||
assertInteger(minor, "minor version");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
compareReleaseVersions,
|
||||
computeNextReleaseVersion,
|
||||
getReleaseInfoFromSourceTag,
|
||||
parseReleaseVersion,
|
||||
@@ -51,3 +52,14 @@ test("emits beta release info from tags", () => {
|
||||
test("rejects non-beta prerelease versions", () => {
|
||||
assert.throws(() => parseReleaseVersion("0.1.60-canary.1"), /Expected beta prerelease versions/);
|
||||
});
|
||||
|
||||
test("compares stable and beta release versions in semver order", () => {
|
||||
assert.equal(compareReleaseVersions("0.17.0-beta.1", "0.16.2"), 1);
|
||||
assert.equal(compareReleaseVersions("0.17.0-beta.2", "0.17.0-beta.1"), 1);
|
||||
assert.equal(compareReleaseVersions("0.17.0", "0.17.0-beta.2"), 1);
|
||||
assert.equal(compareReleaseVersions("0.17.0-beta.2", "0.17.0"), -1);
|
||||
assert.equal(compareReleaseVersions("0.16.3", "0.17.0-beta.1"), -1);
|
||||
assert.equal(compareReleaseVersions("0.16.3", "0.16.2"), 1);
|
||||
assert.equal(compareReleaseVersions("0.17.0", "0.17.0"), 0);
|
||||
assert.equal(compareReleaseVersions("0.17.0-beta.2", "0.17.0-beta.2"), 0);
|
||||
});
|
||||
@@ -61,8 +61,21 @@ if (args.print) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
execFileSync(
|
||||
"npm",
|
||||
["version", nextVersion, "--include-workspace-root", "--message", "chore(release): cut %s"],
|
||||
{ cwd: rootDir, stdio: "inherit" },
|
||||
);
|
||||
const dirty = execFileSync("git", ["status", "--porcelain"], {
|
||||
cwd: rootDir,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
if (dirty) {
|
||||
throw new Error("Git working directory not clean. Commit or stash changes before bumping.");
|
||||
}
|
||||
|
||||
// Keep tagging atomic at `release:push` so `release:prep:*` can push the
|
||||
// release branch for CI verification without creating a local tag early.
|
||||
execFileSync("npm", ["version", nextVersion, "--include-workspace-root", "--no-git-tag-version"], {
|
||||
cwd: rootDir,
|
||||
stdio: "inherit",
|
||||
});
|
||||
execFileSync("git", ["commit", "-m", `chore(release): cut ${nextVersion}`], {
|
||||
cwd: rootDir,
|
||||
stdio: "inherit",
|
||||
});
|
||||
Reference in new issue
Block a user