@jonmilner/local-ci 0.13.0 → 0.14.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
@@ -21,14 +21,14 @@ That writes `pre-push` and `commit-msg` shims, each one line that calls local-ci
21
21
  ## Commands
22
22
 
23
23
  - `local-ci hooks install`: writes executable `#!/bin/sh` `pre-push` and `commit-msg` shims into the hooks directory: `core.hooksPath`, resolved against the repo root, with a Vite+ (or husky) `<dir>/_` dispatcher mapped to `<dir>`, and an absolute path into the main checkout mapped onto the current worktree. Each shim is one line: `pnpm exec local-ci pre-push "$@"` and `pnpm exec local-ci commit-msg "$1"` in a repo with a `package.json`, a global `local-ci …` without one, or `"local-ci": { "exec": "<command>" }` in `package.json` in place of `pnpm exec local-ci` (this repo runs local-ci from source that way). An existing shell hook keeps its other lines and gains the shim line, at the end, only when no line already runs `local-ci pre-push` (or `commit-msg`), so a line with an env prefix such as `LOCAL_CI_COMMAND=… local-ci pre-push "$@"` counts. It prints each file it wrote, or `hooks up to date`; a second run changes nothing. It exits 1 without `core.hooksPath` or with one outside the repo's tracked files (including `.git/hooks`), and for an existing hook in another language (a `node` or `python` shebang), naming the line to add by hand. Run it by hand and commit the result; `prepare` does not run it.
