init project
This commit is contained in:
+74
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env node
|
||||
import process from 'node:process';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {parseArgs} from 'node:util';
|
||||
import {whichCommand, whichCommandAll} from './index.js';
|
||||
|
||||
const help = `
|
||||
Usage
|
||||
$ which-command <command> …
|
||||
|
||||
Options
|
||||
--all, -a List all matching paths, not just the first
|
||||
--silent, -s Suppress output; the exit code still reflects whether all commands were found
|
||||
|
||||
Examples
|
||||
$ which-command node
|
||||
/usr/local/bin/node
|
||||
|
||||
$ which-command --all node
|
||||
/usr/local/bin/node
|
||||
/opt/homebrew/bin/node
|
||||
|
||||
Exits with code 1 if any of the commands could not be found.
|
||||
`;
|
||||
|
||||
let flags;
|
||||
let commands;
|
||||
try {
|
||||
({values: flags, positionals: commands} = parseArgs({
|
||||
allowPositionals: true,
|
||||
options: {
|
||||
all: {type: 'boolean', short: 'a', default: false},
|
||||
silent: {type: 'boolean', short: 's', default: false},
|
||||
help: {type: 'boolean', short: 'h', default: false},
|
||||
version: {type: 'boolean', default: false},
|
||||
},
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (flags.version) {
|
||||
const {version} = JSON.parse(readFileSync(new URL('package.json', import.meta.url), 'utf8'));
|
||||
console.log(version);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (flags.help) {
|
||||
console.log(help);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (commands.length === 0) {
|
||||
console.error(help);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let allFound = true;
|
||||
for (const command of commands) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const paths = flags.all ? await whichCommandAll(command) : [await whichCommand(command)].filter(Boolean);
|
||||
|
||||
if (paths.length === 0) {
|
||||
allFound = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!flags.silent) {
|
||||
console.log(paths.join('\n'));
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(allFound ? 0 : 1);
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
export type Options = {
|
||||
/**
|
||||
The directory to resolve relative paths against.
|
||||
|
||||
Relative `path` entries and commands that contain a directory separator are resolved against this. On Windows, this directory is also searched before `PATH`.
|
||||
|
||||
@default process.cwd()
|
||||
*/
|
||||
readonly cwd?: string;
|
||||
|
||||
/**
|
||||
The `PATH` to search.
|
||||
|
||||
Empty entries are ignored. Unlike a POSIX shell, an empty entry is not treated as the current directory, since implicitly searching the current directory is a security risk.
|
||||
|
||||
@default process.env.PATH
|
||||
*/
|
||||
readonly path?: string;
|
||||
|
||||
/**
|
||||
The executable file extensions to look for, as a `;`-separated string.
|
||||
|
||||
Only used on Windows. Corresponds to the `PATHEXT` environment variable.
|
||||
|
||||
@default process.env.PATHEXT
|
||||
*/
|
||||
readonly pathExt?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
Find the absolute path to a command's executable, like the Unix `which` command.
|
||||
|
||||
@param command - The command name to look for, or a path to check directly. If it contains a directory separator (like `./foo` or `/usr/bin/foo`), it's resolved directly instead of being searched for in `PATH`.
|
||||
@returns The absolute path to the first matching executable, or `undefined` if not found.
|
||||
|
||||
@example
|
||||
```
|
||||
import {whichCommand} from 'which-command';
|
||||
|
||||
await whichCommand('node');
|
||||
//=> '/usr/local/bin/node'
|
||||
|
||||
await whichCommand('does-not-exist');
|
||||
//=> undefined
|
||||
```
|
||||
*/
|
||||
export function whichCommand(command: string, options?: Options): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
Find the absolute path to a command's executable, like the Unix `which` command.
|
||||
|
||||
Same as {@link whichCommand}, but synchronous.
|
||||
|
||||
@param command - The command name to look for, or a path to check directly. If it contains a directory separator (like `./foo` or `/usr/bin/foo`), it's resolved directly instead of being searched for in `PATH`.
|
||||
@returns The absolute path to the first matching executable, or `undefined` if not found.
|
||||
|
||||
@example
|
||||
```
|
||||
import {whichCommandSync} from 'which-command';
|
||||
|
||||
whichCommandSync('node');
|
||||
//=> '/usr/local/bin/node'
|
||||
```
|
||||
*/
|
||||
export function whichCommandSync(command: string, options?: Options): string | undefined;
|
||||
|
||||
/**
|
||||
Find the absolute paths to all of a command's executables in `PATH` order, like `which -a`.
|
||||
|
||||
@param command - The command name to look for, or a path to check directly. If it contains a directory separator (like `./foo` or `/usr/bin/foo`), it's resolved directly instead of being searched for in `PATH`.
|
||||
@returns An array of the absolute paths to all matching executables in `PATH` order, or an empty array if none are found.
|
||||
|
||||
@example
|
||||
```
|
||||
import {whichCommandAll} from 'which-command';
|
||||
|
||||
await whichCommandAll('node');
|
||||
//=> ['/usr/local/bin/node', '/opt/homebrew/bin/node']
|
||||
```
|
||||
*/
|
||||
export function whichCommandAll(command: string, options?: Options): Promise<string[]>;
|
||||
|
||||
/**
|
||||
Find the absolute paths to all of a command's executables in `PATH` order, like `which -a`.
|
||||
|
||||
Same as {@link whichCommandAll}, but synchronous.
|
||||
|
||||
@param command - The command name to look for, or a path to check directly. If it contains a directory separator (like `./foo` or `/usr/bin/foo`), it's resolved directly instead of being searched for in `PATH`.
|
||||
@returns An array of the absolute paths to all matching executables in `PATH` order, or an empty array if none are found.
|
||||
|
||||
@example
|
||||
```
|
||||
import {whichCommandAllSync} from 'which-command';
|
||||
|
||||
whichCommandAllSync('node');
|
||||
//=> ['/usr/local/bin/node', '/opt/homebrew/bin/node']
|
||||
```
|
||||
*/
|
||||
export function whichCommandAllSync(command: string, options?: Options): string[];
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
import fs from 'node:fs';
|
||||
import fsPromises from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
|
||||
const isWindows = process.platform === 'win32';
|
||||
|
||||
// A command containing a directory separator is treated as a path and looked up directly, instead of being searched for in `PATH`. Backslash only counts as a separator on Windows, since it's a valid filename character on other platforms.
|
||||
const separatorPattern = isWindows ? /[\/\\]/v : /\//v;
|
||||
|
||||
// The standard Windows executable extensions, used when `PATHEXT` is not set.
|
||||
const defaultPathExt = '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC';
|
||||
|
||||
function resolveOptions(command, options) {
|
||||
if (typeof command !== 'string' || command.length === 0) {
|
||||
throw new TypeError('Expected a non-empty string.');
|
||||
}
|
||||
|
||||
const {
|
||||
cwd = process.cwd(),
|
||||
// On Windows, `process.env.PATH` can be undefined in some contexts (for example, worker threads), where it's only exposed as `Path`.
|
||||
path: searchPath = process.env.PATH ?? (isWindows ? process.env.Path : undefined) ?? '',
|
||||
// `||` (not `??`) so an empty `PATHEXT` falls back to the default instead of disabling all lookup on Windows.
|
||||
pathExt = process.env.PATHEXT || defaultPathExt,
|
||||
} = options;
|
||||
|
||||
return {cwd, searchPath, pathExt};
|
||||
}
|
||||
|
||||
function windowsExtensions(command, pathExt) {
|
||||
const extensions = pathExt.split(path.delimiter).filter(Boolean);
|
||||
const commandExtension = path.extname(command).toLowerCase();
|
||||
|
||||
// If the command already ends with a known executable extension, also try it verbatim.
|
||||
if (commandExtension !== '' && extensions.some(extension => extension.toLowerCase() === commandExtension)) {
|
||||
return ['', ...extensions];
|
||||
}
|
||||
|
||||
return extensions;
|
||||
}
|
||||
|
||||
function * candidatePaths(command, {cwd, searchPath, pathExt}) {
|
||||
const extensions = isWindows ? windowsExtensions(command, pathExt) : [''];
|
||||
|
||||
if (separatorPattern.test(command)) {
|
||||
const base = path.resolve(cwd, command);
|
||||
for (const extension of extensions) {
|
||||
yield base + extension;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const directories = [
|
||||
// Windows searches the current directory before `PATH`.
|
||||
...(isWindows ? [cwd] : []),
|
||||
...searchPath.split(path.delimiter),
|
||||
];
|
||||
|
||||
for (const directory of directories) {
|
||||
// `PATH` entries can be wrapped in double quotes on Windows.
|
||||
const unquoted = isWindows && directory.length > 1 && directory.startsWith('"') && directory.endsWith('"') ? directory.slice(1, -1) : directory;
|
||||
|
||||
// Skip empty entries. Unlike a POSIX shell, an empty entry is not treated as the current directory, since implicitly searching the current directory is a security risk. Checked after unquoting so a quoted-empty entry (`""`) is skipped too.
|
||||
if (unquoted === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const base = path.resolve(cwd, unquoted, command);
|
||||
for (const extension of extensions) {
|
||||
yield base + extension;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function isExecutable(filePath) {
|
||||
let stats;
|
||||
try {
|
||||
stats = await fsPromises.stat(filePath);
|
||||
} catch (error) {
|
||||
// Windows App Execution Aliases (in `WindowsApps`) throw `EACCES` on `stat`, but are valid, launchable executables.
|
||||
return isWindows && error.code === 'EACCES';
|
||||
}
|
||||
|
||||
// A directory can have the executable bit set, but it's not a command.
|
||||
if (!stats.isFile()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// On Windows, executability is determined by the file extension, which is already validated against `PATHEXT`.
|
||||
if (isWindows) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
await fsPromises.access(filePath, fs.constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isExecutableSync(filePath) {
|
||||
let stats;
|
||||
try {
|
||||
stats = fs.statSync(filePath);
|
||||
} catch (error) {
|
||||
return isWindows && error.code === 'EACCES';
|
||||
}
|
||||
|
||||
if (!stats.isFile()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isWindows) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
fs.accessSync(filePath, fs.constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function whichCommand(command, options = {}) {
|
||||
const resolved = resolveOptions(command, options);
|
||||
|
||||
for (const candidate of candidatePaths(command, resolved)) {
|
||||
// Checked sequentially so the first match in `PATH` order wins and the search can short-circuit.
|
||||
if (await isExecutable(candidate)) { // eslint-disable-line no-await-in-loop
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function whichCommandSync(command, options = {}) {
|
||||
const resolved = resolveOptions(command, options);
|
||||
|
||||
for (const candidate of candidatePaths(command, resolved)) {
|
||||
if (isExecutableSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function whichCommandAll(command, options = {}) {
|
||||
const resolved = resolveOptions(command, options);
|
||||
const candidates = [...candidatePaths(command, resolved)];
|
||||
const matches = await Promise.all(candidates.map(async candidate => (await isExecutable(candidate)) ? candidate : undefined));
|
||||
return [...new Set(matches.filter(Boolean))];
|
||||
}
|
||||
|
||||
export function whichCommandAllSync(command, options = {}) {
|
||||
const resolved = resolveOptions(command, options);
|
||||
const found = [];
|
||||
|
||||
for (const candidate of candidatePaths(command, resolved)) {
|
||||
if (isExecutableSync(candidate)) {
|
||||
found.push(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return [...new Set(found)];
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "which-command",
|
||||
"version": "0.1.0",
|
||||
"description": "Find the absolute path to a command's executable, like the Unix `which` command",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/which-command",
|
||||
"funding": "https://github.com/sindresorhus/which-command?sponsor=1",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "https://sindresorhus.com"
|
||||
},
|
||||
"type": "module",
|
||||
"bin": "./cli.js",
|
||||
"exports": {
|
||||
"types": "./index.d.ts",
|
||||
"default": "./index.js"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && node --test"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts",
|
||||
"cli.js"
|
||||
],
|
||||
"keywords": [
|
||||
"which",
|
||||
"where",
|
||||
"command",
|
||||
"executable",
|
||||
"binary",
|
||||
"path",
|
||||
"find",
|
||||
"locate",
|
||||
"resolve",
|
||||
"lookup",
|
||||
"unix",
|
||||
"cli",
|
||||
"bin"
|
||||
],
|
||||
"devDependencies": {
|
||||
"xo": "^3.0.2"
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
# which-command
|
||||
|
||||
> Find the absolute path to a command's executable, like the Unix [`which`](https://en.wikipedia.org/wiki/Which_(command)) command
|
||||
|
||||
Useful for locating an executable in `PATH` before spawning it, checking whether a tool is installed, or building your own CLI tooling.
|
||||
|
||||
Works cross-platform, including Windows `PATHEXT` handling and App Execution Aliases.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
npm install which-command
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import {whichCommand, whichCommandSync, whichCommandAll} from 'which-command';
|
||||
|
||||
await whichCommand('node');
|
||||
//=> '/usr/local/bin/node'
|
||||
|
||||
await whichCommand('does-not-exist');
|
||||
//=> undefined
|
||||
|
||||
whichCommandSync('node');
|
||||
//=> '/usr/local/bin/node'
|
||||
|
||||
await whichCommandAll('node');
|
||||
//=> ['/usr/local/bin/node', '/opt/homebrew/bin/node']
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### whichCommand(command, options?)
|
||||
|
||||
Returns a `Promise` for the absolute path to the first matching executable, or `undefined` if not found.
|
||||
|
||||
### whichCommandSync(command, options?)
|
||||
|
||||
Same as `whichCommand()`, but synchronous.
|
||||
|
||||
### whichCommandAll(command, options?)
|
||||
|
||||
Returns a `Promise` for an array of the absolute paths to all matching executables in `PATH` order, or an empty array if none are found. Like `which -a`.
|
||||
|
||||
### whichCommandAllSync(command, options?)
|
||||
|
||||
Same as `whichCommandAll()`, but synchronous.
|
||||
|
||||
#### command
|
||||
|
||||
Type: `string`
|
||||
|
||||
The command name to look for, or a path to check directly.
|
||||
|
||||
If it contains a directory separator (like `./foo` or `/usr/bin/foo`), it's resolved directly instead of being searched for in `PATH`.
|
||||
|
||||
#### options
|
||||
|
||||
Type: `object`
|
||||
|
||||
##### cwd
|
||||
|
||||
Type: `string`\
|
||||
Default: [`process.cwd()`](https://nodejs.org/api/process.html#processcwd)
|
||||
|
||||
The directory to resolve relative paths against.
|
||||
|
||||
Relative `path` entries and commands that contain a directory separator are resolved against this. On Windows, this directory is also searched before `PATH`.
|
||||
|
||||
##### path
|
||||
|
||||
Type: `string`\
|
||||
Default: [`process.env.PATH`](https://en.wikipedia.org/wiki/PATH_(variable))
|
||||
|
||||
The `PATH` to search.
|
||||
|
||||
Empty entries are ignored. Unlike a POSIX shell, an empty entry is not treated as the current directory, since implicitly searching the current directory is a security risk.
|
||||
|
||||
##### pathExt
|
||||
|
||||
Type: `string`\
|
||||
Default: `process.env.PATHEXT`
|
||||
|
||||
The executable file extensions to look for, as a `;`-separated string.
|
||||
|
||||
Only used on Windows. Corresponds to the [`PATHEXT`](https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee537574(v=office.14)) environment variable.
|
||||
|
||||
## CLI
|
||||
|
||||
```sh
|
||||
$ npx which-command --help
|
||||
|
||||
Usage
|
||||
$ which-command <command> …
|
||||
|
||||
Options
|
||||
--all, -a List all matching paths, not just the first
|
||||
--silent, -s Suppress output; the exit code still reflects whether all commands were found
|
||||
|
||||
Examples
|
||||
$ which-command node
|
||||
/usr/local/bin/node
|
||||
|
||||
$ which-command --all node
|
||||
/usr/local/bin/node
|
||||
/opt/homebrew/bin/node
|
||||
|
||||
Exits with code 1 if any of the commands could not be found.
|
||||
```
|
||||
|
||||
## FAQ
|
||||
|
||||
### How is it better than the [`which`](https://github.com/npm/node-which) package?
|
||||
|
||||
- Returns `undefined` when a command is not found, instead of throwing.
|
||||
- `whichCommandAll()` deduplicates results, so duplicate `PATH` entries don't produce duplicate matches.
|
||||
- Safer by default: empty `PATH` entries are ignored instead of implicitly searching the current directory.
|
||||
- Finds Windows App Execution Aliases (like the `python` and `winget` stubs in `WindowsApps`), which `which` skips.
|
||||
- Modern: pure ESM with bundled TypeScript types.
|
||||
Reference in New Issue
Block a user