diff --git a/README.md b/README.md index 2a3f718..cae9663 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ With [just](https://github.com/casey/just) installed, `just` lists the same task `npm test` is the primary feedback loop: it drives the compiled binary against throwaway git repositories (a bare `origin` plus a working clone), exercising real `git fetch`/`merge`/`push` behavior end-to-end. `scripts/run-tests.mjs` hands node's runner explicit paths rather than a glob, so a pattern that stops matching fails loudly instead of reporting a green suite that ran nothing. -CI runs the suite on Linux and Windows across Node 22, 24, and 26 — both active LTS lines plus Current. Windows is in the matrix because git-fi behaves differently where the platform has no POSIX file modes: it stores the token without setting or checking `0600` (`AUTH-04`), and `--update` has to reach npm through the shell there (`UPDATE-05`). +CI runs the suite on Linux and Windows across Node 22, 24, and 26 — both active LTS lines plus Current. Windows is in the matrix because git-fi behaves differently where the platform has no POSIX file modes: it stores the token without setting or checking `0600` (`AUTH-04`), and `--update` has to reach npm or pnpm through the shell there (`UPDATE-05`). When something is slow, `--debug` traces every git command with its elapsed time (`OPTION-11`) — which is how the fetch's `--no-tags` came about (`PRE-04`). How much that flag saves depends on the server, so measure with `--debug` in the repository in question rather than assuming. @@ -53,7 +53,7 @@ npm run trial:off # unlink, restore the version it replaced If `git fi` runs something other than what you expect, `which -a git-fi` lists every `git-fi` on your `PATH` in resolution order. -The published package — `npm install -g @gettyimages/git-fi`, documented on the [docs site](https://gettyimages.github.io/git-fi/#/quickstart) — is the official install for end users. Reach for it here mainly to test the distribution itself; local development runs from source. +The published package, installed as the [docs site](https://gettyimages.github.io/git-fi/#/quickstart?id=install) describes, is the official install for end users. Reach for it here mainly to test the distribution itself; local development runs from source. ## Project Structure diff --git a/SPEC.md b/SPEC.md index 1f0a28c..da04b2c 100644 --- a/SPEC.md +++ b/SPEC.md @@ -817,7 +817,7 @@ Install Integrity `git fi` runs whichever `git-fi` comes first on `PATH`, so an installation can be complete and still never run. The state is silent from both ends: npm reports success, and the copy that would notice is the one not being reached. -- `INSTALL-01` Where the `git-fi` that `PATH` resolves first is not the copy executing, `--version` shall report it on stderr: the launcher `git fi` reaches, the copy answering, and how to resolve the two (delete the launcher, or move npm's prefix earlier on `PATH`). Reaching the running copy some other way — `npx`, an absolute path — is the state in which the report can be made at all, and asking which git-fi is installed is the moment it answers a question already being asked. It shall not print on any other command: a second installation is not itself a fault, and a line on every run would be noise to whoever has a reason for it. stdout shall carry only the version string, so anything parsing it is unaffected. `GIT_FI_NO_HINTS` shall suppress it; the update notice's other suppressions (`UPDATE-03`) shall not, since a pipeline reporting which binary it ran is the case this exists for. An unreadable `PATH` entry, an unresolvable entry point, or no `git-fi` on `PATH` at all shall leave the command silent rather than failing it. +- `INSTALL-01` Where the `git-fi` that `PATH` resolves first is not the copy executing, `--version` shall report it on stderr: the launcher `git fi` reaches, the copy answering, and how to resolve the two (delete the launcher, or move the bin directory of the package manager that installed this copy — npm's or pnpm's — earlier on `PATH`). Reaching the running copy some other way — `npx`, an absolute path — is the state in which the report can be made at all, and asking which git-fi is installed is the moment it answers a question already being asked. It shall not print on any other command: a second installation is not itself a fault, and a line on every run would be noise to whoever has a reason for it. stdout shall carry only the version string, so anything parsing it is unaffected. `GIT_FI_NO_HINTS` shall suppress it; the update notice's other suppressions (`UPDATE-03`) shall not, since a pipeline reporting which binary it ran is the case this exists for. An unreadable `PATH` entry, an unresolvable entry point, or no `git-fi` on `PATH` at all shall leave the command silent rather than failing it. A launcher is this copy when it leads to the same resolved entry point: a symlink resolves there, and a generated launcher names it — npm's relative to the launcher's own directory, pnpm's as a recorded `cmd-shim-target` (older pnpm launchers name a path relative to their directory that leaves `node_modules`, into pnpm's global directory). ## `UPDATE` @@ -829,4 +829,4 @@ git-fi notifies the user when a newer version has been published to npm, without - `UPDATE-02` git-fi shall refresh the cached latest version in a detached background process, throttled to at most once per 24 hours via the cache's `checkedAt` timestamp. The check shall be best-effort: a registry error, timeout, or spawn failure leaves the cache untouched and never surfaces or delays the command. - `UPDATE-03` git-fi shall suppress both the notice and the background check when stdout is not a TTY, when `$CI` is set, when `--json` or `--bare` is used, when `$GIT_FI_NO_HINTS` or `$NO_UPDATE_NOTIFIER` is set, or when the running build is a dev build (`BUILD-01`). The notice names `git fi --update`, which installs the published global over the linked checkout and takes the trial down with it. - `UPDATE-04` The cache shall live at `$XDG_CACHE_HOME/git-fi/update-check.json`, falling back to `~/.cache/git-fi/update-check.json`. -- `UPDATE-05` `--update` (`-u`) shall update the installed git-fi by running `npm install -g @latest` with npm's stdio inherited, exiting with npm's exit code and adding no output of its own. Where the platform resolves npm through a `.cmd` shim (Windows), git-fi shall spawn it through the shell, which is the only path left: node finds nothing under the bare name and refuses a direct `.cmd` with `EINVAL`. A consequence is that a missing npm is then the shell's error to report rather than git-fi's, so the `Could not run npm` message is a POSIX-only guarantee. It shall run before the update notice and the pre-flight checks, so it works from any directory. It shall consult neither the cache nor the registry first: the throttle in `UPDATE-02` serves the passive notice, whereas `--update` is an explicit request to install now, and a redundant reinstall is a better answer than refusing one. It shall collide with the actions in `COMMAND-*` the way they collide with each other, and shall reject branch-name arguments. +- `UPDATE-05` `--update` (`-u`) shall update the installed git-fi with the package manager that installed it: `pnpm add -g @latest` when pnpm did, otherwise `npm install -g @latest`, with that tool's stdio inherited, exiting with its exit code and adding no output of its own. pnpm installed the running copy when the `node_modules` directory directly holding the package contains `.modules.yaml`, the marker pnpm writes into every `node_modules` it manages and npm never does; the check is made from both the path the launcher handed node and that path resolved, since pnpm's launcher passes a path through its global directory (where the marker is) and newer pnpm layouts resolve it into the store (where none is). Detection reads the file rather than asking pnpm, so it holds however pnpm and Node themselves were installed — standalone, corepack, npm, Homebrew, a version manager — whereas `pnpm root -g` answers for whichever pnpm the current directory's `packageManager` field selects. For the same reason pnpm shall run from the system temp directory, outside any project: run from a repo, corepack and pnpm's own version management would follow its `packageManager` field to another pnpm (with another global directory) or, in a repo pinned to another tool, refuse. Where pnpm installed git-fi but cannot be run, git-fi shall say so (`Could not run pnpm`) and how to put pnpm on `PATH`, rather than fall back to npm, which would install a second copy behind the one `PATH` reaches. Where the platform resolves npm or pnpm through a `.cmd` shim (Windows), git-fi shall spawn it through the shell, which is the only path left: node finds nothing under the bare name and refuses a direct `.cmd` with `EINVAL`. A consequence is that a missing tool is then the shell's error to report rather than git-fi's, so the `Could not run ` message is a POSIX-only guarantee. It shall run before the update notice and the pre-flight checks, so it works from any directory. It shall consult neither the cache nor the registry first: the throttle in `UPDATE-02` serves the passive notice, whereas `--update` is an explicit request to install now, and a redundant reinstall is a better answer than refusing one. It shall collide with the actions in `COMMAND-*` the way they collide with each other, and shall reject branch-name arguments. diff --git a/STATUS.md b/STATUS.md index f29e6f1..7c0d7e2 100644 --- a/STATUS.md +++ b/STATUS.md @@ -289,7 +289,7 @@ Install Integrity | ID | Description | Status | Location | |--------|----------------------------------|---------|--------------------------------| -| INSTALL-01 | `--version` reports a launcher ahead of this copy | Covered | `src/which.ts` (`gitFiOnPath`, `shadowingLauncher`, `shadowNotice`, `warnIfShadowed`), `src/index.ts` (`parseArgs`) | +| INSTALL-01 | `--version` reports a launcher ahead of this copy | Covered | `src/which.ts` (`gitFiOnPath`, `shadowingLauncher`, `isSameInstall`, `launcherTarget`, `shadowNotice`, `warnIfShadowed`), `src/index.ts` (`parseArgs`) | ## `UPDATE` @@ -301,4 +301,4 @@ Update Notification | UPDATE-02 | Throttled background check | Covered | `src/update-check.ts` (`notifyUpdate`), `src/update-worker.ts` | | UPDATE-03 | Suppression conditions | Covered | `src/style.ts` (`hintsEnabled`), `src/update-check.ts` (`suppressed`), `src/build-info.ts` (`isDevBuild`) | | UPDATE-04 | Cache location | Covered | `src/update-check.ts` (`cachePath`) | -| UPDATE-05 | `--update` installs the latest version | Covered | `src/update-check.ts` (`updateSelf`), `src/index.ts` (`parseArgs`, `main`) | +| UPDATE-05 | `--update` installs the latest version | Covered | `src/update-check.ts` (`updateSelf`), `src/package-manager.ts` (`PackageManager.detect`, `Npm`, `Pnpm`), `src/index.ts` (`parseArgs`, `main`) | diff --git a/docs/home.md b/docs/home.md index a07a9aa..eb77ba6 100644 --- a/docs/home.md +++ b/docs/home.md @@ -2,17 +2,7 @@ A git plugin that maintains a temporary integration branch named `fi`. Merge multiple in-progress feature branches together to detect conflicts early and test features in collaboration — before they land on `main`. -## Get Started - -
- -```bash -npm install -g @gettyimages/git-fi # needs Node.js 22+ and git 2.41+ -``` - -
- -Then run your first integration with the [Quick Start](/quickstart), or follow a branch from first commit to `main` in the [Daily Workflow](/daily-workflow). +Install it and run your first integration with the [Quick Start](/quickstart), or follow a branch from first commit to `main` in the [Daily Workflow](/daily-workflow). ## The Problem diff --git a/docs/index.html b/docs/index.html index 1b53766..bcb5e06 100644 --- a/docs/index.html +++ b/docs/index.html @@ -146,8 +146,43 @@ color: var(--gf-heading); max-width: 38em; } - .markdown-section .gf-start pre { border-left: 3px solid var(--gf-accent); } - .markdown-section .gf-start .docsify-copy-code-button { opacity: 1; } + /* Install switch: the installSwitch plugin's command blocks, one per + package manager, framed as one code surface under the switch. */ + .markdown-section .gf-install { + margin: 1em 0; + border: 1px solid var(--gf-divider); + border-radius: 10px; + background: var(--code-theme-background); + overflow: hidden; + } + .markdown-section .gf-install pre { + margin: 0; + border: 0; + border-radius: 0; + } + .gf-install-switch { + display: flex; + gap: 1.25rem; + padding: 0 1.25rem; + border-bottom: 1px solid var(--gf-divider); + } + .gf-install-switch button { + appearance: none; + background: none; + border: 0; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + padding: 0.6rem 0 0.5rem; + font: 500 0.8rem/1 var(--code-font-family); + color: var(--gf-muted); + cursor: pointer; + transition: color 0.2s ease, border-color 0.2s ease; + } + .gf-install-switch button:hover { color: var(--gf-accent-hover); } + .gf-install-switch button[aria-pressed="true"] { + color: var(--gf-heading); + border-bottom-color: var(--gf-accent); + } /* Visible focus ring (keyboard accessibility, >= 3:1) */ a:focus-visible, @@ -270,7 +305,6 @@ @media screen and (min-width: 768px) { .sidebar-toggle { display: none; } - .markdown-section .gf-start pre { font-size: 1.02rem; } } @@ -340,6 +374,67 @@ }); } + // The one place the docs say how each package manager installs git-fi. + // A page names only the package, in a fenced `install` block: + // + // ```install + // @gettyimages/git-fi + // ``` + // + // and this expands it, before docsify renders the page, into one bash + // block per manager (so they get highlighting and a copy button like any + // other), then joins them under a switch that shows one at a time, so the + // copy button copies the command on screen. The first manager is the + // default; a reader's choice is remembered. + // Hand-rolled rather than docsify-tabs, which forgets the choice when + // the browser session ends and would need restyling to match the theme. + function installSwitch(hook) { + var MANAGERS = [ + { name: 'pnpm', command: 'pnpm add -g ' }, + { name: 'npm', command: 'npm install -g ' } + ]; + var KEY = 'git-fi.install-manager'; + var remembered = null; + try { remembered = localStorage.getItem(KEY); } catch (e) { /* storage blocked */ } + hook.beforeEach(function (markdown) { + return markdown.replace(/^```install\r?\n(.+)\r?\n```$/gm, function (block, pkg) { + return '
\n\n' + MANAGERS.map(function (manager) { + return '```bash\n' + manager.command + pkg.trim() + '\n```'; + }).join('\n\n') + '\n\n
'; + }); + }); + hook.doneEach(function () { + document.querySelectorAll('.gf-install').forEach(function (box) { + var bar = document.createElement('div'); + bar.className = 'gf-install-switch'; + bar.setAttribute('role', 'group'); + bar.setAttribute('aria-label', 'Package manager'); + var options = Array.prototype.map.call(box.querySelectorAll('pre'), function (pre, i) { + var button = document.createElement('button'); + button.type = 'button'; + button.textContent = MANAGERS[i].name; + bar.appendChild(button); + return { name: MANAGERS[i].name, pre: pre, button: button }; + }); + box.insertBefore(bar, box.firstChild); + function show(chosen) { + options.forEach(function (o) { + o.pre.hidden = o !== chosen; + o.button.setAttribute('aria-pressed', String(o === chosen)); + }); + } + options.forEach(function (o) { + o.button.addEventListener('click', function () { + remembered = o.name; + try { localStorage.setItem(KEY, remembered); } catch (e) { /* storage blocked */ } + show(o); + }); + }); + show(options.find(function (o) { return o.name === remembered; }) || options[0]); + }); + }); + } + window.$docsify = { name: 'git-fi', // nameLink is intentionally omitted: Docsify defaults it to @@ -359,7 +454,7 @@ noData: 'No results', depth: 5 }, - plugins: [searchPlainText, mermaidLinks], + plugins: [searchPlainText, mermaidLinks, installSwitch], mermaidConfig: { querySelector: '.mermaid', theme: 'dark', diff --git a/docs/quickstart.md b/docs/quickstart.md index 718d8f2..015d9dc 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -2,12 +2,14 @@ ## Install -git-fi is a git subcommand: once the `git-fi` binary is on your `PATH`, invoke it as `git fi`. Requires Node.js >= 22 and git >= 2.41.0. +git-fi is a git subcommand: once the `git-fi` binary is on your `PATH`, invoke it as `git fi`. -```bash -npm install -g @gettyimages/git-fi +```install +@gettyimages/git-fi ``` +Needs Node.js 22+ and git 2.41+. + Then turn on tab completion, so `git fi --add ` offers your branches. In zsh: ```zsh diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 8bf1cfb..7b6bb4b 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2,24 +2,23 @@ ## Your git is older than 2.41.0 -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: +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 1.2.2, the last release that runs on git 2.13 and newer: -```bash -npm install -g @gettyimages/git-fi@1.2.2 +```install +@gettyimages/git-fi@1.2.2 ``` ## Upgrading from the Ruby gem -git-fi shipped as a Ruby gem through 0.9.3400163. `git fi` runs whichever `git-fi` comes first on your `PATH`, so remove the gem before you install the npm package: +git-fi shipped as a Ruby gem through 0.9.3400163. `git fi` runs whichever `git-fi` comes first on your `PATH`, so remove the gem before you [install](/quickstart#install) the package: ```bash gem uninstall git-fi -npm install -g @gettyimages/git-fi ``` Use `gem uninstall` rather than deleting the gem's files. -Then open a new shell and run `git fi --version`. If it reports a `0.x` version, or fails with `cannot load such file` or `Maybe git-fi is broken?`, an older `git-fi` is ahead of npm's on your `PATH`. List them in resolution order and delete any outside npm's own prefix (`npm config get prefix`): +Then open a new shell and run `git fi --version`. If it reports a `0.x` version, or fails with `cannot load such file` or `Maybe git-fi is broken?`, an older `git-fi` is ahead of the one you installed on your `PATH`. List them in resolution order and delete any outside pnpm's bin directory (`pnpm bin -g`) or npm's own prefix (`npm config get prefix`): ```bash which -a git-fi @@ -57,11 +56,7 @@ git handles `--help` itself, before git-fi runs. Git for Windows opens an HTML p ## Update reports an unknown option -If `git fi --update` reports an unknown option, you're on a version that predates the flag. Update once with npm and you'll have it: - -```bash -npm install -g @gettyimages/git-fi -``` +If `git fi --update` reports an unknown option, you're on a version that predates the flag. Run the [install command](/quickstart#install) once, with the package manager you installed it with, and you'll have it. ## Tab completion offers filenames diff --git a/src/package-manager.ts b/src/package-manager.ts new file mode 100644 index 0000000..6200633 --- /dev/null +++ b/src/package-manager.ts @@ -0,0 +1,129 @@ +// UPDATE-05: the package manager that installed git-fi, and how to have it +// install the latest version over this copy. +// +// Everything that differs between package managers lives in a subclass: how to +// tell it installed the running copy, the command that replaces a global +// install, where to run it, and what to say when it can't be run. Supporting +// another one is a subclass and an entry in `PackageManager.detect`. +import { spawnSync, type SpawnSyncReturns } from "node:child_process"; +import { existsSync, realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; + +export abstract class PackageManager { + /** The command run, and the name used when it can't be. */ + abstract readonly command: string; + + /** The arguments that install `pkg@latest` globally, replacing this copy. */ + protected abstract installLatestArgs(pkg: string): string[]; + + /** Whether this package manager installed the copy running as `entry`. */ + protected abstract installed(pkg: string, entry: string): boolean; + + /** The directory to run the install from; undefined keeps the caller's. */ + protected get cwd(): string | undefined { + return undefined; + } + + /** A line to add when the command can't be run, or null for none. */ + get notFoundHint(): string | null { + return null; + } + + /** + * The package manager that installed the copy running as `entry`. npm is the + * fallback: it is what git-fi has always updated with, and it covers every + * install no other package manager claims (npx, a dev-trial link). + */ + static detect(pkg: string, entry: string | undefined = process.argv[1]): PackageManager { + const candidates: PackageManager[] = [new Pnpm()]; + return (entry && candidates.find((pm) => pm.installed(pkg, entry))) || new Npm(); + } + + /** Install `pkg@latest` globally with stdio inherited, so its output is the user's to read. */ + installLatest(pkg: string): SpawnSyncReturns { + return spawnSync(this.command, this.installLatestArgs(pkg), { + stdio: "inherit", + cwd: this.cwd, + // On Windows npm and pnpm are .cmd shims, which node refuses to spawn + // directly (EINVAL, the CVE-2024-27980 hardening) and finds by bare name + // not at all — so the shell does the PATHEXT lookup. Every argument here + // is a fixed literal, so there is nothing for cmd's parser to mangle. + shell: process.platform === "win32", + }); + } +} + +export class Npm extends PackageManager { + readonly command = "npm"; + + // `install`, not `update`: npm's `update -g` leaves an installed global alone. + protected installLatestArgs(pkg: string): string[] { + return ["install", "-g", `${pkg}@latest`]; + } + + // The fallback in `detect`, so never asked. + protected installed(): boolean { + return true; + } +} + +export class Pnpm extends PackageManager { + readonly command = "pnpm"; + + protected installLatestArgs(pkg: string): string[] { + return ["add", "-g", `${pkg}@latest`]; + } + + /** + * pnpm writes `.modules.yaml` into every `node_modules` it manages, and npm + * never does. + * + * Reading a file rather than asking pnpm keeps the answer independent of how + * pnpm itself got onto the machine. Under corepack, `pnpm root -g` answers for + * whichever pnpm the current directory's `packageManager` field (or corepack's + * last-known-good) selects, which need not be the one that installed git-fi — + * and in a yarn-pinned repo it refuses to run at all. + * + * Both the launch path and its resolved path are tried. pnpm's launchers are + * generated scripts that hand node the path inside its global directory, which + * is where the marker sits; its newer layouts resolve that path into the store, + * where there is none. npm's POSIX launcher is a symlink, so only the resolved + * path reaches the package at all. + * + * Only the `node_modules` directly holding the package counts, not any + * ancestor: npm's global prefix can itself sit inside a pnpm-managed tree when + * node is a pnpm global, and that copy is still npm's. + */ + protected installed(pkg: string, entry: string): boolean { + // Normalized, so a `./` segment can't throw off the walk up from the entry. + const paths = [resolve(entry)]; + try { + paths.push(realpathSync(entry)); + } catch { + // an unresolvable entry leaves only the path as given + } + return paths.some((path) => { + // dist/index.js → the package directory → past its name to node_modules + const pkgDir = dirname(dirname(path)); + const modulesDir = pkg.split("/").reduce((dir) => dirname(dir), pkgDir); + return basename(modulesDir) === "node_modules" && existsSync(join(modulesDir, ".modules.yaml")); + }); + } + + /** + * Outside any project. Corepack and pnpm's own version management both follow + * the nearest `packageManager` field, so run from a repo they could pick + * another pnpm (with another global directory) or, in a yarn-pinned repo, + * refuse outright. A global install has no other use for the directory. + */ + protected get cwd(): string { + return tmpdir(); + } + + // Falling back to npm would install a second copy behind the one PATH + // reaches, so point at how pnpm gets onto PATH instead. + get notFoundHint(): string { + return "git-fi was installed with pnpm; put pnpm on your PATH (with corepack: corepack enable pnpm) and retry."; + } +} diff --git a/src/update-check.ts b/src/update-check.ts index 9f4a0c7..690c755 100644 --- a/src/update-check.ts +++ b/src/update-check.ts @@ -1,4 +1,4 @@ -import { spawn, spawnSync } from "node:child_process"; +import { spawn } from "node:child_process"; import { readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url"; import type { Options } from "./types.js"; import { makeStyle, hintsEnabled } from "./style.js"; import { isDevBuild } from "./build-info.js"; +import { PackageManager } from "./package-manager.js"; const ONE_DAY_MS = 1000 * 60 * 60 * 24; @@ -95,9 +96,10 @@ export function notifyUpdate(name: string, current: string, opts: Options): void } /** - * Hand the update to npm and exit with its verdict. npm's stdio is inherited - * and its exit code becomes ours, so a registry outage, a permissions error, or - * a successful install all read exactly as npm already reports them. + * Hand the update to the package manager that installed this copy (UPDATE-05), + * and exit with its verdict. Its stdio is inherited and its exit code becomes + * ours, so a registry outage, a permissions error, or a successful install all + * read exactly as the package manager already reports them. * * The cache is deliberately not consulted first: the 24-hour throttle (UPDATE-02) * exists to keep a *passive* notice cheap, whereas `--update` is the user asking @@ -105,17 +107,12 @@ export function notifyUpdate(name: string, current: string, opts: Options): void * than a redundant reinstall. */ export function updateSelf(name: string): never { - const npm = spawnSync("npm", ["install", "-g", `${name}@latest`], { - stdio: "inherit", - // On Windows npm is npm.cmd, which node refuses to spawn directly (EINVAL, - // the CVE-2024-27980 hardening) and finds by bare name not at all — so the - // shell does the PATHEXT lookup. Every argument here is a fixed literal, - // so there is nothing for cmd's parser to mangle. - shell: process.platform === "win32", - }); - if (npm.error) { - process.stderr.write(`Could not run npm: ${npm.error.message}\n`); + const pm = PackageManager.detect(name); + const result = pm.installLatest(name); + if (result.error) { + process.stderr.write(`Could not run ${pm.command}: ${result.error.message}\n`); + if (pm.notFoundHint) process.stderr.write(`${pm.notFoundHint}\n`); process.exit(1); } - process.exit(npm.status ?? 1); + process.exit(result.status ?? 1); } diff --git a/src/which.ts b/src/which.ts index 9c943a6..4cde639 100644 --- a/src/which.ts +++ b/src/which.ts @@ -108,9 +108,14 @@ function resolved(path: string): string | null { } /** - * The entry point a generated launcher names, resolved against the launcher's - * own directory — the form npm's `.cmd` and `.ps1` shims write it in - * (`%~dp0\node_modules\...`, `$basedir/node_modules/...`). + * The entry point a generated launcher names. + * + * pnpm's launchers record it outright, as a `cmd-shim-target=` comment holding + * an absolute path, so that is read first. Otherwise the path is the one the + * shim gives relative to its own directory: npm's `.cmd` and `.ps1` shims write + * `%~dp0\node_modules\...` and `$basedir/node_modules/...`, and pnpm's (older + * ones lack the comment) write `$basedir_abs/../global/...`, a directory npm's + * pattern never reaches. */ function launcherTarget(launcher: string): string | null { let text: string; @@ -119,10 +124,15 @@ function launcherTarget(launcher: string): string | null { } catch { return null; } - const named = text.match(/node_modules[\\/][^\s"']*\.[cm]?js/); + const recorded = text.match(/cmd-shim-target=(\S+)/); + if (recorded) return recorded[1]; + + const named = + text.match(/(?:\$basedir\w*|%~dp0|%dp0%)[\\/]([^\s"']*\.[cm]?js)/)?.[1] ?? + text.match(/node_modules[\\/][^\s"']*\.[cm]?js/)?.[0]; // The shim is written for its own platform, so it may carry backslashes that // are ordinary filename characters anywhere else. - return named ? join(dirname(launcher), named[0].replace(/\\/g, "/")) : null; + return named ? join(dirname(launcher), named.replace(/\\/g, "/")) : null; } /** @@ -169,7 +179,8 @@ export function shadowNotice( ` git fi reaches ${winner}\n` + ` this copy is ${entry}\n` + `Delete the one above, or put npm's bin directory (${npmBinHint()})\n` + - `earlier on your PATH. A launcher left behind by the Ruby gem lands in\n` + + `or pnpm's (pnpm bin -g) earlier on your PATH, whichever installed\n` + + `this copy. A launcher left behind by the Ruby gem lands in\n` + `Ruby's bin directory, which removing the gem's own files does not touch.\n` ); } diff --git a/test/cli.test.ts b/test/cli.test.ts index 867f7cf..94b5e65 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -1,10 +1,10 @@ import { test, before, after, beforeEach, afterEach, describe } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, mkdirSync, rmSync, readFileSync, readdirSync, writeFileSync, chmodSync, existsSync } from "node:fs"; +import { mkdtempSync, mkdirSync, rmSync, readFileSync, readdirSync, writeFileSync, chmodSync, existsSync, realpathSync, symlinkSync, unlinkSync } from "node:fs"; import { spawn, spawnSync } from "node:child_process"; import { setTimeout as sleep } from "node:timers/promises"; import { tmpdir } from "node:os"; -import { join, delimiter } from "node:path"; +import { join, delimiter, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { createRequire } from "node:module"; import { runFi, runFiOnTty, makeSandbox, DIST_INDEX, type Sandbox } from "./helpers.ts"; @@ -173,41 +173,119 @@ describe("--update (UPDATE-05)", () => { let dir: string; let path: string; let argvLog: string; - - before(() => { - dir = mkdtempSync(join(tmpdir(), "git-fi-update-")); - const bin = join(dir, "bin"); - argvLog = join(dir, "npm-argv"); - mkdirSync(bin); - // Stand-in npm: records the arguments git-fi handed it, and exits with - // whatever the test asks for. Running the real npm would reinstall the - // developer's global git-fi mid-suite. - // - // The recording lives in a node script behind a per-platform launcher: the - // shebang a lone `sh` shim relies on means nothing to Windows, which needs - // an `npm.cmd` to match how it resolves npm on PATH. - const shim = join(dir, "npm-shim.mjs"); + let pnpmLog: string; + let pnpmEntry: string; + + /** + * A stand-in package manager: records the arguments git-fi handed it and the + * directory it ran in, and exits with whatever the test asks for. Running the + * real one would reinstall the developer's global git-fi mid-suite. + * + * The recording lives in a node script behind a per-platform launcher: the + * shebang a lone `sh` shim relies on means nothing to Windows, which needs + * a `.cmd` to match how it resolves npm and pnpm on PATH. + */ + function fakeTool(bin: string, tool: string, log: string, exitVar: string): void { + const shim = join(dir, `${tool}-shim.mjs`); writeFileSync( shim, `import { writeFileSync } from "node:fs";\n` + - `writeFileSync(${JSON.stringify(argvLog)}, process.argv.slice(2).join("\\n") + "\\n");\n` + - `process.exit(Number(process.env.FAKE_NPM_EXIT ?? 0));\n` + `writeFileSync(${JSON.stringify(log)}, process.argv.slice(2).join("\\n") + "\\n");\n` + + `writeFileSync(${JSON.stringify(log + "-cwd")}, process.cwd());\n` + + `process.exit(Number(process.env.${exitVar} ?? 0));\n` ); if (process.platform === "win32") { writeFileSync( - join(bin, "npm.cmd"), + join(bin, `${tool}.cmd`), `@echo off\r\n"${process.execPath}" "${shim}" %*\r\nexit /b %ERRORLEVEL%\r\n` ); } else { - writeFileSync(join(bin, "npm"), `#!/bin/sh\nexec "${process.execPath}" "${shim}" "$@"\n`, { + writeFileSync(join(bin, tool), `#!/bin/sh\nexec "${process.execPath}" "${shim}" "$@"\n`, { mode: 0o755, }); } + } + + before(() => { + dir = mkdtempSync(join(tmpdir(), "git-fi-update-")); + const bin = join(dir, "bin"); + argvLog = join(dir, "npm-argv"); + pnpmLog = join(dir, "pnpm-argv"); + mkdirSync(bin); + fakeTool(bin, "npm", argvLog, "FAKE_NPM_EXIT"); + fakeTool(bin, "pnpm", pnpmLog, "FAKE_PNPM_EXIT"); path = bin + delimiter + process.env.PATH; + + // A pnpm-shaped global install of this checkout: pnpm's marker beside the + // package, which is linked in the way pnpm 11+ links it from the store. + // pnpmEntry is the path pnpm's launcher would hand node. + const modules = join(dir, "pnpm-global", "node_modules"); + mkdirSync(join(modules, "@gettyimages"), { recursive: true }); + writeFileSync(join(modules, ".modules.yaml"), "layoutVersion: 5\n"); + symlinkSync(dirname(dirname(DIST_INDEX)), join(modules, "@gettyimages", "git-fi"), "junction"); + pnpmEntry = join(modules, "@gettyimages", "git-fi", "dist", "index.js"); + }); + after(() => { + // Drop the link to the checkout on its own first, so the recursive removal + // below can never reach through it into the repo. + unlinkSync(join(dir, "pnpm-global", "node_modules", "@gettyimages", "git-fi")); + rmSync(dir, { recursive: true, force: true }); + }); + beforeEach(() => { + rmSync(argvLog, { force: true }); + rmSync(pnpmLog, { force: true }); }); - after(() => rmSync(dir, { recursive: true, force: true })); const npmArgv = () => readFileSync(argvLog, "utf8").trim().split("\n"); + const pnpmArgv = () => readFileSync(pnpmLog, "utf8").trim().split("\n"); + const pnpmCwd = () => realpathSync(readFileSync(pnpmLog + "-cwd", "utf8")); + + describe("installed with pnpm", () => { + let project: string; + before(() => { + // A repo pinned to another package manager: corepack refuses pnpm here, + // and would pick a pinned pnpm's own global directory. + project = join(dir, "yarn-project"); + mkdirSync(project); + writeFileSync( + join(project, "package.json"), + JSON.stringify({ name: "app", packageManager: "yarn@4.0.0" }) + ); + }); + + test("updates through pnpm, not npm", () => { + const r = runFi(["--update"], project, { PATH: path }, pnpmEntry); + assert.equal(r.status, 0, r.stderr); + assert.deepEqual(pnpmArgv(), ["add", "-g", `${name}@latest`]); + assert.equal(existsSync(argvLog), false, "npm was called"); + }); + + test("runs pnpm outside the project, so its packageManager field cannot steer it", () => { + runFi(["--update"], project, { PATH: path }, pnpmEntry); + assert.equal(pnpmCwd(), realpathSync(tmpdir())); + assert.notEqual(pnpmCwd(), realpathSync(project)); + }); + + test("exits with pnpm's exit code and adds no wrapper output", () => { + const r = runFi(["--update"], project, { PATH: path, FAKE_PNPM_EXIT: "17" }, pnpmEntry); + assert.equal(r.status, 17); + assert.equal(r.stdout, ""); + assert.equal(r.stderr, ""); + }); + + // On Windows the shell resolves pnpm (see updateSelf), so a missing one is + // cmd's error to report, as for npm below. + test("names pnpm and how to get it onto PATH, rather than falling back to npm", { + skip: process.platform === "win32", + }, () => { + const empty = join(dir, "empty"); + mkdirSync(empty, { recursive: true }); + const r = runFi(["--update"], project, { PATH: empty }, pnpmEntry); + assert.equal(r.status, 1); + assert.match(r.stderr, /Could not run pnpm/); + assert.match(r.stderr, /corepack enable pnpm/); + }); + }); test("installs the latest published version, from outside a git repo", () => { // `dir` is a bare temp directory: updating must not require a repo. diff --git a/test/helpers.ts b/test/helpers.ts index 4c9485f..347b511 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -22,11 +22,16 @@ export interface RunResult { stderr: string; } -/** Run the compiled git-fi binary in `cwd`. Never throws on non-zero exit. */ +/** + * Run the compiled git-fi binary in `cwd`. Never throws on non-zero exit. + * `entry` stands in for the path a launcher hands node, for a test that needs + * the binary reached through an installed layout rather than the checkout. + */ export function runFi( args: string[], cwd: string, - extraEnv: Record = {} + extraEnv: Record = {}, + entry: string = DIST_INDEX ): RunResult { // Start from a clean slate so the host's CI / GitLab / color settings can't // leak into the assertions; tests opt back into those vars explicitly. @@ -41,7 +46,7 @@ export function runFi( // spawnSync (not execFileSync) so both stdout and stderr are captured // regardless of exit code — success-path messages land on stderr too. - const r = spawnSync(process.execPath, [DIST_INDEX, ...args], { + const r = spawnSync(process.execPath, [entry, ...args], { cwd, encoding: "utf-8", env: { ...env, ...extraEnv }, diff --git a/test/package-manager.test.ts b/test/package-manager.test.ts new file mode 100644 index 0000000..032aeb3 --- /dev/null +++ b/test/package-manager.test.ts @@ -0,0 +1,77 @@ +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { PackageManager } from "../src/package-manager.ts"; + +describe("PackageManager.detect (UPDATE-05)", () => { + const name = "@gettyimages/git-fi"; + const detected = (entry: string | undefined) => PackageManager.detect(name, entry).command; + + /** A package directory under `modulesDir`, holding the entry point npm and pnpm both run. */ + function stagePackage(modulesDir: string): string { + const entry = join(modulesDir, "@gettyimages", "git-fi", "dist", "index.js"); + mkdirSync(dirname(entry), { recursive: true }); + writeFileSync(entry, ""); + return entry; + } + + /** A `node_modules` pnpm manages: the one marker every pnpm version writes. */ + function pnpmModules(root: string): string { + const modulesDir = join(root, "node_modules"); + mkdirSync(modulesDir, { recursive: true }); + writeFileSync(join(modulesDir, ".modules.yaml"), "layoutVersion: 5\n"); + return modulesDir; + } + + const temp = () => mkdtempSync(join(tmpdir(), "git-fi-pm-")); + + test("a package in a pnpm-managed node_modules (pnpm 10 and earlier)", () => { + const entry = stagePackage(pnpmModules(join(temp(), "global", "5"))); + assert.equal(detected(entry), "pnpm"); + }); + + test("a package linked into the store, launched through the global directory (pnpm 11+)", () => { + // The newer layout resolves the package into the store, where no marker is; + // only the path pnpm's launcher hands node still passes through it. + const root = temp(); + const storeEntry = stagePackage(join(root, "store", "links", "node_modules")); + const modulesDir = pnpmModules(join(root, "global", "v11", "abc123")); + mkdirSync(join(modulesDir, "@gettyimages")); + symlinkSync(dirname(dirname(storeEntry)), join(modulesDir, "@gettyimages", "git-fi"), "junction"); + assert.equal(detected(join(modulesDir, "@gettyimages", "git-fi", "dist", "index.js")), "pnpm"); + }); + + test("an entry path carrying a ./ segment, as pnpm records it", () => { + const modulesDir = pnpmModules(temp()); + stagePackage(modulesDir); + assert.equal(detected(join(modulesDir, "@gettyimages", "git-fi") + "/./dist/index.js"), "pnpm"); + }); + + test("a package in npm's global node_modules", () => { + const entry = stagePackage(join(temp(), "lib", "node_modules")); + assert.equal(detected(entry), "npm"); + }); + + test("npm's symlinked bin launcher, resolved into an unmarked node_modules", () => { + const prefix = temp(); + const entry = stagePackage(join(prefix, "lib", "node_modules")); + mkdirSync(join(prefix, "bin")); + symlinkSync(entry, join(prefix, "bin", "git-fi")); + assert.equal(detected(join(prefix, "bin", "git-fi")), "npm"); + }); + + test("npm's prefix inside a pnpm-managed tree is still npm's", () => { + // Node installed as a pnpm global puts npm's prefix under pnpm's + // node_modules; only the directory holding git-fi decides. + const outer = pnpmModules(join(temp(), "global", "v11", "abc123")); + const entry = stagePackage(join(outer, "node", "lib", "node_modules")); + assert.equal(detected(entry), "npm"); + }); + + test("an entry that does not resolve", () => { + assert.equal(detected(join(temp(), "missing", "dist", "index.js")), "npm"); + assert.equal(detected(undefined), "npm"); + }); +}); diff --git a/test/which.test.ts b/test/which.test.ts index 895d12f..e8f4dea 100644 --- a/test/which.test.ts +++ b/test/which.test.ts @@ -252,6 +252,57 @@ describe("shadowingLauncher (INSTALL-01)", () => { }); }); +describe("pnpm launchers (INSTALL-01)", () => { + /** + * A pnpm global install: the launcher pnpm writes into its bin directory, and + * the entry point it hands node, under the global directory beside it. The + * script is cut down from the one pnpm writes, keeping the lines that name the + * entry point — on every platform it is a generated script, never a symlink. + */ + function pnpmInstall(recordTarget: boolean, hash = "abc123") { + const home = mkdtempSync(join(tmpdir(), "git-fi-pnpm-")); + const relative = `global/v11/${hash}/node_modules/@gettyimages/git-fi/dist/index.js`; + const target = join(home, relative); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, ""); + const launcher = join(home, "bin", "git-fi"); + mkdirSync(dirname(launcher)); + writeFileSync( + launcher, + `#!/bin/sh\n` + + `if [ -x "$basedir/node" ]; then\n` + + ` exec "$basedir/node" "$basedir_abs/../${relative}" "$@"\n` + + `else\n` + + ` exec node "$basedir_abs/../${relative}" "$@"\n` + + `fi\n` + + (recordTarget ? `# cmd-shim-target=${target}\n` : ""), + { mode: 0o755 } + ); + return { launcher, target }; + } + + test("the launcher's recorded target is this install", () => { + const { launcher, target } = pnpmInstall(true); + assert.equal(isSameInstall(launcher, target), true); + }); + + test("a launcher without the record leads here through its relative path", () => { + const { launcher, target } = pnpmInstall(false); + assert.equal(isSameInstall(launcher, target), true); + }); + + test("stays silent when pnpm's launcher is the one PATH resolves", () => { + const { launcher, target } = pnpmInstall(true); + assert.equal(shadowingLauncher(target, onPath(dirname(launcher))), null); + }); + + test("another pnpm install's launcher is not this one", () => { + const mine = pnpmInstall(true, "mine"); + const theirs = pnpmInstall(true, "theirs"); + assert.equal(isSameInstall(theirs.launcher, mine.target), false); + }); +}); + describe("shadowNotice (INSTALL-01)", () => { const s = makeStyle(OPTS); @@ -264,6 +315,7 @@ describe("shadowNotice (INSTALL-01)", () => { test("gives both ways out, not just deletion", () => { const notice = shadowNotice("/ruby/bin/git-fi", "/npm/git-fi", s); assert.ok(notice.includes("npm config get prefix"), notice); + assert.ok(notice.includes("pnpm bin -g"), notice); }); });