@jonmilner/local-ci 0.15.0 → 0.16.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,9 +21,9 @@ 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. 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.
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.
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. 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>`), 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.
@@ -66,7 +66,7 @@ Host github.com
66
66
  ServerAliveInterval 15
67
67
  ```
68
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.
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, it warns on stderr at that moment and again, with the `git ls-remote` commands, at the end. A keepalive is not a guarantee (pushes have dropped with one set, on a loaded machine), so you need not check by hand either: the background poster runs `git ls-remote` once git exits, and for a ref that did not move it posts no `check`, logs it and shows a notification naming the branch and the `git push` that sends it again.
70
70
 
71
71
  ## State
72
72
 
package/dist/cli.js CHANGED
@@ -10,10 +10,11 @@ import { appendLog, checkRunMessage, logLine, passedCommand, recordPass, release
10
10
  import { exec, run } from "./exec.js";
11
11
  import { assertGhAuth, checkStatus, postStatus, prTitleStatus, viewPr, waitForCommit, waitForOpenPr, } from "./github.js";
12
12
  import { hooksDir, installHooks, missingHooks } from "./hooks.js";
13
+ import { confirmPush, PUSH_TARGET } from "./landed.js";
13
14
  import { installRenovateAgent, renovateLog, rotateLog, uninstallRenovateAgent } from "./launchd.js";
14
15
  import { waitForExit } from "./lock.js";
15
16
  import { processTable } from "./processes.js";
16
- import { cannotCheckInPlace, githubRepo, nearestGit, parsePrePush, shasToCheck, slowHookWarning, } from "./push.js";
17
+ import { ALLOW_CONFLICT, cannotCheckInPlace, conflictedFiles, conflictMessage, githubRepo, nearestGit, parsePrePush, shasToCheck, shasToProbe, slowHookWarning, warnWhenSlow, } from "./push.js";
17
18
  import { release, releaseCheck, takeEnvToken } from "./release.js";
18
19
  import { projectsDir, renovate } from "./renovate.js";
19
20
  import { configuredSshCommand, keepaliveWarning, sshHost } from "./ssh.js";
@@ -210,6 +211,94 @@ async function runHooks([subcommand, ...extra]) {
210
211
  const changes = installHooks(root, dir, command);
211
212
  out(changes.length ? changes.join("\n") : "hooks up to date");
212
213
  }
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
+ }
213
302
  async function prePush(remote, remoteUrl) {
214
303
  const current = await repo();
215
304
  await assertHooks(current.root);
@@ -218,6 +307,25 @@ async function prePush(remote, remoteUrl) {
218
307
  const shas = shasToCheck(refs);
219
308
  // git holds an ssh connection open, idle, while this hook runs; an https push holds none.
220
309
  const host = remoteUrl ? sshHost(remoteUrl) : undefined;
310
+ // Timed from process start, like slowHookWarning, and said the moment it passes, mid-wait or mid-check.
311
+ // git sends the push only once this hook exits, so the poster waits on git before GitHub.
312
+ const gitPid = nearestGit(processTable(), process.pid);
313
+ // With git to wait on, the poster also confirms each ref landed before it posts.
314
+ const confirming = gitPid !== undefined && remoteUrl !== undefined;
315
+ const cancelSlow = shas.length && host ? warnWhenSlow(err, remote ?? host, { confirming }) : () => { };
316
+ try {
317
+ await checkPush(current, refs, shas, { remote, remoteUrl, host, gitPid });
318
+ }
319
+ finally {
320
+ cancelSlow();
321
+ }
322
+ }
323
+ /** pre-push after reading its refs: probe, check, then hand each sha to a background poster. */
324
+ async function checkPush(current, refs, shas, { remote, remoteUrl, host, gitPid }) {
325
+ // Post to the remote being pushed, not whichever one gh would pick.
326
+ const ghRepo = remoteUrl ? githubRepo(remoteUrl) : undefined;
327
+ // Before any check, since a check on a head that must still take a merge is wasted.
328
+ await assertNoConflict(refs, shas, remote ?? "origin", ghRepo);
221
329
  if (shas.length && host) {
222
330
  const configured = await configuredSshCommand(exec, current.root);
223
331
  const warning = await keepaliveWarning(exec, host, process.env, configured);
@@ -227,21 +335,29 @@ async function prePush(remote, remoteUrl) {
227
335
  // Check every commit before posting any, so a refused push posts nothing.
228
336
  for (const sha of shas)
229
337
  await runCheck(current, sha);
230
- // Post to the remote being pushed, not whichever one gh would pick.
231
- const ghRepo = remoteUrl ? githubRepo(remoteUrl) : undefined;
232
338
  const env = ghRepo ? { ...process.env, GH_REPO: ghRepo } : { ...process.env };
233
- // git sends the push only once this hook exits, so the poster waits on git before GitHub.
234
- const gitPid = nearestGit(processTable(), process.pid);
235
339
  if (gitPid)
236
340
  env[PUSH_PID] = String(gitPid);
237
341
  else
238
342
  delete env[PUSH_PID];
343
+ const url = gitPid === undefined ? undefined : remoteUrl;
344
+ delete env[PUSH_TARGET];
239
345
  const fd = openSync(current.log, "a");
240
346
  for (const sha of shas) {
347
+ const pushed = refs.filter((ref) => ref.localSha === sha && ref.remoteRef.startsWith("refs/heads/"));
241
348
  spawn(process.execPath, [fileURLToPath(import.meta.url), "post", sha], {
242
349
  cwd: current.root,
243
350
  detached: true,
244
- env,
351
+ env: url
352
+ ? {
353
+ ...env,
354
+ [PUSH_TARGET]: JSON.stringify({
355
+ url,
356
+ remote: remote ?? url,
357
+ refs: pushed,
358
+ }),
359
+ }
360
+ : env,
245
361
  stdio: ["ignore", fd, fd],
246
362
  }).unref();
247
363
  }
@@ -250,7 +366,7 @@ async function prePush(remote, remoteUrl) {
250
366
  err(`local-ci: passed; posting statuses in the background (${current.log})`);
251
367
  // Timed from process start, so node's own startup counts toward the connection's idle time.
252
368
  if (remote && host) {
253
- const slow = slowHookWarning(performance.now(), remote, refs);
369
+ const slow = slowHookWarning(performance.now(), remote, refs, url !== undefined);
254
370
  if (slow)
255
371
  err(slow);
256
372
  }
@@ -261,6 +377,10 @@ async function post({ passed }, sha) {
261
377
  throw new Error(`${sha.slice(0, 7)} has no passing check; run local-ci status ${sha}`);
262
378
  }
263
379
  await waitForPush(sha);
380
+ if (!(await confirmPush(sha, log))) {
381
+ process.exitCode = 1;
382
+ return;
383
+ }
264
384
  await postCheck(sha, checkStatus(command, hostname()));
265
385
  const pr = await waitForOpenPr(exec, sha);
266
386
  if (pr)
@@ -275,7 +395,7 @@ async function waitForPush(sha) {
275
395
  return;
276
396
  log(`${sha.slice(0, 7)}: waiting for git (pid ${pid}) to push`);
277
397
  if (!(await waitForExit(pid))) {
278
- log(`${sha.slice(0, 7)}: git (pid ${pid}) still running after 60 min; waiting for GitHub anyway`);
398
+ log(`${sha.slice(0, 7)}: git (pid ${pid}) still running after 60 min; checking the push anyway`);
279
399
  }
280
400
  }
281
401
  /** Posts `pr-title` on `sha`, or on the PR's head commit when `sha` is omitted. */
@@ -0,0 +1,44 @@
1
+ import { type PushedRef } from "./push.ts";
2
+ /** The env var pre-push sets on a poster to the JSON PushTarget it must confirm before posting. */
3
+ export declare const PUSH_TARGET = "LOCAL_CI_PUSH";
4
+ /** Where a poster's sha was pushed: the push URL, the remote's name for messages, and the refs pushed at it. */
5
+ export interface PushTarget {
6
+ url: string;
7
+ remote: string;
8
+ refs: PushedRef[];
9
+ /** Milliseconds between reads of the remote; unset is unlandedRefs' default. Tests set 0. */
10
+ intervalMs?: number;
11
+ }
12
+ /** The sha `git ls-remote <remote> <ref>` printed for exactly `ref`, or undefined when the remote has no such ref. */
13
+ export declare function lsRemoteSha(output: string, ref: string): string | undefined;
14
+ export interface PushCheckDeps {
15
+ /** Runs one `git ls-remote` for `refs` and resolves with its stdout; rejects when it can't reach the remote. */
16
+ lsRemote: (refs: string[]) => Promise<string>;
17
+ /** Whether `ancestor` is `descendant` or an ancestor of it, false when that can't be shown. */
18
+ isAncestor: (ancestor: string, descendant: string) => Promise<boolean>;
19
+ sleep?: (ms: number) => Promise<void>;
20
+ /** Reads of the remote before a ref still not at its sha, or a remote still unreadable, counts as unlanded. Default 3. */
21
+ attempts?: number;
22
+ /** Milliseconds between reads. Default 5000. */
23
+ intervalMs?: number;
24
+ }
25
+ /** A pushed ref the remote does not show at its sha (or a later commit on top of it), and why. */
26
+ export interface UnlandedRef {
27
+ ref: PushedRef;
28
+ reason: string;
29
+ }
30
+ /**
31
+ * The refs in `refs` that did not land, each read with one `git ls-remote` for all of them: a ref
32
+ * landed when the remote shows it at its pushed sha, or at a commit built on it (a later push).
33
+ * Refs still unlanded, or a remote still unreadable, are read again up to `attempts` times, so a
34
+ * remote whose view of its refs lags a moment is not taken for a dropped push.
35
+ */
36
+ export declare function unlandedRefs(refs: PushedRef[], deps: PushCheckDeps): Promise<UnlandedRef[]>;
37
+ /**
38
+ * After git exits, confirms with `git ls-remote` that each ref pre-push named moved to `sha`. For
39
+ * each that did not (the remote dropped git's connection, or rejected the ref), logs why and the
40
+ * re-push and shows a notification. Returns false, so nothing is posted, only when no ref landed:
41
+ * GitHub then may not have the commit at all, or has it only from some other push. True when a
42
+ * ref landed, or there is nothing to confirm (a `post` run by hand).
43
+ */
44
+ export declare function confirmPush(sha: string, log: (message: string) => void): Promise<boolean>;
package/dist/landed.js ADDED
@@ -0,0 +1,121 @@
1
+ import { execFile, spawnSync } from "node:child_process";
2
+ import { exec } from "./exec.js";
3
+ import { defaultSleep } from "./github.js";
4
+ import { rePushCommand, shortBranch } from "./push.js";
5
+ /** The env var pre-push sets on a poster to the JSON PushTarget it must confirm before posting. */
6
+ export const PUSH_TARGET = "LOCAL_CI_PUSH";
7
+ /** The sha `git ls-remote <remote> <ref>` printed for exactly `ref`, or undefined when the remote has no such ref. */
8
+ export function lsRemoteSha(output, ref) {
9
+ for (const line of output.split("\n")) {
10
+ const [sha, name] = line.trim().split(/\s+/);
11
+ if (sha && name === ref)
12
+ return sha;
13
+ }
14
+ return undefined;
15
+ }
16
+ /** One read of the remote: the refs in `refs` it does not show at their sha or a commit built on it. */
17
+ async function readUnlanded(refs, deps) {
18
+ let output;
19
+ try {
20
+ output = await deps.lsRemote(refs.map((ref) => ref.remoteRef));
21
+ }
22
+ catch (error) {
23
+ const why = error instanceof Error ? error.message : String(error);
24
+ return refs.map((ref) => ({
25
+ ref,
26
+ reason: `could not read ${ref.remoteRef} from the remote (${why})`,
27
+ }));
28
+ }
29
+ const unlanded = [];
30
+ for (const ref of refs) {
31
+ const at = lsRemoteSha(output, ref.remoteRef);
32
+ if (at === ref.localSha || (at && (await deps.isAncestor(ref.localSha, at))))
33
+ continue;
34
+ unlanded.push({
35
+ ref,
36
+ reason: `${ref.remoteRef} is ${at ? `at ${at.slice(0, 7)}` : "missing"} on the remote, not ${ref.localSha.slice(0, 7)}`,
37
+ });
38
+ }
39
+ return unlanded;
40
+ }
41
+ /**
42
+ * The refs in `refs` that did not land, each read with one `git ls-remote` for all of them: a ref
43
+ * landed when the remote shows it at its pushed sha, or at a commit built on it (a later push).
44
+ * Refs still unlanded, or a remote still unreadable, are read again up to `attempts` times, so a
45
+ * remote whose view of its refs lags a moment is not taken for a dropped push.
46
+ */
47
+ export async function unlandedRefs(refs, deps) {
48
+ const { sleep = defaultSleep, attempts = 3, intervalMs = 5_000 } = deps;
49
+ let unlanded = await readUnlanded(refs, deps);
50
+ for (let tries = 1; unlanded.length && tries < attempts; tries++) {
51
+ await sleep(intervalMs);
52
+ unlanded = await readUnlanded(unlanded.map(({ ref }) => ref), deps);
53
+ }
54
+ return unlanded;
55
+ }
56
+ /** How long one `git ls-remote` may take; it runs with no terminal, so it must never prompt or hang. */
57
+ const LS_REMOTE_TIMEOUT_MS = 60_000;
58
+ const lsRemote = (url, refs) => new Promise((resolve, reject) => {
59
+ execFile("git", ["ls-remote", url, ...refs], { env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, timeout: LS_REMOTE_TIMEOUT_MS }, (error, stdout, stderr) => error ? reject(new Error(stderr.trim() || error.message)) : resolve(stdout));
60
+ });
61
+ /**
62
+ * Whether `descendant` contains `ancestor`: by `git merge-base` when this repo has both, else by
63
+ * GitHub's compare API for a commit pushed from elsewhere (GH_REPO names the pushed repo).
64
+ */
65
+ async function isAncestor(ancestor, descendant) {
66
+ const local = await exec("git", ["merge-base", "--is-ancestor", ancestor, descendant]).then(() => true, () => undefined);
67
+ if (local)
68
+ return true;
69
+ // merge-base exits 1 for "not an ancestor" and 128 for an unknown commit; both land here.
70
+ const status = await exec("gh", [
71
+ "api",
72
+ `repos/{owner}/{repo}/compare/${ancestor}...${descendant}`,
73
+ "--jq",
74
+ ".status",
75
+ ]).catch(() => "");
76
+ return ["ahead", "identical"].includes(status.trim());
77
+ }
78
+ /** Shows a macOS notification; where osascript is missing or fails it logs that, and never throws. */
79
+ function notify(log, title, message) {
80
+ const result = spawnSync("osascript", [
81
+ "-e",
82
+ "on run argv",
83
+ "-e",
84
+ "display notification (item 2 of argv) with title (item 1 of argv)",
85
+ "-e",
86
+ "end run",
87
+ title,
88
+ message,
89
+ ], { stdio: "ignore", timeout: 10_000 });
90
+ if (result.status !== 0) {
91
+ log(`could not show a notification (${result.error?.message ?? result.signal ?? `exit ${result.status}`})`);
92
+ }
93
+ }
94
+ /**
95
+ * After git exits, confirms with `git ls-remote` that each ref pre-push named moved to `sha`. For
96
+ * each that did not (the remote dropped git's connection, or rejected the ref), logs why and the
97
+ * re-push and shows a notification. Returns false, so nothing is posted, only when no ref landed:
98
+ * GitHub then may not have the commit at all, or has it only from some other push. True when a
99
+ * ref landed, or there is nothing to confirm (a `post` run by hand).
100
+ */
101
+ export async function confirmPush(sha, log) {
102
+ const json = process.env[PUSH_TARGET];
103
+ if (!json)
104
+ return true;
105
+ const { url, remote, refs, intervalMs } = JSON.parse(json);
106
+ const unlanded = await unlandedRefs(refs, {
107
+ lsRemote: (names) => lsRemote(url, names),
108
+ isAncestor,
109
+ ...(intervalMs === undefined ? {} : { intervalMs }),
110
+ });
111
+ if (!unlanded.length)
112
+ return true;
113
+ const landed = unlanded.length < refs.length;
114
+ for (const { ref, reason } of unlanded) {
115
+ log(`${sha.slice(0, 7)}: push did not land: ${reason}${landed ? "" : "; not posting check"}. Unless git printed a rejection, push again: ${rePushCommand(remote, ref)}`);
116
+ }
117
+ const branches = unlanded.map(({ ref }) => shortBranch(ref.remoteRef)).join(", ");
118
+ const rePush = unlanded.map(({ ref }) => rePushCommand(remote, ref)).join("; ");
119
+ notify(log, "local-ci: push did not land", `${branches} did not reach ${remote}. Unless git printed a rejection, push again: ${rePush}`);
120
+ return landed;
121
+ }
package/dist/push.d.ts CHANGED
@@ -13,9 +13,35 @@ export declare const SLOW_HOOK_MS = 30000;
13
13
  * have dropped the connection git opened before the hook, so it names the `git ls-remote` that
14
14
  * shows whether each pushed ref landed.
15
15
  */
16
- export declare function slowHookWarning(elapsedMs: number, remote: string, refs: PushedRef[]): string | undefined;
16
+ export declare function slowHookWarning(elapsedMs: number, remote: string, refs: PushedRef[], confirming?: boolean): string | undefined;
17
+ /**
18
+ * Calls `warn` with a notice once `thresholdMs` (default SLOW_HOOK_MS) has passed since
19
+ * `startedMs` (on the `performance.now()` clock), so a long lock wait or check says at that moment
20
+ * that git's connection may drop. `confirming` says a poster will confirm the push landed. Returns a cancel for when the hook ends first; the timer never keeps the
21
+ * process alive.
22
+ */
23
+ export declare function warnWhenSlow(warn: (message: string) => void, remote: string, { confirming, startedMs, thresholdMs }?: {
24
+ confirming?: boolean | undefined;
25
+ startedMs?: number | undefined;
26
+ thresholdMs?: number | undefined;
27
+ }): () => void;
28
+ /** A ref's branch name: `refs/heads/x` is `x`; any other ref stays as it is. */
29
+ export declare const shortBranch: (ref: string) => string;
30
+ /** The `git push` that sends `ref` again. */
31
+ export declare function rePushCommand(remote: string, ref: PushedRef): string;
17
32
  /** The distinct commits pushed to branches. Deletes and tags are skipped. */
18
33
  export declare function shasToCheck(refs: PushedRef[]): string[];
34
+ /** The distinct commits pushed to branches other than `defaultBranch`, the only ones that can conflict with it. */
35
+ export declare function shasToProbe(refs: PushedRef[], defaultBranch: string): string[];
36
+ /** The conflicted paths in `git merge-tree --write-tree --name-only --no-messages` output: every line after the tree. */
37
+ export declare function conflictedFiles(output: string): string[];
38
+ /** The env var that lets a push through though its head conflicts with the default branch. */
39
+ export declare const ALLOW_CONFLICT = "LOCAL_CI_ALLOW_CONFLICT";
40
+ /** The refusal for pushed commits that conflict with `<remote>/<branch>`, naming the files, the fix and the override. */
41
+ export declare function conflictMessage(remote: string, branch: string, conflicts: {
42
+ files: string[];
43
+ sha: string;
44
+ }[]): string;
19
45
  /**
20
46
  * Why `sha` can't be checked in place, or null when it can: it must be HEAD, with a clean
21
47
  * working tree, so the result reflects the commit rather than uncommitted files.
package/dist/push.js CHANGED
@@ -20,15 +20,37 @@ export const SLOW_HOOK_MS = 30_000;
20
20
  * have dropped the connection git opened before the hook, so it names the `git ls-remote` that
21
21
  * shows whether each pushed ref landed.
22
22
  */
23
- export function slowHookWarning(elapsedMs, remote, refs) {
23
+ export function slowHookWarning(elapsedMs, remote, refs, confirming = false) {
24
24
  const pushed = refs.filter((ref) => !ZERO_SHA.test(ref.localSha));
25
25
  if (elapsedMs < SLOW_HOOK_MS || !pushed.length)
26
26
  return undefined;
27
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:`,
28
+ `local-ci: this hook ran ${Math.round(elapsedMs / 1000)}s, long enough for the remote to drop git's connection; ${confirming ? "local-ci confirms the push landed once git exits. To check by hand:" : 'if git then fails or prints "closed by remote host", the push did not land. Confirm with:'}`,
29
29
  ...pushed.map((ref) => ` git ls-remote ${remote} ${ref.remoteRef} # should print ${ref.localSha}`),
30
30
  ].join("\n");
31
31
  }
32
+ /**
33
+ * Calls `warn` with a notice once `thresholdMs` (default SLOW_HOOK_MS) has passed since
34
+ * `startedMs` (on the `performance.now()` clock), so a long lock wait or check says at that moment
35
+ * that git's connection may drop. `confirming` says a poster will confirm the push landed. Returns a cancel for when the hook ends first; the timer never keeps the
36
+ * process alive.
37
+ */
38
+ export function warnWhenSlow(warn, remote, { confirming = false, startedMs = 0, thresholdMs = SLOW_HOOK_MS } = {}) {
39
+ const then = confirming
40
+ ? "after git exits, local-ci checks the push landed and notifies you if it did not"
41
+ : 'if git then fails or prints "closed by remote host", the push did not land';
42
+ const timer = setTimeout(() => warn(`local-ci: this hook has run ${Math.round(thresholdMs / 1000)}s, long enough for ${remote} to drop git's connection; ${then}`), Math.max(0, thresholdMs - (performance.now() - startedMs)));
43
+ timer.unref();
44
+ return () => clearTimeout(timer);
45
+ }
46
+ /** A ref's branch name: `refs/heads/x` is `x`; any other ref stays as it is. */
47
+ export const shortBranch = (ref) => ref.replace(/^refs\/heads\//, "");
48
+ /** The `git push` that sends `ref` again. */
49
+ export function rePushCommand(remote, ref) {
50
+ const local = shortBranch(ref.localRef);
51
+ const target = shortBranch(ref.remoteRef);
52
+ return `git push ${remote} ${local === target ? target : `${local}:${target}`}`;
53
+ }
32
54
  /** The distinct commits pushed to branches. Deletes and tags are skipped. */
33
55
  export function shasToCheck(refs) {
34
56
  const shas = refs
@@ -36,6 +58,27 @@ export function shasToCheck(refs) {
36
58
  .map((ref) => ref.localSha);
37
59
  return [...new Set(shas)];
38
60
  }
61
+ /** The distinct commits pushed to branches other than `defaultBranch`, the only ones that can conflict with it. */
62
+ export function shasToProbe(refs, defaultBranch) {
63
+ return shasToCheck(refs.filter((ref) => ref.remoteRef !== `refs/heads/${defaultBranch}`));
64
+ }
65
+ /** The conflicted paths in `git merge-tree --write-tree --name-only --no-messages` output: every line after the tree. */
66
+ export function conflictedFiles(output) {
67
+ return output.split("\n").slice(1).filter(Boolean);
68
+ }
69
+ /** The env var that lets a push through though its head conflicts with the default branch. */
70
+ export const ALLOW_CONFLICT = "LOCAL_CI_ALLOW_CONFLICT";
71
+ /** The refusal for pushed commits that conflict with `<remote>/<branch>`, naming the files, the fix and the override. */
72
+ export function conflictMessage(remote, branch, conflicts) {
73
+ const base = `${remote}/${branch}`;
74
+ return [
75
+ ...conflicts.flatMap(({ sha, files }) => [
76
+ `${sha.slice(0, 7)} conflicts with ${base} in:`,
77
+ ...files.map((file) => ` ${file}`),
78
+ ]),
79
+ `Merge it in first (\`git merge ${base}\`), resolve the conflicts, commit and push again, so the check runs on the head that will merge. To push anyway: \`${ALLOW_CONFLICT}=1 git push\`.`,
80
+ ].join("\n");
81
+ }
39
82
  /**
40
83
  * Why `sha` can't be checked in place, or null when it can: it must be HEAD, with a clean
41
84
  * working tree, so the result reflects the commit rather than uncommitted files.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jonmilner/local-ci",
3
- "version": "0.15.0",
3
+ "version": "0.16.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": {