@jonmilner/local-ci 0.15.0 → 0.16.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 +1 -1
- package/dist/cli.js +93 -3
- package/dist/push.d.ts +11 -0
- package/dist/push.js +21 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,7 +21,7 @@ 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)), and a run of 30 seconds or more ends by printing how long it ran and, for each pushed ref, the `git ls-remote <remote> <ref>` that should print the pushed sha.
|
|
25
25
|
- `local-ci commit-msg <file>`: lints the commit message in `<file>` with `@jonmilner/commitlint-config`, for a git `commit-msg` hook (git passes `.git/COMMIT_EDITMSG`). `local-ci commit-msg -` reads the message from stdin, for PR titles. Comment lines (starting with `#`) and everything after a `# ------------------------ >8 ------------------------` scissors line are stripped first; merge commits, `fixup!`/`squash!` and reverts are skipped. Each error or warning goes to stderr as `commit-msg: <message> [<rule>]`, followed by the offending header; it exits 1 when there are errors (warnings alone exit 0), and 2 when no file is given. It makes no network, git or GitHub calls.
|
|
26
26
|
- `local-ci post <ref>`: resolves `<ref>` (a full or short sha, `HEAD`, a branch) to a local commit's full sha, failing with `<ref> is not a commit in this repo` when it names none, and with `<sha> has no passing check` when that commit never passed. When started by `pre-push`, first waits for the pushing `git` to exit (polling each second, up to 60 minutes, logging if it gives up), since git sends the push only after the whole hook exits, so a slow step after local-ci in the hook can't run out the clock; run by hand, it skips that wait. It then waits up to 3 minutes for GitHub to have the commit, posts status `check` = `success` (`<command> passed on <hostname>`), then posts `pr-title` on it for an open PR that contains it (waiting up to 30s for GitHub to link them). A PR opened after the push, or a retitled one, needs `local-ci pr-title` run by hand.
|
|
27
27
|
- `local-ci pr-title [<pr>]`: lints the PR title (the current branch's PR by default) with `@jonmilner/commitlint-config` and posts status `pr-title` on its head commit, `failure` with the first error when the title does not pass.
|
package/dist/cli.js
CHANGED
|
@@ -13,7 +13,7 @@ import { hooksDir, installHooks, missingHooks } from "./hooks.js";
|
|
|
13
13
|
import { installRenovateAgent, renovateLog, rotateLog, uninstallRenovateAgent } from "./launchd.js";
|
|
14
14
|
import { waitForExit } from "./lock.js";
|
|
15
15
|
import { processTable } from "./processes.js";
|
|
16
|
-
import { cannotCheckInPlace, githubRepo, nearestGit, parsePrePush, shasToCheck, slowHookWarning, } from "./push.js";
|
|
16
|
+
import { ALLOW_CONFLICT, cannotCheckInPlace, conflictedFiles, conflictMessage, githubRepo, nearestGit, parsePrePush, shasToCheck, shasToProbe, slowHookWarning, } from "./push.js";
|
|
17
17
|
import { release, releaseCheck, takeEnvToken } from "./release.js";
|
|
18
18
|
import { projectsDir, renovate } from "./renovate.js";
|
|
19
19
|
import { configuredSshCommand, keepaliveWarning, sshHost } from "./ssh.js";
|
|
@@ -210,12 +210,104 @@ async function runHooks([subcommand, ...extra]) {
|
|
|
210
210
|
const changes = installHooks(root, dir, command);
|
|
211
211
|
out(changes.length ? changes.join("\n") : "hooks up to date");
|
|
212
212
|
}
|
|
213
|
+
/** How long a conflict-probe git command may run before the probe gives up and lets the push go on. */
|
|
214
|
+
const PROBE_TIMEOUT_MS = 30_000;
|
|
215
|
+
/**
|
|
216
|
+
* Runs git for the conflict probe, never prompting and never hanging the push: a credential prompt
|
|
217
|
+
* fails at once and a stalled fetch is killed after PROBE_TIMEOUT_MS.
|
|
218
|
+
*/
|
|
219
|
+
const probeGit = (args) => spawnSync("git", args, {
|
|
220
|
+
encoding: "utf8",
|
|
221
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
222
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
223
|
+
timeout: PROBE_TIMEOUT_MS,
|
|
224
|
+
});
|
|
225
|
+
/** Why a probe git command failed: its stderr, else the spawn error or signal, else its exit status. */
|
|
226
|
+
const failure = (result) => result.stderr?.trim() || result.error?.message || result.signal || `exit ${result.status}`;
|
|
227
|
+
const skipConflictCheck = (why) => err(`local-ci: ${why}; skipping the conflict check`);
|
|
228
|
+
/** The remote's default branch: its `HEAD` symref, else GitHub's for `ghRepo`, else undefined. */
|
|
229
|
+
async function defaultBranch(remote, ghRepo) {
|
|
230
|
+
const head = await git("symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`).catch(() => "");
|
|
231
|
+
if (head.startsWith(`${remote}/`))
|
|
232
|
+
return head.slice(remote.length + 1);
|
|
233
|
+
if (!ghRepo)
|
|
234
|
+
return undefined;
|
|
235
|
+
const name = await exec("gh", [
|
|
236
|
+
"repo",
|
|
237
|
+
"view",
|
|
238
|
+
ghRepo,
|
|
239
|
+
"--json",
|
|
240
|
+
"defaultBranchRef",
|
|
241
|
+
"--jq",
|
|
242
|
+
".defaultBranchRef.name",
|
|
243
|
+
]).catch(() => "");
|
|
244
|
+
return name.trim() || undefined;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Refuses the push, naming the files and the fix, when a commit pushed to a branch other than the
|
|
248
|
+
* default conflicts with the remote's latest default branch, so no check runs on a head that has
|
|
249
|
+
* to change. A probe that can't run warns and lets the push go on.
|
|
250
|
+
*/
|
|
251
|
+
async function assertNoConflict(refs, shas, remote, ghRepo) {
|
|
252
|
+
if (process.env[ALLOW_CONFLICT] === "1" || !shas.length)
|
|
253
|
+
return;
|
|
254
|
+
const branch = await defaultBranch(remote, ghRepo);
|
|
255
|
+
if (!branch) {
|
|
256
|
+
skipConflictCheck(`could not find ${remote}'s default branch`);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const probed = shasToProbe(refs, branch);
|
|
260
|
+
if (!probed.length)
|
|
261
|
+
return;
|
|
262
|
+
// A push to a URL has no `<remote>/<branch>` to merge, so the fix the refusal names can't work.
|
|
263
|
+
if (probeGit(["config", "--get", `remote.${remote}.url`]).status !== 0) {
|
|
264
|
+
skipConflictCheck(`${remote} is not a named remote`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
// Into the tracking ref the refusal tells you to merge, whatever `remote.<name>.fetch` covers.
|
|
268
|
+
const tracking = `refs/remotes/${remote}/${branch}`;
|
|
269
|
+
const fetched = probeGit([
|
|
270
|
+
"fetch",
|
|
271
|
+
"--quiet",
|
|
272
|
+
"--no-tags",
|
|
273
|
+
remote,
|
|
274
|
+
`+refs/heads/${branch}:${tracking}`,
|
|
275
|
+
]);
|
|
276
|
+
if (fetched.status !== 0) {
|
|
277
|
+
skipConflictCheck(`could not fetch ${remote} ${branch} (${failure(fetched)})`);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const base = resolveCommit(tracking);
|
|
281
|
+
const conflicts = [];
|
|
282
|
+
for (const sha of probed) {
|
|
283
|
+
const result = probeGit([
|
|
284
|
+
"merge-tree",
|
|
285
|
+
"--write-tree",
|
|
286
|
+
"--name-only",
|
|
287
|
+
"--no-messages",
|
|
288
|
+
sha,
|
|
289
|
+
base,
|
|
290
|
+
]);
|
|
291
|
+
// merge-tree exits 1 for a conflict; anything else but 0 means it could not merge at all.
|
|
292
|
+
if (result.status === 1)
|
|
293
|
+
conflicts.push({ sha, files: conflictedFiles(result.stdout) });
|
|
294
|
+
else if (result.status !== 0) {
|
|
295
|
+
skipConflictCheck(`git merge-tree failed on ${sha.slice(0, 7)} (${failure(result)})`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (conflicts.length)
|
|
299
|
+
throw new Error(conflictMessage(remote, branch, conflicts));
|
|
300
|
+
}
|
|
213
301
|
async function prePush(remote, remoteUrl) {
|
|
214
302
|
const current = await repo();
|
|
215
303
|
await assertHooks(current.root);
|
|
216
304
|
await assertGhAuth(exec);
|
|
217
305
|
const refs = parsePrePush(readFileSync(0, "utf8"));
|
|
218
306
|
const shas = shasToCheck(refs);
|
|
307
|
+
// Post to the remote being pushed, not whichever one gh would pick.
|
|
308
|
+
const ghRepo = remoteUrl ? githubRepo(remoteUrl) : undefined;
|
|
309
|
+
// Before any check, since a check on a head that must still take a merge is wasted.
|
|
310
|
+
await assertNoConflict(refs, shas, remote ?? "origin", ghRepo);
|
|
219
311
|
// git holds an ssh connection open, idle, while this hook runs; an https push holds none.
|
|
220
312
|
const host = remoteUrl ? sshHost(remoteUrl) : undefined;
|
|
221
313
|
if (shas.length && host) {
|
|
@@ -227,8 +319,6 @@ async function prePush(remote, remoteUrl) {
|
|
|
227
319
|
// Check every commit before posting any, so a refused push posts nothing.
|
|
228
320
|
for (const sha of shas)
|
|
229
321
|
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
322
|
const env = ghRepo ? { ...process.env, GH_REPO: ghRepo } : { ...process.env };
|
|
233
323
|
// git sends the push only once this hook exits, so the poster waits on git before GitHub.
|
|
234
324
|
const gitPid = nearestGit(processTable(), process.pid);
|
package/dist/push.d.ts
CHANGED
|
@@ -16,6 +16,17 @@ export declare const SLOW_HOOK_MS = 30000;
|
|
|
16
16
|
export declare function slowHookWarning(elapsedMs: number, remote: string, refs: PushedRef[]): string | undefined;
|
|
17
17
|
/** The distinct commits pushed to branches. Deletes and tags are skipped. */
|
|
18
18
|
export declare function shasToCheck(refs: PushedRef[]): string[];
|
|
19
|
+
/** The distinct commits pushed to branches other than `defaultBranch`, the only ones that can conflict with it. */
|
|
20
|
+
export declare function shasToProbe(refs: PushedRef[], defaultBranch: string): string[];
|
|
21
|
+
/** The conflicted paths in `git merge-tree --write-tree --name-only --no-messages` output: every line after the tree. */
|
|
22
|
+
export declare function conflictedFiles(output: string): string[];
|
|
23
|
+
/** The env var that lets a push through though its head conflicts with the default branch. */
|
|
24
|
+
export declare const ALLOW_CONFLICT = "LOCAL_CI_ALLOW_CONFLICT";
|
|
25
|
+
/** The refusal for pushed commits that conflict with `<remote>/<branch>`, naming the files, the fix and the override. */
|
|
26
|
+
export declare function conflictMessage(remote: string, branch: string, conflicts: {
|
|
27
|
+
files: string[];
|
|
28
|
+
sha: string;
|
|
29
|
+
}[]): string;
|
|
19
30
|
/**
|
|
20
31
|
* Why `sha` can't be checked in place, or null when it can: it must be HEAD, with a clean
|
|
21
32
|
* working tree, so the result reflects the commit rather than uncommitted files.
|
package/dist/push.js
CHANGED
|
@@ -36,6 +36,27 @@ export function shasToCheck(refs) {
|
|
|
36
36
|
.map((ref) => ref.localSha);
|
|
37
37
|
return [...new Set(shas)];
|
|
38
38
|
}
|
|
39
|
+
/** The distinct commits pushed to branches other than `defaultBranch`, the only ones that can conflict with it. */
|
|
40
|
+
export function shasToProbe(refs, defaultBranch) {
|
|
41
|
+
return shasToCheck(refs.filter((ref) => ref.remoteRef !== `refs/heads/${defaultBranch}`));
|
|
42
|
+
}
|
|
43
|
+
/** The conflicted paths in `git merge-tree --write-tree --name-only --no-messages` output: every line after the tree. */
|
|
44
|
+
export function conflictedFiles(output) {
|
|
45
|
+
return output.split("\n").slice(1).filter(Boolean);
|
|
46
|
+
}
|
|
47
|
+
/** The env var that lets a push through though its head conflicts with the default branch. */
|
|
48
|
+
export const ALLOW_CONFLICT = "LOCAL_CI_ALLOW_CONFLICT";
|
|
49
|
+
/** The refusal for pushed commits that conflict with `<remote>/<branch>`, naming the files, the fix and the override. */
|
|
50
|
+
export function conflictMessage(remote, branch, conflicts) {
|
|
51
|
+
const base = `${remote}/${branch}`;
|
|
52
|
+
return [
|
|
53
|
+
...conflicts.flatMap(({ sha, files }) => [
|
|
54
|
+
`${sha.slice(0, 7)} conflicts with ${base} in:`,
|
|
55
|
+
...files.map((file) => ` ${file}`),
|
|
56
|
+
]),
|
|
57
|
+
`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\`.`,
|
|
58
|
+
].join("\n");
|
|
59
|
+
}
|
|
39
60
|
/**
|
|
40
61
|
* Why `sha` can't be checked in place, or null when it can: it must be HEAD, with a clean
|
|
41
62
|
* working tree, so the result reflects the commit rather than uncommitted files.
|