Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): swizzle finds gh on PATH instead of running gh auth status (#8626)

Christopher Chedeau086a500b3848
diff --git a/.changeset/swizzle-gh-without-running.md b/.changeset/swizzle-gh-without-running.md
new file mode 100644
index 0000000000..13dcf09055
--- /dev/null
+++ b/.changeset/swizzle-gh-without-running.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx swizzle` no longer runs `gh auth status` before it reports: the ready `gh issue create` line appears when `gh` is on your PATH, found without running it, so a copy never waits on a process start or on GitHub. The line now also appears when `gh` is installed but not logged in; running it, gh asks you to log in.
+
+@vjeux
diff --git a/docs/specs/AST-031/spec.md b/docs/specs/AST-031/spec.md
index b26eca0381..5f658a3a75 100644
--- a/docs/specs/AST-031/spec.md
+++ b/docs/specs/AST-031/spec.md
@@ -181,6 +181,10 @@ fail-closed guard MUST break a test.
the CLI offers to file via `gh issue create`. This fallback is consent-gated
(`public` audience). Any other `issuesUrl` scheme produces a `routed_only`
receipt. The fallback is suppressed entirely when at least one handler exists.
+ `astryx swizzle`'s receipt offers its `gh issue create` line when `gh` is on
+ PATH, whatever its login state. A logged-out `gh` asks for its own login when
+ the line runs. The text receipt shows the command; the JSON receipt keeps the
+ command and the issues URL.
- **FR9 — Project config field.** `astryx.config` gains a `gapReport` field
accepting a `GapReportHandler`. This is the project-level handler and runs
diff --git a/packages/cli/api/swizzle/_adapter.mjs b/packages/cli/api/swizzle/_adapter.mjs
index 082d0ac0e4..5417581393 100644
--- a/packages/cli/api/swizzle/_adapter.mjs
+++ b/packages/cli/api/swizzle/_adapter.mjs
@@ -8,14 +8,37 @@
* of swizzlable components: `list` returns the names directly, `copy` uses them
* for its "component not found" suggestions. Resolving core + listing lives
* here once so neither leaf re-walks the filesystem. Throws AstryxError
- * (ERR_CORE_NOT_FOUND) when core can't be located.
+ * (ERR_CORE_NOT_FOUND) when core can't be located. The copy receipt's `gh`
+ * lookup is here too, on the shared search-path walk.
*/
+import {executablesOnSearchPath} from '../../foundation/env/search-path.mjs';
import {findProjectCoreDir, listComponents} from '../../foundation/fs/paths.mjs';
import {resolveComponentReplacements} from '../../foundation/discovery/component-replacement.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {AstryxError} from '../error.mjs';
+/**
+ * Whether an executable `gh` is on `PATH` (with a `PATHEXT` extension on
+ * Windows), found without running it. The copy receipt offers its
+ * `gh issue create` line on it. Running `gh` would make every copy wait on a
+ * process start, and for `gh auth status` on GitHub, before it reports.
+ * @param {NodeJS.ProcessEnv} [env]
+ * @param {NodeJS.Platform} [platform]
+ * @returns {boolean}
+ */
+export function checkGhCli(env = process.env, platform = process.platform) {
+ const names =
+ platform === 'win32'
+ ? (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
+ .split(';')
+ .filter(Boolean)
+ .map(extension => `gh${extension.toLowerCase()}`)
+ : ['gh'];
+ const searchPath = env.PATH ?? env.Path ?? '';
+ return executablesOnSearchPath(names, {searchPath, platform}).length > 0;
+}
+
/** The package that owns Core's components, hooks, and codemods. */
export {CORE_PROVIDER_ID as CORE_PACKAGE} from '../../foundation/identity/providers.mjs';
diff --git a/packages/cli/api/swizzle/_adapter.test.mjs b/packages/cli/api/swizzle/_adapter.test.mjs
new file mode 100644
index 0000000000..dbd8a3af2d
--- /dev/null
+++ b/packages/cli/api/swizzle/_adapter.test.mjs
@@ -0,0 +1,130 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit tests for the swizzle adapter's `checkGhCli()`.
+ * @input temporary PATH folders; a `node:child_process` mock
+ * @output `checkGhCli` finds an executable `gh` on PATH, through the shared
+ * search-path walk, without running it. A swizzle never waits on a process
+ * start or on GitHub.
+ * @position Unit test of packages/cli/api/swizzle/_adapter.mjs
+ */
+
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {execFileSync, spawn, spawnSync} from 'node:child_process';
+import {checkGhCli} from './_adapter.mjs';
+
+vi.mock('node:fs', async importOriginal => {
+ const actual = await importOriginal();
+ return {...actual, statSync: vi.fn(actual.statSync)};
+});
+
+vi.mock('node:child_process', () => ({
+ execFileSync: vi.fn(),
+ spawn: vi.fn(),
+ spawnSync: vi.fn(),
+}));
+
+/** @type {string[]} */
+const dirs = [];
+afterEach(() => {
+ vi.clearAllMocks();
+ for (const dir of dirs.splice(0)) {
+ fs.rmSync(dir, {recursive: true, force: true});
+ }
+});
+
+/** A temporary directory, holding `files` with their modes. */
+function dirWith(/** @type {Record<string, number>} */ files) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-gh-path-'));
+ dirs.push(dir);
+ for (const [name, mode] of Object.entries(files)) {
+ fs.writeFileSync(path.join(dir, name), '');
+ fs.chmodSync(path.join(dir, name), mode);
+ }
+ return dir;
+}
+
+describe('checkGhCli', () => {
+ it('finds an executable gh on PATH, without running it', () => {
+ const empty = dirWith({});
+ const tools = dirWith({gh: 0o755});
+ const PATH = [empty, tools].join(path.delimiter);
+ expect(checkGhCli({PATH}, 'linux')).toBe(true);
+ expect(execFileSync).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ expect(spawnSync).not.toHaveBeenCalled();
+ });
+
+ it('does not count a gh that cannot be executed, or a directory named gh', () => {
+ const plain = dirWith({gh: 0o644});
+ const folder = dirWith({});
+ fs.mkdirSync(path.join(folder, 'gh'));
+ expect(
+ checkGhCli({PATH: [plain, folder].join(path.delimiter)}, 'linux'),
+ ).toBe(false);
+ });
+
+ it('is false with no gh on PATH, or no PATH', () => {
+ expect(checkGhCli({PATH: dirWith({git: 0o755})}, 'linux')).toBe(false);
+ expect(checkGhCli({}, 'linux')).toBe(false);
+ });
+
+ it('reads a PATH entry that does not exist, is a file, or cannot be searched as holding no gh', () => {
+ const missing = path.join(dirWith({}), 'missing');
+ const file = path.join(dirWith({tool: 0o644}), 'tool');
+ const locked = dirWith({gh: 0o755});
+ fs.chmodSync(locked, 0o000);
+ try {
+ expect(
+ checkGhCli(
+ {PATH: [missing, file, locked].join(path.delimiter)},
+ 'linux',
+ ),
+ ).toBe(process.getuid?.() === 0);
+ } finally {
+ fs.chmodSync(locked, 0o755);
+ }
+ });
+
+ it('reads a gh symlink loop, or a PATH entry too long to resolve, as no gh there', () => {
+ const looped = dirWith({});
+ fs.symlinkSync('gh', path.join(looped, 'gh'));
+ const tooLong = path.join(dirWith({}), 'x'.repeat(300));
+ expect(
+ checkGhCli({PATH: [looped, tooLong].join(path.delimiter)}, 'linux'),
+ ).toBe(false);
+ });
+
+ it('finds a working gh after a PATH entry on a stale or disconnected mount', () => {
+ const stale = dirWith({});
+ const tools = dirWith({gh: 0o755});
+ vi.mocked(fs.statSync).mockImplementationOnce(() => {
+ throw Object.assign(new Error('ESTALE: stale file handle, stat'), {
+ code: 'ESTALE',
+ });
+ });
+ expect(
+ checkGhCli({PATH: [stale, tools].join(path.delimiter)}, 'linux'),
+ ).toBe(true);
+ });
+
+ it('reads any error about a candidate as no gh there, and goes on', () => {
+ const odd = dirWith({});
+ const tools = dirWith({gh: 0o755});
+ vi.mocked(fs.statSync).mockImplementationOnce(() => {
+ throw new TypeError('not a path');
+ });
+ expect(checkGhCli({PATH: [odd, tools].join(path.delimiter)}, 'linux')).toBe(
+ true,
+ );
+ });
+
+ it('on Windows, finds gh with a PATHEXT extension', () => {
+ const tools = dirWith({'gh.exe': 0o644});
+ expect(checkGhCli({PATH: tools, PATHEXT: '.COM;.EXE'}, 'win32')).toBe(true);
+ expect(checkGhCli({PATH: tools, PATHEXT: '.CMD'}, 'win32')).toBe(false);
+ });
+});
diff --git a/packages/cli/api/swizzle/_github.mjs b/packages/cli/api/swizzle/_github.mjs
deleted file mode 100644
index f54a939e16..0000000000
--- a/packages/cli/api/swizzle/_github.mjs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file GitHub utilities for Astryx CLI
- *
- * Shared helpers for interacting with the GitHub CLI (`gh`).
- */
-
-import {execFileSync} from 'node:child_process';
-
-/**
- * Check if `gh` CLI is installed and authenticated.
- * Returns true if ready, false otherwise.
- */
-export function checkGhCli() {
- try {
- execFileSync('gh', ['auth', 'status'], {stdio: 'ignore'});
- return true;
- } catch {
- return false;
- }
-}
diff --git a/packages/cli/api/swizzle/_github.test.mjs b/packages/cli/api/swizzle/_github.test.mjs
deleted file mode 100644
index 555b6f3b5b..0000000000
--- a/packages/cli/api/swizzle/_github.test.mjs
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * Unit tests for `checkGhCli()` — the only export of utils/github.mjs.
- *
- * `checkGhCli` shells out to `gh auth status` via `execFileSync`. These tests
- * mock `node:child_process` so they never depend on `gh` being installed or
- * authenticated in CI, and assert both the success and failure contracts plus
- * the exact (non-shell, static-arg) invocation — the property that keeps this
- * helper injection-free.
- */
-
-import {describe, it, expect, vi, afterEach} from 'vitest';
-import {execFileSync} from 'node:child_process';
-import {checkGhCli} from './_github.mjs';
-
-vi.mock('node:child_process', () => ({execFileSync: vi.fn()}));
-
-afterEach(() => {
- vi.clearAllMocks();
-});
-
-describe('checkGhCli', () => {
- it('returns true when `gh auth status` succeeds', () => {
- vi.mocked(execFileSync).mockReturnValue(Buffer.from(''));
- expect(checkGhCli()).toBe(true);
- });
-
- it('invokes gh with a static, non-shell argument array (no injection surface)', () => {
- vi.mocked(execFileSync).mockReturnValue(Buffer.from(''));
- checkGhCli();
- expect(execFileSync).toHaveBeenCalledTimes(1);
- expect(execFileSync).toHaveBeenCalledWith('gh', ['auth', 'status'], {
- stdio: 'ignore',
- });
- });
-
- it('returns false when gh is missing or unauthenticated (throws)', () => {
- vi.mocked(execFileSync).mockImplementation(() => {
- throw new Error('command not found: gh');
- });
- expect(checkGhCli()).toBe(false);
- });
-
- it('swallows a non-zero exit (unauthenticated) and returns false', () => {
- vi.mocked(execFileSync).mockImplementation(() => {
- const err = new Error('gh: not logged in');
- /** @type {any} */ (err).status = 1;
- throw err;
- });
- expect(checkGhCli()).toBe(false);
- });
-});
diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs
index 2945c9c8c7..fb8cdc07d7 100644
--- a/packages/cli/api/swizzle/copy/copy.mjs
+++ b/packages/cli/api/swizzle/copy/copy.mjs
@@ -15,9 +15,12 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {resolveComponentReplacement, resolveCore} from '../_adapter.mjs';
+import {
+ checkGhCli,
+ resolveComponentReplacement,
+ resolveCore,
+} from '../_adapter.mjs';
import {assertWithin, sanitizeName, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
-import {checkGhCli} from '../_github.mjs';
import {Project} from '../../../foundation/config/project.mjs';
import {
CORE_PACKAGE,
@@ -299,6 +302,10 @@ export async function swizzleCopy(component, options = {}) {
const outputBase = confineWrite(output, cwd, {label: 'output directory'});
const outputDir = path.join(outputBase, dirName);
+ // The receipt's feedback first: a swizzle that fails must fail before it
+ // writes anything.
+ const feedback = buildFeedback(dirName, owner.issuesUrl);
+
// Pre-flight path and overwrite checks before any mkdir/writeFile.
const sourceFiles = fs.readdirSync(componentDir).filter(file => {
if (isExcludedFromCopy(file)) return false;
@@ -380,8 +387,6 @@ export async function swizzleCopy(component, options = {}) {
!isExcludedFromCopy(f) &&
fs.statSync(path.join(componentDir, f)).isFile(),
);
- const feedback = buildFeedback(dirName, owner.issuesUrl);
-
/** @type {import('../swizzle.type.mjs').SwizzleCopyResponse['data']} */
const data = {
component: dirName,
diff --git a/packages/cli/api/swizzle/copy/copy.test.mjs b/packages/cli/api/swizzle/copy/copy.test.mjs
index f362d876a6..86bb9060e7 100644
--- a/packages/cli/api/swizzle/copy/copy.test.mjs
+++ b/packages/cli/api/swizzle/copy/copy.test.mjs
@@ -6,12 +6,28 @@
* becomes a path segment) must both be confined to cwd.
*/
-import {describe, it, expect, afterEach} from 'vitest';
+import {describe, it, expect, afterEach, vi} from 'vitest';
import * as fs from 'node:fs';
+import * as os from 'node:os';
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
import {swizzle} from '../swizzle.mjs';
+/** Set by a test to make the gh lookup throw an error it does not expect. */
+let ghLookupFails = false;
+vi.mock('../_adapter.mjs', async importOriginal => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ checkGhCli: (...args) => {
+ if (ghLookupFails) {
+ throw new TypeError('the gh lookup failed');
+ }
+ return actual.checkGhCli(...args);
+ },
+ };
+});
+
// api/swizzle/copy/ -> up 5 = repo root.
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../..');
const OUT = 'tmp-swizzle-copy-test';
@@ -58,3 +74,69 @@ describe('swizzle.copy — path safety', () => {
expect(r2.data.filesCopied).toBe(r.data.filesCopied);
}, SLOW);
});
+
+describe('swizzle.copy — the gh feedback line', () => {
+ afterEach(() => {
+ ghLookupFails = false;
+ fs.rmSync(path.join(REPO, OUT), {recursive: true, force: true});
+ });
+
+ it(
+ 'returns its receipt, without the gh line, when the only gh on PATH is a symlink loop',
+ async () => {
+ const bin = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-swizzle-gh-loop-'),
+ );
+ fs.symlinkSync('gh', path.join(bin, 'gh'));
+ const original = process.env.PATH;
+ process.env.PATH = bin;
+ try {
+ const r = await swizzle('Button', {cwd: REPO, output: './' + OUT});
+ expect(r.type).toBe('swizzle.copy');
+ expect(r.data.filesCopied).toBeGreaterThan(0);
+ expect(r.data.feedback?.ghCommand).toBeUndefined();
+ } finally {
+ process.env.PATH = original;
+ fs.rmSync(bin, {recursive: true, force: true});
+ }
+ },
+ SLOW,
+ );
+
+ it(
+ 'fails before writing anything when the gh lookup throws',
+ async () => {
+ ghLookupFails = true;
+ await expect(
+ swizzle('Button', {cwd: REPO, output: './' + OUT}),
+ ).rejects.toThrow(/the gh lookup failed/);
+ expect(fs.existsSync(path.join(REPO, OUT))).toBe(false);
+ },
+ SLOW,
+ );
+
+ it(
+ 'offers the gh command when gh is on PATH, without running gh',
+ async () => {
+ // A gh that records each run: a swizzle must not wait on it.
+ const bin = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-swizzle-gh-'));
+ const ran = path.join(bin, 'ran');
+ fs.writeFileSync(
+ path.join(bin, 'gh'),
+ `#!/bin/sh\necho run >> ${JSON.stringify(ran)}\nexit 0\n`,
+ );
+ fs.chmodSync(path.join(bin, 'gh'), 0o755);
+ const original = process.env.PATH;
+ process.env.PATH = [bin, original].join(path.delimiter);
+ try {
+ const r = await swizzle('Button', {cwd: REPO, output: './' + OUT});
+ expect(r.data.feedback?.ghCommand).toMatch(/^gh issue create --repo /);
+ expect(fs.existsSync(ran)).toBe(false);
+ } finally {
+ process.env.PATH = original;
+ fs.rmSync(bin, {recursive: true, force: true});
+ }
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 786616b0cf..d1469e1407 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -56,10 +56,6 @@ const RUNNERS = {
runs: "`npm pack`, `tar`, and a Node script that resolves the packed specifiers, to check a package as published, and the package's doc modules, to see which need a newer CLI",
sites: ['child_process.spawnSync ×3', 'loadTopicModule'],
},
- 'api/swizzle/_github.mjs': {
- runs: '`gh auth status`, to check the GitHub CLI is signed in',
- sites: ['child_process.execFileSync'],
- },
'api/theme/_adapter.mjs': {
runs: 'recorded built theme modules through the shared app-theme loader',
sites: ['importThemeArtifact'],
diff --git a/packages/cli/foundation/env/search-path.mjs b/packages/cli/foundation/env/search-path.mjs
index 02930d0fce..54fe3100b4 100644
--- a/packages/cli/foundation/env/search-path.mjs
+++ b/packages/cli/foundation/env/search-path.mjs
@@ -13,9 +13,10 @@
* package folder is read from the shim's text.
*
* @input the search path and, on Windows, its executable names
- * @output one row per `astryx` command found
- * @position packages/cli/foundation/env — read by doctor, init --user, and
- * the update notices.
+ * @output one row per `astryx` command found, and the executable files that
+ * any command name finds there
+ * @position packages/cli/foundation/env — read by doctor, init --user, the
+ * update notices, and swizzle's `gh` lookup.
*/
import * as fs from 'node:fs';
@@ -146,6 +147,53 @@ function namesCliPackage(file) {
}
}
+/**
+ * Whether `file` is a file this user may run. On Windows, any file counts.
+ * @param {string} file
+ * @param {boolean} windows
+ * @returns {boolean}
+ */
+function isRunnableFile(file, windows) {
+ try {
+ if (!fs.statSync(file).isFile()) return false;
+ if (!windows) fs.accessSync(file, fs.constants.X_OK);
+ return true;
+ } catch {
+ // The shell skips a candidate the system cannot read: a missing folder, a
+ // stale mount, a symlink loop. `which` and execvp read PATH the same way.
+ return false;
+ }
+}
+
+/**
+ * The executable files on the search path named one of `names`, in the order
+ * a shell tries them. In each folder, it takes the first name that is a file
+ * this user may run. Nothing is started.
+ * @param {readonly string[]} names
+ * @param {{searchPath?: string, platform?: NodeJS.Platform}} [options]
+ * @returns {string[]}
+ */
+export function executablesOnSearchPath(
+ names,
+ {
+ searchPath = process.env.PATH ?? process.env.Path ?? '',
+ platform = process.platform,
+ } = {},
+) {
+ const windows = platform === 'win32';
+ /** @type {string[]} */
+ const files = [];
+ for (const dir of searchPath.split(windows ? ';' : path.delimiter)) {
+ if (!dir) continue;
+ // One command per folder: the shell runs the first name it finds.
+ const file = names
+ .map(name => path.join(dir, name))
+ .find(candidate => isRunnableFile(candidate, windows));
+ if (file !== undefined) files.push(file);
+ }
+ return files;
+}
+
/**
* Every `astryx` command on the search path, in the order a shell tries
* them. The first row is the one that runs.
@@ -156,50 +204,30 @@ export function astryxCommandsOnSearchPath({
searchPath = process.env.PATH ?? process.env.Path ?? '',
platform = process.platform,
} = {}) {
- const windows = platform === 'win32';
- const names = windows
- ? ['astryx.cmd', 'astryx.exe', 'astryx.ps1', 'astryx']
- : [COMMAND];
+ const names =
+ platform === 'win32'
+ ? ['astryx.cmd', 'astryx.exe', 'astryx.ps1', 'astryx']
+ : [COMMAND];
/** @type {SearchPathCommand[]} */
const rows = [];
const seen = new Set();
- for (const dir of searchPath.split(windows ? ';' : path.delimiter)) {
- if (!dir) continue;
- for (const name of names) {
- const file = path.join(dir, name);
- let stat;
- try {
- stat = fs.statSync(file);
- } catch {
- continue;
- }
- if (!stat.isFile()) continue;
- if (!windows) {
- try {
- fs.accessSync(file, fs.constants.X_OK);
- } catch {
- continue;
- }
- }
- let key = file;
- try {
- key = fs.realpathSync(file);
- } catch {
- // Keep the path as found.
- }
- if (seen.has(key)) break;
- seen.add(key);
- const cliRoot = astryxCliRootOf(file);
- rows.push({
- file,
- astryx: cliRoot !== null || namesCliPackage(file),
- cliRoot,
- version: cliRoot ? cliVersionAt(cliRoot) : null,
- handsOff: cliRoot ? handsOffAt(cliRoot) : null,
- });
- // One command per folder: the shell runs the first name it finds.
- break;
+ for (const file of executablesOnSearchPath(names, {searchPath, platform})) {
+ let key = file;
+ try {
+ key = fs.realpathSync(file);
+ } catch {
+ // Keep the path as found.
}
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const cliRoot = astryxCliRootOf(file);
+ rows.push({
+ file,
+ astryx: cliRoot !== null || namesCliPackage(file),
+ cliRoot,
+ version: cliRoot ? cliVersionAt(cliRoot) : null,
+ handsOff: cliRoot ? handsOffAt(cliRoot) : null,
+ });
}
return rows;
}
diff --git a/packages/cli/foundation/env/search-path.test.mjs b/packages/cli/foundation/env/search-path.test.mjs
index 0d4cbcef40..a1e6634172 100644
--- a/packages/cli/foundation/env/search-path.test.mjs
+++ b/packages/cli/foundation/env/search-path.test.mjs
@@ -3,13 +3,17 @@
/**
* @file Reading the `astryx` commands on the search path (spec AST-081
* FR11): links, and each package manager's shim, down to the CLI package and
- * its version.
+ * its version. Also the walk every command name takes along the search path.
*/
import {afterEach, describe, expect, it} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {astryxCommandsOnSearchPath, astryxCliRootOf} from './search-path.mjs';
+import {
+ astryxCommandsOnSearchPath,
+ astryxCliRootOf,
+ executablesOnSearchPath,
+} from './search-path.mjs';
import {
cleanupFixtures,
tempDir,
@@ -120,3 +124,34 @@ describe.skipIf(process.platform === 'win32')('astryxCliRootOf', () => {
).toMatchObject({version: '0.8.0', handsOff: true});
});
});
+
+describe.skipIf(process.platform === 'win32')('executablesOnSearchPath', () => {
+ it("finds each folder's first runnable name, in search-path order", () => {
+ const first = tempDir('walk');
+ shim(path.join(first, 'tool'), '');
+ const second = tempDir('walk');
+ shim(path.join(second, 'tool.cmd'), '');
+ shim(path.join(second, 'tool'), '');
+ expect(
+ executablesOnSearchPath(['tool.cmd', 'tool'], {
+ searchPath: [first, second].join(path.delimiter),
+ platform: 'linux',
+ }),
+ ).toEqual([path.join(first, 'tool'), path.join(second, 'tool.cmd')]);
+ });
+
+ it('skips a file this user may not run, a directory, and a missing folder', () => {
+ const plain = tempDir('walk');
+ fs.writeFileSync(path.join(plain, 'tool'), '');
+ fs.chmodSync(path.join(plain, 'tool'), 0o644);
+ const folder = tempDir('walk');
+ fs.mkdirSync(path.join(folder, 'tool'));
+ const missing = path.join(tempDir('walk'), 'missing');
+ expect(
+ executablesOnSearchPath(['tool'], {
+ searchPath: ['', plain, folder, missing].join(path.delimiter),
+ platform: 'linux',
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjs
index 18de745ace..5b0f5b6d48 100644
--- a/scripts/check-cli-structure.mjs
+++ b/scripts/check-cli-structure.mjs
@@ -484,8 +484,6 @@ const INV21_KNOWN_GAPS = new Map([
['integration/validate-integration.mjs', new Set(['fs', 'discovery'])],
// remove with the layout command
['layout/expand/expand.mjs', new Set(['fs'])],
- // imported by a leaf (copy), not only by the adapter
- ['swizzle/_github.mjs', new Set(['child_process'])],
['swizzle/copy/copy.mjs', new Set(['fs', 'project', 'discovery'])],
['template/cdn/cdn.mjs', new Set(['fs'])],
['template/copy/copy.mjs', new Set(['fs', 'discovery'])],