Files
shakespeare/src/lib/commands/cp.test.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

146 lines
4.9 KiB
TypeScript

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { CpCommand } from './cp';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('CpCommand', () => {
let mockFS: JSRuntimeFS;
let cpCommand: CpCommand;
const testCwd = '/test/dir';
beforeEach(() => {
mockFS = createMockFS();
cpCommand = new CpCommand(mockFS);
});
it('should have correct command properties', () => {
expect(cpCommand.name).toBe('cp');
expect(cpCommand.description).toBe('Copy files and directories');
expect(cpCommand.usage).toBe('cp [-rRfinpavT] [--] source... destination');
});
it.skip('should copy a file', async () => {
// TODO: Fix this test - complex mocking scenario
const fileContent = new Uint8Array([1, 2, 3, 4]);
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({
isDirectory: () => false,
isFile: () => true,
})
.mockRejectedValueOnce(new Error('ENOENT')) // destination doesn't exist
.mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
}); // parent directory exists for all subsequent calls
vi.mocked(mockFS.readFile).mockResolvedValue(fileContent);
vi.mocked(mockFS.writeFile).mockResolvedValue();
const result = await cpCommand.execute(['source.txt', 'dest.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(mockFS.readFile).toHaveBeenCalledWith('/test/dir/source.txt');
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/dest.txt', fileContent);
});
it.skip('should copy file into directory', async () => {
// TODO: Fix this test - complex mocking scenario
const fileContent = new Uint8Array([1, 2, 3, 4]);
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({
isDirectory: () => false,
isFile: () => true,
})
.mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
}); // destination is directory, all other stat calls succeed
vi.mocked(mockFS.readFile).mockResolvedValue(fileContent);
vi.mocked(mockFS.writeFile).mockResolvedValue();
const result = await cpCommand.execute(['source.txt', 'destdir'], testCwd);
expect(result.exitCode).toBe(0);
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/destdir/source.txt', fileContent);
});
it('should return error when trying to copy directory without -r', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await cpCommand.execute(['sourcedir', 'destdir'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('-r not specified');
});
it.skip('should copy directory with -r flag', async () => {
// TODO: Fix this test - complex mocking scenario
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({
isDirectory: () => true,
isFile: () => false,
})
.mockRejectedValueOnce(new Error('ENOENT')); // destination doesn't exist
vi.mocked(mockFS.readdir).mockResolvedValue([]);
vi.mocked(mockFS.mkdir).mockResolvedValue();
const result = await cpCommand.execute(['-r', 'sourcedir', 'destdir'], testCwd);
expect(result.exitCode).toBe(0);
expect(mockFS.mkdir).toHaveBeenCalledWith('/test/dir/destdir', { recursive: true });
});
it('should return error for non-existent source', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await cpCommand.execute(['nonexistent.txt', 'dest.txt'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
});
it('should reject absolute destination paths outside allowed directories', async () => {
const result = await cpCommand.execute(['src/test.txt', '/absolute/dest'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('write access denied');
});
it('should return error when missing operands', async () => {
const result1 = await cpCommand.execute([], testCwd);
expect(result1.exitCode).toBe(1);
expect(result1.stderr).toContain('missing file operand');
const result2 = await cpCommand.execute(['source.txt'], testCwd);
expect(result2.exitCode).toBe(1);
expect(result2.stderr).toContain('missing');
});
it('should return error when multiple sources but destination is not directory', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT'));
const result = await cpCommand.execute(['file1.txt', 'file2.txt', 'dest.txt'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('is not a directory');
});
});