@jonmilner/local-ci 0.6.1 → 0.8.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
@@ -10,16 +10,19 @@ pnpm add -D @jonmilner/local-ci
10
10
 
11
11
  Needs `gh` logged in with the `repo` scope (`gh auth login --scopes repo`, or `gh auth refresh --scopes repo`).
12
12
 
13
- Add the hook, for example as `.githooks/pre-push` with `git config core.hooksPath .githooks`:
13
+ Point `core.hooksPath` at the repo's hooks directory (Vite+ repos get `.vite-hooks/_` from `vp config` in `prepare`; elsewhere, for example, `git config core.hooksPath .githooks`), then write the hooks and commit them:
14
14
 
15
15
  ```sh
16
- #!/bin/sh
17
- exec pnpm exec local-ci pre-push "$@"
16
+ pnpm exec local-ci hooks install
18
17
  ```
19
18
 
19
+ That writes `pre-push` and `commit-msg` shims, each one line that calls local-ci, so every repo runs the same checks and none hand-writes its hooks. `local-ci pre-push` refuses a push when either is missing.
20
+
20
21
  ## Commands
21
22
 
22
- - `local-ci pre-push`: the hook. 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 lets the push go ahead.
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 lets the push go ahead.
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.
23
26
  - `local-ci post <sha>`: 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.
24
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.
25
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.
@@ -49,7 +52,7 @@ exec pnpm exec local-ci pre-push "$@"
49
52
  { "local-ci": { "command": "pnpm lint && pnpm test" } }
50
53
  ```
51
54
 
52
- A repo without a `package.json` sets `LOCAL_CI_COMMAND`, for example in the hook: `LOCAL_CI_COMMAND=./scripts/check.sh exec local-ci pre-push "$@"`.
55
+ 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 "$@"`.
53
56
 
54
57
  ## State
55
58
 
package/dist/cli.js CHANGED
@@ -2,11 +2,13 @@
2
2
  import { execFileSync, spawn } from "node:child_process";
3
3
  import { closeSync, openSync, readFileSync } from "node:fs";
4
4
  import { hostname } from "node:os";
