mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
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.
130 lines
4.4 KiB
TypeScript
130 lines
4.4 KiB
TypeScript
import { dirname } from "path-browserify";
|
|
import type { JSRuntimeFS } from "../JSRuntime";
|
|
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
|
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
|
import { validateWritePath } from "../security";
|
|
import { classifyFsError, parseOptions, resolvePath } from "./utils";
|
|
|
|
/**
|
|
* Implementation of the 'mkdir' command.
|
|
*
|
|
* Supported options:
|
|
* -p, --parents Create parent directories as needed; no error if existing
|
|
* -v, --verbose Print a message for each created directory
|
|
* -m, --mode Set file mode (accepted but ignored — VFS has no mode)
|
|
* -- End of options
|
|
*/
|
|
export class MkdirCommand implements ShellCommand {
|
|
name = 'mkdir';
|
|
description = 'Create directories';
|
|
usage = 'mkdir [-pv] [-m mode] [--] directory...';
|
|
|
|
private fs: JSRuntimeFS;
|
|
|
|
constructor(fs: JSRuntimeFS) {
|
|
this.fs = fs;
|
|
}
|
|
|
|
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
|
|
const parsed = parseOptions(args, {
|
|
booleanShort: ['p', 'v'],
|
|
valueShort: ['m'],
|
|
booleanLong: ['parents', 'verbose'],
|
|
valueLong: ['mode'],
|
|
longToShort: { parents: 'p', verbose: 'v', mode: 'm' },
|
|
});
|
|
|
|
if (parsed.unknown.length > 0) {
|
|
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
|
|
}
|
|
|
|
const opts = {
|
|
parents: parsed.flags.has('p'),
|
|
verbose: parsed.flags.has('v'),
|
|
};
|
|
|
|
const directories = parsed.operands;
|
|
if (directories.length === 0) {
|
|
return createErrorResult(`${this.name}: missing operand\nUsage: ${this.usage}`);
|
|
}
|
|
|
|
const verboseOut: string[] = [];
|
|
|
|
for (const dirPath of directories) {
|
|
try {
|
|
validateWritePath(dirPath, this.name, cwd);
|
|
} catch (error) {
|
|
return createErrorResult(error instanceof Error ? error.message : 'Unknown error');
|
|
}
|
|
|
|
const absolutePath = resolvePath(dirPath, cwd);
|
|
|
|
if (opts.parents) {
|
|
try {
|
|
await this.createRecursive(absolutePath, verboseOut, opts.verbose);
|
|
} catch (error) {
|
|
const { message } = classifyFsError(error);
|
|
return createErrorResult(`${this.name}: cannot create directory '${dirPath}': ${message}`);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
// Without -p: error if exists or parent missing.
|
|
try {
|
|
await this.fs.stat(absolutePath);
|
|
return createErrorResult(`${this.name}: cannot create directory '${dirPath}': File exists`);
|
|
} catch (error) {
|
|
const { kind } = classifyFsError(error);
|
|
if (kind !== 'ENOENT') {
|
|
return createErrorResult(`${this.name}: ${dirPath}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
}
|
|
}
|
|
|
|
const parentDir = dirname(absolutePath);
|
|
try {
|
|
const parentStats = await this.fs.stat(parentDir);
|
|
if (!parentStats.isDirectory()) {
|
|
return createErrorResult(`${this.name}: cannot create directory '${dirPath}': Not a directory`);
|
|
}
|
|
} catch {
|
|
return createErrorResult(`${this.name}: cannot create directory '${dirPath}': No such file or directory`);
|
|
}
|
|
|
|
try {
|
|
await this.fs.mkdir(absolutePath);
|
|
if (opts.verbose) verboseOut.push(`${this.name}: created directory '${dirPath}'`);
|
|
} catch (error) {
|
|
const { message } = classifyFsError(error);
|
|
return createErrorResult(`${this.name}: cannot create directory '${dirPath}': ${message}`);
|
|
}
|
|
}
|
|
|
|
return createSuccessResult(verboseOut.length > 0 ? verboseOut.join('\n') + '\n' : '');
|
|
}
|
|
|
|
private async createRecursive(absolutePath: string, verboseOut: string[], verbose: boolean): Promise<void> {
|
|
try {
|
|
const stats = await this.fs.stat(absolutePath);
|
|
if (stats.isDirectory()) return;
|
|
throw new Error(`File exists`);
|
|
} catch (error) {
|
|
const { kind } = classifyFsError(error);
|
|
if (kind !== 'ENOENT') throw error;
|
|
}
|
|
|
|
const parent = dirname(absolutePath);
|
|
if (parent !== absolutePath && parent !== '') {
|
|
await this.createRecursive(parent, verboseOut, verbose);
|
|
}
|
|
|
|
try {
|
|
await this.fs.mkdir(absolutePath);
|
|
if (verbose) verboseOut.push(`${this.name}: created directory '${absolutePath}'`);
|
|
} catch (error) {
|
|
const { kind } = classifyFsError(error);
|
|
// EEXIST is fine under -p (race).
|
|
if (kind !== 'EEXIST') throw error;
|
|
}
|
|
}
|
|
}
|