@jonmilner/local-ci 0.4.0 → 0.6.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 CHANGED
@@ -38,6 +38,9 @@ exec pnpm exec local-ci pre-push "$@"
38
38
 
39
39
  One sweep runs at a time (`renovate.lock` in the state directory); a second exits with `renovate in progress`. A sweep killed before its cleanup leaves its worktree behind, and the next sweep removes it. It logs one timestamped line per PR and exits non-zero when any PR's check failed or could not run; a PR title that fails lint fails only `pr-title`.
40
40
 
41
+ - `local-ci renovate --install` (macOS): runs `local-ci renovate` on a schedule, so Renovate PRs get `check` and `pr-title` and automerge without you. It writes `~/Library/LaunchAgents/com.jonmilner.local-ci.renovate.plist` and loads it with `launchctl enable` (clearing any earlier `launchctl disable`) and `launchctl bootstrap`; the agent runs a sweep at once, at each login, and every 15 minutes after. It runs only while the Mac is awake: launchd skips the intervals the Mac slept through and runs one sweep on wake. launchd's own `PATH` lacks pnpm, gh and node, so the plist sets `PATH` to the installing shell's, less any `node_modules` directory and with the running node's directory last, and passes `LOCAL_CI_COMMAND`, `LOCAL_CI_PROJECTS` and `XDG_STATE_HOME` when set. No other shell variable reaches it, `GH_TOKEN` included, so `gh` must be logged in with its keyring (`gh auth login`). It runs `/usr/bin/env node` on that `PATH` and this copy of the CLI, through the package's `node_modules/<pkg>` link rather than pnpm's version-named store path, so upgrading node or local-ci keeps it working. Output goes to `renovate.log` in the state directory, moved to `renovate.log.1` at the start of a sweep once it passes 10MB. Re-running it replaces the agent; run it again after changing `PATH`, and install from a checkout that stays put (not a worktree you will delete), since the agent runs that copy. In this repo: `node packages/local-ci/src/cli.ts renovate --install`; elsewhere `pnpm exec local-ci renovate --install`.
42
+ - `local-ci renovate --uninstall`: unloads the agent (`launchctl bootout`) and deletes its plist; it prints `… is not installed` and exits 0 when there is none.
43
+
41
44
  ## Check command
42
45
 
43
46
  `pnpm check` by default. Override it per repo in `package.json`:
@@ -50,6 +53,8 @@ A repo without a `package.json` sets `LOCAL_CI_COMMAND`, for example in the hook
50
53
 
51
54
  ## State
52
55
 
