@jonmilner/local-ci 0.16.1 → 0.17.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
@@ -21,14 +21,15 @@ 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. Then, before any check runs, it refuses a push whose commit, pushed to a branch other than the remote's default, conflicts with that default branch's latest commit, since a check on a head that must still take a merge is wasted: it fetches the default branch (the remote's `refs/remotes/<remote>/HEAD`, else GitHub's `defaultBranchRef` for the pushed repo) into `refs/remotes/<remote>/<default>` and runs `git merge-tree --write-tree` on the two, with no checkout, and the refusal names each conflicting commit and file and the fix (`<short-sha> conflicts with origin/main in: <files>`, then merge with `git merge origin/main`, resolve, commit and push again). `LOCAL_CI_ALLOW_CONFLICT=1 git push` lets such a push through on purpose and runs the check as usual, so `--no-verify` stays for emergencies. Pushes to the default branch, tags and deletes skip this probe, and one that can't run (a push to a URL rather than a named remote, no default branch found, a failed fetch, a `git` command still running after 30 seconds, a `merge-tree` error such as unrelated histories; git's own credential prompt is turned off, and the timeout caps any ssh prompt) prints `local-ci: <why>; skipping the conflict check` and lets the push go on. 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)), warns on stderr the moment the hook has run 30 seconds (in a lock wait or mid-check), 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. The hook still exits 0 either way.
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. Then, before any check runs, it refuses a push whose commit, pushed to a branch other than the remote's default, conflicts with that default branch's latest commit, since a check on a head that must still take a merge is wasted: it fetches the default branch (the remote's `refs/remotes/<remote>/HEAD`, else GitHub's `defaultBranchRef` for the pushed repo) into `refs/remotes/<remote>/<default>` and runs `git merge-tree --write-tree` on the two, with no checkout, and the refusal names each conflicting commit and file and the fix (`<short-sha> conflicts with origin/main in: <files>`, then merge with `git merge origin/main`, resolve, commit and push again). `LOCAL_CI_ALLOW_CONFLICT=1 git push` lets such a push through on purpose and runs the check as usual, so `--no-verify` stays for emergencies. Pushes to the default branch, tags and deletes skip this probe, and one that can't run (a push to a URL rather than a named remote, no default branch found, a failed fetch, a `git` command still running after 30 seconds, a `merge-tree` error such as unrelated histories; git's own credential prompt is turned off, and the timeout caps any ssh prompt) prints `local-ci: <why>; skipping the conflict check` and lets the push go on. For each commit pushed to a branch (deletes and tags are skipped) that has not already passed, runs the check command: the [fast set](#fast-check-set) in a repo that declares one, unless `LOCAL_CI_FULL=1` is set, else the full one. 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)), warns on stderr the moment the hook has run 30 seconds (in a lock wait or mid-check), 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. The hook still exits 0 either way.
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
- - `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. Then it confirms the push landed: for each branch pushed at that sha (`LOCAL_CI_PUSH`, JSON with the push URL, remote name and refs), one `git ls-remote` must show the ref at the sha or at a commit built on it (by `git merge-base`, else GitHub's compare API for a commit this clone lacks). Refs not yet there, or a remote that can't be read, are read again up to 3 times, 5 seconds apart. For each ref still behind it logs `<sha>: push did not land: <why>. Unless git printed a rejection, push again: git push <remote> <branch>` and shows a macOS notification naming the branch and that command (where `osascript` is missing or fails it logs that instead). When no ref at the sha landed, it posts nothing and exits 1; when another ref at it did, it posts as usual. A git still running after the 60-minute wait is confirmed the same way. 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.
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. Then it confirms the push landed: for each branch pushed at that sha (`LOCAL_CI_PUSH`, JSON with the push URL, remote name and refs), one `git ls-remote` must show the ref at the sha or at a commit built on it (by `git merge-base`, else GitHub's compare API for a commit this clone lacks). Refs not yet there, or a remote that can't be read, are read again up to 3 times, 5 seconds apart. For each ref still behind it logs `<sha>: push did not land: <why>. Unless git printed a rejection, push again: git push <remote> <branch>` and shows a macOS notification naming the branch and that command (where `osascript` is missing or fails it logs that instead). When no ref at the sha landed, it posts nothing and exits 1; when another ref at it did, it posts as usual. A git still running after the 60-minute wait is confirmed the same way. It then waits up to 3 minutes for GitHub to have the commit, posts status `check` = `success` (`<command> passed on <hostname>`), or `pending` (`fast check passed on <hostname>; full check pending`) when only the fast set passed, reading the record just before it posts, 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
- - `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.
28
+ - `local-ci status [<sha>]`: posts `check` for a commit (default `HEAD`) that already passed the full check, or runs the full check first; a fast pass alone never counts, so it always runs the full set before posting `success`. 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
+ - `local-ci run --fast`: runs the repo's [fast set](#fast-check-set), or its full check command when it declares none or `LOCAL_CI_FULL=1` is set, through `sh -c` in the repo root, on the working tree as it is (uncommitted files included), under the check lock like `run --`. It posts no status and records no pass, and exits with the command's status. Use it to check a branch with the default branch merged in, before merging, without a push.
30
31
  - `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`; 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
+ 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 with `LOCAL_CI_FULL=1` (the hook runs the full check and posts `check` = `success`, which the merge waits for; 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
33
  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
34
  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
35
 
@@ -38,7 +39,7 @@ That writes `pre-push` and `commit-msg` shims, each one line that calls local-ci
38
39
 
39
40
  - `local-ci renovate`: posts `check` and `pr-title` on Renovate PRs, which no push from this machine ever covers. It finds every open PR the Renovate app opened in the `gh` user's repos (`gh search prs --author app/renovate`) and takes only those on a `renovate/**` branch of the repo itself; any other PR is left to its own push. For each, from the clone at `~/git/<repo>` (`LOCAL_CI_PROJECTS` overrides `~/git`) whose `origin` is that repo, it:
40
41
  - skips a repo with no such clone, logging why;
41
- - skips a head commit that already has a `check` status, posting `pr-title` if that is missing, so a failed check is not rerun on every sweep (rerun it with `local-ci status <sha>` in a checkout of the head);
42
+ - skips a head commit that already has a `check` status other than `pending` (a fast set's pending still gets the full run below), posting `pr-title` if that is missing, so a failed check is not rerun on every sweep (rerun it with `local-ci status <sha>` in a checkout of the head);
42
43
  - posts without rerunning a head that already passed here (`<repo>.passed`);
43
44
  - otherwise fetches the head into a temporary worktree, runs `pnpm install --frozen-lockfile --ignore-scripts` (the head is bot-authored, so no lifecycle scripts run, the root project's included), then `local-ci status <sha>` there, which runs the check command and posts `check` (`success` or `failure`) and `pr-title`. A failed install posts `check` `failure` too. The worktree is removed afterwards, pass or fail; the clone's own checkout is never touched.
44
45
 
@@ -57,6 +58,23 @@ That writes `pre-push` and `commit-msg` shims, each one line that calls local-ci
57
58
 
58
59
  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
60
 
61
+ ## Fast check set
62
+
63
+ A repo can declare a fast set, a quicker command whose checks are all in the full one (typically typecheck, lint, format check and fast unit tests, about 30 seconds), so each push waits on it rather than the full check:
64
+
65
+ ```json
66
+ { "local-ci": { "command": "pnpm check", "fast": "pnpm check:fast" } }
67
+ ```
68
+
69
+ A repo without a `package.json` sets `LOCAL_CI_FAST_COMMAND`. A fast command equal to the full one counts as none. With a fast set:
70
+
71
+ - `pre-push` runs the fast set; a failure blocks the push. The background poster posts `check` = `pending` with the description `fast check passed on <hostname>; full check pending` (the suffix `; full check pending` is kept even when the description is cut to GitHub's 140 characters, so readers can match on it), then `pr-title` as usual. A commit that already passed the full check (or whose tree did) skips the fast run and posts `success`.
72
+ - `pending` blocks merge wherever `check` is required, until `local-ci status` runs the full set on that commit and posts `success` or `failure` over it. The poster reads the pass record just before posting, and again after a `pending` post, posting `success` over it if the full set passed meanwhile, so a `status` run right after the push is not overwritten by a late `pending`.
73
+ - `LOCAL_CI_FULL=1 git push` runs the full set in the hook instead, for a push about to merge. A slow full set risks the remote dropping the idle connection (see [SSH keepalive](#ssh-keepalive)), so `local-ci status` after the push is the safer path.
74
+ - `local-ci run --fast` runs the fast set on the working tree by hand, posting nothing.
75
+
76
+ Without a fast set, every push runs the full check, as before.
77
+
60
78
  ## SSH keepalive
61
79
 
62
80
  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`:
@@ -72,7 +90,7 @@ Host github.com
72
90
 
73
91
  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.
74
92
 
75
- A pass is recorded by commit and by tree: `<repo>.passed` gets a `<sha>\t<command>` line and a `tree:<tree>\t<command as JSON>` line (`git rev-parse <sha>^{tree}`; JSON keeps a command over several lines on one line). A commit that has not passed but whose tree passed under the same check command (a squash or merge commit with the PR head's files, or a reworded commit) counts as passed without running the check: `pre-push` and `status` skip it, record a pass for its sha, and print and log `<short-sha>: <command> already passed on tree <short-tree>; reused without running`. A different tree or command runs the check. Unlike a commit record, a tree record counts only for a clean `HEAD`, so the command it matches is the one that commit's `package.json` names. It assumes the check reads only the commit's files: a check that reads the commit message or history (a commitlint of `HEAD`, a diff from a merge base) can pass on one commit and fail on another with the same tree, and its result is reused anyway. Records written before tree lines existed still match their sha, but no tree.
93
+ A pass is recorded by commit and by tree: `<repo>.passed` gets a `<sha>\t<command>` line and a `tree:<tree>\t<command as JSON>` line (`git rev-parse <sha>^{tree}`; JSON keeps a command over several lines on one line). A commit that has not passed but whose tree passed under the same check command (a squash or merge commit with the PR head's files, or a reworded commit) counts as passed without running the check: `pre-push` and `status` skip it, record a pass for its sha, and print and log `<short-sha>: <command> already passed on tree <short-tree>; reused without running`. A different tree or command runs the check. Unlike a commit record, a tree record counts only for a clean `HEAD`, so the command it matches is the one that commit's `package.json` names. It assumes the check reads only the commit's files: a check that reads the commit message or history (a commitlint of `HEAD`, a diff from a merge base) can pass on one commit and fail on another with the same tree, and its result is reused anyway. Records written before tree lines existed still match their sha, but no tree. A fast pass is recorded apart, as `fast:<sha>\t<command as JSON>` with no tree line, so it never counts as a full pass for `pre-push`, `status`, `post` or `renovate`, and versions before fast sets skip it.
76
94
 
77
95
  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 (one that reuses a pass on its tree logs that instead, see above). Ctrl-C stops the check, which logs `did not finish after`.
78
96
 
package/dist/cli.js CHANGED
@@ -1,34 +1,37 @@
1
1
  #!/usr/bin/env node
2
- import { spawn, spawnSync } from "node:child_process";
2
+ import { spawn } from "node:child_process";
3
3
  import { closeSync, openSync, readFileSync } from "node:fs";
4
4
  import { constants, hostname } from "node:os";
5
5
  import { basename, dirname, join, relative, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { heldCheckLock, lockCheck, withCheckLock } from "./check-lock.js";
8
8
  import { commitMsg } from "./commit-msg.js";
9
- import { appendLog, checkRunMessage, logLine, passedCommand, recordPass, releaseEnabled, resolveCommand, shimCommand, statePaths, treePassed, treeReuseMessage, } from "./config.js";
10
- import { exec, run } from "./exec.js";
11
- import { assertGhAuth, checkStatus, postStatus, prTitleStatus, viewPr, waitForCommit, waitForOpenPr, } from "./github.js";
9
+ import { appendLog, checkRunMessage, fastPassed, logLine, passedCommand, recordFastPass, recordPass, releaseEnabled, resolveCommand, resolveFastCommand, shimCommand, statePaths, treePassed, treeReuseMessage, } from "./config.js";
10
+ import { assertNoConflict } from "./conflict.js";
11
+ import { exec, git, resolveCommit, run } from "./exec.js";
12
+ import { assertGhAuth, checkStatus, fastCheckStatus, postStatus, prTitleStatus, viewPr, waitForCommit, waitForOpenPr, } from "./github.js";
12
13
  import { hooksDir, installHooks, missingHooks } from "./hooks.js";
13
14
  import { confirmPush, PUSH_TARGET } from "./landed.js";
14
15
  import { installRenovateAgent, renovateLog, rotateLog, uninstallRenovateAgent } from "./launchd.js";
15
16
  import { waitForExit } from "./lock.js";
16
17
  import { processTable } from "./processes.js";
17
- import { ALLOW_CONFLICT, cannotCheckInPlace, conflictedFiles, conflictMessage, githubRepo, nearestGit, parsePrePush, shasToCheck, shasToProbe, slowHookWarning, warnWhenSlow, } from "./push.js";
18
+ import { cannotCheckInPlace, FULL_CHECK, githubRepo, nearestGit, parsePrePush, shasToCheck, slowHookWarning, warnWhenSlow, } from "./push.js";
18
19
  import { release, releaseCheck, takeEnvToken } from "./release.js";
19
20
  import { projectsDir, renovate } from "./renovate.js";
20
21
  import { configuredSshCommand, keepaliveWarning, sshHost } from "./ssh.js";
21
22
  import { lintTitle } from "./title.js";
22
23
  const USAGE = `Usage:
23
- local-ci pre-push run the check for each pushed commit (git pre-push hook)
24
+ local-ci pre-push run the check (the fast set, if any) for each pushed commit (git pre-push hook)
24
25
  local-ci post <ref> wait for <ref> on GitHub, then post its check and pr-title statuses
25
26
  local-ci pr-title [<pr>] lint the PR title and post the pr-title status
26
27
  local-ci commit-msg <file|->
27
28
  lint a commit message file (git commit-msg hook) or stdin (-)
28
29
  local-ci hooks install write the repo's pre-push and commit-msg hook shims
29
- local-ci status [<sha>] post check for <sha> (default HEAD), running the check if needed
30
+ local-ci status [<sha>] post check for <sha> (default HEAD), running the full check if needed
30
31
  local-ci run -- <command>
31
32
  run a command under the machine-wide check lock
33
+ local-ci run --fast run the fast check (the full one without a fast set) on the working
34
+ tree under the check lock, posting nothing
32
35
  local-ci release version pending changesets through a PR, publish to npm and push tags
33
36
  local-ci release --check say whether release has anything to do, changing nothing
34
37
  local-ci renovate check each open Renovate PR in your repos and post check and pr-title
@@ -36,21 +39,6 @@ const USAGE = `Usage:
36
39
  run renovate every 15 minutes with a launchd agent (macOS)
37
40
  local-ci renovate --uninstall
38
41
  remove that agent`;
39
- const git = async (...args) => (await exec("git", args)).trim();
40
- /** The full sha `ref` names, so a short sha or `HEAD` matches the full-sha pass records. */
41
- function resolveCommit(ref) {
42
- const result = spawnSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
43
- encoding: "utf8",
44
- });
45
- if (result.status === 0)
46
- return result.stdout.trim();
47
- // `--quiet` keeps git silent only for a ref that names no commit; anything else (an ambiguous
48
- // short sha, no repo, no git) keeps git's own message.
49
- const stderr = result.stderr?.trim();
50
- if (result.status === 1 && !stderr)
51
- throw new Error(`${ref} is not a commit in this repo`);
52
- throw new Error(`git rev-parse: ${stderr || result.error?.message || `exit ${result.status}`}`);
53
- }
54
42
  async function repo() {
55
43
  const root = await git("rev-parse", "--show-toplevel");
56
44
  // The common dir names the repo even from a linked worktree.
@@ -77,14 +65,18 @@ async function assertCheckable(sha) {
77
65
  }
78
66
  /**
79
67
  * Runs the check at `sha` in place, after the clean-tree rule, unless it already passed. One check
80
- * runs at a time across all repos, so overlapping checks can't starve each other's tests.
68
+ * runs at a time across all repos, so overlapping checks can't starve each other's tests. With
69
+ * `fast`, runs that command instead, unless the full set or that fast set already passed.
81
70
  */
82
- async function runCheck(current, sha) {
71
+ async function runCheck(current, sha, fast) {
72
+ // A fast pass, like a tree reuse, waits for the clean-tree rule, so the command it matches is
73
+ // the one `sha`'s own package.json names.
74
+ const fastDone = () => fast !== undefined && fastPassed(current.passed, sha, fast);
83
75
  if (passedCommand(current.passed, sha))
84
76
  return;
85
- // A tree reuse waits for the clean-tree rule too, so the command it matches is the one `sha`'s
86
- // own package.json names.
87
77
  await assertCheckable(sha);
78
+ if (fastDone())
79
+ return;
88
80
  const tree = await git("rev-parse", `${sha}^{tree}`);
89
81
  if (reuseTreePass(current, sha, tree))
90
82
  return;
@@ -94,9 +86,9 @@ async function runCheck(current, sha) {
94
86
  if (passedCommand(current.passed, sha))
95
87
  return;
96
88
  await assertCheckable(sha);
97
- if (reuseTreePass(current, sha, tree))
89
+ if (fastDone() || reuseTreePass(current, sha, tree))
98
90
  return;
99
- await runLocked(current, sha, tree);
91
+ await runLocked(current, sha, tree, fast);
100
92
  }
101
93
  finally {
102
94
  unlock();
@@ -146,9 +138,12 @@ async function runHeld(file, args, cwd) {
146
138
  held.child = undefined;
147
139
  return { ...result, interrupted: held?.signal };
148
140
  }
149
- /** Runs the check command under the check lock, logging its duration and recording a pass. */
150
- async function runLocked({ root, passed, log: logFile }, sha, tree) {
151
- const command = resolveCommand(root);
141
+ /**
142
+ * Runs the check command (or `fast`) under the check lock, logging its duration and recording a
143
+ * pass. A fast pass is recorded apart, so it never counts as a full one.
144
+ */
145
+ async function runLocked({ root, passed, log: logFile }, sha, tree, fast) {
146
+ const command = fast ?? resolveCommand(root);
152
147
  err(`local-ci: running ${command} on ${sha.slice(0, 7)}`);
153
148
  const started = performance.now();
154
149
  const result = await runHeld("sh", ["-c", command], root);
@@ -164,23 +159,44 @@ async function runLocked({ root, passed, log: logFile }, sha, tree) {
164
159
  }
165
160
  if (status !== 0)
166
161
  throw new CheckFailed(command, sha);
167
- recordPass(passed, sha, command, tree);
162
+ if (fast)
163
+ recordFastPass(passed, sha, command);
164
+ else
165
+ recordPass(passed, sha, command, tree);
168
166
  }
169
167
  /**
170
168
  * Runs `-- <command>` under the check lock, so a full check started by hand waits its turn with
171
169
  * the checks `pre-push` runs. Exits with the command's status, or 128 plus the signal that ended it.
172
170
  */
173
171
  async function runUnderLock(args) {
172
+ if (args[0] === "--fast")
173
+ return runFast(args.slice(1));
174
174
  const [separator, file, ...rest] = args;
175
175
  if (separator !== "--" || !file)
176
176
  throw new Error(`run: expected -- <command>\n${USAGE}`);
177
177
  // Outside a git repo there is no repo name, and nothing else here needs one.
178
178
  const name = (await repo().catch(() => undefined))?.name ?? basename(process.cwd());
179
+ await runLabelled(name, [file, ...rest].join(" "), file, rest);
180
+ }
181
+ /**
182
+ * `run --fast`: the repo's fast command, else its full one, on the working tree as it is, under
183
+ * the check lock. It posts no status and records no pass, since the tree need not be a commit.
184
+ */
185
+ async function runFast(extra) {
186
+ if (extra.length)
187
+ throw new Error(`run --fast: unexpected ${extra.join(" ")}\n${USAGE}`);
188
+ const { root, name } = await repo();
189
+ const full = process.env[FULL_CHECK] === "1";
190
+ const command = (full ? undefined : resolveFastCommand(root)) ?? resolveCommand(root);
191
+ err(`local-ci: running ${command} on the working tree`);
192
+ await runLabelled(name, command, "sh", ["-c", command], root);
193
+ }
194
+ /** Runs `file` under the check lock, labelled `<name> <command>`, and exits with its status. */
195
+ async function runLabelled(name, command, file, args, cwd) {
179
196
  // Other sessions print this while they wait, so a long script mustn't fill their output.
180
- const command = [file, ...rest].join(" ");
181
197
  const label = command.length > 60 ? `${command.slice(0, 57)}...` : command;
182
198
  // After a signal the release dies of it, so a command told to stop never reports a status.
183
- const result = await withCheckLock(`${name} ${label}`, () => runHeld(file, rest));
199
+ const result = await withCheckLock(`${name} ${label}`, () => runHeld(file, args, cwd));
184
200
  if (result.error)
185
201
  throw new Error(`could not run ${file}: ${result.error}`);
186
202
  process.exitCode = result.status ?? 128 + constants.signals[result.signal];
@@ -211,94 +227,6 @@ async function runHooks([subcommand, ...extra]) {
211
227
  const changes = installHooks(root, dir, command);
212
228
  out(changes.length ? changes.join("\n") : "hooks up to date");
213
229
  }
214
- /** How long a conflict-probe git command may run before the probe gives up and lets the push go on. */
215
- const PROBE_TIMEOUT_MS = 30_000;
216
- /**
217
- * Runs git for the conflict probe, never prompting and never hanging the push: a credential prompt
218
- * fails at once and a stalled fetch is killed after PROBE_TIMEOUT_MS.
219
- */
220
- const probeGit = (args) => spawnSync("git", args, {
221
- encoding: "utf8",
222
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
223
- maxBuffer: 16 * 1024 * 1024,
224
- timeout: PROBE_TIMEOUT_MS,
225
- });
226
- /** Why a probe git command failed: its stderr, else the spawn error or signal, else its exit status. */
227
- const failure = (result) => result.stderr?.trim() || result.error?.message || result.signal || `exit ${result.status}`;
228
- const skipConflictCheck = (why) => err(`local-ci: ${why}; skipping the conflict check`);
229
- /** The remote's default branch: its `HEAD` symref, else GitHub's for `ghRepo`, else undefined. */
230
- async function defaultBranch(remote, ghRepo) {
231
- const head = await git("symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`).catch(() => "");
232
- if (head.startsWith(`${remote}/`))
233
- return head.slice(remote.length + 1);
234
- if (!ghRepo)
235
- return undefined;
236
- const name = await exec("gh", [
237
- "repo",
238
- "view",
239
- ghRepo,
240
- "--json",
241
- "defaultBranchRef",
242
- "--jq",
243
- ".defaultBranchRef.name",
244
- ]).catch(() => "");
245
- return name.trim() || undefined;
246
- }
247
- /**
248
- * Refuses the push, naming the files and the fix, when a commit pushed to a branch other than the
249
- * default conflicts with the remote's latest default branch, so no check runs on a head that has
250
- * to change. A probe that can't run warns and lets the push go on.
251
- */
252
- async function assertNoConflict(refs, shas, remote, ghRepo) {
253
- if (process.env[ALLOW_CONFLICT] === "1" || !shas.length)
254
- return;
255
- const branch = await defaultBranch(remote, ghRepo);
256
- if (!branch) {
257
- skipConflictCheck(`could not find ${remote}'s default branch`);
258
- return;
259
- }
260
- const probed = shasToProbe(refs, branch);
261
- if (!probed.length)
262
- return;
263
- // A push to a URL has no `<remote>/<branch>` to merge, so the fix the refusal names can't work.
264
- if (probeGit(["config", "--get", `remote.${remote}.url`]).status !== 0) {
265
- skipConflictCheck(`${remote} is not a named remote`);
266
- return;
267
- }
268
- // Into the tracking ref the refusal tells you to merge, whatever `remote.<name>.fetch` covers.
269
- const tracking = `refs/remotes/${remote}/${branch}`;
270
- const fetched = probeGit([
271
- "fetch",
272
- "--quiet",
273
- "--no-tags",
274
- remote,
275
- `+refs/heads/${branch}:${tracking}`,
276
- ]);
277
- if (fetched.status !== 0) {
278
- skipConflictCheck(`could not fetch ${remote} ${branch} (${failure(fetched)})`);
279
- return;
280
- }
281
- const base = resolveCommit(tracking);
282
- const conflicts = [];
283
- for (const sha of probed) {
284
- const result = probeGit([
285
- "merge-tree",
286
- "--write-tree",
287
- "--name-only",
288
- "--no-messages",
289
- sha,
290
- base,
291
- ]);
292
- // merge-tree exits 1 for a conflict; anything else but 0 means it could not merge at all.
293
- if (result.status === 1)
294
- conflicts.push({ sha, files: conflictedFiles(result.stdout) });
295
- else if (result.status !== 0) {
296
- skipConflictCheck(`git merge-tree failed on ${sha.slice(0, 7)} (${failure(result)})`);
297
- }
298
- }
299
- if (conflicts.length)
300
- throw new Error(conflictMessage(remote, branch, conflicts));
301
- }
302
230
  async function prePush(remote, remoteUrl) {
303
231
  const current = await repo();
304
232
  await assertHooks(current.root);
@@ -332,9 +260,11 @@ async function checkPush(current, refs, shas, { remote, remoteUrl, host, gitPid
332
260
  if (warning)
333
261
  err(warning);
334
262
  }
263
+ // The fast set, unless the repo has none or LOCAL_CI_FULL=1 asks for the full one.
264
+ const fast = process.env[FULL_CHECK] === "1" ? undefined : resolveFastCommand(current.root);
335
265
  // Check every commit before posting any, so a refused push posts nothing.
336
266
  for (const sha of shas)
337
- await runCheck(current, sha);
267
+ await runCheck(current, sha, fast);
338
268
  const env = ghRepo ? { ...process.env, GH_REPO: ghRepo } : { ...process.env };
339
269
  if (gitPid)
340
270
  env[PUSH_PID] = String(gitPid);
@@ -362,8 +292,13 @@ async function checkPush(current, refs, shas, { remote, remoteUrl, host, gitPid
362
292
  }).unref();
363
293
  }
364
294
  closeSync(fd);
365
- if (shas.length)
366
- err(`local-ci: passed; posting statuses in the background (${current.log})`);
295
+ if (shas.length) {
296
+ const pending = shas.some((sha) => !passedCommand(current.passed, sha));
297
+ const posting = pending
298
+ ? "posting check pending until the full check runs"
299
+ : "posting statuses";
300
+ err(`local-ci: passed; ${posting} in the background (${current.log})`);
301
+ }
367
302
  // Timed from process start, so node's own startup counts toward the connection's idle time.
368
303
  if (remote && host) {
369
304
  const slow = slowHookWarning(performance.now(), remote, refs, url !== undefined);
@@ -372,8 +307,7 @@ async function checkPush(current, refs, shas, { remote, remoteUrl, host, gitPid
372
307
  }
373
308
  }
374
309
  async function post({ passed }, sha) {
375
- const command = passedCommand(passed, sha);
376
- if (!command) {
310
+ if (!passedCommand(passed, sha) && !fastPassed(passed, sha)) {
377
311
  throw new Error(`${sha.slice(0, 7)} has no passing check; run local-ci status ${sha}`);
378
312
  }
379
313
  await waitForPush(sha);
@@ -381,7 +315,16 @@ async function post({ passed }, sha) {
381
315
  process.exitCode = 1;
382
316
  return;
383
317
  }
384
- await postCheck(sha, checkStatus(command, hostname()));
318
+ // Read just before posting, so a full pass (`status` run right after the push) that landed
319
+ // while this waited is never overwritten by a late pending.
320
+ const latest = () => {
321
+ const full = passedCommand(passed, sha);
322
+ return full ? checkStatus(full, hostname()) : fastCheckStatus(hostname());
323
+ };
324
+ const posted = await postCheck(sha, latest);
325
+ // A full pass recorded while the pending post was in flight may have posted success first.
326
+ if (posted.state === "pending" && latest().state === "success")
327
+ await postCheck(sha, latest);
385
328
  const pr = await waitForOpenPr(exec, sha);
386
329
  if (pr)
387
330
  await prTitle(String(pr), sha);
@@ -408,16 +351,19 @@ async function prTitle(pr, sha) {
408
351
  log(`#${number} ${target.slice(0, 7)}: posted pr-title ${status.state}: ${status.description}`);
409
352
  return errors.length === 0;
410
353
  }
354
+ /** Posts `check` on `sha` once GitHub has it, with the status `status()` gives at that moment. */
411
355
  async function postCheck(sha, status) {
412
356
  log(`${sha.slice(0, 7)}: waiting for GitHub`);
413
357
  await waitForCommit(exec, sha);
414
- await postStatus(exec, sha, status);
415
- log(`${sha.slice(0, 7)}: posted check ${status.state}`);
358
+ const payload = status();
359
+ await postStatus(exec, sha, payload);
360
+ log(`${sha.slice(0, 7)}: posted check ${payload.state}`);
361
+ return payload;
416
362
  }
417
363
  /** Posts `check` = `failure`, reporting rather than throwing a failed post so the check's own failure stays the error. */
418
364
  async function postFailure(sha, command) {
419
365
  try {
420
- await postCheck(sha, checkStatus(command, hostname(), "failure"));
366
+ await postCheck(sha, () => checkStatus(command, hostname(), "failure"));
421
367
  }
422
368
  catch (error) {
423
369
  err(`local-ci: could not post check failure: ${error instanceof Error ? error.message : String(error)}`);
package/dist/config.d.ts CHANGED
@@ -1,6 +1,11 @@
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
+ /**
5
+ * The fast check command, or undefined for a repo with none: `local-ci.fast` in package.json, else
6
+ * `LOCAL_CI_FAST_COMMAND`. One equal to the full command is no fast set at all.
7
+ */
8
+ export declare function resolveFastCommand(root: string, env?: NodeJS.ProcessEnv): string | undefined;
4
9
  /**
5
10
  * The command hook shims run local-ci with: `local-ci.exec` in package.json, else
6
11
  * `pnpm exec local-ci` in a repo with a package.json, else a global `local-ci`.
@@ -34,7 +39,11 @@ export declare function checkRunMessage(sha: string, command: string, status: nu
34
39
  * same files can reuse the pass. JSON keeps a command written over several lines on one line.
35
40
  */
36
41
  export declare function recordPass(file: string, sha: string, command: string, tree?: string): void;
37
- /** The command that last passed at `sha`, or undefined if it was never checked. */
42
+ /** Records that the fast `command` passed at `sha`. */
43
+ export declare function recordFastPass(file: string, sha: string, command: string): void;
44
+ /** Whether the fast `command` passed at `sha`, or, without `command`, whether any fast set did. */
45
+ export declare function fastPassed(file: string, sha: string, command?: string): boolean;
46
+ /** The full command that last passed at `sha`, or undefined if it was never checked. */
38
47
  export declare function passedCommand(file: string, sha: string): string | undefined;
39
48
  /** Whether `command` passed on a commit whose tree is `tree`. Sha-only records never match. */
40
49
  export declare function treePassed(file: string, tree: string, command: string): boolean;
package/dist/config.js CHANGED
@@ -17,6 +17,15 @@ export function resolveCommand(root, env = process.env) {
17
17
  return command;
18
18
  return env.LOCAL_CI_COMMAND?.trim() || DEFAULT_COMMAND;
19
19
  }
20
+ /**
21
+ * The fast check command, or undefined for a repo with none: `local-ci.fast` in package.json, else
22
+ * `LOCAL_CI_FAST_COMMAND`. One equal to the full command is no fast set at all.
23
+ */
24
+ export function resolveFastCommand(root, env = process.env) {
25
+ const { fast } = localCiConfig(root);
26
+ const command = typeof fast === "string" && fast.trim() ? fast.trim() : env.LOCAL_CI_FAST_COMMAND?.trim();
27
+ return command && command !== resolveCommand(root, env).trim() ? command : undefined;
28
+ }
20
29
  /**
21
30
  * The command hook shims run local-ci with: `local-ci.exec` in package.json, else
22
31
  * `pnpm exec local-ci` in a repo with a package.json, else a global `local-ci`.
@@ -81,9 +90,27 @@ const TREE_PREFIX = "tree:";
81
90
  export function recordPass(file, sha, command, tree) {
82
91
  appendFileSync(file, `${sha}\t${command}\n`);
83
92
  if (tree)
84
- appendFileSync(file, `${treeLine(tree, command)}\n`);
93
+ appendFileSync(file, `${keyedLine(TREE_PREFIX, tree, command)}\n`);
94
+ }
95
+ /**
96
+ * Starts a fast pass record, `fast:<sha>\t<json command>`. It never matches a sha, so the full-pass
97
+ * readers (older versions included) skip it and a fast pass never counts as a full one.
98
+ */
99
+ const FAST_PREFIX = "fast:";
100
+ /** Records that the fast `command` passed at `sha`. */
101
+ export function recordFastPass(file, sha, command) {
102
+ appendFileSync(file, `${keyedLine(FAST_PREFIX, sha, command)}\n`);
103
+ }
104
+ /** Whether the fast `command` passed at `sha`, or, without `command`, whether any fast set did. */
105
+ export function fastPassed(file, sha, command) {
106
+ if (!existsSync(file))
107
+ return false;
108
+ const lines = readFileSync(file, "utf8").split("\n");
109
+ if (command !== undefined)
110
+ return lines.includes(keyedLine(FAST_PREFIX, sha, command));
111
+ return lines.some((line) => line.startsWith(`${FAST_PREFIX}${sha}\t`));
85
112
  }
86
- /** The command that last passed at `sha`, or undefined if it was never checked. */
113
+ /** The full command that last passed at `sha`, or undefined if it was never checked. */
87
114
  export function passedCommand(file, sha) {
88
115
  if (!existsSync(file))
89
116
  return undefined;
@@ -99,10 +126,13 @@ export function passedCommand(file, sha) {
99
126
  export function treePassed(file, tree, command) {
100
127
  if (!existsSync(file))
101
128
  return false;
102
- return readFileSync(file, "utf8").split("\n").includes(treeLine(tree, command));
129
+ return readFileSync(file, "utf8")
130
+ .split("\n")
131
+ .includes(keyedLine(TREE_PREFIX, tree, command));
103
132
  }
104
- function treeLine(tree, command) {
105
- return `${TREE_PREFIX}${tree}\t${JSON.stringify(command)}`;
133
+ /** A `<prefix><key>\t<json command>` record line; JSON keeps a command over several lines on one. */
134
+ function keyedLine(prefix, key, command) {
135
+ return `${prefix}${key}\t${JSON.stringify(command)}`;
106
136
  }
107
137
  /** The log line for a commit that reused a pass on the same tree instead of running the check. */
108
138
  export function treeReuseMessage(sha, command, tree) {
@@ -0,0 +1,7 @@
1
+ import { type PushedRef } from "./push.ts";
2
+ /**
3
+ * Refuses the push, naming the files and the fix, when a commit pushed to a branch other than the
4
+ * default conflicts with the remote's latest default branch, so no check runs on a head that has
5
+ * to change. A probe that can't run warns and lets the push go on.
6
+ */
7
+ export declare function assertNoConflict(refs: PushedRef[], shas: string[], remote: string, ghRepo?: string): Promise<void>;
@@ -0,0 +1,92 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { exec, git, resolveCommit } from "./exec.js";
3
+ import { ALLOW_CONFLICT, conflictedFiles, conflictMessage, shasToProbe, } from "./push.js";
4
+ const err = (s) => process.stderr.write(`${s}\n`);
5
+ /** How long a conflict-probe git command may run before the probe gives up and lets the push go on. */
6
+ const PROBE_TIMEOUT_MS = 30_000;
7
+ /**
8
+ * Runs git for the conflict probe, never prompting and never hanging the push: a credential prompt
9
+ * fails at once and a stalled fetch is killed after PROBE_TIMEOUT_MS.
10
+ */
11
+ const probeGit = (args) => spawnSync("git", args, {
12
+ encoding: "utf8",
13
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
14
+ maxBuffer: 16 * 1024 * 1024,
15
+ timeout: PROBE_TIMEOUT_MS,
16
+ });
17
+ /** Why a probe git command failed: its stderr, else the spawn error or signal, else its exit status. */
18
+ const failure = (result) => result.stderr?.trim() || result.error?.message || result.signal || `exit ${result.status}`;
19
+ const skipConflictCheck = (why) => err(`local-ci: ${why}; skipping the conflict check`);
20
+ /** The remote's default branch: its `HEAD` symref, else GitHub's for `ghRepo`, else undefined. */
21
+ async function defaultBranch(remote, ghRepo) {
22
+ const head = await git("symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`).catch(() => "");
23
+ if (head.startsWith(`${remote}/`))
24
+ return head.slice(remote.length + 1);
25
+ if (!ghRepo)
26
+ return undefined;
27
+ const name = await exec("gh", [
28
+ "repo",
29
+ "view",
30
+ ghRepo,
31
+ "--json",
32
+ "defaultBranchRef",
33
+ "--jq",
34
+ ".defaultBranchRef.name",
35
+ ]).catch(() => "");
36
+ return name.trim() || undefined;
37
+ }
38
+ /**
39
+ * Refuses the push, naming the files and the fix, when a commit pushed to a branch other than the
40
+ * default conflicts with the remote's latest default branch, so no check runs on a head that has
41
+ * to change. A probe that can't run warns and lets the push go on.
42
+ */
43
+ export async function assertNoConflict(refs, shas, remote, ghRepo) {
44
+ if (process.env[ALLOW_CONFLICT] === "1" || !shas.length)
45
+ return;
46
+ const branch = await defaultBranch(remote, ghRepo);
47
+ if (!branch) {
48
+ skipConflictCheck(`could not find ${remote}'s default branch`);
49
+ return;
50
+ }
51
+ const probed = shasToProbe(refs, branch);
52
+ if (!probed.length)
53
+ return;
54
+ // A push to a URL has no `<remote>/<branch>` to merge, so the fix the refusal names can't work.
55
+ if (probeGit(["config", "--get", `remote.${remote}.url`]).status !== 0) {
56
+ skipConflictCheck(`${remote} is not a named remote`);
57
+ return;
58
+ }
59
+ // Into the tracking ref the refusal tells you to merge, whatever `remote.<name>.fetch` covers.
60
+ const tracking = `refs/remotes/${remote}/${branch}`;
61
+ const fetched = probeGit([
62
+ "fetch",
63
+ "--quiet",
64
+ "--no-tags",
65
+ remote,
66
+ `+refs/heads/${branch}:${tracking}`,
67
+ ]);
68
+ if (fetched.status !== 0) {
69
+ skipConflictCheck(`could not fetch ${remote} ${branch} (${failure(fetched)})`);
70
+ return;
71
+ }
72
+ const base = resolveCommit(tracking);
73
+ const conflicts = [];
74
+ for (const sha of probed) {
75
+ const result = probeGit([
76
+ "merge-tree",
77
+ "--write-tree",
78
+ "--name-only",
79
+ "--no-messages",
80
+ sha,
81
+ base,
82
+ ]);
83
+ // merge-tree exits 1 for a conflict; anything else but 0 means it could not merge at all.
84
+ if (result.status === 1)
85
+ conflicts.push({ sha, files: conflictedFiles(result.stdout) });
86
+ else if (result.status !== 0) {
87
+ skipConflictCheck(`git merge-tree failed on ${sha.slice(0, 7)} (${failure(result)})`);
88
+ }
89
+ }
90
+ if (conflicts.length)
91
+ throw new Error(conflictMessage(remote, branch, conflicts));
92
+ }
package/dist/exec.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  /** Runs a program and resolves with its stdout; rejects with its stderr on a non-zero exit. */
2
2
  export type Exec = (file: string, args: string[]) => Promise<string>;
3
3
  export declare const exec: Exec;
4
+ /** Runs git with `args` and resolves with its trimmed stdout. */
5
+ export declare const git: (...args: string[]) => Promise<string>;
4
6
  /** Runs a program in `cwd` with its output shown, throwing unless it exits 0. */
5
7
  export declare function run(file: string, args: string[], cwd: string, env?: NodeJS.ProcessEnv): void;
8
+ /** The full sha `ref` names, so a short sha or `HEAD` matches the full-sha pass records. */
9
+ export declare function resolveCommit(ref: string): string;
package/dist/exec.js CHANGED
@@ -8,6 +8,8 @@ export const exec = (file, args) => new Promise((resolve, reject) => {
8
8
  resolve(stdout);
9
9
  });
10
10
  });
11
+ /** Runs git with `args` and resolves with its trimmed stdout. */
12
+ export const git = async (...args) => (await exec("git", args)).trim();
11
13
  /** Runs a program in `cwd` with its output shown, throwing unless it exits 0. */
12
14
  export function run(file, args, cwd, env) {
13
15
  const result = spawnSync(file, args, { cwd, env, stdio: ["ignore", "inherit", "inherit"] });
@@ -16,3 +18,17 @@ export function run(file, args, cwd, env) {
16
18
  throw new Error(`${basename(file)} ${args.join(" ")} failed (${cause})`);
17
19
  }
18
20
  }
21
+ /** The full sha `ref` names, so a short sha or `HEAD` matches the full-sha pass records. */
22
+ export function resolveCommit(ref) {
23
+ const result = spawnSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
24
+ encoding: "utf8",
25
+ });
26
+ if (result.status === 0)
27
+ return result.stdout.trim();
28
+ // `--quiet` keeps git silent only for a ref that names no commit; anything else (an ambiguous
29
+ // short sha, no repo, no git) keeps git's own message.
30
+ const stderr = result.stderr?.trim();
31
+ if (result.status === 1 && !stderr)
32
+ throw new Error(`${ref} is not a commit in this repo`);
33
+ throw new Error(`git rev-parse: ${stderr || result.error?.message || `exit ${result.status}`}`);
34
+ }
package/dist/github.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import type { Exec } from "./exec.ts";
2
2
  export interface StatusPayload {
3
- state: "success" | "failure";
3
+ state: "success" | "failure" | "pending";
4
4
  context: string;
5
5
  description: string;
6
6
  }
7
7
  /** Fails with the command that fixes it unless `gh` is logged in with `repo` scope. */
8
8
  export declare function assertGhAuth(exec: Exec): Promise<void>;
9
- export declare function checkStatus(command: string, host: string, state?: StatusPayload["state"]): StatusPayload;
9
+ export declare function checkStatus(command: string, host: string, state?: "success" | "failure"): StatusPayload;
10
+ /** `check` = `pending` after a fast pass: never `success`, which only the full set may post. */
11
+ export declare function fastCheckStatus(host: string): StatusPayload;
10
12
  export declare function prTitleStatus(errors: string[]): StatusPayload;
11
13
  export declare function postStatus(exec: Exec, sha: string, status: StatusPayload, repo?: string): Promise<void>;
12
14
  export declare const defaultSleep: (ms: number) => Promise<void>;
package/dist/github.js CHANGED
@@ -17,13 +17,25 @@ export async function assertGhAuth(exec) {
17
17
  throw new Error("gh lacks the repo scope. Run: gh auth refresh --scopes repo");
18
18
  }
19
19
  }
20
- function truncate(text) {
21
- return text.length <= DESCRIPTION_LIMIT ? text : `${text.slice(0, DESCRIPTION_LIMIT - 1)}…`;
20
+ /** `text` then `suffix`, within GitHub's limit; only `text` is cut, so a suffix readers match on survives. */
21
+ function truncate(text, suffix = "") {
22
+ const room = DESCRIPTION_LIMIT - suffix.length;
23
+ return `${text.length <= room ? text : `${text.slice(0, room - 1)}…`}${suffix}`;
22
24
  }
23
25
  export function checkStatus(command, host, state = "success") {
24
26
  const outcome = state === "success" ? "passed" : "failed";
25
27
  return { state, context: "check", description: truncate(`${command} ${outcome} on ${host}`) };
26
28
  }
29
+ /** The suffix that marks local-ci's `pending` check, so a reader can tell it from any other. */
30
+ const FULL_PENDING = "; full check pending";
31
+ /** `check` = `pending` after a fast pass: never `success`, which only the full set may post. */
32
+ export function fastCheckStatus(host) {
33
+ return {
34
+ state: "pending",
35
+ context: "check",
36
+ description: truncate(`fast check passed on ${host}`, FULL_PENDING),
37
+ };
38
+ }
27
39
  export function prTitleStatus(errors) {
28
40
  return errors[0]
29
41
  ? { state: "failure", context: "pr-title", description: truncate(errors[0]) }
package/dist/push.d.ts CHANGED
@@ -37,6 +37,8 @@ export declare function shasToProbe(refs: PushedRef[], defaultBranch: string): s
37
37
  export declare function conflictedFiles(output: string): string[];
38
38
  /** The env var that lets a push through though its head conflicts with the default branch. */
39
39
  export declare const ALLOW_CONFLICT = "LOCAL_CI_ALLOW_CONFLICT";
40
+ /** The env var that makes pre-push run the full check, not the fast set. */
41
+ export declare const FULL_CHECK = "LOCAL_CI_FULL";
40
42
  /** The refusal for pushed commits that conflict with `<remote>/<branch>`, naming the files, the fix and the override. */
41
43
  export declare function conflictMessage(remote: string, branch: string, conflicts: {
42
44
  files: string[];
package/dist/push.js CHANGED
@@ -68,6 +68,8 @@ export function conflictedFiles(output) {
68
68
  }
69
69
  /** The env var that lets a push through though its head conflicts with the default branch. */
70
70
  export const ALLOW_CONFLICT = "LOCAL_CI_ALLOW_CONFLICT";
71
+ /** The env var that makes pre-push run the full check, not the fast set. */
72
+ export const FULL_CHECK = "LOCAL_CI_FULL";
71
73
  /** The refusal for pushed commits that conflict with `<remote>/<branch>`, naming the files, the fix and the override. */
72
74
  export function conflictMessage(remote, branch, conflicts) {
73
75
  const base = `${remote}/${branch}`;
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 { FULL_CHECK } from "./push.js";
8
9
  import { configuredSshCommand, keepaliveEnv } from "./ssh.js";
9
10
  /** The npm token's name, both as an environment variable and in the `secret` store. */
10
11
  export const TOKEN_NAME = "NPM_TOKEN_JONMILNER";
@@ -415,7 +416,12 @@ export async function release(exec, context) {
415
416
  // Unguarded, like the token read below, so the fallback can't swallow an interrupt.
416
417
  const base = await defaultBranch(git, root);
417
418
  await stepGit(root, "worktree", "add", "--detach", dir, `origin/${base}`);
418
- stepEnv = keepaliveEnv(process.env, await configuredSshCommand(exec, dir));
419
+ // Its pushes run the full check: the merge waits for `check` = `success`, which a fast set's
420
+ // pending never becomes.
421
+ stepEnv = {
422
+ ...keepaliveEnv(process.env, await configuredSshCommand(exec, dir)),
423
+ [FULL_CHECK]: "1",
424
+ };
419
425
  const { changesets: pending, current, packages: unpublishedNow } = await plan(step, dir);
420
426
  let packages = unpublishedNow;
421
427
  if (!pending.length && !packages.length) {
@@ -438,7 +444,7 @@ export async function release(exec, context) {
438
444
  await stepGit(dir, "add", "-A");
439
445
  await stepGit(dir, "commit", "-m", VERSION_TITLE);
440
446
  const sha = await stepGit(dir, "rev-parse", "HEAD");
441
- // The pre-push hook runs the check and posts `check`.
447
+ // The pre-push hook runs the full check (stepEnv sets FULL_CHECK) and posts `check`.
442
448
  await stepRun("git", ["push", "-u", "origin", branch], dir);
443
449
  remoteBranch = branch;
444
450
  repo = (await step("gh", ["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"])).trim();
package/dist/renovate.js CHANGED
@@ -113,7 +113,8 @@ export async function checkRenovatePr(context, found) {
113
113
  };
114
114
  const posted = await commitStatuses(exec, sha, repo);
115
115
  const check = posted.get("check");
116
- if (check) {
116
+ // A pending check (a fast set passed on a push to the branch) still needs the full run below.
117
+ if (check && check !== "pending") {
117
118
  // A failed check stays failed until someone reruns it, so a sweep doesn't rerun it every time.
118
119
  const title = posted.has("pr-title") ? "" : postTitle();
119
120
  return `skipped: ${short} already has check ${check}${title}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jonmilner/local-ci",
3
- "version": "0.16.1",
3
+ "version": "0.17.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": {