Files
shakespeare/src/lib/commands/which.ts
T
Alex Gleason 376a982449 Overhaul shell commands for POSIX compliance and AI-agent ergonomics
Each built-in shell command has been audited and rewritten to support the
options AI agents (and humans) typically reach for, close critical behavior
gaps, and align with POSIX/GNU conventions:

- Shared argument parser (utils.ts) handles combined short flags, long
  options with '=VALUE' or space-separated values, the '--' sentinel,
  numeric shortcuts like 'head -5', and '-' for stdin.
- cat, ls, cp, mv, rm, mkdir, touch: added missing common flags; removed
  the legacy 'absolute paths are not supported' and 'reading from stdin
  is not supported' barriers where they made agent use awkward.
- mv now overwrites destinations by default (POSIX) and supports -n.
- touch updates mtime on existing files (by rewriting content) and
  accepts -c/-a/-m/-h/-r/-d/-t options.
- find: new expression engine with -iname, -path, -regex, -type,
  -empty, -size, -maxdepth, -mindepth, -not, -or, -print/-print0,
  -delete, -quit.
- grep: -v, -c, -l, -L, -w, -x, -o, -q, -E, -F, -G, -H, -h, -A/-B/-C
  context, --include/--exclude, multiple -e, -f scriptfile.
- head/tail: -c bytes, -NUM shorthand, negative/positive line counts,
  proper multi-file headers.
- sort: -k keys, -t separator, -o output, -f/-b/-d/-s, -h/-V/-M modes.
- uniq: -i, -f, -s, -w, -D, and the [input [output]] form.
- wc: -m characters and -L longest line; -c now counts bytes (UTF-8).
- cut: open-ended ranges (3-, -5), -s, --complement, --output-delimiter.
- tr: -c/-s/-t, [:class:] character classes, escape sequences.
- sed: real multi-command parser supporting ';', addresses (N, $,
  /re/, N,M), '!' negation, proper -n quiet mode, y///, and -i[SUFFIX].
- echo: -n, -e, -E with standard backslash escapes.
- pwd/cd: -L/-P, plus cd -, cd ~, cd $HOME with OLDPWD tracking.
- diff: proper LCS algorithm producing correct normal and unified
  output; adds -q, -s, -N, -i, -w, -b, -B.
- env: -i, -u, NAME=VAL assignments; reads the live shell environment.
- date: -u, -d, -R, -I, and a full GNU-subset format specifier set.

Tests for each command were updated to reflect the corrected behavior
(e.g. absolute paths and stdin are now accepted, POSIX error messages).
All 1334 tests pass; typecheck and production build succeed.
2026-04-26 23:58:13 -05:00

60 lines
1.8 KiB
TypeScript

import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { parseOptions } from "./utils";
/**
* Implementation of the 'which' command.
*
* Supported options:
* -a Print all matching pathnames (only ever one per name in our registry)
* -s Silent mode — no output, only exit status
* -- End of options
*/
export class WhichCommand implements ShellCommand {
name = 'which';
description = 'Locate a command';
usage = 'which [-as] [--] command...';
private commands: Map<string, ShellCommand>;
constructor(commands: Map<string, ShellCommand>) {
this.commands = commands;
}
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
const parsed = parseOptions(args, {
booleanShort: ['a', 's'],
});
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
}
if (parsed.operands.length === 0) {
return createErrorResult(`${this.name}: missing operand`);
}
const silent = parsed.flags.has('s');
const results: string[] = [];
let hasError = false;
for (const commandName of parsed.operands) {
if (this.commands.has(commandName)) {
results.push(`/usr/bin/${commandName}`);
} else {
if (!silent) results.push(`${this.name}: no ${commandName} in (/usr/bin)`);
hasError = true;
}
}
if (silent) {
return hasError
? { exitCode: 1, stdout: '', stderr: '' }
: createSuccessResult('');
}
const output = results.join('\n') + (results.length > 0 ? '\n' : '');
return hasError ? createErrorResult(output, 1) : createSuccessResult(output);
}
}