diff --git a/README.md b/README.md index c39708c..2a3f718 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Requires Node.js >= 22 and git >= 2.41.0. The Node floor is the `engines` field in `package.json`, and it tracks active LTS: 22 is the oldest line still supported upstream, and CI runs both LTS lines plus Current. Raising it means moving `engines` and the CI matrix together. -The git floor tracks the newest git feature the code calls rather than a support policy. Today that feature is the `%(ahead-behind:)` format atom, which carries the per-branch behind count (`READY-01`) and which git gained in 2.41.0; next below it are `git merge-tree --write-tree` (2.38.0), which is how the merge itself is built (`MERGE-08`), and `git branch -r --format=` (2.13.0) for the batched branch listing (`PERF-01`). Dropping the newest of the three would move the floor to 2.38.0, not back to 2.13.0. Reaching for a newer git feature means raising the floor in `PRE-02`, `src/git.ts`, and `scripts/postinstall.mjs` together, and naming the feature that moved it so the next person doesn't have to re-derive the number. The postinstall refuses the install below the floor (`PRE-06`) and cannot import the number from the build, so a test pins the two against each other. +The git floor tracks the newest git feature the code calls rather than a support policy. Today that feature is the `%(ahead-behind:)` format atom, which carries the per-branch behind count (`READY-01`) and which git gained in 2.41.0; next below it are `git merge-tree --write-tree` (2.38.0), which is how the merge itself is built (`MERGE-08`), and `git branch -r --format=` (2.13.0) for the batched branch listing (`PERF-01`). Dropping the newest of the three would move the floor to 2.38.0, not back to 2.13.0. Reaching for a newer git feature means raising the floor in `PRE-02` and in `engines.git` in `package.json` (which `src/git.ts` reads) together, and naming the feature that moved it so the next person doesn't have to re-derive the number. ```bash git clone https://github.com/gettyimages/git-fi.git @@ -64,7 +64,7 @@ justfile Task runner wrapping the npm scripts src/ TypeScript implementation test/ Integration suite (Node test runner) docs/ Docsify documentation site -scripts/ Build-time generators, the npm postinstall, the trial:on/off helper, the docs server +scripts/ Build-time generators, the trial:on/off helper, the docs server man/ Generated man page (git-fi.1) completions/ Generated bash + zsh completions (_git-fi, _git_fi, git-fi.bash) ``` @@ -73,7 +73,7 @@ The man page and shell completions are generated by `scripts/gen-docs.ts`, which Three completion files ship because `git fi` is dispatched by two different providers: `_git-fi` drives zsh's built-in `_git`; `git-fi.bash` (defining `_git_fi`, git-completion style) drives git's own completion wrapper in bash; and `_git_fi` is the same `_git_fi` body on the zsh fpath, for git's wrapper under zsh. The git-native body (`git-fi.bash.tmpl`) is shared by the last two, so they can't drift. Each file has an `install-completions` target that prints it — `bash`, `zsh`, `zsh-git` respectively — and `--write ` installs the zsh pair onto an fpath directory (`COMPLETE-06`); adding a file here means adding its target in `src/install-completions.ts`. -A global `npm install` copies the zsh pair into `/share/zsh/site-functions` from `scripts/postinstall.mjs` (`COMPLETE-07`), so completion works with no extra step on the setups that carry that directory on their `fpath`. It's plain `.mjs` and lists the two filenames itself because npm runs `postinstall` before `prepare`, so `dist/` doesn't exist yet on a fresh clone; a test pins its file list to what `--write` installs. That copy exits 0 on any failure and does nothing for a local install. The git floor check ahead of it (`PRE-06`) is the one thing in the file that does fail an install, which is the point: a non-zero postinstall stops the install outright, so a git below the floor never gets a git-fi that cannot run on it. +The published package runs nothing at install time. Install scripts are a common supply-chain attack path, and many users and registries audit or block them, so completion is a command the user runs (`COMPLETE-06`, surfaced in `git fi -h` and the quickstart) and the git floor is checked when git-fi runs (`PRE-02`). ## Contributing diff --git a/SPEC.md b/SPEC.md index 703d867..567298e 100644 --- a/SPEC.md +++ b/SPEC.md @@ -25,7 +25,6 @@ Before any command executes, git-fi runs the following pre-flight checks: 3. `PRE-03` If `git config push.default` is `upstream` or `tracking`, then git-fi shall abort with: `Your default git push config is set to a hazardous option.` 4. `PRE-04` git-fi shall run `git fetch --quiet --prune --no-tags origin` once per invocation, memoizing to avoid redundant fetches. `--no-tags` because git-fi reads branches and never a tag, so asking for the tag refspec buys nothing it uses. What that saves is server-dependent and can be large: on one GitLab project, paired runs measured 12–15 s with tags against 1–2 s without, repeatably and while transferring no tags at all (the local and remote tag sets were identical); on another project of similar size and tag count on the same host, both forms took about a second. Tag count, missing tags, annotated-vs-lightweight, and repo size were each ruled out as the difference, so the cost is something server-side that git-fi can only decline to pay, not predict. A consequence worth knowing: `git fi` no longer refreshes tags as a side effect, so a stale tag is `git fetch`'s job rather than this one's. 5. `PRE-05` Where `GIT_FI_NO_FETCH` is set, git-fi shall skip the fetch (`PRE-04`) on read-only operations (`list`) and operate on the already-fetched remote-tracking refs. Shell completion sets this so tab-completion stays offline. Mutating operations always fetch regardless, so an integration merge never builds on stale refs. (All environment variables are catalogued in [Environment Variables](#environment-variables).) -6. `PRE-06` Installing git-fi shall check the git version before installing anything, and shall fail the install when git is absent, unreadable, or below the floor (`PRE-02`), naming the version found and giving the reader both ways forward: upgrade git, or install the last release built against the older floor. npm reads a non-zero postinstall as a failed install, so a git-fi that cannot run on the git present never lands; the floor is the one condition worth failing an install over, and the completion install (`COMPLETE-07`) stays soft. This does not replace `PRE-02`: `npm install --ignore-scripts` skips the check entirely, and git can be downgraded after a successful install, so the run-time check is the one that governs a run. ```mermaid %%{ init: { 'look': 'handDrawn' } }%% @@ -89,7 +88,7 @@ Shell Completion `COMPLETE-06` `install-completions --write ` shall write the zsh completion files into ``, creating it if absent, and shall name each path written. With no target it shall write both zsh files, so one command covers whichever provider (`COMPLETE-02`) the user's git install dispatches to; with `zsh` or `zsh-git` it shall write that one file, and with `bash` it shall abort — bash completion is sourced from an rc file and has no fpath to land on. It shall report reloading completions as a step for the user to run. git-fi shall not edit the user's rc files or write to any directory the user did not name; when `` cannot be created or written, it shall abort naming the path and how to install into a directory the user owns. -`COMPLETE-07` Installing git-fi globally shall install the zsh completion files, so `git fi ` works without a further step. They shall go under npm's own prefix (`/share/zsh/site-functions`, the directory Homebrew and `/usr/local` zsh setups carry on their fpath, and the prefix npm already links the man page into); git-fi shall write nothing outside that prefix and shall not edit the user's rc files. A local (non-global) install shall install nothing. A prefix that cannot be resolved or written shall not fail the install: git-fi shall report the `COMPLETE-06` command that finishes the job and exit 0. +`COMPLETE-08` The usage summary (`HELP-01`) and the man page (`HELP-02`) shall show, for each supported shell, the one command that sets up completion. The package runs nothing at install time, so completion is a step the user takes, and the help is where they look for it. ## `TERM` @@ -789,7 +788,7 @@ Build Provenance A developer can put an unpublished checkout on PATH under the same `git fi` name the published install uses. These requirements keep the two tellable apart, so a bug report names the build it came from, and govern what ending that trial hands back. -- `BUILD-01` git-fi shall treat itself as a dev build when a `.git` entry exists at its own package root. A published tarball carries none — npm's `files` list ships `dist`, `man`, `completions`, and the postinstall script — so the marker separates a linked checkout from an installed copy. It shall be read at the package root rather than the working directory, which is a git repository on every ordinary run. +- `BUILD-01` git-fi shall treat itself as a dev build when a `.git` entry exists at its own package root. A published tarball carries none — npm's `files` list ships `dist`, `man`, and `completions` — so the marker separates a linked checkout from an installed copy. It shall be read at the package root rather than the working directory, which is a git repository on every ordinary run. - `BUILD-02` On a dev build, `--version` (`OPTION-05`) shall report the released version followed by `-dev.g`, naming the commit the build came from, and shall append `.dirty` when the checkout's tree differs from that commit. The `g` prefix is what keeps the identifier valid semver: a sha of all digits would otherwise read as a numeric identifier, which may not carry leading zeros. When no commit can be read, git-fi shall report `-dev` alone rather than dropping the marker. - `BUILD-03` Ending a trial shall restore the exact published version the trial displaced. `npm link` overwrites the global install, so the version is read before the link and kept under `.trial/`; `trial:off` then installs that version rather than whatever is newest, because a trial borrows an install and should hand back the one it borrowed. Where no published version was recorded — the package was absent, or already linked to a checkout — the trial shall say which of the two it found and install the latest, rather than leave the developer with no `git fi` at all. Where a version was recorded, the trial shall install that version or fail saying so; a recorded version that no longer resolves is not grounds for substituting another. A recorded value that is not a bare version shall be refused rather than passed to the installer, which reads the wider `name@spec` grammar. - `BUILD-04` Ending a trial shall remove only the rc-file block it wrote, delimited by its own markers, and shall report any remaining line naming the trial's completion directory by its literal path rather than editing it away. That directory is deleted as the trial ends, so a hand-copied `fpath` entry naming it would otherwise be left pointing at nothing, and a line the developer wrote is not the script's to remove. A reference spelled through `~` or a variable is not detected. diff --git a/STATUS.md b/STATUS.md index 1c5700c..7bd5495 100644 --- a/STATUS.md +++ b/STATUS.md @@ -2,7 +2,7 @@ Tracks implementation status of each requirement in [SPEC.md](/SPEC.md). -**Last updated:** 2026-09-23 +**Last updated:** 2026-10-22 Locations name the file and the enclosing symbol rather than a line range, so an edit elsewhere in the same file leaves the row correct. `git grep` the symbol to @@ -12,8 +12,8 @@ land on it. | Status | Count | |---------|-------| -| Covered | 137 | -| Total | 137 | +| Covered | 138 | +| Total | 138 | ## `PRE` @@ -26,7 +26,6 @@ Pre-flight Checks | PRE-03 | Push config | Covered | `src/git.ts` (`preflightChecks`)| | PRE-04 | Fetch | Covered | `src/git.ts` (`ensureFetched`) | | PRE-05 | `GIT_FI_NO_FETCH` skips fetch | Covered | `src/git.ts` (`ensureFetched`) | -| PRE-06 | Install-time git floor | Covered | `scripts/postinstall.mjs` (`refuse`) | ## `OPTION` @@ -69,7 +68,7 @@ Shell Completion | COMPLETE-04 | Offline membership | Covered | `scripts/completion/git-fi.bash.tmpl` (`GIT_FI_NO_FETCH`), `src/git.ts` (`ensureFetched`) | | COMPLETE-05 | `install-completions` subcommand | Covered | `src/install-completions.ts` (`scriptFor`, `installCompletions`), `src/index.ts` (`parseArgs`) | | COMPLETE-06 | `--write ` onto the fpath | Covered | `src/install-completions.ts` (`writeToFpath`) | -| COMPLETE-07 | Completion installed on `npm i -g` | Covered | `scripts/postinstall.mjs`, `package.json` (`postinstall`, `files`) | +| COMPLETE-08 | Completion setup shown in help | Covered | `src/help.ts` (`COMPLETION_SETUP`, `renderHelp`), `scripts/gen-docs.ts` | ## `TERM` diff --git a/docs/quickstart.md b/docs/quickstart.md index c341974..ed09cd3 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -8,6 +8,14 @@ git-fi is a git subcommand: once the `git-fi` binary is on your `PATH`, invoke i npm install -g @gettyimages/git-fi ``` +Then turn on tab completion, so `git fi --add ` offers your branches. In zsh: + +```zsh +git fi install-completions --write "${fpath[1]}" +``` + +In bash, add `source <(git fi install-completions bash)` to `~/.bashrc`. [Shell completion](#shell-completion) has the details. + To try it without installing, run `npx @gettyimages/git-fi --help` (this runs as `npx @gettyimages/git-fi`, not `git fi`). On older git, or upgrading from the Ruby gem? See [Troubleshooting](/troubleshooting). @@ -94,7 +102,13 @@ git fi --help # opens the man page ### Shell completion -In zsh, `npm install -g` sets this up for you — open a new shell and press ``: +In zsh, write both completion files onto your `fpath`. The command creates the directory if needed and names each file it wrote: + +```zsh +git fi install-completions --write "${fpath[1]}" +``` + +Open a new shell and press ``: ```zsh git fi # actions, options, subcommands @@ -102,6 +116,8 @@ git fi --add # origin branches not yet in fi git fi --remove # only branches currently in fi ``` +If `${fpath[1]}` isn't writable (a root-owned `/usr/local`, say), the command stops and shows how to install into a directory you own instead. Run it again after `git fi --update` so completion picks up new flags. + For bash, add one line to `~/.bashrc` (git's bash completion has to be loaded first): ```bash diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index bd5be80..0399c2d 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2,7 +2,7 @@ ## Your git is older than 2.41.0 -The install checks git first and stops if it is older than 2.41.0, naming the version it found. Where the git you have is the one your platform gives you (a long-support distribution, Apple's command line tools), install the last release that runs on git 2.13 and newer: +Every `git fi` command checks git first and stops if it is older than 2.41.0, naming the version it found. Where the git you have is the one your platform gives you (a long-support distribution, Apple's command line tools), install the last release that runs on git 2.13 and newer: ```bash npm install -g @gettyimages/git-fi@1.2.2 @@ -55,7 +55,7 @@ npm install -g @gettyimages/git-fi ## Tab completion offers filenames -`npm install -g` writes the zsh completion files into npm's own prefix (`$(npm config get prefix)/share/zsh/site-functions`), the directory Homebrew and `/usr/local` zsh setups already read. If `git fi ` offers filenames instead, that directory isn't on your `fpath`. Install into one that is; this creates it if needed and tells you what it wrote: +git-fi's completion isn't loaded. Install it into a directory on your `fpath`; this creates the directory if needed and tells you what it wrote: ```zsh git fi install-completions --write "${fpath[1]}" diff --git a/man/git-fi.1 b/man/git-fi.1 index d9bb118..be87e3c 100644 --- a/man/git-fi.1 +++ b/man/git-fi.1 @@ -69,5 +69,12 @@ Print the shell completion script (zsh\-git: for git's own zsh wrapper) .TP .B install\-completions \-\-write Write both zsh completion files onto an fpath directory +.SH SHELL COMPLETION +.TP +.B zsh +git fi install\-completions \-\-write "${fpath[1]}" +.TP +.B bash +add to ~/.bashrc: source <(git fi install\-completions bash) .SH SEE ALSO Full documentation: https://gettyimages.github.io/git\-fi/ diff --git a/package.json b/package.json index 6190e6f..8ed50df 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,6 @@ "gen:docs": "node --import tsx scripts/gen-docs.ts", "build": "tsc && npm run gen:docs", "prepare": "tsc", - "postinstall": "node scripts/postinstall.mjs", "test": "tsc && npm run verify:generated && node scripts/run-tests.mjs", "verify:generated": "node --import tsx scripts/gen-docs.ts --check", "prepublishOnly": "npm test", @@ -23,8 +22,7 @@ "files": [ "dist", "man", - "completions", - "scripts/postinstall.mjs" + "completions" ], "publishConfig": { "access": "public" diff --git a/scripts/gen-docs.ts b/scripts/gen-docs.ts index e35ca6f..55e4383 100644 --- a/scripts/gen-docs.ts +++ b/scripts/gen-docs.ts @@ -10,7 +10,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; -import { ACTIONS, OPTIONS, SUBCOMMANDS, TAGLINE, DOCS_URL, longForm, type Flag } from "../src/help.js"; +import { ACTIONS, OPTIONS, SUBCOMMANDS, COMPLETION_SETUP, TAGLINE, DOCS_URL, longForm, type Flag } from "../src/help.js"; const here = dirname(fileURLToPath(import.meta.url)); const root = join(here, ".."); @@ -58,6 +58,8 @@ const man = OPTIONS.map(manEntry).join("\n") + "\n" + `.SH COMMANDS\n` + SUBCOMMANDS.map((c) => `.TP\n.B ${roff(c.usage)}\n${roff(c.desc)}`).join("\n") + "\n" + + `.SH SHELL COMPLETION\n` + + COMPLETION_SETUP.map((c) => `.TP\n.B ${c.shell}\n${roff(c.how)}`).join("\n") + "\n" + `.SH SEE ALSO\n` + `Full documentation: ${roff(DOCS_URL)}\n`; diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjs deleted file mode 100644 index 4c477cb..0000000 --- a/scripts/postinstall.mjs +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env node -// Two jobs with opposite failure policies. -// -// First, the git floor (PRE-06): a hard failure, because npm reads a non-zero -// postinstall as a failed install, so the package never lands. Refusing here is -// what turns "you updated and every command now aborts" into "the update -// declined to land, and told you why". -// -// Second, the zsh completion files (COMPLETE-07), so tab completion works out of -// the box instead of being a step the user has to find. That half stays soft: a -// prefix we cannot write to (a root-owned /usr/local, a distro package) prints -// the one command that finishes the job and exits 0. -// -// The destination is npm's own global prefix — /share/zsh/site-functions -// — which is the directory Homebrew and /usr/local zsh setups already have on -// their fpath, and the same prefix npm links the man page into. Nothing outside -// the prefix is touched: no rc files, no dotfiles, no guessing at the user's -// fpath. -// -// Plain .mjs rather than part of the TypeScript build: npm runs postinstall -// before prepare, so on a fresh clone dist/ does not exist yet and a compiled -// entry point would fail the install. -import { spawnSync } from "node:child_process"; -import { createRequire } from "node:module"; -import { copyFileSync, mkdirSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { fileURLToPath } from "node:url"; - -// The floor is package.json's `engines.git`, which preflightChecks in -// src/git.ts reads too — npm records the field but enforces only `node`, so -// both of git-fi's entry points do the enforcing. Read from package.json rather -// than imported from the compiled source because this file runs before the -// build. A test pins the range's shape and the comparison below. -const MIN_GIT = createRequire(import.meta.url)("../package.json") - .engines.git.replace(/^>=/, ""); -const ordinal = (v) => v.split(".").reduce((n, part) => n * 100 + Number(part), 0); - -// `npm install --ignore-scripts` skips this file entirely, and git can be -// downgraded after the fact, so preflightChecks re-checks at run time (PRE-02). -// This one exists to stop the bad install, not to replace that check. -function refuse(reason, advice) { - process.stderr.write(`git-fi requires git ${MIN_GIT} or newer, and ${reason}.\n\n${advice}`); - process.exit(1); -} - -// Pinning is the escape hatch for someone whose git is fixed by their platform: -// a long-support distribution, Apple's command line tools. 1.2.2 is the last -// release built against the older floor, so the version is a fact about history -// rather than a number that drifts. -const TOO_OLD = - ` Upgrade git, then install git-fi again.\n` + - ` To stay on the git you have, install the last release that supports it:\n` + - ` npm install -g @gettyimages/git-fi@1.2.2\n`; -const NO_GIT = ` Install git ${MIN_GIT} or newer, then install git-fi again.\n`; - -const probe = spawnSync("git", ["--version"], { encoding: "utf-8" }); -if (probe.error || probe.status !== 0) refuse("no working git was found on PATH", NO_GIT); - -const found = (probe.stdout || "").match(/\d+\.\d+\.\d+/); -if (!found) { - refuse( - `could not read a version from \`git --version\` (${(probe.stdout || "").trim()})`, - NO_GIT - ); -} - -if (ordinal(found[0]) < ordinal(MIN_GIT)) { - refuse(`this system has git ${found[0]}`, TOO_OLD); -} - -// The zsh pair from completions/: one file per provider that dispatches -// `git fi` (COMPLETE-02). Kept in step with install-completions' own targets by a -// test, since the names live in both places. -const FILES = ["_git-fi", "_git_fi"]; - -const root = join(dirname(fileURLToPath(import.meta.url)), ".."); - -// Local installs (working on git-fi itself) get nothing: the trial helper owns -// that, and a dev checkout shouldn't write into a shared prefix on npm install. -if (process.env.npm_config_global !== "true") process.exit(0); - -const prefix = process.env.npm_config_prefix || process.env.PREFIX; -if (!prefix) { - console.log( - `git-fi: could not resolve npm's prefix, so shell completion is not installed.\n` + - ` Install it with: git fi install-completions --write "\${fpath[1]}"` - ); - process.exit(0); -} - -const dest = join(prefix, "share", "zsh", "site-functions"); - -try { - mkdirSync(dest, { recursive: true }); - for (const file of FILES) { - copyFileSync(join(root, "completions", file), join(dest, file)); - } - console.log( - `git-fi: installed zsh completion in ${dest}\n` + - ` Open a new shell to use it. If it stays quiet, that directory is not on\n` + - ` your fpath — install into one that is:\n` + - ` git fi install-completions --write "\${fpath[1]}"` - ); -} catch (e) { - console.log( - `git-fi: could not write shell completion to ${dest} (${e.message}).\n` + - ` Install it yourself with: git fi install-completions --write "\${fpath[1]}"` - ); -} diff --git a/src/build-info.ts b/src/build-info.ts index c88ee8f..c8fdb42 100644 --- a/src/build-info.ts +++ b/src/build-info.ts @@ -9,8 +9,7 @@ const PKG_ROOT = fileURLToPath(new URL("..", import.meta.url)); /** * A checkout carries a `.git`; a published tarball never does, because npm's - * `files` list ships only `dist`, `man`, `completions`, and the postinstall - * script. That marker at the *package* root — not the user's cwd, which is + * `files` list ships only `dist`, `man`, and `completions`. That marker at the *package* root — not the user's cwd, which is * a git repo on every ordinary run — is what separates a `just trial-on` link * from an installed copy (BUILD-01), and it costs one stat. */ diff --git a/src/git.ts b/src/git.ts index 7291385..ec57fe6 100644 --- a/src/git.ts +++ b/src/git.ts @@ -104,11 +104,9 @@ export function gitExitCode(args: string[], gitOpts: GitOpts = {}): number { return gitOutcome(args, gitOpts).status; } -// The git floor lives in package.json's `engines.git` (PRE-02, PRE-06), which -// npm records but does not enforce — so this and scripts/postinstall.mjs both -// read it and do the enforcing. package.json rather than a shared module -// because npm runs the postinstall before the build, so there is no dist/ to -// import from; a test pins the range's shape and the comparison below. +// The git floor lives in package.json's `engines.git` (PRE-02), which npm +// records but does not enforce, so preflightChecks does. A test pins the +// range's shape to what the strip below expects. const MIN_GIT = createRequire(import.meta.url)("../package.json") .engines.git.replace(/^>=/, ""); diff --git a/src/help.ts b/src/help.ts index f7c56b0..0f208fb 100644 --- a/src/help.ts +++ b/src/help.ts @@ -78,6 +78,11 @@ export const SUBCOMMANDS: Subcommand[] = [ { usage: "install-completions --write ", desc: "Write both zsh completion files onto an fpath directory" }, ]; +export const COMPLETION_SETUP: { shell: string; how: string }[] = [ + { shell: "zsh", how: `git fi install-completions --write "\${fpath[1]}"` }, + { shell: "bash", how: "add to ~/.bashrc: source <(git fi install-completions bash)" }, +]; + // A long-only flag is indented by the width of the "-x, " it does not have, so // every long form still starts in the same column. function flagLabel(f: Flag): string { @@ -110,6 +115,9 @@ export function renderHelp(): string { `Commands:\n` + SUBCOMMANDS.map(cmdLine).join("\n") + "\n" + `\n` + + `Tab completion:\n` + + COMPLETION_SETUP.map((c) => ` ${c.shell.padEnd(6)}${c.how}`).join("\n") + "\n" + + `\n` + `Full documentation: ${DOCS_URL}\n` ); } diff --git a/test/cli.test.ts b/test/cli.test.ts index 1a56cb7..867f7cf 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -261,132 +261,37 @@ describe("--update (UPDATE-05)", () => { }); }); -describe("postinstall completion install (COMPLETE-07)", () => { - const script = fileURLToPath(new URL("../scripts/postinstall.mjs", import.meta.url)); - let dir: string; - before(() => { - dir = mkdtempSync(join(tmpdir(), "git-fi-prefix-")); - }); - after(() => rmSync(dir, { recursive: true, force: true })); - - /** Run the postinstall as npm would, with the given npm_config_* env. */ - const run = (env: Record) => - spawnSync(process.execPath, [script], { encoding: "utf-8", env: { ...process.env, ...env } }); - - test("a global install writes both zsh files under npm's prefix", () => { - const prefix = join(dir, "global"); - const r = run({ npm_config_global: "true", npm_config_prefix: prefix }); - assert.equal(r.status, 0, r.stderr); - const dest = join(prefix, "share", "zsh", "site-functions"); - assert.match(readFileSync(join(dest, "_git-fi"), "utf8"), /^#compdef git-fi/); - assert.match(readFileSync(join(dest, "_git_fi"), "utf8"), /^#autoload/); - assert.match(r.stdout, /installed zsh completion/); - }); - - test("a local install writes nothing and says nothing", () => { - const prefix = join(dir, "local"); - const r = run({ npm_config_global: "", npm_config_prefix: prefix }); - assert.equal(r.status, 0, r.stderr); - assert.equal(r.stdout.trim(), ""); - assert.throws(() => readFileSync(join(prefix, "share", "zsh", "site-functions", "_git-fi"))); - }); - - test("an unwritable prefix reports the manual command without failing", () => { - // A postinstall that exits non-zero fails `npm install -g` outright, so a - // root-owned prefix has to degrade to advice, not an error. - const blocker = join(dir, "not-a-prefix"); - writeFileSync(blocker, ""); - const r = run({ npm_config_global: "true", npm_config_prefix: join(blocker, "nope") }); - assert.equal(r.status, 0, r.stderr); - assert.match(r.stdout, /install-completions --write/); - }); - - test("installs exactly the files --write installs", () => { - // The names live in both places (the postinstall can't import the compiled - // TypeScript — npm runs it before the build), so pin them together. - const prefix = join(dir, "parity"); - assert.equal(run({ npm_config_global: "true", npm_config_prefix: prefix }).status, 0); - const written = join(dir, "parity-write"); - assert.equal(runFi(["install-completions", "--write", written], dir).status, 0); - assert.deepEqual( - readdirSync(join(prefix, "share", "zsh", "site-functions")).sort(), - readdirSync(written).sort() - ); - }); -}); - -describe("postinstall git floor (PRE-06)", () => { - const script = fileURLToPath(new URL("../scripts/postinstall.mjs", import.meta.url)); - const gitTs = fileURLToPath(new URL("../src/git.ts", import.meta.url)); +describe("git floor (PRE-02)", () => { let dir: string; let bin: string; before(() => { dir = mkdtempSync(join(tmpdir(), "git-fi-floor-")); + mkdirSync(join(dir, ".git")); bin = join(dir, "bin"); - mkdirSync(bin, { recursive: true }); - // A shell shim only: the postinstall spawns git without a shell, and node - // refuses to spawn a .cmd that way (the CVE-2024-27980 hardening, see - // updateSelf), so Windows has no shape of this fake that git would resolve. + mkdirSync(bin); + // A shell shim only: git-fi spawns git without a shell, and node refuses to + // spawn a .cmd that way (the CVE-2024-27980 hardening, see updateSelf), so + // Windows has no shape of this fake that git would resolve. writeFileSync(join(bin, "git"), `#!/bin/sh\necho "git version 2.39.5"\n`, { mode: 0o755 }); }); after(() => rmSync(dir, { recursive: true, force: true })); - const prefix = () => join(dir, "prefix"); - const run = (path: string) => - spawnSync(process.execPath, [script], { - encoding: "utf-8", - env: { ...process.env, PATH: path, npm_config_global: "true", npm_config_prefix: prefix() }, - }); - - const notWindows = { skip: process.platform === "win32" }; - - test("a git below the floor fails the install", notWindows, () => { - const r = run(bin + delimiter + process.env.PATH); + test("a git below the floor aborts before any command runs", { skip: process.platform === "win32" }, () => { + const r = runFi([], dir, { PATH: bin + delimiter + process.env.PATH }); assert.equal(r.status, 1); - assert.match(r.stderr, /requires git 2\.41\.0 or newer, and this system has git 2\.39\.5/); - // The escape hatch for a git the user does not control (PRE-06): without it - // the reader is told to upgrade and given nowhere to go if they cannot. - assert.match(r.stderr, /npm install -g @gettyimages\/git-fi@1\.2\.2/); - // Refusing means refusing everything, not installing half of it. - assert.throws(() => readdirSync(join(prefix(), "share", "zsh", "site-functions"))); + assert.match(r.stderr, /git version 2\.39\.5 is too old, please upgrade to at least 2\.41\.0\./); }); - test("a missing git fails the install", notWindows, () => { - const empty = join(dir, "empty"); - mkdirSync(empty, { recursive: true }); - const r = run(empty); - assert.equal(r.status, 1); - assert.match(r.stderr, /no working git was found on PATH/); - }); - - const pick = (src: string, re: RegExp, what: string): string => { - const m = src.match(re); - assert.ok(m, `${re} found nothing: ${what} moved somewhere this test cannot see`); - return m[1]; - }; - - test("engines.git states the floor as a >= range (PRE-02, PRE-06)", () => { - // Both readers strip a leading `>=` and compare what is left as a dotted - // triple. Any other range shape — `^2.41.0`, `2.41.x` — survives that strip - // and makes `ordinal` return NaN, so every comparison is false and the floor - // stops being enforced without anything failing. + test("engines.git states the floor as a >= range", () => { + // preflightChecks strips a leading `>=` and compares what is left as a + // dotted triple. Any other range shape (`^2.41.0`, `2.41.x`) survives that + // strip and makes `ordinal` return NaN, so every comparison is false and the + // floor stops being enforced without anything failing. const { engines } = JSON.parse( readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8") ); assert.match(engines.git, /^>=\d+\.\d+\.\d+$/); }); - - test("both enforcers compare the floor the same way (PRE-02)", () => { - // The postinstall cannot import the compiled comparison — npm runs it before - // the build — so `ordinal` is written out in both files. Agreeing on the - // floor while disagreeing on the radix refuses an install at one version and - // aborts a command at another. - const body = /ordinal = \(v(?:: string)?\)(?:: number)? =>\s*(v\.split[^;]+);/; - assert.equal( - pick(readFileSync(script, "utf8"), body, "the comparison"), - pick(readFileSync(gitTs, "utf8"), body, "the comparison") - ); - }); }); describe("generated completions (COMPLETE-02)", () => {