@jonmilner/local-ci 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -1
- package/dist/cli.js +14 -2
- package/dist/config.d.ts +4 -1
- package/dist/config.js +21 -9
- package/dist/github.d.ts +3 -0
- package/dist/github.js +21 -1
- package/dist/release.d.ts +34 -0
- package/dist/release.js +263 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -23,6 +23,12 @@ exec pnpm exec local-ci pre-push "$@"
|
|
|
23
23
|
- `local-ci post <sha>`: waits up to 3 minutes for GitHub to have the commit, posts status `check` = `success` (`<command> passed on <hostname>`), then posts `pr-title` on it for an open PR that contains it (waiting up to 30s for GitHub to link them). A PR opened after the push, or a retitled one, needs `local-ci pr-title` run by hand.
|
|
24
24
|
- `local-ci pr-title [<pr>]`: lints the PR title (the current branch's PR by default) with `@jonmilner/commitlint-config` and posts status `pr-title` on its head commit, `failure` with the first error when the title does not pass.
|
|
25
25
|
- `local-ci status [<sha>]`: posts `check` for a commit (default `HEAD`) that already passed, or runs the check first. When the check command fails, it posts `check` = `failure` (`<command> failed on <hostname>`) and exits non-zero; a later passing run posts `success` over it. A dirty tree, a commit that is not `HEAD`, or a `gh` error posts nothing. Use it after a push that skipped hooks (`--no-verify`) or a lost background poster.
|
|
26
|
+
- `local-ci release`: publishes the repo's packages from this machine. Off unless `package.json` has `"local-ci": { "release": true }`; otherwise it prints `release not enabled` and exits 0. It needs a clean working tree, then fetches `origin` and takes a lock, so a second run exits with `release in progress`. In a temporary worktree at `origin`'s default branch:
|
|
27
|
+
1. With pending changesets, it creates `release/<short-sha>`, runs `pnpm changeset version`, commits `chore: version packages`, pushes (the hook runs the check and posts `check`), opens the PR, posts `pr-title`, waits for both statuses, and squash-merges it.
|
|
28
|
+
2. At the merge commit (or the default branch, with no changesets pending), it runs `local-ci status`, then `pnpm release` with the npm token, then pushes the tags `changeset publish` created.
|
|
29
|
+
3. It checks each published `name@version` with `npm view`.
|
|
30
|
+
|
|
31
|
+
Step 2 runs even with no changesets pending, so a rerun after a failed publish finishes the job. With nothing pending and every version already on npm it prints `nothing to release`. The repo needs changesets and a root `release` script (for example `pnpm build && changeset publish`). The npm token comes from the macOS Keychain (service `local-ci-npm`) and is passed only in `pnpm release`'s environment, never written to `.npmrc` or logged; see [npm publish token](../../docs/new-machine.md#npm-publish-token).
|
|
26
32
|
|
|
27
33
|
## Check command
|
|
28
34
|
|
|
@@ -36,6 +42,6 @@ A repo without a `package.json` sets `LOCAL_CI_COMMAND`, for example in the hook
|
|
|
36
42
|
|
|
37
43
|
## State
|
|
38
44
|
|
|
39
|
-
Logs
|
|
45
|
+
Logs, the record of passed commits and the release lock live in `~/.local/state/local-ci/<repo>.log`, `<repo>.passed` and `<repo>.release.lock` (`$XDG_STATE_HOME` if set). A lock whose process has died is taken over.
|
|
40
46
|
|
|
41
47
|
Part of [jonmilner/config](https://github.com/jonmilner/config#readme).
|
package/dist/cli.js
CHANGED
|
@@ -4,16 +4,18 @@ import { closeSync, openSync, readFileSync } from "node:fs";
|
|
|
4
4
|
import { hostname } from "node:os";
|
|
5
5
|
import { basename, dirname, resolve } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
|
-
import { passedCommand, recordPass, resolveCommand, statePaths } from "./config.js";
|
|
7
|
+
import { passedCommand, recordPass, releaseEnabled, resolveCommand, statePaths } from "./config.js";
|
|
8
8
|
import { exec } from "./exec.js";
|
|
9
9
|
import { assertGhAuth, checkStatus, postStatus, prTitleStatus, viewPr, waitForCommit, waitForOpenPr, } from "./github.js";
|
|
10
10
|
import { cannotCheckInPlace, githubRepo, parsePrePush, shasToCheck } from "./push.js";
|
|
11
|
+
import { release } from "./release.js";
|
|
11
12
|
import { lintTitle } from "./title.js";
|
|
12
13
|
const USAGE = `Usage:
|
|
13
14
|
local-ci pre-push run the check for each pushed commit (git pre-push hook)
|
|
14
15
|
local-ci post <sha> wait for <sha> on GitHub, then post its check and pr-title statuses
|
|
15
16
|
local-ci pr-title [<pr>] lint the PR title and post the pr-title status
|
|
16
|
-
local-ci status [<sha>] post check for <sha> (default HEAD), running the check if needed
|
|
17
|
+
local-ci status [<sha>] post check for <sha> (default HEAD), running the check if needed
|
|
18
|
+
local-ci release version pending changesets through a PR, publish to npm and push tags`;
|
|
17
19
|
const git = async (...args) => (await exec("git", args)).trim();
|
|
18
20
|
async function repo() {
|
|
19
21
|
const root = await git("rev-parse", "--show-toplevel");
|
|
@@ -127,9 +129,19 @@ async function status(ref = "HEAD") {
|
|
|
127
129
|
}
|
|
128
130
|
await post(current, sha);
|
|
129
131
|
}
|
|
132
|
+
async function runRelease() {
|
|
133
|
+
const { root, lock } = await repo();
|
|
134
|
+
// Off by default, so a repo that publishes some other way can't release by accident.
|
|
135
|
+
if (!releaseEnabled(root))
|
|
136
|
+
return out("release not enabled");
|
|
137
|
+
await assertGhAuth(exec);
|
|
138
|
+
out(await release(exec, { root, lock, cli: fileURLToPath(import.meta.url), prTitle, log }));
|
|
139
|
+
}
|
|
130
140
|
async function main([command, ...args]) {
|
|
131
141
|
if (command === "pre-push")
|
|
132
142
|
return prePush(args[1]);
|
|
143
|
+
if (command === "release")
|
|
144
|
+
return runRelease();
|
|
133
145
|
if (command === "post" || command === "pr-title" || command === "status") {
|
|
134
146
|
await assertGhAuth(exec);
|
|
135
147
|
}
|
package/dist/config.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
export declare const DEFAULT_COMMAND = "pnpm check";
|
|
2
2
|
/** The check command: `local-ci.command` in package.json, else `LOCAL_CI_COMMAND`, else `pnpm check`. */
|
|
3
3
|
export declare function resolveCommand(root: string, env?: NodeJS.ProcessEnv): string;
|
|
4
|
+
/** Whether `local-ci release` is switched on, with `"local-ci": { "release": true }` in package.json. */
|
|
5
|
+
export declare function releaseEnabled(root: string): boolean;
|
|
4
6
|
export declare function stateDir(env?: NodeJS.ProcessEnv): string;
|
|
5
|
-
/** Where a repo's log
|
|
7
|
+
/** Where a repo's log, record of passed commits and release lock live, created on first use. */
|
|
6
8
|
export declare function statePaths(repo: string, env?: NodeJS.ProcessEnv): {
|
|
7
9
|
log: string;
|
|
8
10
|
passed: string;
|
|
11
|
+
lock: string;
|
|
9
12
|
};
|
|
10
13
|
/** Records that `command` passed at `sha`, one `<sha>\t<command>` line per commit. */
|
|
11
14
|
export declare function recordPass(file: string, sha: string, command: string): void;
|
package/dist/config.js
CHANGED
|
@@ -2,25 +2,37 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
export const DEFAULT_COMMAND = "pnpm check";
|
|
5
|
+
/** The `local-ci` key of the repo's package.json, or `{}` without one. */
|
|
6
|
+
function localCiConfig(root) {
|
|
7
|
+
const manifest = join(root, "package.json");
|
|
8
|
+
if (!existsSync(manifest))
|
|
9
|
+
return {};
|
|
10
|
+
const pkg = JSON.parse(readFileSync(manifest, "utf8"));
|
|
11
|
+
return pkg["local-ci"] ?? {};
|
|
12
|
+
}
|
|
5
13
|
/** The check command: `local-ci.command` in package.json, else `LOCAL_CI_COMMAND`, else `pnpm check`. */
|
|
6
14
|
export function resolveCommand(root, env = process.env) {
|
|
7
|
-
const
|
|
8
|
-
if (
|
|
9
|
-
|
|
10
|
-
const command = pkg["local-ci"]?.command;
|
|
11
|
-
if (typeof command === "string" && command.trim())
|
|
12
|
-
return command;
|
|
13
|
-
}
|
|
15
|
+
const { command } = localCiConfig(root);
|
|
16
|
+
if (typeof command === "string" && command.trim())
|
|
17
|
+
return command;
|
|
14
18
|
return env.LOCAL_CI_COMMAND?.trim() || DEFAULT_COMMAND;
|
|
15
19
|
}
|
|
20
|
+
/** Whether `local-ci release` is switched on, with `"local-ci": { "release": true }` in package.json. */
|
|
21
|
+
export function releaseEnabled(root) {
|
|
22
|
+
return localCiConfig(root).release === true;
|
|
23
|
+
}
|
|
16
24
|
export function stateDir(env = process.env) {
|
|
17
25
|
return join(env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "local-ci");
|
|
18
26
|
}
|
|
19
|
-
/** Where a repo's log
|
|
27
|
+
/** Where a repo's log, record of passed commits and release lock live, created on first use. */
|
|
20
28
|
export function statePaths(repo, env = process.env) {
|
|
21
29
|
const dir = stateDir(env);
|
|
22
30
|
mkdirSync(dir, { recursive: true });
|
|
23
|
-
return {
|
|
31
|
+
return {
|
|
32
|
+
log: join(dir, `${repo}.log`),
|
|
33
|
+
passed: join(dir, `${repo}.passed`),
|
|
34
|
+
lock: join(dir, `${repo}.release.lock`),
|
|
35
|
+
};
|
|
24
36
|
}
|
|
25
37
|
/** Records that `command` passed at `sha`, one `<sha>\t<command>` line per commit. */
|
|
26
38
|
export function recordPass(file, sha, command) {
|
package/dist/github.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ export declare function assertGhAuth(exec: Exec): Promise<void>;
|
|
|
9
9
|
export declare function checkStatus(command: string, host: string, state?: StatusPayload["state"]): StatusPayload;
|
|
10
10
|
export declare function prTitleStatus(errors: string[]): StatusPayload;
|
|
11
11
|
export declare function postStatus(exec: Exec, sha: string, status: StatusPayload): Promise<void>;
|
|
12
|
+
export declare const defaultSleep: (ms: number) => Promise<void>;
|
|
12
13
|
export interface WaitOptions {
|
|
13
14
|
intervalMs?: number;
|
|
14
15
|
timeoutMs?: number;
|
|
@@ -27,3 +28,5 @@ export interface PullRequest {
|
|
|
27
28
|
}
|
|
28
29
|
/** The given PR, or the current branch's PR when `pr` is omitted. */
|
|
29
30
|
export declare function viewPr(exec: Exec, pr?: string): Promise<PullRequest>;
|
|
31
|
+
/** Polls until every context in `contexts` is `success` on `sha`; throws on the first that fails. */
|
|
32
|
+
export declare function waitForStatuses(exec: Exec, sha: string, contexts: string[], options?: WaitOptions): Promise<void>;
|
package/dist/github.js
CHANGED
|
@@ -43,7 +43,7 @@ export async function postStatus(exec, sha, status) {
|
|
|
43
43
|
`description=${status.description}`,
|
|
44
44
|
]);
|
|
45
45
|
}
|
|
46
|
-
const defaultSleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
46
|
+
export const defaultSleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
47
47
|
/** Polls until GitHub knows `sha`, since a pre-push hook runs before the push lands. */
|
|
48
48
|
export async function waitForCommit(exec, sha, options = {}) {
|
|
49
49
|
const { intervalMs = 5_000, timeoutMs = 180_000 } = options;
|
|
@@ -84,3 +84,23 @@ export async function viewPr(exec, pr) {
|
|
|
84
84
|
const args = ["pr", "view", ...(pr ? [pr] : []), "--json", "number,title,headRefOid"];
|
|
85
85
|
return JSON.parse(await exec("gh", args));
|
|
86
86
|
}
|
|
87
|
+
/** Polls until every context in `contexts` is `success` on `sha`; throws on the first that fails. */
|
|
88
|
+
export async function waitForStatuses(exec, sha, contexts, options = {}) {
|
|
89
|
+
const { intervalMs = 5_000, timeoutMs = 600_000 } = options;
|
|
90
|
+
const { sleep = defaultSleep } = options;
|
|
91
|
+
for (let waited = 0;; waited += intervalMs) {
|
|
92
|
+
// The combined status holds the latest status per context.
|
|
93
|
+
const { statuses } = JSON.parse(await exec("gh", ["api", `${REPO}/commits/${sha}/status`]));
|
|
94
|
+
const states = new Map(statuses.map((status) => [status.context, status.state]));
|
|
95
|
+
const failed = contexts.find((context) => /^(failure|error)$/.test(states.get(context) ?? ""));
|
|
96
|
+
if (failed)
|
|
97
|
+
throw new Error(`${failed} failed on ${sha.slice(0, 7)}`);
|
|
98
|
+
if (contexts.every((context) => states.get(context) === "success"))
|
|
99
|
+
return;
|
|
100
|
+
if (waited + intervalMs > timeoutMs) {
|
|
101
|
+
const missing = contexts.filter((context) => states.get(context) !== "success");
|
|
102
|
+
throw new Error(`${missing.join(" and ")} did not pass on ${sha.slice(0, 7)} within ${timeoutMs / 1000}s`);
|
|
103
|
+
}
|
|
104
|
+
await sleep(intervalMs);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Exec } from "./exec.ts";
|
|
2
|
+
/** The macOS Keychain generic password that holds the npm token. */
|
|
3
|
+
export declare const TOKEN_SERVICE = "local-ci-npm";
|
|
4
|
+
/** npm and pnpm read a registry token from this variable; it is set only for `pnpm release`. */
|
|
5
|
+
export declare const TOKEN_ENV = "NPM_CONFIG_//registry.npmjs.org/:_authToken";
|
|
6
|
+
export interface Package {
|
|
7
|
+
name: string;
|
|
8
|
+
version: string;
|
|
9
|
+
}
|
|
10
|
+
/** Takes the release lock and returns its release, or throws while a live process holds it. */
|
|
11
|
+
export declare function takeLock(file: string): () => void;
|
|
12
|
+
/** The changeset files waiting in `dir`'s `.changeset` folder. */
|
|
13
|
+
export declare function pendingChangesets(dir: string): string[];
|
|
14
|
+
/** The workspace's public packages at `dir`, with the versions in their package.json. */
|
|
15
|
+
export declare function publicPackages(exec: Exec, dir: string): Promise<Package[]>;
|
|
16
|
+
/** Whether npm has this exact version. A 404 means no; any other error is thrown. */
|
|
17
|
+
export declare function isPublished(exec: Exec, pkg: Package): Promise<boolean>;
|
|
18
|
+
/** Reads the npm token from the Keychain, failing with the setup doc when it is missing. */
|
|
19
|
+
export declare function readToken(exec: Exec): Promise<string>;
|
|
20
|
+
export interface ReleaseContext {
|
|
21
|
+
/** The checkout the command runs from. */
|
|
22
|
+
root: string;
|
|
23
|
+
lock: string;
|
|
24
|
+
/** This CLI, run as `status` in the release worktree to check the commit before publishing. */
|
|
25
|
+
cli: string;
|
|
26
|
+
/** Lints the PR title and posts `pr-title`, resolving false when the title fails. */
|
|
27
|
+
prTitle: (pr: string) => Promise<boolean>;
|
|
28
|
+
log: (message: string) => void;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Versions pending changesets through a merged PR, publishes what npm lacks, pushes the tags and
|
|
32
|
+
* verifies the publish. Resolves with a one-line summary.
|
|
33
|
+
*/
|
|
34
|
+
export declare function release(exec: Exec, context: ReleaseContext): Promise<string>;
|
package/dist/release.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, linkSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { defaultSleep, waitForStatuses } from "./github.js";
|
|
6
|
+
/** The macOS Keychain generic password that holds the npm token. */
|
|
7
|
+
export const TOKEN_SERVICE = "local-ci-npm";
|
|
8
|
+
/** npm and pnpm read a registry token from this variable; it is set only for `pnpm release`. */
|
|
9
|
+
export const TOKEN_ENV = "NPM_CONFIG_//registry.npmjs.org/:_authToken";
|
|
10
|
+
const SETUP_DOC = "https://github.com/jonmilner/config/blob/main/docs/new-machine.md#npm-publish-token";
|
|
11
|
+
const VERSION_TITLE = "chore: version packages";
|
|
12
|
+
// What npm and pnpm print when the registry rejects the token, or wants an OTP it can't bypass.
|
|
13
|
+
const AUTH_ERROR = /\b(?:E401|E403|EOTP|401 Unauthorized|403 Forbidden)\b/;
|
|
14
|
+
const id = ({ name, version }) => `${name}@${version}`;
|
|
15
|
+
function alive(pid) {
|
|
16
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
17
|
+
return false;
|
|
18
|
+
try {
|
|
19
|
+
process.kill(pid, 0);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
// EPERM: the process exists but belongs to another user.
|
|
24
|
+
return error.code === "EPERM";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Takes the release lock and returns its release, or throws while a live process holds it. */
|
|
28
|
+
export function takeLock(file) {
|
|
29
|
+
// Linking a file that already holds the pid publishes the lock atomically, so nobody reads it empty.
|
|
30
|
+
const mine = `${file}.${process.pid}`;
|
|
31
|
+
writeFileSync(mine, String(process.pid));
|
|
32
|
+
try {
|
|
33
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
34
|
+
try {
|
|
35
|
+
linkSync(mine, file);
|
|
36
|
+
return () => rmSync(file, { force: true });
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error.code !== "EEXIST")
|
|
40
|
+
throw error;
|
|
41
|
+
const pid = Number(readFileSync(file, "utf8"));
|
|
42
|
+
if (alive(pid))
|
|
43
|
+
throw new Error(`release in progress (pid ${pid}, lock ${file})`);
|
|
44
|
+
// The holder died without releasing it.
|
|
45
|
+
rmSync(file, { force: true });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
rmSync(mine, { force: true });
|
|
51
|
+
}
|
|
52
|
+
throw new Error(`could not take the release lock ${file}`);
|
|
53
|
+
}
|
|
54
|
+
/** The changeset files waiting in `dir`'s `.changeset` folder. */
|
|
55
|
+
export function pendingChangesets(dir) {
|
|
56
|
+
const folder = join(dir, ".changeset");
|
|
57
|
+
if (!existsSync(folder))
|
|
58
|
+
return [];
|
|
59
|
+
return readdirSync(folder).filter((file) => file.endsWith(".md") && file !== "README.md");
|
|
60
|
+
}
|
|
61
|
+
/** The workspace's public packages at `dir`, with the versions in their package.json. */
|
|
62
|
+
export async function publicPackages(exec, dir) {
|
|
63
|
+
const projects = JSON.parse(await exec("pnpm", ["-C", dir, "ls", "-r", "--depth", "-1", "--json"]));
|
|
64
|
+
return projects.flatMap(({ name, version, private: isPrivate }) => name && version && !isPrivate ? [{ name, version }] : []);
|
|
65
|
+
}
|
|
66
|
+
/** Whether npm has this exact version. A 404 means no; any other error is thrown. */
|
|
67
|
+
export async function isPublished(exec, pkg) {
|
|
68
|
+
try {
|
|
69
|
+
return (await exec("npm", ["view", id(pkg), "version"])).trim() === pkg.version;
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error instanceof Error && /\bE404\b/.test(error.message))
|
|
73
|
+
return false;
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async function unpublished(exec, packages) {
|
|
78
|
+
const published = await Promise.all(packages.map((pkg) => isPublished(exec, pkg)));
|
|
79
|
+
return packages.filter((_, index) => !published[index]);
|
|
80
|
+
}
|
|
81
|
+
/** Reads the npm token from the Keychain, failing with the setup doc when it is missing. */
|
|
82
|
+
export async function readToken(exec) {
|
|
83
|
+
let token = "";
|
|
84
|
+
try {
|
|
85
|
+
token = (await exec("security", ["find-generic-password", "-s", TOKEN_SERVICE, "-w"])).trim();
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Not found, or the Keychain is locked: either way there is no token to use.
|
|
89
|
+
}
|
|
90
|
+
if (!token) {
|
|
91
|
+
throw new Error(`no npm token in the macOS Keychain (service ${TOKEN_SERVICE}). Create and store one: ${SETUP_DOC}`);
|
|
92
|
+
}
|
|
93
|
+
return token;
|
|
94
|
+
}
|
|
95
|
+
/** Runs a command in `cwd` with its output shown, throwing when it exits non-zero. */
|
|
96
|
+
function run(file, args, cwd) {
|
|
97
|
+
const result = spawnSync(file, args, { cwd, stdio: ["ignore", "inherit", "inherit"] });
|
|
98
|
+
if (result.status !== 0) {
|
|
99
|
+
const cause = result.error?.message ?? result.signal ?? `exit ${result.status}`;
|
|
100
|
+
throw new Error(`${file} ${args.join(" ")} failed (${cause})`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Runs `pnpm release` with the token in its env only, teeing its output to spot a rejected token. */
|
|
104
|
+
function publish(dir, token) {
|
|
105
|
+
return new Promise((resolve, reject) => {
|
|
106
|
+
const child = spawn("pnpm", ["release"], {
|
|
107
|
+
cwd: dir,
|
|
108
|
+
// CI makes changesets fail on an OTP request instead of prompting on an ignored stdin.
|
|
109
|
+
env: { ...process.env, CI: "true", [TOKEN_ENV]: token },
|
|
110
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
111
|
+
});
|
|
112
|
+
let authError = false;
|
|
113
|
+
const tee = (stream, sink) => {
|
|
114
|
+
// Keep a tail so a match split across chunks is still seen.
|
|
115
|
+
let tail = "";
|
|
116
|
+
stream.on("data", (chunk) => {
|
|
117
|
+
sink.write(chunk);
|
|
118
|
+
const text = tail + chunk.toString();
|
|
119
|
+
if (AUTH_ERROR.test(text))
|
|
120
|
+
authError = true;
|
|
121
|
+
tail = text.slice(-32);
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
tee(child.stdout, process.stdout);
|
|
125
|
+
tee(child.stderr, process.stderr);
|
|
126
|
+
child.on("error", reject);
|
|
127
|
+
child.on("close", (code, signal) => {
|
|
128
|
+
if (code === 0)
|
|
129
|
+
return resolve();
|
|
130
|
+
reject(new Error(authError
|
|
131
|
+
? `npm rejected the token in the Keychain (service ${TOKEN_SERVICE}); it may have expired or lack "bypass 2FA". Rotate it: ${SETUP_DOC}`
|
|
132
|
+
: `pnpm release failed (${code === null ? signal : `exit ${code}`})`));
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/** Polls npm until each package is visible, since the registry lags a publish slightly. */
|
|
137
|
+
async function verify(exec, packages, options = {}) {
|
|
138
|
+
const { intervalMs = 5_000, timeoutMs = 60_000, sleep = defaultSleep } = options;
|
|
139
|
+
for (const pkg of packages) {
|
|
140
|
+
for (let waited = 0; !(await isPublished(exec, pkg)); waited += intervalMs) {
|
|
141
|
+
if (waited + intervalMs > timeoutMs)
|
|
142
|
+
throw new Error(`${id(pkg)} is not on npm after publishing`);
|
|
143
|
+
await sleep(intervalMs);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** Pushes the local `name@version` tags of `packages` that origin lacks, resolving with their names. */
|
|
148
|
+
async function pushTags(git, dir, packages) {
|
|
149
|
+
const local = new Set((await git(dir, "tag", "--list")).split("\n"));
|
|
150
|
+
const remote = new Set((await git(dir, "ls-remote", "--tags", "origin"))
|
|
151
|
+
.split("\n")
|
|
152
|
+
.map((line) => line.split("\t")[1]?.replace(/^refs\/tags\//, "")));
|
|
153
|
+
const missing = packages.map(id).filter((tag) => local.has(tag) && !remote.has(tag));
|
|
154
|
+
if (missing.length)
|
|
155
|
+
run("git", ["push", "origin", ...missing.map((tag) => `refs/tags/${tag}`)], dir);
|
|
156
|
+
return missing;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Versions pending changesets through a merged PR, publishes what npm lacks, pushes the tags and
|
|
160
|
+
* verifies the publish. Resolves with a one-line summary.
|
|
161
|
+
*/
|
|
162
|
+
export async function release(exec, context) {
|
|
163
|
+
const { root, log } = context;
|
|
164
|
+
const git = async (cwd, ...args) => (await exec("git", ["-C", cwd, ...args])).trim();
|
|
165
|
+
if (await git(root, "status", "--porcelain")) {
|
|
166
|
+
throw new Error("the working tree has uncommitted or untracked files; commit or stash them first");
|
|
167
|
+
}
|
|
168
|
+
await git(root, "fetch", "origin");
|
|
169
|
+
const unlock = takeLock(context.lock);
|
|
170
|
+
const temp = mkdtempSync(join(tmpdir(), "local-ci-release-"));
|
|
171
|
+
const dir = join(temp, "worktree");
|
|
172
|
+
let branch;
|
|
173
|
+
// Set from the push until the merge, so a failure in between closes the PR and deletes the branch.
|
|
174
|
+
let remoteBranch;
|
|
175
|
+
let repo;
|
|
176
|
+
let pr;
|
|
177
|
+
try {
|
|
178
|
+
const remoteHead = await git(root, "symbolic-ref", "--short", "refs/remotes/origin/HEAD").catch(() => "origin/main");
|
|
179
|
+
const base = remoteHead.replace(/^origin\//, "");
|
|
180
|
+
await git(root, "worktree", "add", "--detach", dir, `origin/${base}`);
|
|
181
|
+
const pending = pendingChangesets(dir);
|
|
182
|
+
const current = await publicPackages(exec, dir);
|
|
183
|
+
let packages = await unpublished(exec, current);
|
|
184
|
+
if (!pending.length && !packages.length) {
|
|
185
|
+
// A run that published but failed to push its tags leaves them here for the next one.
|
|
186
|
+
const pushed = await pushTags(git, dir, current);
|
|
187
|
+
return pushed.length ? `pushed tags ${pushed.join(", ")}` : "nothing to release";
|
|
188
|
+
}
|
|
189
|
+
// Read it before changing anything, so a missing token stops the run with nothing to undo.
|
|
190
|
+
const token = await readToken(exec);
|
|
191
|
+
if (pending.length) {
|
|
192
|
+
branch = `release/${await git(dir, "rev-parse", "--short", "HEAD")}`;
|
|
193
|
+
log(`versioning ${pending.length} changeset(s) on ${branch}`);
|
|
194
|
+
await git(dir, "switch", "-c", branch);
|
|
195
|
+
run("pnpm", ["install", "--frozen-lockfile"], dir);
|
|
196
|
+
run("pnpm", ["exec", "changeset", "version"], dir);
|
|
197
|
+
// Bumped workspace specifiers change the lockfile, which the frozen install below needs.
|
|
198
|
+
run("pnpm", ["install", "--lockfile-only"], dir);
|
|
199
|
+
await git(dir, "add", "-A");
|
|
200
|
+
await git(dir, "commit", "-m", VERSION_TITLE);
|
|
201
|
+
const sha = await git(dir, "rev-parse", "HEAD");
|
|
202
|
+
// The pre-push hook runs the check and posts `check`.
|
|
203
|
+
run("git", ["push", "-u", "origin", branch], dir);
|
|
204
|
+
remoteBranch = branch;
|
|
205
|
+
repo = (await exec("gh", ["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"])).trim();
|
|
206
|
+
const url = await exec("gh", [
|
|
207
|
+
"pr",
|
|
208
|
+
"create",
|
|
209
|
+
"--repo",
|
|
210
|
+
repo,
|
|
211
|
+
"--base",
|
|
212
|
+
base,
|
|
213
|
+
"--head",
|
|
214
|
+
branch,
|
|
215
|
+
"--title",
|
|
216
|
+
VERSION_TITLE,
|
|
217
|
+
"--body",
|
|
218
|
+
"Versions the pending changesets. Opened by `local-ci release`.",
|
|
219
|
+
]);
|
|
220
|
+
pr = /\/pull\/(\d+)/.exec(url)?.[1];
|
|
221
|
+
if (!pr)
|
|
222
|
+
throw new Error(`could not read the PR number from: ${url.trim()}`);
|
|
223
|
+
log(`opened #${pr}; waiting for check and pr-title`);
|
|
224
|
+
if (!(await context.prTitle(pr)))
|
|
225
|
+
throw new Error(`#${pr} has a failing pr-title`);
|
|
226
|
+
await waitForStatuses(exec, sha, ["check", "pr-title"]);
|
|
227
|
+
// --repo keeps gh from switching branches in this worktree after the merge.
|
|
228
|
+
await exec("gh", ["pr", "merge", pr, "--repo", repo, "--squash", "--delete-branch"]);
|
|
229
|
+
const merged = JSON.parse(await exec("gh", ["pr", "view", pr, "--repo", repo, "--json", "state,mergeCommit"]));
|
|
230
|
+
if (merged.state !== "MERGED" || !merged.mergeCommit) {
|
|
231
|
+
throw new Error(`#${pr} did not merge (state ${merged.state})`);
|
|
232
|
+
}
|
|
233
|
+
// Merging deleted the branch.
|
|
234
|
+
remoteBranch = undefined;
|
|
235
|
+
log(`merged #${pr} as ${merged.mergeCommit.oid.slice(0, 7)}`);
|
|
236
|
+
await git(dir, "fetch", "origin");
|
|
237
|
+
await git(dir, "switch", "--detach", merged.mergeCommit.oid);
|
|
238
|
+
packages = await unpublished(exec, await publicPackages(exec, dir));
|
|
239
|
+
}
|
|
240
|
+
run("pnpm", ["install", "--frozen-lockfile"], dir);
|
|
241
|
+
// The same check the push required, on the commit being published.
|
|
242
|
+
run(process.execPath, [context.cli, "status"], dir);
|
|
243
|
+
log(`publishing ${packages.map(id).join(", ") || "nothing new"}`);
|
|
244
|
+
await publish(dir, token);
|
|
245
|
+
// Every current version, so a tag an earlier half-failed run left unpushed goes too.
|
|
246
|
+
await pushTags(git, dir, await publicPackages(exec, dir));
|
|
247
|
+
await verify(exec, packages);
|
|
248
|
+
return packages.length ? `released ${packages.map(id).join(", ")}` : "nothing to release";
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
if (remoteBranch) {
|
|
252
|
+
log(`cleaning up ${pr ? `#${pr} and ` : ""}${remoteBranch} so the next run starts fresh`);
|
|
253
|
+
await (pr && repo
|
|
254
|
+
? exec("gh", ["pr", "close", pr, "--repo", repo, "--delete-branch"])
|
|
255
|
+
: git(root, "push", "origin", "--delete", remoteBranch)).catch((error) => log(`cleanup failed: ${error.message}`));
|
|
256
|
+
}
|
|
257
|
+
await git(root, "worktree", "remove", "--force", dir).catch(() => { });
|
|
258
|
+
if (branch)
|
|
259
|
+
await git(root, "branch", "-D", branch).catch(() => { });
|
|
260
|
+
rmSync(temp, { recursive: true, force: true });
|
|
261
|
+
unlock();
|
|
262
|
+
}
|
|
263
|
+
}
|