53
- 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. Each check run appends its duration and outcome to the log when it ends, e.g. `[<end time>] abc1234: pnpm check passed in 71.2s` (or `failed in`, or `did not finish after` when the check is killed by a signal or can't start); a commit that already passed is skipped and logs nothing. Ctrl-C stops local-ci along with the check, so that run logs nothing.
56
+ 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.
57
+
58
+ One check command runs at a time on the machine, across every repo, so overlapping checks can't starve each other's tests: `pre-push`, `status`, and the `status` runs `renovate` starts each take `check.lock` in the same directory around the check command (not the status posts). A run that finds it held prints `local-ci: waiting for the check lock, held by pid <pid> (<repo> <short-sha>)`, again whenever another run takes it first, and polls every second until the holder exits or dies; Ctrl-C stops the wait. After the wait it skips a commit that passed meanwhile and re-applies the clean-tree rule. The lock goes when the check passes, fails or is killed by a signal. Ctrl-C, SIGTERM or SIGHUP to local-ci passes the signal to the check's whole process group (so a check script's children get it too), waits for the check to exit, then releases the lock and dies of the signal, so a check never outlives its lock. A lock whose holder died (SIGKILL, a crash) or that predates the last boot is taken over by the next run. A local-ci check nested inside a check (one that pushes, say) sees its ancestor holds the lock and runs without waiting. Each check run appends its duration and outcome to the log when it ends, e.g. `[<end time>] abc1234: pnpm check passed in 71.2s` (or `failed in`, or `did not finish after` when the check is killed by a signal or can't start); a commit that already passed is skipped and logs nothing. Ctrl-C stops the check, which logs `did not finish after`.
54
59
 
55
60
  Part of [jonmilner/config](https://github.com/jonmilner/config#readme).
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { spawn, spawnSync } from "node:child_process";
2
+ import { execFileSync, spawn } from "node:child_process";
3
3
  import { closeSync, openSync, readFileSync } from "node:fs";
4
4
  import { hostname } from "node:os";
5
5
  import { basename, dirname, resolve } from "node:path";
@@ -7,6 +7,8 @@ import { fileURLToPath } from "node:url";
7
7
  import { appendLog, checkRunMessage, logLine, passedCommand, recordPass, releaseEnabled, resolveCommand, statePaths, } from "./config.js";
8
8
  import { exec, run } from "./exec.js";
9
9
  import { assertGhAuth, checkStatus, postStatus, prTitleStatus, viewPr, waitForCommit, waitForOpenPr, } from "./github.js";
10
+ import { installRenovateAgent, renovateLog, rotateLog, uninstallRenovateAgent } from "./launchd.js";
11
+ import { LockHeld, takeLock, waitForLock } from "./lock.js";
10
12
  import { cannotCheckInPlace, githubRepo, parsePrePush, shasToCheck } from "./push.js";
11
13
  import { release } from "./release.js";
12
14
  import { projectsDir, renovate } from "./renovate.js";
@@ -17,14 +19,18 @@ const USAGE = `Usage:
17
19
  local-ci pr-title [<pr>] lint the PR title and post the pr-title status
18
20
  local-ci status [<sha>] post check for <sha> (default HEAD), running the check if needed
19
21
  local-ci release version pending changesets through a PR, publish to npm and push tags
20
- local-ci renovate check each open Renovate PR in your repos and post check and pr-title`;
22
+ local-ci renovate check each open Renovate PR in your repos and post check and pr-title
23
+ local-ci renovate --install
24
+ run renovate every 15 minutes with a launchd agent (macOS)
25
+ local-ci renovate --uninstall
26
+ remove that agent`;
21
27
  const git = async (...args) => (await exec("git", args)).trim();
22
28
  async function repo() {
23
29
  const root = await git("rev-parse", "--show-toplevel");
24
30
  // The common dir names the repo even from a linked worktree.
25
31
  const common = resolve(root, await git("rev-parse", "--git-common-dir"));
26
32
  const name = basename(common) === ".git" ? basename(dirname(common)) : basename(common, ".git");
27
- return { root, ...statePaths(name) };
33
+ return { root, name, ...statePaths(name) };
28
34
  }
29
35
  const out = (s) => process.stdout.write(`${s}\n`);
30
36
  const err = (s) => process.stderr.write(`${s}\n`);
@@ -37,34 +43,154 @@ class CheckFailed extends Error {
37
43
  this.command = command;
38
44
  }
39
45
  }
40
- /** Runs the check at `sha` in place, after the clean-tree rule, unless it already passed. */
41
- async function runCheck({ root, passed, log: logFile }, sha) {
42
- if (passedCommand(passed, sha))
46
+ /** This process's ancestors' pids, or none when `ps` can't list them. */
47
+ function ancestors() {
48
+ const parents = new Map();
49
+ try {
50
+ for (const line of execFileSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8" }).split("\n")) {
51
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);
52
+ if (pid && ppid !== undefined)
53
+ parents.set(pid, ppid);
54
+ }
55
+ }
56
+ catch {
57
+ return new Set();
58
+ }
59
+ const found = new Set();
60
+ for (let pid = process.ppid; pid > 1 && !found.has(pid); pid = parents.get(pid) ?? 0)
61
+ found.add(pid);
62
+ return found;
63
+ }
64
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
65
+ /** The check lock this process holds, the check running under it, and a signal it deferred. */
66
+ let held;
67
+ /** Dies of `signal` as if local-ci had no handler for it. */
68
+ function reraise(signal) {
69
+ for (const name of SIGNALS)
70
+ process.off(name, onSignal);
71
+ process.kill(process.pid, signal);
72
+ // The default action has ended the process by now; this only satisfies the type.
73
+ process.exit(1);
74
+ }
75
+ /**
76
+ * While a check runs, passes the signal on and lets the check stop first, so it never outlives
77
+ * the lock; its release then dies of the signal. Otherwise releases the lock and dies of it now.
78
+ */
79
+ function onSignal(signal) {
80
+ if (held?.child) {
81
+ held.signal ??= signal;
82
+ // The check leads its own process group, so the signal reaches a script's children too.
83
+ try {
84
+ process.kill(-held.child.pid, signal);
85
+ }
86
+ catch {
87
+ held.child.kill(signal);
88
+ }
43
89
  return;
90
+ }
91
+ held?.unlock();
92
+ held = undefined;
93
+ reraise(signal);
94
+ }
95
+ /** Holds `unlock` until the returned release, releasing it on SIGINT, SIGTERM or SIGHUP too. */
96
+ function releaseOnSignal(unlock) {
97
+ if (!process.listenerCount("SIGINT", onSignal)) {
98
+ for (const name of SIGNALS)
99
+ process.on(name, onSignal);
100
+ }
101
+ const lock = { unlock };
102
+ held = lock;
103
+ return () => {
104
+ if (held === lock)
105
+ held = undefined;
106
+ unlock();
107
+ if (lock.signal)
108
+ reraise(lock.signal);
109
+ };
110
+ }
111
+ /** Throws unless `sha` can be checked in place: it is HEAD and the tree is clean. */
112
+ async function assertCheckable(sha) {
44
113
  const reason = cannotCheckInPlace(sha, await git("rev-parse", "HEAD"), await git("status", "--porcelain"));
45
114
  if (reason)
46
115
  throw new Error(`cannot check ${sha.slice(0, 7)}: ${reason}`);
116
+ }
117
+ /** Takes the machine-wide check lock, waiting while another repo's check holds it. */
118
+ async function lockCheck({ name, checkLock }, sha) {
119
+ const holder = `${name} ${sha.slice(0, 7)}`;
120
+ try {
121
+ return releaseOnSignal(takeLock(checkLock, "check", holder));
122
+ }
123
+ catch (error) {
124
+ if (!(error instanceof LockHeld))
125
+ throw error;
126
+ // A check nested in a check (one that pushes, say) runs under its ancestor's lock rather
127
+ // than waiting forever on it.
128
+ if (ancestors().has(error.pid))
129
+ return () => { };
130
+ }
131
+ return releaseOnSignal(await waitForLock(checkLock, {
132
+ what: "check",
133
+ holder,
134
+ onWait: ({ pid, holder }) => err(`local-ci: waiting for the check lock, held by pid ${pid} (${holder || "unknown"})`),
135
+ }));
136
+ }
137
+ /**
138
+ * Runs the check at `sha` in place, after the clean-tree rule, unless it already passed. One check
139
+ * runs at a time across all repos, so overlapping checks can't starve each other's tests.
140
+ */
141
+ async function runCheck(current, sha) {
142
+ if (passedCommand(current.passed, sha))
143
+ return;
144
+ await assertCheckable(sha);
145
+ const unlock = await lockCheck(current, sha);
146
+ try {
147
+ // Another run may have passed it, or the tree changed, while this one waited.
148
+ if (passedCommand(current.passed, sha))
149
+ return;
150
+ await assertCheckable(sha);
151
+ await runLocked(current, sha);
152
+ }
153
+ finally {
154
+ unlock();
155
+ }
156
+ }
157
+ /** Runs the check command under the check lock, logging its duration and recording a pass. */
158
+ async function runLocked({ root, passed, log: logFile }, sha) {
47
159
  const command = resolveCommand(root);
48
160
  err(`local-ci: running ${command} on ${sha.slice(0, 7)}`);
49
161
  const started = performance.now();
50
- const result = spawnSync("sh", ["-c", command], {
162
+ const child = spawn("sh", ["-c", command], {
51
163
  cwd: root,
164
+ // Its own process group, so onSignal can stop everything the check started. A nested check
165
+ // has no handler and stays in its parent check's group, which that check's signal reaches.
166
+ detached: held !== undefined,
52
167
  stdio: ["ignore", "inherit", "inherit"],
53
168
  });
169
+ if (held)
170
+ held.child = child;
171
+ const result = await new Promise((resolve) => {
172
+ child.on("error", (error) => resolve({ status: null, cause: error.message }));
173
+ child.on("close", (status, signal) => resolve({ status, cause: signal ?? undefined }));
174
+ });
175
+ if (held)
176
+ held.child = undefined;
177
+ // A check local-ci was told to stop never finished, whatever it exited with.
178
+ const interrupted = held?.signal;
179
+ const status = interrupted ? null : result.status;
54
180
  // Every run's duration goes in the log, so a faster check can be measured against a slower one.
55
181
  // A log that can't be written must not change the check's outcome.
56
182
  try {
57
- appendLog(logFile, checkRunMessage(sha, command, result.status, performance.now() - started));
183
+ appendLog(logFile, checkRunMessage(sha, command, status, performance.now() - started));
58
184
  }
59
185
  catch (error) {
60
186
  err(`local-ci: could not log the run: ${error instanceof Error ? error.message : String(error)}`);
61
187
  }
62
188
  // A spawn error or a signal means the check never finished, so it is not a failure to post.
63
- if (result.status === null) {
64
- const cause = result.error?.message ?? result.signal;
189
+ if (status === null) {
190
+ const cause = interrupted ?? result.cause;
65
191
  throw new Error(`${command} did not finish on ${sha.slice(0, 7)}: ${cause}`);
66
192
  }
67
- if (result.status !== 0)
193
+ if (status !== 0)
68
194
  throw new CheckFailed(command, sha);
69
195
  recordPass(passed, sha, command);
70
196
  }
@@ -148,9 +274,18 @@ async function runRelease() {
148
274
  await assertGhAuth(exec);
149
275
  out(await release(exec, { root, lock, cli: fileURLToPath(import.meta.url), prTitle, log }));
150
276
  }
151
- async function runRenovate() {
152
- await assertGhAuth(exec);
277
+ async function runRenovate([flag, ...extra]) {
153
278
  const cli = fileURLToPath(import.meta.url);
279
+ if (extra.length)
280
+ throw new Error(`renovate: unexpected ${extra.join(" ")}\n${USAGE}`);
281
+ if (flag === "--install")
282
+ return out(await installRenovateAgent({ exec, cli }));
283
+ if (flag === "--uninstall")
284
+ return out(await uninstallRenovateAgent({ exec }));
285
+ if (flag)
286
+ throw new Error(`renovate: unknown option ${flag}\n${USAGE}`);
287
+ rotateLog(renovateLog());
288
+ await assertGhAuth(exec);
154
289
  const failed = await renovate({ exec, run, cli, projects: projectsDir() }, log);
155
290
  if (failed)
156
291
  process.exitCode = 1;
@@ -161,7 +296,7 @@ async function main([command, ...args]) {
161
296
  if (command === "release")
162
297
  return runRelease();
163
298
  if (command === "renovate")
164
- return runRenovate();
299
+ return runRenovate(args);
165
300
  if (command === "post" || command === "pr-title" || command === "status") {
166
301
  await assertGhAuth(exec);
167
302
  }
package/dist/config.d.ts CHANGED
@@ -4,11 +4,15 @@ export declare function resolveCommand(root: string, env?: NodeJS.ProcessEnv): s
4
4
  /** Whether `local-ci release` is switched on, with `"local-ci": { "release": true }` in package.json. */
5
5
  export declare function releaseEnabled(root: string): boolean;
6
6
  export declare function stateDir(env?: NodeJS.ProcessEnv): string;
7
- /** Where a repo's log, record of passed commits and release lock live, created on first use. */
7
+ /**
8
+ * Where a repo's log, record of passed commits and release lock live, and the check lock all repos
9
+ * share, created on first use.
10
+ */
8
11
  export declare function statePaths(repo: string, env?: NodeJS.ProcessEnv): {
9
12
  log: string;
10
13
  passed: string;
11
14
  lock: string;
15
+ checkLock: string;
12
16
  };
13
17
  /** A line of the repo's log: the message after an ISO timestamp. */
14
18
  export declare function logLine(message: string, now?: Date): string;
package/dist/config.js CHANGED
@@ -24,7 +24,10 @@ export function releaseEnabled(root) {
24
24
  export function stateDir(env = process.env) {
25
25
  return join(env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "local-ci");
26
26
  }
27
- /** Where a repo's log, record of passed commits and release lock live, created on first use. */
27
+ /**
28
+ * Where a repo's log, record of passed commits and release lock live, and the check lock all repos
29
+ * share, created on first use.
30
+ */
28
31
  export function statePaths(repo, env = process.env) {
29
32
  const dir = stateDir(env);
30
33
  mkdirSync(dir, { recursive: true });
@@ -32,6 +35,7 @@ export function statePaths(repo, env = process.env) {
32
35
  log: join(dir, `${repo}.log`),
33
36
  passed: join(dir, `${repo}.passed`),
34
37
  lock: join(dir, `${repo}.release.lock`),
38
+ checkLock: join(dir, "check.lock"),
35
39
  };
36
40
  }
37
41
  /** A line of the repo's log: the message after an ISO timestamp. */
@@ -0,0 +1,58 @@
1
+ import type { Exec } from "./exec.ts";
2
+ /** The launchd label of the agent that runs `local-ci renovate`. */
3
+ export declare const RENOVATE_LABEL = "com.jonmilner.local-ci.renovate";
4
+ /** 15 minutes, in seconds. */
5
+ export declare const RENOVATE_INTERVAL = 900;
6
+ /** The agent's log is moved aside to `<log>.1` past this size, so it never grows without bound. */
7
+ export declare const LOG_MAX_BYTES: number;
8
+ /** The agent's log, which launchd appends the sweep's output to. */
9
+ export declare const renovateLog: (env?: NodeJS.ProcessEnv) => string;
10
+ /**
11
+ * Moves `file` to `<file>.1` once it passes `max` bytes. launchd opens the log for each run, so the
12
+ * run under way finishes in `.1` and the next starts a new file.
13
+ */
14
+ export declare function rotateLog(file: string, max?: number): void;
15
+ /**
16
+ * The CLI path to run on a schedule. Under pnpm, `cli` is the real path in the version-named
17
+ * `node_modules/.pnpm/<pkg>@<version>…` directory, which the next upgrade deletes, so this prefers
18
+ * the package's stable link (`node_modules/<pkg>/…`) in `cwd` or the store's own project.
19
+ */
20
+ export declare function stableCli(cli: string, cwd?: string): string;
21
+ /**
22
+ * The agent's PATH: the installing shell's, less any project's `node_modules/.bin` (which `pnpm
23
+ * exec` adds), with this node's directory last so node resolves even when the shell found it some
24
+ * other way. A directory a later upgrade removes is skipped, not fatal, since `env` searches on.
25
+ */
26
+ export declare function agentPath(path: string, node: string): string;
27
+ export interface AgentOptions {
28
+ label: string;
29
+ /** The program and its arguments, absolute paths. */
30
+ args: string[];
31
+ env: Record<string, string>;
32
+ workingDirectory: string;
33
+ log: string;
34
+ interval: number;
35
+ }
36
+ /** A launchd agent plist that runs `args` at load and every `interval` seconds after. */
37
+ export declare function agentPlist({ label, args, env, workingDirectory, log, interval, }: AgentOptions): string;
38
+ export interface LaunchdContext {
39
+ exec: Exec;
40
+ /** This CLI, which the agent runs as `renovate`. */
41
+ cli: string;
42
+ /** The node running this CLI, whose directory the agent's PATH ends with. */
43
+ node?: string;
44
+ cwd?: string;
45
+ env?: NodeJS.ProcessEnv;
46
+ home?: string;
47
+ uid?: number;
48
+ platform?: NodeJS.Platform;
49
+ sleep?: (ms: number) => Promise<void>;
50
+ }
51
+ /**
52
+ * Writes the agent's plist and loads it, replacing an agent already loaded. It runs node through
53
+ * `env` on the installing shell's PATH (see `agentPath`), since launchd's own lacks pnpm, gh and
54
+ * node, and a node upgrade must not leave it pointing at a deleted binary.
55
+ */
56
+ export declare function installRenovateAgent(context: LaunchdContext): Promise<string>;
57
+ /** Unloads the agent and deletes its plist; a no-op when it is not installed. */
58
+ export declare function uninstallRenovateAgent(context: Omit<LaunchdContext, "cli">): Promise<string>;
@@ -0,0 +1,171 @@
1
+ import { existsSync, mkdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { delimiter, dirname, join, sep } from "node:path";
4
+ import { stateDir } from "./config.js";
5
+ import { defaultSleep } from "./github.js";
6
+ /** The launchd label of the agent that runs `local-ci renovate`. */
7
+ export const RENOVATE_LABEL = "com.jonmilner.local-ci.renovate";
8
+ /** 15 minutes, in seconds. */
9
+ export const RENOVATE_INTERVAL = 900;
10
+ /** The variables the sweep reads that launchd would otherwise not pass on. */
11
+ const PASSED_ENV = ["LOCAL_CI_COMMAND", "LOCAL_CI_PROJECTS", "XDG_STATE_HOME"];
12
+ /** The agent's log is moved aside to `<log>.1` past this size, so it never grows without bound. */
13
+ export const LOG_MAX_BYTES = 10 * 1024 * 1024;
14
+ /** The agent's log, which launchd appends the sweep's output to. */
15
+ export const renovateLog = (env = process.env) => join(stateDir(env), "renovate.log");
16
+ /**
17
+ * Moves `file` to `<file>.1` once it passes `max` bytes. launchd opens the log for each run, so the
18
+ * run under way finishes in `.1` and the next starts a new file.
19
+ */
20
+ export function rotateLog(file, max = LOG_MAX_BYTES) {
21
+ try {
22
+ if (statSync(file).size > max)
23
+ renameSync(file, `${file}.1`);
24
+ }
25
+ catch (error) {
26
+ if (error.code !== "ENOENT")
27
+ throw error;
28
+ }
29
+ }
30
+ /**
31
+ * The CLI path to run on a schedule. Under pnpm, `cli` is the real path in the version-named
32
+ * `node_modules/.pnpm/<pkg>@<version>…` directory, which the next upgrade deletes, so this prefers
33
+ * the package's stable link (`node_modules/<pkg>/…`) in `cwd` or the store's own project.
34
+ */
35
+ export function stableCli(cli, cwd = process.cwd()) {
36
+ const store = `${sep}node_modules${sep}.pnpm${sep}`;
37
+ const at = cli.indexOf(store);
38
+ if (at < 0)
39
+ return cli;
40
+ const inner = cli.indexOf(`${sep}node_modules${sep}`, at + store.length);
41
+ if (inner < 0)
42
+ return cli;
43
+ const rest = cli.slice(inner);
44
+ for (const root of [cwd, cli.slice(0, at)]) {
45
+ const link = join(root, rest);
46
+ try {
47
+ if (realpathSync(link) === realpathSync(cli))
48
+ return link;
49
+ }
50
+ catch {
51
+ // No such link here.
52
+ }
53
+ }
54
+ return cli;
55
+ }
56
+ /**
57
+ * The agent's PATH: the installing shell's, less any project's `node_modules/.bin` (which `pnpm
58
+ * exec` adds), with this node's directory last so node resolves even when the shell found it some
59
+ * other way. A directory a later upgrade removes is skipped, not fatal, since `env` searches on.
60
+ */
61
+ export function agentPath(path, node) {
62
+ const dirs = path
63
+ .split(delimiter)
64
+ .filter((dir) => dir && !dir.split(sep).includes("node_modules"));
65
+ return [...new Set([...dirs, dirname(node)])].join(delimiter);
66
+ }
67
+ const escape = (s) => s.replace(/[&<>"']/g, (c) => `&${{ "&": "amp", "<": "lt", ">": "gt", '"': "quot", "'": "apos" }[c]};`);
68
+ const string = (s) => `<string>${escape(s)}</string>`;
69
+ /** A launchd agent plist that runs `args` at load and every `interval` seconds after. */
70
+ export function agentPlist({ label, args, env, workingDirectory, log, interval, }) {
71
+ const vars = Object.entries(env).map(([key, value]) => ` <key>${escape(key)}</key>\n ${string(value)}`);
72
+ return `<?xml version="1.0" encoding="UTF-8"?>
73
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
74
+ <plist version="1.0">
75
+ <dict>
76
+ <key>Label</key>
77
+ ${string(label)}
78
+ <key>ProgramArguments</key>
79
+ <array>
80
+ ${args.map((arg) => ` ${string(arg)}`).join("\n")}
81
+ </array>
82
+ <key>EnvironmentVariables</key>
83
+ <dict>
84
+ ${vars.join("\n")}
85
+ </dict>
86
+ <key>WorkingDirectory</key>
87
+ ${string(workingDirectory)}
88
+ <key>RunAtLoad</key>
89
+ <true/>
90
+ <key>StartInterval</key>
91
+ <integer>${interval}</integer>
92
+ <key>StandardOutPath</key>
93
+ ${string(log)}
94
+ <key>StandardErrorPath</key>
95
+ ${string(log)}
96
+ </dict>
97
+ </plist>
98
+ `;
99
+ }
100
+ function resolve(context) {
101
+ const { env = process.env, home = homedir(), uid = process.getuid?.() ?? 0 } = context;
102
+ if ((context.platform ?? process.platform) !== "darwin") {
103
+ throw new Error("the renovate agent needs macOS (launchd)");
104
+ }
105
+ return {
106
+ env,
107
+ home,
108
+ domain: `gui/${uid}`,
109
+ service: `gui/${uid}/${RENOVATE_LABEL}`,
110
+ plist: join(home, "Library", "LaunchAgents", `${RENOVATE_LABEL}.plist`),
111
+ };
112
+ }
113
+ /** Whether launchd has the agent loaded. */
114
+ const loaded = (exec, service) => exec("launchctl", ["print", service]).then(() => true, () => false);
115
+ /**
116
+ * Unloads the agent if loaded, waiting until launchd has let it go so a bootstrap can follow, and
117
+ * resolves with whether it was loaded.
118
+ */
119
+ async function bootout(context, service) {
120
+ const { exec, sleep = defaultSleep } = context;
121
+ if (!(await loaded(exec, service)))
122
+ return false;
123
+ // launchd gives a running sweep up to 20s to exit before killing it, so wait past that.
124
+ const failed = await exec("launchctl", ["bootout", service]).then(() => "", (error) => `: ${error.message}`);
125
+ for (let tries = 0; await loaded(exec, service); tries++) {
126
+ if (tries >= 250)
127
+ throw new Error(`launchctl could not unload ${service}${failed}`);
128
+ await sleep(100);
129
+ }
130
+ return true;
131
+ }
132
+ /**
133
+ * Writes the agent's plist and loads it, replacing an agent already loaded. It runs node through
134
+ * `env` on the installing shell's PATH (see `agentPath`), since launchd's own lacks pnpm, gh and
135
+ * node, and a node upgrade must not leave it pointing at a deleted binary.
136
+ */
137
+ export async function installRenovateAgent(context) {
138
+ const { env, home, domain, service, plist } = resolve(context);
139
+ const log = renovateLog(env);
140
+ const vars = {
141
+ PATH: agentPath(env.PATH ?? "", context.node ?? process.execPath),
142
+ };
143
+ for (const key of PASSED_ENV)
144
+ if (env[key])
145
+ vars[key] = env[key];
146
+ // Written before the old agent goes, so a failed write leaves that one running.
147
+ mkdirSync(dirname(plist), { recursive: true });
148
+ mkdirSync(dirname(log), { recursive: true });
149
+ writeFileSync(plist, agentPlist({
150
+ label: RENOVATE_LABEL,
151
+ args: ["/usr/bin/env", "node", stableCli(context.cli, context.cwd), "renovate"],
152
+ env: vars,
153
+ workingDirectory: home,
154
+ log,
155
+ interval: RENOVATE_INTERVAL,
156
+ }));
157
+ await bootout(context, service);
158
+ // A `launchctl disable` outlives bootout and the plist, and would make bootstrap fail.
159
+ await context.exec("launchctl", ["enable", service]);
160
+ await context.exec("launchctl", ["bootstrap", domain, plist]);
161
+ return `installed ${RENOVATE_LABEL}: runs local-ci renovate now and every ${RENOVATE_INTERVAL / 60} minutes while the Mac is awake; log ${log}`;
162
+ }
163
+ /** Unloads the agent and deletes its plist; a no-op when it is not installed. */
164
+ export async function uninstallRenovateAgent(context) {
165
+ const { service, plist } = resolve(context);
166
+ const wasLoaded = await bootout(context, service);
167
+ if (!wasLoaded && !existsSync(plist))
168
+ return `${RENOVATE_LABEL} is not installed`;
169
+ rmSync(plist, { force: true });
170
+ return `uninstalled ${RENOVATE_LABEL}`;
171
+ }
package/dist/lock.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /** A live process holds the lock. `holder` is what it wrote after its pid, such as its repo. */
2
+ export declare class LockHeld extends Error {
3
+ readonly pid: number;
4
+ readonly holder: string;
5
+ constructor(what: string, file: string, pid: number, holder: string);
6
+ }
7
+ /**
8
+ * Takes the lock and returns its release, or throws `LockHeld` while a live process holds it. The
9
+ * lock file holds the pid, then `holder` on a second line when given.
10
+ */
11
+ export declare function takeLock(file: string, what?: string, holder?: string): () => void;
12
+ export interface WaitForLockOptions {
13
+ what: string;
14
+ holder?: string;
15
+ /** Called when the wait starts, and again whenever another process takes the lock first. */
16
+ onWait?: (held: LockHeld) => void;
17
+ intervalMs?: number;
18
+ sleep?: (ms: number) => Promise<void>;
19
+ }
20
+ /** Takes the lock, polling while a live process holds it, and returns its release. */
21
+ export declare function waitForLock(file: string, { what, holder, onWait, intervalMs, sleep }: WaitForLockOptions): Promise<() => void>;
package/dist/lock.js ADDED
@@ -0,0 +1,97 @@
1
+ import { linkSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { uptime } from "node:os";
3
+ import { defaultSleep } from "./github.js";
4
+ /** Whether a process with this pid is running. */
5
+ function alive(pid) {
6
+ if (!Number.isInteger(pid) || pid <= 0)
7
+ return false;
8
+ try {
9
+ process.kill(pid, 0);
10
+ return true;
11
+ }
12
+ catch (error) {
13
+ // EPERM: the process exists but belongs to another user.
14
+ return error.code === "EPERM";
15
+ }
16
+ }
17
+ /**
18
+ * Whether the lock file was written before the machine booted, so its pid, alive or not, belongs to
19
+ * a process that never held it.
20
+ */
21
+ function beforeBoot(file) {
22
+ try {
23
+ return statSync(file).mtimeMs < Date.now() - uptime() * 1_000;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ /** A live process holds the lock. `holder` is what it wrote after its pid, such as its repo. */
30
+ export class LockHeld extends Error {
31
+ pid;
32
+ holder;
33
+ constructor(what, file, pid, holder) {
34
+ super(`${what} in progress (pid ${pid}, lock ${file})`);
35
+ this.pid = pid;
36
+ this.holder = holder;
37
+ }
38
+ }
39
+ /**
40
+ * Takes the lock and returns its release, or throws `LockHeld` while a live process holds it. The
41
+ * lock file holds the pid, then `holder` on a second line when given.
42
+ */
43
+ export function takeLock(file, what = "release", holder) {
44
+ // Linking a file that already holds the pid publishes the lock atomically, so nobody reads it empty.
45
+ const mine = `${file}.${process.pid}`;
46
+ writeFileSync(mine, holder ? `${process.pid}\n${holder}` : String(process.pid));
47
+ try {
48
+ // Each pass takes the lock, finds a live holder, or clears a released or dead one.
49
+ for (;;) {
50
+ try {
51
+ linkSync(mine, file);
52
+ return () => rmSync(file, { force: true });
53
+ }
54
+ catch (error) {
55
+ if (error.code !== "EEXIST")
56
+ throw error;
57
+ let content;
58
+ try {
59
+ content = readFileSync(file, "utf8");
60
+ }
61
+ catch (readError) {
62
+ // Released between the link and the read: try again.
63
+ if (readError.code === "ENOENT")
64
+ continue;
65
+ throw readError;
66
+ }
67
+ const [pid = "", ...rest] = content.split("\n");
68
+ if (alive(Number(pid)) && !beforeBoot(file)) {
69
+ throw new LockHeld(what, file, Number(pid), rest.join("\n"));
70
+ }
71
+ // The holder died without releasing it, or its pid is another process's since a reboot.
72
+ rmSync(file, { force: true });
73
+ }
74
+ }
75
+ }
76
+ finally {
77
+ rmSync(mine, { force: true });
78
+ }
79
+ }
80
+ /** Takes the lock, polling while a live process holds it, and returns its release. */
81
+ export async function waitForLock(file, { what, holder, onWait, intervalMs = 1_000, sleep = defaultSleep }) {
82
+ let last;
83
+ for (;;) {
84
+ try {
85
+ return takeLock(file, what, holder);
86
+ }
87
+ catch (error) {
88
+ if (!(error instanceof LockHeld))
89
+ throw error;
90
+ const seen = `${error.pid}\n${error.holder}`;
91
+ if (seen !== last)
92
+ onWait?.(error);
93
+ last = seen;
94
+ await sleep(intervalMs);
95
+ }
96
+ }
97
+ }
package/dist/release.d.ts CHANGED
@@ -8,8 +8,6 @@ export interface Package {
8
8
  name: string;
9
9
  version: string;
10
10
  }
11
- /** Takes the lock and returns its release, or throws `<what> in progress` while a live process holds it. */
12
- export declare function takeLock(file: string, what?: string): () => void;
13
11
  /** The changeset files waiting in `dir`'s `.changeset` folder. */
14
12
  export declare function pendingChangesets(dir: string): string[];
15
13
  /** How `dir` versions its changesets: its root `version-packages` script, else `changeset version`. */
package/dist/release.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync, linkSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
2
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
3
3
  import { constants, tmpdir } from "node:os";
4
4
  import { basename, dirname, join } from "node:path";
5
5
  import { run } from "./exec.js";
6
6
  import { defaultSleep, waitForStatuses } from "./github.js";
7
+ import { takeLock } from "./lock.js";
7
8
  /** The macOS Keychain generic password that holds the npm token. */
8
9
  export const TOKEN_SERVICE = "local-ci-npm";
9
10
  /** npm and pnpm read a registry token from this variable; it is set only for `pnpm release`. */
@@ -20,45 +21,6 @@ const AUTH_ERROR = /\b(?:E401|E403|EOTP|ERR_PNPM_OTP_NON_INTERACTIVE|401 Unautho
20
21
  // What npm prints when the version is already on the registry. It comes with an E403, so it is checked before AUTH_ERROR.
21
22
  const PUBLISH_OVER = /cannot publish over the previously published version/;
22
23
  const id = ({ name, version }) => `${name}@${version}`;
23
- function alive(pid) {
24
- if (!Number.isInteger(pid) || pid <= 0)
25
- return false;
26
- try {
27
- process.kill(pid, 0);
28
- return true;
29
- }
30
- catch (error) {
31
- // EPERM: the process exists but belongs to another user.
32
- return error.code === "EPERM";
33
- }
34
- }
35
- /** Takes the lock and returns its release, or throws `<what> in progress` while a live process holds it. */
36
- export function takeLock(file, what = "release") {
37
- // Linking a file that already holds the pid publishes the lock atomically, so nobody reads it empty.
38
- const mine = `${file}.${process.pid}`;
39
- writeFileSync(mine, String(process.pid));
40
- try {
41
- for (let attempt = 0; attempt < 2; attempt++) {
42
- try {
43
- linkSync(mine, file);
44
- return () => rmSync(file, { force: true });
45
- }
46
- catch (error) {
47
- if (error.code !== "EEXIST")
48
- throw error;
49
- const pid = Number(readFileSync(file, "utf8"));
50
- if (alive(pid))
51
- throw new Error(`${what} in progress (pid ${pid}, lock ${file})`);
52
- // The holder died without releasing it.
53
- rmSync(file, { force: true });
54
- }
55
- }
56
- }
57
- finally {
58
- rmSync(mine, { force: true });
59
- }
60
- throw new Error(`could not take the ${what} lock ${file}`);
61
- }
62
24
  /** The changeset files waiting in `dir`'s `.changeset` folder. */
63
25
  export function pendingChangesets(dir) {
64
26
  const folder = join(dir, ".changeset");
package/dist/renovate.js CHANGED
@@ -3,8 +3,8 @@ import { homedir, hostname, tmpdir } from "node:os";
3
3
  import { basename, dirname, join } from "node:path";
4
4
  import { passedCommand, stateDir, statePaths } from "./config.js";
5
5
  import { checkStatus, commitStatuses, postStatus } from "./github.js";
6
+ import { takeLock } from "./lock.js";
6
7
  import { githubRepo } from "./push.js";
7
- import { takeLock } from "./release.js";
8
8
  /** The login `gh` gives the Renovate GitHub app. */
9
9
  export const RENOVATE_AUTHOR = "app/renovate";
10
10
  export const RENOVATE_BRANCH = "renovate/";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jonmilner/local-ci",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
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": {