5
- import { basename, dirname, resolve } from "node:path";
5
+ import { basename, dirname, join, relative, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import { appendLog, checkRunMessage, logLine, passedCommand, recordPass, releaseEnabled, resolveCommand, statePaths, } from "./config.js";
7
+ import { commitMsg } from "./commit-msg.js";
8
+ import { appendLog, checkRunMessage, logLine, passedCommand, recordPass, releaseEnabled, resolveCommand, shimCommand, statePaths, } from "./config.js";
8
9
  import { exec, run } from "./exec.js";
9
10
  import { assertGhAuth, checkStatus, postStatus, prTitleStatus, viewPr, waitForCommit, waitForOpenPr, } from "./github.js";
11
+ import { hooksDir, installHooks, missingHooks } from "./hooks.js";
10
12
  import { installRenovateAgent, renovateLog, rotateLog, uninstallRenovateAgent } from "./launchd.js";
11
13
  import { LockHeld, takeLock, waitForLock } from "./lock.js";
12
14
  import { cannotCheckInPlace, githubRepo, parsePrePush, shasToCheck } from "./push.js";
@@ -17,6 +19,9 @@ const USAGE = `Usage:
17
19
  local-ci pre-push run the check for each pushed commit (git pre-push hook)
18
20
  local-ci post <sha> wait for <sha> on GitHub, then post its check and pr-title statuses
19
21
  local-ci pr-title [<pr>] lint the PR title and post the pr-title status
22
+ local-ci commit-msg <file|->
23
+ lint a commit message file (git commit-msg hook) or stdin (-)
24
+ local-ci hooks install write the repo's pre-push and commit-msg hook shims
20
25
  local-ci status [<sha>] post check for <sha> (default HEAD), running the check if needed
21
26
  local-ci release version pending changesets through a PR, publish to npm and push tags
22
27
  local-ci renovate check each open Renovate PR in your repos and post check and pr-title
@@ -194,9 +199,36 @@ async function runLocked({ root, passed, log: logFile }, sha) {
194
199
  throw new CheckFailed(command, sha);
195
200
  recordPass(passed, sha, command);
196
201
  }
202
+ /** The repo root, its hooks directory, and the command its hook shims run local-ci with. */
203
+ async function hooksTarget(root) {
204
+ // `git config --get` exits 1 when the key is unset.
205
+ const hooksPath = await git("config", "--type=path", "--get", "core.hooksPath").catch(() => "");
206
+ // A linked worktree's main checkout is the directory holding the common `.git` dir.
207
+ const common = resolve(root, await git("rev-parse", "--git-common-dir"));
208
+ const mainRoot = basename(common) === ".git" ? dirname(common) : root;
209
+ return { dir: hooksDir(root, hooksPath || undefined, mainRoot), command: shimCommand(root) };
210
+ }
211
+ /** Throws, naming the fix, unless both hook files run local-ci, so no repo's hooks drift. */
212
+ async function assertHooks(root) {
213
+ const { dir, command } = await hooksTarget(root);
214
+ const missing = missingHooks(dir, command).map((hook) => relative(root, join(dir, hook)));
215
+ if (missing.length) {
216
+ throw new Error(`hooks out of date: ${missing.join(" and ")} must run local-ci; run \`${command} hooks install\` and commit the result`);
217
+ }
218
+ }
219
+ async function runHooks([subcommand, ...extra]) {
220
+ if (subcommand !== "install" || extra.length) {
221
+ throw new Error(`hooks: expected install\n${USAGE}`);
222
+ }
223
+ const { root } = await repo();
224
+ const { dir, command } = await hooksTarget(root);
225
+ const changes = installHooks(root, dir, command);
226
+ out(changes.length ? changes.join("\n") : "hooks up to date");
227
+ }
197
228
  async function prePush(remoteUrl) {
198
- await assertGhAuth(exec);
199
229
  const current = await repo();
230
+ await assertHooks(current.root);
231
+ await assertGhAuth(exec);
200
232
  const shas = shasToCheck(parsePrePush(readFileSync(0, "utf8")));
201
233
  // Check every commit before posting any, so a refused push posts nothing.
202
234
  for (const sha of shas)
@@ -293,6 +325,21 @@ async function runRenovate([flag, ...extra]) {
293
325
  async function main([command, ...args]) {
294
326
  if (command === "pre-push")
295
327
  return prePush(args[1]);
328
+ if (command === "commit-msg") {
329
+ if (!args[0] || args.length > 1) {
330
+ err(USAGE);
331
+ process.exitCode = 2;
332
+ return;
333
+ }
334
+ const { lines, ok } = await commitMsg(args[0]);
335
+ for (const line of lines)
336
+ err(line);
337
+ if (!ok)
338
+ process.exitCode = 1;
339
+ return;
340
+ }
341
+ if (command === "hooks")
342
+ return runHooks(args);
296
343
  if (command === "release")
297
344
  return runRelease();
298
345
  if (command === "renovate")
@@ -0,0 +1,10 @@
1
+ /** Drops what git strips from a commit message: `#` comment lines, and everything after a scissors line. */
2
+ export declare function stripComments(message: string): string;
3
+ /**
4
+ * Lints the commit message in `source` (a file path, or `-` for stdin). Returns the lines for
5
+ * stderr and whether it passed; warnings alone still pass.
6
+ */
7
+ export declare function commitMsg(source: string): Promise<{
8
+ lines: string[];
9
+ ok: boolean;
10
+ }>;
@@ -0,0 +1,25 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { lintMessage } from "./title.js";
3
+ const SCISSORS = /^# -+ >8 -+$/;
4
+ /** Drops what git strips from a commit message: `#` comment lines, and everything after a scissors line. */
5
+ export function stripComments(message) {
6
+ const lines = message.split(/\r?\n/);
7
+ const end = lines.findIndex((line) => SCISSORS.test(line));
8
+ return (end === -1 ? lines : lines.slice(0, end))
9
+ .filter((line) => !line.startsWith("#"))
10
+ .join("\n")
11
+ .trim();
12
+ }
13
+ /**
14
+ * Lints the commit message in `source` (a file path, or `-` for stdin). Returns the lines for
15
+ * stderr and whether it passed; warnings alone still pass.
16
+ */
17
+ export async function commitMsg(source) {
18
+ const raw = readFileSync(source === "-" ? 0 : source, "utf8");
19
+ const message = stripComments(raw);
20
+ const { errors, warnings } = await lintMessage(message);
21
+ const lines = [...errors, ...warnings].map(({ message, rule }) => `commit-msg: ${message} [${rule}]`);
22
+ if (errors.length)
23
+ lines.push(`commit-msg: in "${message.split("\n")[0]}"`);
24
+ return { lines, ok: errors.length === 0 };
25
+ }
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 command hook shims run local-ci with: `local-ci.exec` in package.json, else
6
+ * `pnpm exec local-ci` in a repo with a package.json, else a global `local-ci`.
7
+ */
8
+ export declare function shimCommand(root: string): string;
4
9
  /** Whether `local-ci release` is switched on, with `"local-ci": { "release": true }` in package.json. */
5
10
  export declare function releaseEnabled(root: string): boolean;
6
11
  export declare function stateDir(env?: NodeJS.ProcessEnv): string;
package/dist/config.js CHANGED
@@ -17,6 +17,16 @@ 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 command hook shims run local-ci with: `local-ci.exec` in package.json, else
22
+ * `pnpm exec local-ci` in a repo with a package.json, else a global `local-ci`.
23
+ */
24
+ export function shimCommand(root) {
25
+ if (!existsSync(join(root, "package.json")))
26
+ return "local-ci";
27
+ const { exec } = localCiConfig(root);
28
+ return typeof exec === "string" && exec.trim() ? exec.trim() : "pnpm exec local-ci";
29
+ }
20
30
  /** Whether `local-ci release` is switched on, with `"local-ci": { "release": true }` in package.json. */
21
31
  export function releaseEnabled(root) {
22
32
  return localCiConfig(root).release === true;
@@ -0,0 +1,29 @@
1
+ /** The git hooks local-ci owns, each with the arguments its shim passes on. */
2
+ declare const HOOKS: {
3
+ readonly "pre-push": "\"$@\"";
4
+ readonly "commit-msg": "\"$1\"";
5
+ };
6
+ export type Hook = keyof typeof HOOKS;
7
+ /**
8
+ * The directory holding the repo's hook files: `core.hooksPath` resolved against the repo root,
9
+ * with a Vite+ (or husky) `<dir>/_` dispatcher mapped to `<dir>`, which holds the hooks it runs.
10
+ * An absolute path into the main checkout (`mainRoot`) maps onto `root`, so a linked worktree
11
+ * finds its own copy of the tracked hooks.
12
+ */
13
+ export declare function hooksDir(root: string, hooksPath: string | undefined, mainRoot?: string): string;
14
+ /** The line a shim adds to run local-ci's `hook` with `command`, e.g. `pnpm exec local-ci pre-push "$@"`. */
15
+ export declare function shimLine(hook: Hook, command: string): string;
16
+ /**
17
+ * Whether `content` has a line, other than a comment, that runs `local-ci <hook>` or
18
+ * `<command> <hook>`. Anything may come before it on the line, such as `LOCAL_CI_COMMAND=… `.
19
+ */
20
+ export declare function runsHook(content: string, hook: Hook, command: string): boolean;
21
+ /** The hooks in `dir` whose file is missing or has no line running local-ci for it. */
22
+ export declare function missingHooks(dir: string, command: string): Hook[];
23
+ /**
24
+ * Writes an executable `#!/bin/sh` shim for each hook into `dir`, or adds its line to the end of an
25
+ * existing shell script, keeping every other line. Throws for an existing hook in another language.
26
+ * Returns what changed, with paths relative to `root`; none when every hook was already in place.
27
+ */
28
+ export declare function installHooks(root: string, dir: string, command: string): string[];
29
+ export {};
package/dist/hooks.js ADDED
@@ -0,0 +1,92 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ /** The git hooks local-ci owns, each with the arguments its shim passes on. */
4
+ const HOOKS = { "pre-push": '"$@"', "commit-msg": '"$1"' };
5
+ const HOOK_NAMES = Object.keys(HOOKS);
6
+ /**
7
+ * The directory holding the repo's hook files: `core.hooksPath` resolved against the repo root,
8
+ * with a Vite+ (or husky) `<dir>/_` dispatcher mapped to `<dir>`, which holds the hooks it runs.
9
+ * An absolute path into the main checkout (`mainRoot`) maps onto `root`, so a linked worktree
10
+ * finds its own copy of the tracked hooks.
11
+ */
12
+ export function hooksDir(root, hooksPath, mainRoot = root) {
13
+ if (!hooksPath) {
14
+ throw new Error("core.hooksPath is not set; point it at the repo's hooks directory (`vp config` does in a Vite+ repo, or `git config core.hooksPath .githooks`), then run local-ci hooks install");
15
+ }
16
+ let resolved = resolve(root, hooksPath);
17
+ if (isAbsolute(hooksPath) && !within(root, resolved) && within(mainRoot, resolved)) {
18
+ resolved = join(root, relative(mainRoot, resolved));
19
+ }
20
+ const dir = basename(resolved) === "_" ? dirname(resolved) : resolved;
21
+ const inside = relative(root, dir);
22
+ if (!within(root, dir) || inside === ".git" || inside.startsWith(`.git${sep}`)) {
23
+ throw new Error(`core.hooksPath ${hooksPath} is outside the repo's tracked files; local-ci's hooks must be committed, so point it at a directory in the repo`);
24
+ }
25
+ return dir;
26
+ }
27
+ /** Whether `path` is strictly inside `dir`. */
28
+ function within(dir, path) {
29
+ const inside = relative(dir, path);
30
+ return Boolean(inside) && !inside.startsWith("..") && !isAbsolute(inside);
31
+ }
32
+ /** The line a shim adds to run local-ci's `hook` with `command`, e.g. `pnpm exec local-ci pre-push "$@"`. */
33
+ export function shimLine(hook, command) {
34
+ return `${command} ${hook} ${HOOKS[hook]}`;
35
+ }
36
+ /** A shebang for a shell that can run the shim line. */
37
+ const SHELL = /^#!.*\b(?:sh|bash|dash|zsh|ksh)\b/;
38
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
39
+ /**
40
+ * Whether `content` has a line, other than a comment, that runs `local-ci <hook>` or
41
+ * `<command> <hook>`. Anything may come before it on the line, such as `LOCAL_CI_COMMAND=… `.
42
+ */
43
+ export function runsHook(content, hook, command) {
44
+ const runner = [...new Set(["local-ci", command])].map(escape).join("|");
45
+ const pattern = new RegExp(`(?:^|[\\s/])(?:${runner})\\s+${hook}(?:\\s|$)`);
46
+ return content
47
+ .split("\n")
48
+ .some((line) => !line.trimStart().startsWith("#") && pattern.test(line));
49
+ }
50
+ /** The hooks in `dir` whose file is missing or has no line running local-ci for it. */
51
+ export function missingHooks(dir, command) {
52
+ return HOOK_NAMES.filter((hook) => {
53
+ const file = join(dir, hook);
54
+ return !existsSync(file) || !runsHook(readFileSync(file, "utf8"), hook, command);
55
+ });
56
+ }
57
+ /**
58
+ * Writes an executable `#!/bin/sh` shim for each hook into `dir`, or adds its line to the end of an
59
+ * existing shell script, keeping every other line. Throws for an existing hook in another language.
60
+ * Returns what changed, with paths relative to `root`; none when every hook was already in place.
61
+ */
62
+ export function installHooks(root, dir, command) {
63
+ mkdirSync(dir, { recursive: true });
64
+ const changes = [];
65
+ for (const hook of HOOK_NAMES) {
66
+ const file = join(dir, hook);
67
+ const shown = relative(root, file);
68
+ const before = existsSync(file) ? readFileSync(file, "utf8") : "";
69
+ if (before.startsWith("#!") && !SHELL.test(before)) {
70
+ throw new Error(`${shown} is not a shell script; add \`${shimLine(hook, command)}\` to it by hand`);
71
+ }
72
+ let after = before;
73
+ if (!runsHook(after, hook, command)) {
74
+ const separator = after && !after.endsWith("\n") ? "\n" : "";
75
+ after = `${after}${separator}${shimLine(hook, command)}\n`;
76
+ }
77
+ // Git runs a hook file directly unless a dispatcher like Vite+'s runs it with sh.
78
+ if (!after.startsWith("#!"))
79
+ after = `#!/bin/sh\n${after}`;
80
+ if (after !== before)
81
+ writeFileSync(file, after);
82
+ const { mode } = statSync(file);
83
+ const executable = (mode & 0o100) !== 0;
84
+ if (!executable)
85
+ chmodSync(file, mode | 0o755);
86
+ if (after !== before)
87
+ changes.push(before ? `updated ${shown}` : `wrote ${shown}`);
88
+ else if (!executable)
89
+ changes.push(`made ${shown} executable`);
90
+ }
91
+ return changes;
92
+ }
package/dist/title.d.ts CHANGED
@@ -1,2 +1,11 @@
1
+ export interface Problem {
2
+ message: string;
3
+ rule: string;
4
+ }
5
+ /** Lints a message with @jonmilner/commitlint-config, keeping commitlint's default ignores (merges, fixup!, reverts). */
6
+ export declare function lintMessage(message: string): Promise<{
7
+ errors: Problem[];
8
+ warnings: Problem[];
9
+ }>;
1
10
  /** Lints a PR title with @jonmilner/commitlint-config and returns its error messages. */
2
11
  export declare function lintTitle(title: string): Promise<string[]>;
package/dist/title.js CHANGED
@@ -1,12 +1,25 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  import lint from "@commitlint/lint";
3
3
  import load from "@commitlint/load";
4
- /** Lints a PR title with @jonmilner/commitlint-config and returns its error messages. */
5
- export async function lintTitle(title) {
4
+ /** Lints a message with @jonmilner/commitlint-config, keeping commitlint's default ignores (merges, fixup!, reverts). */
5
+ export async function lintMessage(message) {
6
6
  // Load this package's own config file, so it resolves the same in any repo being checked.
7
7
  const cwd = fileURLToPath(new URL("..", import.meta.url));
8
8
  const config = await load({}, { cwd, file: "commitlint.config.js" });
9
9
  const parserOpts = config.parserPreset?.parserOpts;
10
- const result = await lint(title, config.rules, parserOpts ? { parserOpts } : {});
11
- return result.errors.map((error) => `${error.message} [${error.name}]`);
10
+ const result = await lint(message, config.rules, {
11
+ ...(parserOpts ? { parserOpts } : {}),
12
+ defaultIgnores: config.defaultIgnores,
13
+ ignores: config.ignores,
14
+ });
15
+ const problem = ({ message, name }) => ({
16
+ message,
17
+ rule: name,
18
+ });
19
+ return { errors: result.errors.map(problem), warnings: result.warnings.map(problem) };
20
+ }
21
+ /** Lints a PR title with @jonmilner/commitlint-config and returns its error messages. */
22
+ export async function lintTitle(title) {
23
+ const { errors } = await lintMessage(title);
24
+ return errors.map((error) => `${error.message} [${error.rule}]`);
12
25
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jonmilner/local-ci",
3
- "version": "0.6.1",
3
+ "version": "0.8.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": {