24
- - `local-ci pre-push`: the hook. It first checks that both hook files are in place, as `local-ci hooks install` would leave them, and refuses the push otherwise (``hooks out of date: <file> must run local-ci; run `<command> hooks install` and commit the result``), so a repo's hooks can't drift. For each commit pushed to a branch (deletes and tags are skipped) that has not already passed, runs the check command. The pushed commit must be `HEAD` with a clean working tree (`git status --porcelain` empty), so the result reflects the commit; otherwise the push is refused. A failing check blocks the push. When every commit passes, it starts `local-ci post <sha>` in the background, aimed at the pushed remote and told the pid of the `git` process doing the push (`LOCAL_CI_PUSH_PID`), and lets the push go ahead.
24
+ - `local-ci pre-push`: the hook. It first checks that both hook files are in place, as `local-ci hooks install` would leave them, and refuses the push otherwise (``hooks out of date: <file> must run local-ci; run `<command> hooks install` and commit the result``), so a repo's hooks can't drift. For each commit pushed to a branch (deletes and tags are skipped) that has not already passed, runs the check command. The pushed commit must be `HEAD` with a clean working tree (`git status --porcelain` empty), so the result reflects the commit; otherwise the push is refused. A failing check blocks the push. When every commit passes, it starts `local-ci post <sha>` in the background, aimed at the pushed remote and told the pid of the `git` process doing the push (`LOCAL_CI_PUSH_PID`), and lets the push go ahead. For an ssh remote, it first warns when ssh to its host sends no keepalive (see [SSH keepalive](#ssh-keepalive)), and a run of 30 seconds or more ends by printing how long it ran and, for each pushed ref, the `git ls-remote <remote> <ref>` that should print the pushed sha.
25
25
  - `local-ci commit-msg <file>`: lints the commit message in `<file>` with `@jonmilner/commitlint-config`, for a git `commit-msg` hook (git passes `.git/COMMIT_EDITMSG`). `local-ci commit-msg -` reads the message from stdin, for PR titles. Comment lines (starting with `#`) and everything after a `# ------------------------ >8 ------------------------` scissors line are stripped first; merge commits, `fixup!`/`squash!` and reverts are skipped. Each error or warning goes to stderr as `commit-msg: <message> [<rule>]`, followed by the offending header; it exits 1 when there are errors (warnings alone exit 0), and 2 when no file is given. It makes no network, git or GitHub calls.
26
26
  - `local-ci post <ref>`: resolves `<ref>` (a full or short sha, `HEAD`, a branch) to a local commit's full sha, failing with `<ref> is not a commit in this repo` when it names none, and with `<sha> has no passing check` when that commit never passed. When started by `pre-push`, first waits for the pushing `git` to exit (polling each second, up to 60 minutes, logging if it gives up), since git sends the push only after the whole hook exits, so a slow step after local-ci in the hook can't run out the clock; run by hand, it skips that wait. It then 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.
27
27
  - `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.
28
28
  - `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.
29
29
  - `local-ci run -- <command>`: runs `<command>` under the machine-wide check lock (see [State](#state)), for a full check started by hand or from a script: `local-ci run -- pnpm check`. It waits its turn with every other check, and they wait for it; like any check, it runs beside a background job rather than waiting for one (see [State](#state)). The arguments after `--` go to the program as they are, with no shell (`local-ci run -- sh -c 'a && b'` for a shell line). Stdin is `/dev/null` and the command has no controlling terminal, so anything that prompts on `/dev/tty` fails; output goes straight through. It exits with the command's status, 128 plus the signal number if a signal killed the command, or 1 if the command can't start. It works outside a git repo, needs no `gh` login, posts no status and records no pass. Inside a check that already holds the lock it runs at once, so a repo's `check` script can wrap itself in `local-ci run` without deadlocking its own pre-push.
30
30
  - `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:
31
- 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.
31
+ 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`; the push adds `-o ServerAliveInterval=15` to the ssh command git would run (an OpenSSH one), so a long check can't drop it, see [SSH keepalive](#ssh-keepalive)), opens the PR, posts `pr-title`, waits for both statuses, and squash-merges it.
32
32
  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.
33
33
  3. It checks each published `name@version` with `npm view`, waiting up to 5 minutes in all for the registry to list them. A timeout or `npm view` error here exits non-zero, but the publish already ran: check with the `npm view` command the error gives before rerunning.
34
34
 
@@ -57,11 +57,22 @@ That writes `pre-push` and `commit-msg` shims, each one line that calls local-ci
57
57
 
58
58
  A repo without a `package.json` sets `LOCAL_CI_COMMAND`, for example on the hook's line: `LOCAL_CI_COMMAND=./scripts/check.sh local-ci pre-push "$@"`.
59
59
 
60
+ ## SSH keepalive
61
+
62
+ git opens the push connection before it runs the `pre-push` hook and sends the pack only after the hook exits, so the connection sits idle while the hook waits for the check lock and runs the check. GitHub closes an ssh connection that idles too long (drops were seen after hooks of 36 seconds and more), printing `Connection to github.com closed by remote host.`; git then exits 141 (SIGPIPE) and the ref on GitHub never moves, though the hook passed. Keep the connection alive in `~/.ssh/config`:
63
+
64
+ ```
65
+ Host github.com
66
+ ServerAliveInterval 15
67
+ ```
68
+
69
+ `local-ci pre-push` runs the ssh command git would (`$GIT_SSH_COMMAND`, `core.sshCommand`, `$GIT_SSH`, else `ssh`) with `-G <host>` for an ssh remote, which prints the effective config, that command's own `-F` and `-o` options included, without connecting, and warns, naming these lines, when it shows no `ServerAliveInterval`. It checks nothing for an https remote, or when that command is not OpenSSH (its program isn't `ssh`, such as plink). `local-ci release` adds `-o ServerAliveInterval=15` to that command for its own pushes (an OpenSSH one only), so it needs no config. After a hook of 30 seconds or more on an ssh remote, timed from local-ci's start, confirm the push landed with the `git ls-remote` command the hook prints; if it shows the old sha, push again.
70
+
60
71
  ## State
61
72
 
62
73
  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.
63
74
 
64
- 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`, the `status` runs `renovate` starts, and `local-ci run` each take `check.lock` in the same directory around the command they run (not the status posts). Nothing else takes it: a bare `pnpm check` or `pnpm test` runs beside every other check, so start a full check by hand with `local-ci run -- pnpm check`. The lock only runs checks one at a time; it does not wait for memory pressure or swap to clear. A run that finds it held prints `local-ci: waiting for the check lock, held by pid <pid> (<repo> <short-sha>)` (`<repo> <command>` for `local-ci run`, with the command cut to 60 characters), 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, SIGHUP or SIGQUIT (Ctrl-\\) 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. A check that finds a background job's lock (see below) runs beside the job instead of waiting and leaves that lock alone, printing `local-ci: running beside background job pid <pid> (<holder>), without the check lock`; it holds `check.lock.beside` meanwhile, so another check waits for it rather than overlapping, and signals still stop it and release that lock as above. 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`.
75
+ 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`, the `status` runs `renovate` starts, and `local-ci run` each take `check.lock` in the same directory around the command they run (not the status posts). Nothing else takes it: a bare `pnpm check` or `pnpm test` runs beside every other check, so start a full check by hand with `local-ci run -- pnpm check`. The lock only runs checks one at a time; it does not wait for memory pressure or swap to clear. A run that finds it held prints `local-ci: waiting for the check lock, held by pid <pid> (<repo> <short-sha>)` (`<repo> <command>` for `local-ci run`, with the command cut to 60 characters), again whenever another run takes it first, and polls every second until the holder exits or dies; Ctrl-C stops the wait. Checks don't queue, so the next one to poll after a release goes first; background jobs wait in arrival order (see [below](#taking-the-check-lock-from-your-own-scripts)). 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, SIGHUP or SIGQUIT (Ctrl-\\) 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. A check that finds a background job's lock (see below) runs beside the job instead of waiting and leaves that lock alone, printing `local-ci: running beside background job pid <pid> (<holder>), without the check lock`; it holds `check.lock.beside` meanwhile, so another check waits for it rather than overlapping, and signals still stop it and release that lock as above. 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`.
65
76
 
66
77
  ### Taking the check lock from your own scripts
67
78
 
@@ -75,6 +86,6 @@ await withCheckLock("my-repo browser", async () => {
75
86
  });
76
87
  ```
77
88
 
78
- `withCheckLock(holder, fn, options?)` waits while another holder has the lock, logging `local-ci: waiting for the check lock, held by pid <pid> (<holder>)` to stderr as the CLI does, runs `fn`, and releases the lock when `fn` returns or throws. `holder` is the label other waiters see. `lockCheck(holder, options?)` does the take and returns the release function, for callers that can't wrap their work in a function. `options.file` overrides the lock path and `options.onWait` replaces the wait message. The path is `check.lock` in the state directory above, so no repo config is needed. A call nested under an ancestor process that holds the lock runs without waiting and leaves the lock alone. Pass `options.background: true` for a long job run after a push, such as a browser suite: it still waits for a running check, but `local-ci` checks (and other non-background callers) run beside it instead of waiting, so a push never sits in its hook behind its run. Background jobs still queue behind each other. A check run beside a background job takes `check.lock.beside` instead, so checks still run one at a time: a second check started during the job waits for the first, and whoever takes `check.lock` after the background job ends (another background job or a check) waits for a check still running beside it. A background job waiting that way holds `check.lock` as a check would, without the `background` line, until the beside check ends, so checks arriving meanwhile wait in turn rather than run beside a job that has not started. A check nested in a beside check runs under its lock without waiting. A beside lock whose holder died is taken over, as `check.lock` is. Versions before the beside lock ignore it, so a check from such a version (another repo pinned to an older local-ci) can still run beside a newer beside check. The lock file marks such a lock with a third line, `background`; a file without it (as older versions wrote) is waited on as before. SIGINT, SIGTERM or SIGHUP releases the lock and ends the process, so a job that needs its own signal cleanup should run it before calling the release itself. The package has an `exports` map, so deep imports other than `./lock` no longer resolve.
89
+ `withCheckLock(holder, fn, options?)` waits while another holder has the lock, logging `local-ci: waiting for the check lock, held by pid <pid> (<holder>)` to stderr as the CLI does, runs `fn`, and releases the lock when `fn` returns or throws. `holder` is the label other waiters see. `lockCheck(holder, options?)` does the take and returns the release function, for callers that can't wrap their work in a function. `options.file` overrides the lock path and `options.onWait` replaces the wait message. The path is `check.lock` in the state directory above, so no repo config is needed. A call nested under an ancestor process that holds the lock runs without waiting and leaves the lock alone. Pass `options.background: true` for a long job run after a push, such as a browser suite: it still waits for a running check, but `local-ci` checks (and other non-background callers) run beside it instead of waiting, so a push never sits in its hook behind its run. Background jobs queue behind each other in arrival order: each waiter writes a ticket file to `check.lock.queue/` with its pid, arrival time and head start, and takes the lock only when no live ticket sorts before its own. `options.headStartMs` (milliseconds, default 0) moves a background job up by that much: it sorts by arrival minus head start, so it passes jobs that arrived less than that long before it, and no others. A ticket whose process died, that predates the last boot, or that can't be parsed is removed by the next waiter that finds it, so a killed waiter can't wedge the queue. A job held back only by a ticket, with the lock free, says so: `local-ci: waiting for the check lock, held by pid <pid> (queued ahead)`. Checks take no ticket and never wait behind queued background jobs; when the lock is free, whichever polls first takes it. Versions before the queue ignore tickets, so a waiter from such a version (another repo pinned to an older local-ci) can still take the lock out of turn. A check run beside a background job takes `check.lock.beside` instead, so checks still run one at a time: a second check started during the job waits for the first, and whoever takes `check.lock` after the background job ends (another background job or a check) waits for a check still running beside it. A background job waiting that way holds `check.lock` as a check would, without the `background` line, until the beside check ends, so checks arriving meanwhile wait in turn rather than run beside a job that has not started. A check nested in a beside check runs under its lock without waiting. A beside lock whose holder died is taken over, as `check.lock` is. Versions before the beside lock ignore it, so a check from such a version (another repo pinned to an older local-ci) can still run beside a newer beside check. The lock file marks such a lock with a third line, `background`; a file without it (as older versions wrote) is waited on as before. SIGINT, SIGTERM or SIGHUP releases the lock and ends the process, so a job that needs its own signal cleanup should run it before calling the release itself. The package has an `exports` map, so deep imports other than `./lock` no longer resolve.
79
90
 
80
91
  Part of [jonmilner/config](https://github.com/jonmilner/config#readme).
@@ -16,6 +16,11 @@ export interface LockCheckOptions {
16
16
  * waits for a running check, but checks run beside it instead of waiting for it to finish.
17
17
  */
18
18
  background?: boolean;
19
+ /**
20
+ * With `background`, how many milliseconds earlier than its arrival this job counts as having
21
+ * arrived when queueing behind other background jobs. Default 0. Ignored for a check.
22
+ */
23
+ headStartMs?: number;
19
24
  }
20
25
  /** The machine-wide check lock's path, in `$XDG_STATE_HOME/local-ci` (default `~/.local/state`). */
21
26
  export declare function checkLockPath(env?: NodeJS.ProcessEnv): string;
@@ -25,9 +30,10 @@ export declare function checkLockPath(env?: NodeJS.ProcessEnv): string;
25
30
  * that holds the lock runs without waiting, and its release leaves the lock alone. A check (not
26
31
  * `background`) that finds a background job holding it runs beside the job under a second lock,
27
32
  * `<file>.beside`, instead: a second such check waits for it, and whoever takes the check lock
28
- * next waits for it to clear. SIGINT, SIGTERM, SIGHUP and SIGQUIT release the lock and end the
33
+ * next waits for it to clear. Background jobs take the lock in arrival order, less any
34
+ * `headStartMs`; a check doesn't queue. SIGINT, SIGTERM, SIGHUP and SIGQUIT release the lock and end the
29
35
  * process.
30
36
  */
31
- export declare function lockCheck(holder: string, { file, onWait, background }?: LockCheckOptions): Promise<() => void>;
37
+ export declare function lockCheck(holder: string, { file, onWait, background, headStartMs }?: LockCheckOptions): Promise<() => void>;
32
38
  /** Runs `fn` under the machine-wide check lock, so it queues behind `local-ci` checks and vice versa. */
33
39
  export declare function withCheckLock<T>(holder: string, fn: () => Promise<T>, options?: LockCheckOptions): Promise<T>;
@@ -75,10 +75,11 @@ function besideLockPath(file) {
75
75
  * that holds the lock runs without waiting, and its release leaves the lock alone. A check (not
76
76
  * `background`) that finds a background job holding it runs beside the job under a second lock,
77
77
  * `<file>.beside`, instead: a second such check waits for it, and whoever takes the check lock
78
- * next waits for it to clear. SIGINT, SIGTERM, SIGHUP and SIGQUIT release the lock and end the
78
+ * next waits for it to clear. Background jobs take the lock in arrival order, less any
79
+ * `headStartMs`; a check doesn't queue. SIGINT, SIGTERM, SIGHUP and SIGQUIT release the lock and end the
79
80
  * process.
80
81
  */
81
- export async function lockCheck(holder, { file = checkLockPath(), onWait, background = false } = {}) {
82
+ export async function lockCheck(holder, { file = checkLockPath(), onWait, background = false, headStartMs = 0 } = {}) {
82
83
  const sidecar = besideLockPath(file);
83
84
  let mine;
84
85
  // A check nested in a check (one that pushes, say) runs under its ancestor's lock rather than
@@ -98,9 +99,10 @@ export async function lockCheck(holder, { file = checkLockPath(), onWait, backgr
98
99
  for (;;) {
99
100
  let beside = false;
100
101
  const skip = (held) => nested(held) || (beside = besides(held));
102
+ const queue = background ? { headStartMs } : undefined;
101
103
  // Taken as a check's lock even for a background job, so checks wait for it rather than run
102
104
  // beside it until it starts its run.
103
- const unlock = await waitForLock(file, { ...options, skip });
105
+ const unlock = await waitForLock(file, { ...options, skip, queue });
104
106
  if (unlock) {
105
107
  const release = releaseOnSignal(unlock);
106
108
  try {
package/dist/cli.js CHANGED
@@ -13,9 +13,10 @@ import { hooksDir, installHooks, missingHooks } from "./hooks.js";
13
13
  import { installRenovateAgent, renovateLog, rotateLog, uninstallRenovateAgent } from "./launchd.js";
14
14
  import { waitForExit } from "./lock.js";
15
15
  import { processTable } from "./processes.js";
16
- import { cannotCheckInPlace, githubRepo, nearestGit, parsePrePush, shasToCheck } from "./push.js";
16
+ import { cannotCheckInPlace, githubRepo, nearestGit, parsePrePush, shasToCheck, slowHookWarning, } from "./push.js";
17
17
  import { release, releaseCheck, takeEnvToken } from "./release.js";
18
18
  import { projectsDir, renovate } from "./renovate.js";
19
+ import { configuredSshCommand, keepaliveWarning, sshHost } from "./ssh.js";
19
20
  import { lintTitle } from "./title.js";
20
21
  const USAGE = `Usage:
21
22
  local-ci pre-push run the check for each pushed commit (git pre-push hook)
@@ -184,11 +185,20 @@ async function runHooks([subcommand, ...extra]) {
184
185
  const changes = installHooks(root, dir, command);
185
186
  out(changes.length ? changes.join("\n") : "hooks up to date");
186
187
  }
187
- async function prePush(remoteUrl) {
188
+ async function prePush(remote, remoteUrl) {
188
189
  const current = await repo();
189
190
  await assertHooks(current.root);
190
191
  await assertGhAuth(exec);
191
- const shas = shasToCheck(parsePrePush(readFileSync(0, "utf8")));
192
+ const refs = parsePrePush(readFileSync(0, "utf8"));
193
+ const shas = shasToCheck(refs);
194
+ // git holds an ssh connection open, idle, while this hook runs; an https push holds none.
195
+ const host = remoteUrl ? sshHost(remoteUrl) : undefined;
196
+ if (shas.length && host) {
197
+ const configured = await configuredSshCommand(exec, current.root);
198
+ const warning = await keepaliveWarning(exec, host, process.env, configured);
199
+ if (warning)
200
+ err(warning);
201
+ }
192
202
  // Check every commit before posting any, so a refused push posts nothing.
193
203
  for (const sha of shas)
194
204
  await runCheck(current, sha);
@@ -196,9 +206,9 @@ async function prePush(remoteUrl) {
196
206
  const ghRepo = remoteUrl ? githubRepo(remoteUrl) : undefined;
197
207
  const env = ghRepo ? { ...process.env, GH_REPO: ghRepo } : { ...process.env };
198
208
  // git sends the push only once this hook exits, so the poster waits on git before GitHub.
199
- const git = nearestGit(processTable(), process.pid);
200
- if (git)
201
- env[PUSH_PID] = String(git);
209
+ const gitPid = nearestGit(processTable(), process.pid);
210
+ if (gitPid)
211
+ env[PUSH_PID] = String(gitPid);
202
212
  else
203
213
  delete env[PUSH_PID];
204
214
  const fd = openSync(current.log, "a");
@@ -213,6 +223,12 @@ async function prePush(remoteUrl) {
213
223
  closeSync(fd);
214
224
  if (shas.length)
215
225
  err(`local-ci: passed; posting statuses in the background (${current.log})`);
226
+ // Timed from process start, so node's own startup counts toward the connection's idle time.
227
+ if (remote && host) {
228
+ const slow = slowHookWarning(performance.now(), remote, refs);
229
+ if (slow)
230
+ err(slow);
231
+ }
216
232
  }
217
233
  async function post({ passed }, sha) {
218
234
  const command = passedCommand(passed, sha);
@@ -318,7 +334,7 @@ async function runRenovate([flag, ...extra]) {
318
334
  }
319
335
  async function main([command, ...args]) {
320
336
  if (command === "pre-push")
321
- return prePush(args[1]);
337
+ return prePush(args[0], args[1]);
322
338
  if (command === "commit-msg") {
323
339
  if (!args[0] || args.length > 1) {
324
340
  err(USAGE);
@@ -343,6 +359,7 @@ async function main([command, ...args]) {
343
359
  if (command === "post" || command === "pr-title" || command === "status") {
344
360
  await assertGhAuth(exec);
345
361
  }
362
+ // oxlint-disable-next-line typescript/switch-exhaustiveness-check -- default prints usage for any other command
346
363
  switch (command) {
347
364
  case "post":
348
365
  if (!args[0])
package/dist/lock.d.ts CHANGED
@@ -38,8 +38,18 @@ export interface WaitForLockOptions extends TakeLockOptions {
38
38
  holder?: string;
39
39
  /** A holder this caller need not wait behind: the wait ends, returning `undefined`, untaken. */
40
40
  skip?: (held: LockHeld) => boolean;
41
- /** Called when the wait starts, and again whenever another process takes the lock first. */
41
+ /**
42
+ * Called when the wait starts, and again whenever another process takes the lock first. A queued
43
+ * waiter held back only by another waiter's ticket gets that waiter, with the holder `queued ahead`.
44
+ */
42
45
  onWait?: (held: LockHeld) => void;
46
+ /**
47
+ * Waits in line for the lock: this caller takes it only when no live waiter's arrival minus head
48
+ * start sorts before its own. Waiters without this option don't queue and aren't held back.
49
+ */
50
+ queue?: {
51
+ headStartMs: number;
52
+ };
43
53
  intervalMs?: number;
44
54
  sleep?: (ms: number) => Promise<void>;
45
55
  }
package/dist/lock.js CHANGED
@@ -1,5 +1,7 @@
1
- import { linkSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import { linkSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
3
  import { uptime } from "node:os";
4
+ import { join } from "node:path";
3
5
  import { defaultSleep } from "./github.js";
4
6
  /** Whether a process with this pid is running. */
5
7
  export function alive(pid) {
@@ -131,27 +133,115 @@ export function takeLock(file, what = "release", holder, options = {}) {
131
133
  rmSync(mine, { force: true });
132
134
  }
133
135
  }
136
+ const queueDir = (file) => `${file}.queue`;
137
+ /** Earliest arrival minus head start first; arrival, then name, settle a tie the same for everyone. */
138
+ function ticketOrder(a, b) {
139
+ return (a.arrival - a.headStartMs - (b.arrival - b.headStartMs) ||
140
+ a.arrival - b.arrival ||
141
+ (a.name < b.name ? -1 : 1));
142
+ }
143
+ /** Joins the queue for `file`, arriving now. */
144
+ function takeTicket(file, headStartMs) {
145
+ if (!Number.isFinite(headStartMs) || headStartMs < 0) {
146
+ throw new RangeError(`headStartMs must be a finite number of 0 or more, got ${headStartMs}`);
147
+ }
148
+ const dir = queueDir(file);
149
+ mkdirSync(dir, { recursive: true });
150
+ const ticket = {
151
+ name: `${process.pid}-${randomUUID()}`,
152
+ pid: process.pid,
153
+ arrival: Date.now(),
154
+ headStartMs,
155
+ };
156
+ // Renaming publishes it whole; the temporary name is beside the queue so nobody lists it.
157
+ const unpublished = `${dir}.${ticket.name}`;
158
+ writeFileSync(unpublished, `${ticket.pid}\n${ticket.arrival}\n${ticket.headStartMs}`);
159
+ renameSync(unpublished, join(dir, ticket.name));
160
+ return ticket;
161
+ }
162
+ /** The ticket stored at `path`, or `undefined` for one that is gone or can't be read. */
163
+ function readTicket(path, name) {
164
+ let content;
165
+ try {
166
+ content = readFileSync(path, "utf8");
167
+ }
168
+ catch {
169
+ return undefined;
170
+ }
171
+ const [pid = NaN, arrival = NaN, headStartMs = NaN] = content
172
+ .split("\n")
173
+ .map((field) => (field === "" ? NaN : Number(field)));
174
+ return { name, pid, arrival, headStartMs };
175
+ }
176
+ /** The live ticket that goes next before `mine`, if any, removing dead and pre-boot ones it finds. */
177
+ function ticketAhead(file, mine) {
178
+ const dir = queueDir(file);
179
+ let names;
180
+ try {
181
+ names = readdirSync(dir);
182
+ }
183
+ catch (error) {
184
+ if (error.code === "ENOENT")
185
+ return undefined;
186
+ throw error;
187
+ }
188
+ let ahead;
189
+ for (const name of names) {
190
+ if (name === mine.name)
191
+ continue;
192
+ const path = join(dir, name);
193
+ const ticket = readTicket(path, name);
194
+ if (!ticket)
195
+ continue;
196
+ if (!alive(ticket.pid) ||
197
+ beforeBoot(path) ||
198
+ !Number.isFinite(ticket.arrival) ||
199
+ !Number.isFinite(ticket.headStartMs)) {
200
+ rmSync(path, { force: true });
201
+ }
202
+ else if (ticketOrder(ticket, ahead ?? mine) < 0) {
203
+ ahead = ticket;
204
+ }
205
+ }
206
+ return ahead;
207
+ }
134
208
  /**
135
209
  * Takes the lock, polling while a live process holds it, and returns its release, or `undefined`
136
210
  * once it finds a holder `skip` accepts.
137
211
  */
138
212
  export async function waitForLock(file, options) {
139
- const { what, holder, skip, onWait, intervalMs = 1_000, sleep = defaultSleep } = options;
213
+ const { what, holder, skip, onWait, queue, intervalMs = 1_000, sleep = defaultSleep } = options;
214
+ const ticket = queue && takeTicket(file, queue.headStartMs);
140
215
  let last;
141
- for (;;) {
142
- try {
143
- return takeLock(file, what, holder, { background: options.background });
144
- }
145
- catch (error) {
146
- if (!(error instanceof LockHeld))
147
- throw error;
148
- if (skip?.(error))
216
+ try {
217
+ for (;;) {
218
+ const ahead = ticket && ticketAhead(file, ticket);
219
+ let held;
220
+ if (ahead) {
221
+ held = lockHolder(file, what);
222
+ }
223
+ else {
224
+ try {
225
+ return takeLock(file, what, holder, { background: options.background });
226
+ }
227
+ catch (error) {
228
+ if (!(error instanceof LockHeld))
229
+ throw error;
230
+ held = error;
231
+ }
232
+ }
233
+ if (held && skip?.(held))
149
234
  return undefined;
150
- const seen = `${error.pid}\n${error.holder}`;
235
+ const blocker = held ?? new LockHeld(what, file, ahead.pid, "queued ahead");
236
+ const seen = `${blocker.pid}\n${blocker.holder}`;
151
237
  if (seen !== last)
152
- onWait?.(error);
238
+ onWait?.(blocker);
153
239
  last = seen;
154
240
  await sleep(intervalMs);
155
241
  }
156
242
  }
243
+ finally {
244
+ if (ticket)
245
+ rmSync(join(queueDir(file), ticket.name), { force: true });
246
+ }
157
247
  }
package/dist/push.d.ts CHANGED
@@ -6,6 +6,14 @@ export interface PushedRef {
6
6
  }
7
7
  /** Parses the `<local ref> <local sha> <remote ref> <remote sha>` lines git feeds a pre-push hook. */
8
8
  export declare function parsePrePush(input: string): PushedRef[];
9
+ /** A hook run at least this long may have outlived the remote's idle timeout (the shortest drop seen came after 36s). */
10
+ export declare const SLOW_HOOK_MS = 30000;
11
+ /**
12
+ * The warning to print after a hook that ran `elapsedMs`, at least SLOW_HOOK_MS: an ssh remote may
13
+ * have dropped the connection git opened before the hook, so it names the `git ls-remote` that
14
+ * shows whether each pushed ref landed.
15
+ */
16
+ export declare function slowHookWarning(elapsedMs: number, remote: string, refs: PushedRef[]): string | undefined;
9
17
  /** The distinct commits pushed to branches. Deletes and tags are skipped. */
10
18
  export declare function shasToCheck(refs: PushedRef[]): string[];
11
19
  /**
package/dist/push.js CHANGED
@@ -13,6 +13,22 @@ export function parsePrePush(input) {
13
13
  return { localRef, localSha, remoteRef, remoteSha };
14
14
  });
15
15
  }
16
+ /** A hook run at least this long may have outlived the remote's idle timeout (the shortest drop seen came after 36s). */
17
+ export const SLOW_HOOK_MS = 30_000;
18
+ /**
19
+ * The warning to print after a hook that ran `elapsedMs`, at least SLOW_HOOK_MS: an ssh remote may
20
+ * have dropped the connection git opened before the hook, so it names the `git ls-remote` that
21
+ * shows whether each pushed ref landed.
22
+ */
23
+ export function slowHookWarning(elapsedMs, remote, refs) {
24
+ const pushed = refs.filter((ref) => !ZERO_SHA.test(ref.localSha));
25
+ if (elapsedMs < SLOW_HOOK_MS || !pushed.length)
26
+ return undefined;
27
+ return [
28
+ `local-ci: this hook ran ${Math.round(elapsedMs / 1000)}s, long enough for the remote to drop git's connection; if git then fails or prints "closed by remote host", the push did not land. Confirm with:`,
29
+ ...pushed.map((ref) => ` git ls-remote ${remote} ${ref.remoteRef} # should print ${ref.localSha}`),
30
+ ].join("\n");
31
+ }
16
32
  /** The distinct commits pushed to branches. Deletes and tags are skipped. */
17
33
  export function shasToCheck(refs) {
18
34
  const shas = refs
package/dist/release.js CHANGED
@@ -5,6 +5,7 @@ import { basename, dirname, join } from "node:path";
5
5
  import { run } from "./exec.js";
6
6
  import { defaultSleep, waitForStatuses } from "./github.js";
7
7
  import { takeLock } from "./lock.js";
8
+ import { configuredSshCommand, keepaliveEnv } from "./ssh.js";
8
9
  /** The npm token's name, both as an environment variable and in the `secret` store. */
9
10
  export const TOKEN_NAME = "NPM_TOKEN_JONMILNER";
10
11
  /** How many days ahead of the token's expiry a release starts warning. */
@@ -370,9 +371,12 @@ export async function release(exec, context) {
370
371
  return track(exec(file, args));
371
372
  };
372
373
  const stepGit = gitWith(step);
374
+ // Set once the worktree exists, so its pushes keep ssh alive and GitHub can't drop one while the
375
+ // pre-push hook waits for the check lock and runs the check.
376
+ let stepEnv;
373
377
  const stepRun = async (file, args, cwd) => {
374
378
  await live();
375
- run(file, args, cwd);
379
+ run(file, args, cwd, stepEnv);
376
380
  };
377
381
  // Set once the run is cleaning up on its own, so a signal then doesn't turn a success into an exit.
378
382
  let finishing = false;
@@ -411,6 +415,7 @@ export async function release(exec, context) {
411
415
  // Unguarded, like the token read below, so the fallback can't swallow an interrupt.
412
416
  const base = await defaultBranch(git, root);
413
417
  await stepGit(root, "worktree", "add", "--detach", dir, `origin/${base}`);
418
+ stepEnv = keepaliveEnv(process.env, await configuredSshCommand(exec, dir));
414
419
  const { changesets: pending, current, packages: unpublishedNow } = await plan(step, dir);
415
420
  let packages = unpublishedNow;
416
421
  if (!pending.length && !packages.length) {
package/dist/ssh.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { Exec } from "./exec.ts";
2
+ /**
3
+ * Seconds between ssh keepalives. git opens the push connection before the pre-push hook runs and
4
+ * sends the pack only after it exits, so without keepalives GitHub drops a connection that idles
5
+ * through a long hook.
6
+ */
7
+ export declare const KEEPALIVE_SECONDS = 15;
8
+ /** The host of an ssh remote URL (`ssh://[user@]host[:port]/path` or scp-like `[user@]host:path`), or undefined for any other. */
9
+ export declare function sshHost(url: string): string | undefined;
10
+ /** The ServerAliveInterval `ssh -G` printed, 0 when it names none. */
11
+ export declare function serverAliveInterval(sshConfig: string): number;
12
+ /** `core.sshCommand` in the repo at `cwd`, or "" when it is unset. */
13
+ export declare function configuredSshCommand(exec: Exec, cwd: string): Promise<string>;
14
+ /**
15
+ * `env` with GIT_SSH_COMMAND set to the ssh command git would run plus a keepalive, so a push
16
+ * survives a long pre-push hook whatever the user's ssh config says. `configured` is
17
+ * `core.sshCommand`. A command that is not OpenSSH is left alone. An earlier
18
+ * `-o ServerAliveInterval` in the command still wins, as ssh takes the first value it reads.
19
+ */
20
+ export declare function keepaliveEnv(env: NodeJS.ProcessEnv, configured?: string): NodeJS.ProcessEnv;
21
+ /**
22
+ * The warning to print when pushing over ssh to `host` with no keepalive, judged by running the
23
+ * ssh command git would (`env`, `configured` as in keepaliveEnv) with `-G`, which prints the
24
+ * effective config, its own `-F` and `-o` options included, without connecting. Undefined when a
25
+ * keepalive is in place, or for a command that is not OpenSSH or whose `-G` fails, since those
26
+ * can't be judged.
27
+ */
28
+ export declare function keepaliveWarning(exec: Exec, host: string, env: NodeJS.ProcessEnv, configured?: string): Promise<string | undefined>;
package/dist/ssh.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Seconds between ssh keepalives. git opens the push connection before the pre-push hook runs and
3
+ * sends the pack only after it exits, so without keepalives GitHub drops a connection that idles
4
+ * through a long hook.
5
+ */
6
+ export const KEEPALIVE_SECONDS = 15;
7
+ /** The host of an ssh remote URL (`ssh://[user@]host[:port]/path` or scp-like `[user@]host:path`), or undefined for any other. */
8
+ export function sshHost(url) {
9
+ const full = /^(?:git\+)?ssh(?:\+git)?:\/\/(?:[^@/]+@)?(\[[^\]/]+\]|[^:/]+)/.exec(url);
10
+ if (full)
11
+ return full[1].replace(/^\[(.*)\]$/, "$1");
12
+ if (url.includes("://"))
13
+ return undefined;
14
+ // git reads scp-like syntax only when no slash comes before the first colon.
15
+ return /^(?:[^@/:]+@)?([^/:]+):/.exec(url)?.[1];
16
+ }
17
+ /** The ServerAliveInterval `ssh -G` printed, 0 when it names none. */
18
+ export function serverAliveInterval(sshConfig) {
19
+ return Number(/^serveraliveinterval\s+(\d+)\s*$/im.exec(sshConfig)?.[1] ?? 0);
20
+ }
21
+ /** `core.sshCommand` in the repo at `cwd`, or "" when it is unset. */
22
+ export async function configuredSshCommand(exec, cwd) {
23
+ // `git config --get` exits 1 when the key is unset.
24
+ return (await exec("git", ["-C", cwd, "config", "--get", "core.sshCommand"]).catch(() => "")).trim();
25
+ }
26
+ /**
27
+ * The ssh command git runs, in git's own order: $GIT_SSH_COMMAND, `configured` (core.sshCommand),
28
+ * $GIT_SSH, then ssh. Undefined unless it is OpenSSH (its program is `ssh`), since another program
29
+ * such as plink takes neither `-o` nor `-G`.
30
+ */
31
+ function openSshCommand(env, configured) {
32
+ const command = env.GIT_SSH_COMMAND || configured || env.GIT_SSH || "ssh";
33
+ return /^(?:\S*\/)?ssh(?:\s|$)/.test(command) ? command : undefined;
34
+ }
35
+ /**
36
+ * `env` with GIT_SSH_COMMAND set to the ssh command git would run plus a keepalive, so a push
37
+ * survives a long pre-push hook whatever the user's ssh config says. `configured` is
38
+ * `core.sshCommand`. A command that is not OpenSSH is left alone. An earlier
39
+ * `-o ServerAliveInterval` in the command still wins, as ssh takes the first value it reads.
40
+ */
41
+ export function keepaliveEnv(env, configured) {
42
+ const command = openSshCommand(env, configured);
43
+ if (!command)
44
+ return env;
45
+ return { ...env, GIT_SSH_COMMAND: `${command} -o ServerAliveInterval=${KEEPALIVE_SECONDS}` };
46
+ }
47
+ /**
48
+ * The warning to print when pushing over ssh to `host` with no keepalive, judged by running the
49
+ * ssh command git would (`env`, `configured` as in keepaliveEnv) with `-G`, which prints the
50
+ * effective config, its own `-F` and `-o` options included, without connecting. Undefined when a
51
+ * keepalive is in place, or for a command that is not OpenSSH or whose `-G` fails, since those
52
+ * can't be judged.
53
+ */
54
+ export async function keepaliveWarning(exec, host, env, configured) {
55
+ const command = openSshCommand(env, configured);
56
+ if (!command)
57
+ return undefined;
58
+ // git runs the command through a shell too.
59
+ const config = await exec("sh", ["-c", `${command} -G "$1"`, "sh", host]).catch(() => undefined);
60
+ if (config === undefined || serverAliveInterval(config) > 0)
61
+ return undefined;
62
+ return [
63
+ `local-ci: ssh to ${host} sends no keepalive, so ${host} can drop this push while the check runs; add to ~/.ssh/config:`,
64
+ ` Host ${host}`,
65
+ ` ServerAliveInterval ${KEEPALIVE_SECONDS}`,
66
+ ].join("\n");
67
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jonmilner/local-ci",
3
- "version": "0.13.0",
3
+ "version": "0.14.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": {