@jonmilner/local-ci 0.2.0 → 0.3.1

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 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 the root `version-packages` script if `package.json` has one (for steps such as a size-history entry that belong in the version PR) or `pnpm changeset version` otherwise, 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
+ A failure after the push closes the PR and deletes `release/<short-sha>`; Ctrl-C (SIGINT) or SIGTERM stops the running step (killing `pnpm release`), does the same cleanup, then exits 130 or 143 (a second signal exits at once). A run killed outright leaves its temp worktree and local branch, which the next run removes; its PR and remote branch stay open for you to close. 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 and the record of passed commits live in `~/.local/state/local-ci/<repo>.log` and `<repo>.passed` (`$XDG_STATE_HOME` if set).
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 and record of passed commits live, created on first use. */
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 manifest = join(root, "package.json");
8
- if (existsSync(manifest)) {
9
- const pkg = JSON.parse(readFileSync(manifest, "utf8"));
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 and record of passed commits live, created on first use. */
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 { log: join(dir, `${repo}.log`), passed: join(dir, `${repo}.passed`) };
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,37 @@
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
+ /** How `dir` versions its changesets: its root `version-packages` script, else `changeset version`. */
15
+ export declare function versionCommand(dir: string): string[];
16
+ /** The workspace's public packages at `dir`, with the versions in their package.json. */
17
+ export declare function publicPackages(exec: Exec, dir: string): Promise<Package[]>;
18
+ /** Whether npm has this exact version. A 404 means no; any other error is thrown. */
19
+ export declare function isPublished(exec: Exec, pkg: Package): Promise<boolean>;
20
+ /** Reads the npm token from the Keychain, failing with the setup doc when it is missing. */
21
+ export declare function readToken(exec: Exec): Promise<string>;
22
+ export interface ReleaseContext {
23
+ /** The checkout the command runs from. */
24
+ root: string;
25
+ lock: string;
26
+ /** This CLI, run as `status` in the release worktree to check the commit before publishing. */
27
+ cli: string;
28
+ /** Lints the PR title and posts `pr-title`, resolving false when the title fails. */
29
+ prTitle: (pr: string) => Promise<boolean>;
30
+ log: (message: string) => void;
31
+ }
32
+ /**
33
+ * Versions pending changesets through a merged PR, publishes what npm lacks, pushes the tags and
34
+ * verifies the publish. Resolves with a one-line summary. SIGINT or SIGTERM runs the same cleanup
35
+ * as a failure, then exits 128 + the signal number.
36
+ */
37
+ export declare function release(exec: Exec, context: ReleaseContext): Promise<string>;
@@ -0,0 +1,358 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, linkSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
3
+ import { constants, tmpdir } from "node:os";
4
+ import { basename, dirname, 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
+ const TEMP_PREFIX = "local-ci-release-";
13
+ const SIGNALS = ["SIGINT", "SIGTERM"];
14
+ // What npm and pnpm print when the registry rejects the token, or wants an OTP it can't bypass.
15
+ const AUTH_ERROR = /\b(?:E401|E403|EOTP|401 Unauthorized|403 Forbidden)\b/;
16
+ const id = ({ name, version }) => `${name}@${version}`;
17
+ function alive(pid) {
18
+ if (!Number.isInteger(pid) || pid <= 0)
19
+ return false;
20
+ try {
21
+ process.kill(pid, 0);
22
+ return true;
23
+ }
24
+ catch (error) {
25
+ // EPERM: the process exists but belongs to another user.
26
+ return error.code === "EPERM";
27
+ }
28
+ }
29
+ /** Takes the release lock and returns its release, or throws while a live process holds it. */
30
+ export function takeLock(file) {
31
+ // Linking a file that already holds the pid publishes the lock atomically, so nobody reads it empty.
32
+ const mine = `${file}.${process.pid}`;
33
+ writeFileSync(mine, String(process.pid));
34
+ try {
35
+ for (let attempt = 0; attempt < 2; attempt++) {
36
+ try {
37
+ linkSync(mine, file);
38
+ return () => rmSync(file, { force: true });
39
+ }
40
+ catch (error) {
41
+ if (error.code !== "EEXIST")
42
+ throw error;
43
+ const pid = Number(readFileSync(file, "utf8"));
44
+ if (alive(pid))
45
+ throw new Error(`release in progress (pid ${pid}, lock ${file})`);
46
+ // The holder died without releasing it.
47
+ rmSync(file, { force: true });
48
+ }
49
+ }
50
+ }
51
+ finally {
52
+ rmSync(mine, { force: true });
53
+ }
54
+ throw new Error(`could not take the release lock ${file}`);
55
+ }
56
+ /** The changeset files waiting in `dir`'s `.changeset` folder. */
57
+ export function pendingChangesets(dir) {
58
+ const folder = join(dir, ".changeset");
59
+ if (!existsSync(folder))
60
+ return [];
61
+ return readdirSync(folder).filter((file) => file.endsWith(".md") && file !== "README.md");
62
+ }
63
+ /** How `dir` versions its changesets: its root `version-packages` script, else `changeset version`. */
64
+ export function versionCommand(dir) {
65
+ const { scripts } = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
66
+ const script = scripts?.["version-packages"];
67
+ return typeof script === "string" && script.trim()
68
+ ? ["run", "version-packages"]
69
+ : ["exec", "changeset", "version"];
70
+ }
71
+ /** The workspace's public packages at `dir`, with the versions in their package.json. */
72
+ export async function publicPackages(exec, dir) {
73
+ const projects = JSON.parse(await exec("pnpm", ["-C", dir, "ls", "-r", "--depth", "-1", "--json"]));
74
+ return projects.flatMap(({ name, version, private: isPrivate }) => name && version && !isPrivate ? [{ name, version }] : []);
75
+ }
76
+ /** Whether npm has this exact version. A 404 means no; any other error is thrown. */
77
+ export async function isPublished(exec, pkg) {
78
+ try {
79
+ return (await exec("npm", ["view", id(pkg), "version"])).trim() === pkg.version;
80
+ }
81
+ catch (error) {
82
+ if (error instanceof Error && /\bE404\b/.test(error.message))
83
+ return false;
84
+ throw error;
85
+ }
86
+ }
87
+ async function unpublished(exec, packages) {
88
+ const published = await Promise.all(packages.map((pkg) => isPublished(exec, pkg)));
89
+ return packages.filter((_, index) => !published[index]);
90
+ }
91
+ /** Reads the npm token from the Keychain, failing with the setup doc when it is missing. */
92
+ export async function readToken(exec) {
93
+ let token = "";
94
+ try {
95
+ token = (await exec("security", ["find-generic-password", "-s", TOKEN_SERVICE, "-w"])).trim();
96
+ }
97
+ catch {
98
+ // Not found, or the Keychain is locked: either way there is no token to use.
99
+ }
100
+ if (!token) {
101
+ throw new Error(`no npm token in the macOS Keychain (service ${TOKEN_SERVICE}). Create and store one: ${SETUP_DOC}`);
102
+ }
103
+ return token;
104
+ }
105
+ /** Runs a command in `cwd` with its output shown, throwing when it exits non-zero. */
106
+ function run(file, args, cwd) {
107
+ const result = spawnSync(file, args, { cwd, stdio: ["ignore", "inherit", "inherit"] });
108
+ if (result.status !== 0) {
109
+ const cause = result.error?.message ?? result.signal ?? `exit ${result.status}`;
110
+ throw new Error(`${file} ${args.join(" ")} failed (${cause})`);
111
+ }
112
+ }
113
+ /** Runs `pnpm release` with the token in its env only, teeing its output to spot a rejected token. */
114
+ function publish(dir, token, signal) {
115
+ return new Promise((resolve, reject) => {
116
+ const child = spawn("pnpm", ["release"], {
117
+ cwd: dir,
118
+ // An interrupt kills it, and the close below settles only once it has exited.
119
+ signal,
120
+ // CI makes changesets fail on an OTP request instead of prompting on an ignored stdin.
121
+ env: { ...process.env, CI: "true", [TOKEN_ENV]: token },
122
+ stdio: ["ignore", "pipe", "pipe"],
123
+ });
124
+ let authError = false;
125
+ const tee = (stream, sink) => {
126
+ // Keep a tail so a match split across chunks is still seen.
127
+ let tail = "";
128
+ stream.on("data", (chunk) => {
129
+ sink.write(chunk);
130
+ const text = tail + chunk.toString();
131
+ if (AUTH_ERROR.test(text))
132
+ authError = true;
133
+ tail = text.slice(-32);
134
+ });
135
+ };
136
+ tee(child.stdout, process.stdout);
137
+ tee(child.stderr, process.stderr);
138
+ child.on("error", (error) => {
139
+ if (!signal.aborted)
140
+ reject(error);
141
+ });
142
+ child.on("close", (code, killed) => {
143
+ if (code === 0)
144
+ return resolve();
145
+ reject(new Error(authError
146
+ ? `npm rejected the token in the Keychain (service ${TOKEN_SERVICE}); it may have expired or lack "bypass 2FA". Rotate it: ${SETUP_DOC}`
147
+ : `pnpm release failed (${code === null ? killed : `exit ${code}`})`));
148
+ });
149
+ });
150
+ }
151
+ /** Polls npm until each package is visible, since the registry lags a publish slightly. */
152
+ async function verify(exec, packages, options = {}) {
153
+ const { intervalMs = 5_000, timeoutMs = 60_000, sleep = defaultSleep } = options;
154
+ for (const pkg of packages) {
155
+ for (let waited = 0; !(await isPublished(exec, pkg)); waited += intervalMs) {
156
+ if (waited + intervalMs > timeoutMs)
157
+ throw new Error(`${id(pkg)} is not on npm after publishing`);
158
+ await sleep(intervalMs);
159
+ }
160
+ }
161
+ }
162
+ const gitWith = (exec) => async (cwd, ...args) => (await exec("git", ["-C", cwd, ...args])).trim();
163
+ /** Pushes the local `name@version` tags of `packages` that origin lacks, resolving with their names. */
164
+ async function pushTags(git, run, dir, packages) {
165
+ const local = new Set((await git(dir, "tag", "--list")).split("\n"));
166
+ const remote = new Set((await git(dir, "ls-remote", "--tags", "origin"))
167
+ .split("\n")
168
+ .map((line) => line.split("\t")[1]?.replace(/^refs\/tags\//, "")));
169
+ const missing = packages.map(id).filter((tag) => local.has(tag) && !remote.has(tag));
170
+ if (missing.length)
171
+ await run("git", ["push", "origin", ...missing.map((tag) => `refs/tags/${tag}`)], dir);
172
+ return missing;
173
+ }
174
+ /**
175
+ * Removes the temp worktrees and `release/*` branches that runs killed before their cleanup left,
176
+ * then `branch` if it remains. `own` is this run's worktree, which stays. The lock is held, so none of them belongs to a live run.
177
+ */
178
+ async function pruneStale(git, root, own, branch) {
179
+ // Forgets worktrees whose directory is gone, so their branch can be deleted.
180
+ await git(root, "worktree", "prune");
181
+ const branches = new Set([branch]);
182
+ for (const entry of (await git(root, "worktree", "list", "--porcelain")).split("\n\n")) {
183
+ const path = /^worktree (.+)$/m.exec(entry)?.[1];
184
+ // Only a temp directory as `release` creates it, other than this run's. Its unique name tells
185
+ // them apart, since git may report a path with its symlinks resolved.
186
+ const temp = path && basename(path) === "worktree" ? basename(dirname(path)) : "";
187
+ if (!path || !temp.startsWith(TEMP_PREFIX) || temp === basename(dirname(own)))
188
+ continue;
189
+ // Twice, so a locked worktree goes too.
190
+ await git(root, "worktree", "remove", "--force", "--force", path);
191
+ rmSync(dirname(path), { recursive: true, force: true });
192
+ const held = /^branch refs\/heads\/(release\/.+)$/m.exec(entry)?.[1];
193
+ if (held)
194
+ branches.add(held);
195
+ }
196
+ for (const name of branches) {
197
+ if (await git(root, "branch", "--list", name))
198
+ await git(root, "branch", "-D", name);
199
+ }
200
+ }
201
+ /**
202
+ * Versions pending changesets through a merged PR, publishes what npm lacks, pushes the tags and
203
+ * verifies the publish. Resolves with a one-line summary. SIGINT or SIGTERM runs the same cleanup
204
+ * as a failure, then exits 128 + the signal number.
205
+ */
206
+ export async function release(exec, context) {
207
+ const { root, log } = context;
208
+ const git = gitWith(exec);
209
+ if (await git(root, "status", "--porcelain")) {
210
+ throw new Error("the working tree has uncommitted or untracked files; commit or stash them first");
211
+ }
212
+ await git(root, "fetch", "origin");
213
+ const unlock = takeLock(context.lock);
214
+ const temp = mkdtempSync(join(tmpdir(), TEMP_PREFIX));
215
+ const dir = join(temp, "worktree");
216
+ let branch;
217
+ // Set from the push until the merge, so a failure in between closes the PR and deletes the branch.
218
+ let remoteBranch;
219
+ let repo;
220
+ let pr;
221
+ let interrupted;
222
+ const abort = new AbortController();
223
+ // Once a signal arrives no step starts, so nothing races the cleanup or outlives it.
224
+ const live = async () => {
225
+ // A signal that arrived during a synchronous step is delivered only once the event loop turns.
226
+ await new Promise((resolve) => setImmediate(resolve));
227
+ if (interrupted)
228
+ throw new Error(`interrupted by ${interrupted}`);
229
+ };
230
+ // The step running now, which the cleanup waits for so it never pulls the worktree from under it.
231
+ let inFlight = Promise.resolve();
232
+ const track = (promise) => {
233
+ inFlight = promise.catch(() => { });
234
+ return promise;
235
+ };
236
+ const step = async (file, args) => {
237
+ await live();
238
+ return track(exec(file, args));
239
+ };
240
+ const stepGit = gitWith(step);
241
+ const stepRun = async (file, args, cwd) => {
242
+ await live();
243
+ run(file, args, cwd);
244
+ };
245
+ // Set once the run is cleaning up on its own, so a signal then doesn't turn a success into an exit.
246
+ let finishing = false;
247
+ let cleaning;
248
+ const cleanup = () => (cleaning ??= (async () => {
249
+ if (remoteBranch) {
250
+ log(`cleaning up ${pr ? `#${pr} and ` : ""}${remoteBranch} so the next run starts fresh`);
251
+ await (pr && repo
252
+ ? exec("gh", ["pr", "close", pr, "--repo", repo, "--delete-branch"])
253
+ : git(root, "push", "origin", "--delete", remoteBranch)).catch((error) => log(`cleanup failed: ${error.message}`));
254
+ }
255
+ await git(root, "worktree", "remove", "--force", dir).catch(() => { });
256
+ if (branch)
257
+ await git(root, "branch", "-D", branch).catch(() => { });
258
+ rmSync(temp, { recursive: true, force: true });
259
+ unlock();
260
+ })());
261
+ const onSignal = (signal) => {
262
+ // `once` hands a second signal back to Node's default, which exits at once.
263
+ if (finishing)
264
+ return;
265
+ interrupted = signal;
266
+ abort.abort();
267
+ log(`${signal}: cleaning up before exiting; send it again to exit now`);
268
+ void inFlight
269
+ .then(() => cleanup())
270
+ .finally(() => process.exit(128 + constants.signals[signal]));
271
+ };
272
+ for (const signal of SIGNALS)
273
+ process.once(signal, onSignal);
274
+ try {
275
+ await live();
276
+ // Unguarded, like the token read below, so the fallback can't swallow an interrupt.
277
+ const remoteHead = await git(root, "symbolic-ref", "--short", "refs/remotes/origin/HEAD").catch(() => "origin/main");
278
+ const base = remoteHead.replace(/^origin\//, "");
279
+ await stepGit(root, "worktree", "add", "--detach", dir, `origin/${base}`);
280
+ const pending = pendingChangesets(dir);
281
+ const current = await publicPackages(step, dir);
282
+ let packages = await unpublished(step, current);
283
+ if (!pending.length && !packages.length) {
284
+ // A run that published but failed to push its tags leaves them here for the next one.
285
+ const pushed = await pushTags(stepGit, stepRun, dir, current);
286
+ return pushed.length ? `pushed tags ${pushed.join(", ")}` : "nothing to release";
287
+ }
288
+ // Read it before changing anything, so a missing token stops the run with nothing to undo.
289
+ await live();
290
+ const token = await readToken(exec);
291
+ if (pending.length) {
292
+ branch = `release/${await stepGit(dir, "rev-parse", "--short", "HEAD")}`;
293
+ await pruneStale(stepGit, root, dir, branch);
294
+ log(`versioning ${pending.length} changeset(s) on ${branch}`);
295
+ await stepGit(dir, "switch", "-c", branch);
296
+ await stepRun("pnpm", ["install", "--frozen-lockfile"], dir);
297
+ await stepRun("pnpm", versionCommand(dir), dir);
298
+ // Bumped workspace specifiers change the lockfile, which the frozen install below needs.
299
+ await stepRun("pnpm", ["install", "--lockfile-only"], dir);
300
+ await stepGit(dir, "add", "-A");
301
+ await stepGit(dir, "commit", "-m", VERSION_TITLE);
302
+ const sha = await stepGit(dir, "rev-parse", "HEAD");
303
+ // The pre-push hook runs the check and posts `check`.
304
+ await stepRun("git", ["push", "-u", "origin", branch], dir);
305
+ remoteBranch = branch;
306
+ repo = (await step("gh", ["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"])).trim();
307
+ const url = await step("gh", [
308
+ "pr",
309
+ "create",
310
+ "--repo",
311
+ repo,
312
+ "--base",
313
+ base,
314
+ "--head",
315
+ branch,
316
+ "--title",
317
+ VERSION_TITLE,
318
+ "--body",
319
+ "Versions the pending changesets. Opened by `local-ci release`.",
320
+ ]);
321
+ pr = /\/pull\/(\d+)/.exec(url)?.[1];
322
+ if (!pr)
323
+ throw new Error(`could not read the PR number from: ${url.trim()}`);
324
+ log(`opened #${pr}; waiting for check and pr-title`);
325
+ if (!(await context.prTitle(pr)))
326
+ throw new Error(`#${pr} has a failing pr-title`);
327
+ await waitForStatuses(step, sha, ["check", "pr-title"]);
328
+ // --repo keeps gh from switching branches in this worktree after the merge.
329
+ await step("gh", ["pr", "merge", pr, "--repo", repo, "--squash", "--delete-branch"]);
330
+ const merged = JSON.parse(await step("gh", ["pr", "view", pr, "--repo", repo, "--json", "state,mergeCommit"]));
331
+ if (merged.state !== "MERGED" || !merged.mergeCommit) {
332
+ throw new Error(`#${pr} did not merge (state ${merged.state})`);
333
+ }
334
+ // Merging deleted the branch.
335
+ remoteBranch = undefined;
336
+ log(`merged #${pr} as ${merged.mergeCommit.oid.slice(0, 7)}`);
337
+ await stepGit(dir, "fetch", "origin");
338
+ await stepGit(dir, "switch", "--detach", merged.mergeCommit.oid);
339
+ packages = await unpublished(step, await publicPackages(step, dir));
340
+ }
341
+ await stepRun("pnpm", ["install", "--frozen-lockfile"], dir);
342
+ // The same check the push required, on the commit being published.
343
+ await stepRun(process.execPath, [context.cli, "status"], dir);
344
+ await live();
345
+ log(`publishing ${packages.map(id).join(", ") || "nothing new"}`);
346
+ await track(publish(dir, token, abort.signal));
347
+ // Every current version, so a tag an earlier half-failed run left unpushed goes too.
348
+ await pushTags(stepGit, stepRun, dir, await publicPackages(step, dir));
349
+ await verify(step, packages);
350
+ return packages.length ? `released ${packages.map(id).join(", ")}` : "nothing to release";
351
+ }
352
+ finally {
353
+ finishing = true;
354
+ await cleanup();
355
+ for (const signal of SIGNALS)
356
+ process.off(signal, onSignal);
357
+ }
358
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jonmilner/local-ci",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Run a repo's check in a pre-push hook and post the result as GitHub commit statuses",
5
5
  "license": "MIT",
6
6
  "repository": {