Add a bunch more shell commands

This commit is contained in:
Alex Gleason committed 2025-09-09 20:51:14 -05:00
1 parent 9d5f575765
commit 695f500ab0
24 files changed
+2185 -6

No files matched your search

+235 -1
View File
@@ -24,7 +24,7 @@ Commands return a `ShellCommandResult` object containing:
## Available Commands
The shell supports 15 essential commands for file and directory operations, text processing, and content analysis.
The shell supports 25 essential commands for file and directory operations, text processing, content analysis, and system utilities.
### cat
@@ -361,6 +361,240 @@ mv file1.txt file2.txt dest/ # Move multiple files to directory
- Handles multiple source files
- Prevents overwriting existing files
### sort
**Usage:** `sort [-r] [-n] [-u] [file...]`
Sort lines of text files.
**Options:**
- `-r`: Sort in reverse order
- `-n`: Sort numerically instead of alphabetically
- `-u`: Remove duplicate lines (unique)
**Examples:**
```bash
sort file.txt # Sort lines alphabetically
sort -r file.txt # Sort in reverse order
sort -n numbers.txt # Sort numerically
sort -u file.txt # Sort and remove duplicates
sort -rnu data.txt # Combine options: reverse, numeric, unique
```
**Features:**
- Alphabetical and numerical sorting
- Reverse order sorting
- Duplicate removal
- Multiple file support
- Configurable sort behavior
### uniq
**Usage:** `uniq [-c] [-d] [-u] [file]`
Report or omit repeated consecutive lines.
**Options:**
- `-c`: Show count of each line
- `-d`: Show only duplicate lines
- `-u`: Show only unique lines (not repeated)
**Examples:**
```bash
uniq file.txt # Remove consecutive duplicates
uniq -c file.txt # Show count of each line
uniq -d file.txt # Show only duplicated lines
uniq -u file.txt # Show only unique lines
```
**Features:**
- Removes consecutive duplicate lines
- Line counting with `-c` option
- Filter duplicates or unique lines
- Formatted output with proper spacing
- Note: Only removes consecutive duplicates (use with `sort` for all duplicates)
### cut
**Usage:** `cut -c LIST | -f LIST [-d DELIM] [file...]`
Extract sections from lines of files.
**Options:**
- `-c LIST`: Extract characters at specified positions
- `-f LIST`: Extract fields using delimiter
- `-d DELIM`: Use DELIM as field delimiter (default: tab)
**LIST format:**
- `1,3,5`: Specific positions
- `1-5`: Range of positions
- `1,3-5,7`: Combination of positions and ranges
**Examples:**
```bash
cut -c 1,3,5 file.txt # Extract characters 1, 3, and 5
cut -c 1-10 file.txt # Extract characters 1 through 10
cut -f 1,3 data.csv # Extract fields 1 and 3 (tab-delimited)
cut -f 2-4 -d ',' data.csv # Extract fields 2-4 using comma delimiter
```
**Features:**
- Character-based extraction
- Field-based extraction with custom delimiters
- Range and list specifications
- Multiple file support
### tr
**Usage:** `tr [-d] SET1 [SET2] [file...]`
Translate or delete characters.
**Options:**
- `-d`: Delete characters in SET1
**SET format:**
- `abc`: Literal characters
- `a-z`: Character ranges
- `0-9`: Numeric ranges
**Examples:**
```bash
tr 'a-z' 'A-Z' file.txt # Convert lowercase to uppercase
tr -d 'aeiou' file.txt # Delete all vowels
tr '0-9' 'X' file.txt # Replace all digits with 'X'
tr 'abc' '123' file.txt # Replace a→1, b→2, c→3
```
**Features:**
- Character translation with ranges
- Character deletion
- Multiple file support
- Range expansion (a-z, 0-9, etc.)
### diff
**Usage:** `diff [-u] file1 file2`
Compare files line by line.
**Options:**
- `-u`: Use unified diff format
**Examples:**
```bash
diff file1.txt file2.txt # Compare files in normal format
diff -u file1.txt file2.txt # Compare files in unified format
```
**Features:**
- Line-by-line file comparison
- Normal and unified diff formats
- Shows additions, deletions, and changes
- Exit code 0 for identical files, 1 for differences
### which
**Usage:** `which command...`
Locate commands and show their paths.
**Examples:**
```bash
which ls # Show path to ls command
which cat grep find # Show paths to multiple commands
```
**Features:**
- Locates available shell commands
- Shows simulated paths (/usr/bin/command)
- Multiple command support
- Exit code 1 if any command not found
### whoami
**Usage:** `whoami`
Display current username.
**Examples:**
```bash
whoami # Display current user
```
**Features:**
- Simple username display
- No arguments accepted
- Always returns "user" in this implementation
### date
**Usage:** `date [+FORMAT]`
Display current date and time.
**Format specifiers:**
- `%Y`: 4-digit year
- `%y`: 2-digit year
- `%m`: Month (01-12)
- `%d`: Day of month (01-31)
- `%H`: Hour (00-23)
- `%M`: Minute (00-59)
- `%S`: Second (00-59)
- `%A`: Full weekday name
- `%a`: Abbreviated weekday name
- `%B`: Full month name
- `%b`: Abbreviated month name
- `%s`: Unix timestamp
- `%%`: Literal %
**Examples:**
```bash
date # Default format
date '+%Y-%m-%d' # ISO date format
date '+%H:%M:%S' # Time only
date '+%A, %B %d, %Y' # Full date
date '+%s' # Unix timestamp
```
**Features:**
- Default and custom date formatting
- Standard format specifiers
- Unix timestamp support
- Weekday and month name formatting
### env
**Usage:** `env`
Display environment variables.
**Examples:**
```bash
env # Show all environment variables
```
**Features:**
- Displays simulated environment variables
- Shows common variables (HOME, PATH, USER, PWD, etc.)
- PWD reflects current working directory
### clear
**Usage:** `clear`
Clear terminal screen.
**Examples:**
```bash
clear # Clear screen
```
**Features:**
- Sends ANSI escape sequence to clear screen
- Moves cursor to top-left position
- No arguments accepted
## Usage with ShellTool
Commands are executed through the `ShellTool` which handles:
+21
View File
@@ -0,0 +1,21 @@
import { describe, it, expect } from 'vitest';
import { ClearCommand } from './clear';
describe('ClearCommand', () => {
const clearCommand = new ClearCommand();
it('should return ANSI clear screen sequence', async () => {
const result = await clearCommand.execute([], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('\x1b[2J\x1b[H');
expect(result.stderr).toBe('');
});
it('should error when arguments provided', async () => {
const result = await clearCommand.execute(['arg'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('arguments not supported');
});
});
+22
View File
@@ -0,0 +1,22 @@
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'clear' command
* Clear terminal screen
*/
export class ClearCommand implements ShellCommand {
name = 'clear';
description = 'Clear terminal screen';
usage = 'clear';
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
// clear doesn't accept any arguments
if (args.length > 0) {
return createErrorResult(`${this.name}: arguments not supported`);
}
// Return ANSI escape sequence to clear screen and move cursor to top-left
return createSuccessResult('\x1b[2J\x1b[H');
}
}
+146
View File
@@ -0,0 +1,146 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { CutCommand } from './cut';
import type { JSRuntimeFS } from '../JSRuntime';
describe('CutCommand', () => {
const mockFS = {
stat: vi.fn(),
readFile: vi.fn(),
} as unknown as JSRuntimeFS;
const cutCommand = new CutCommand(mockFS);
beforeEach(() => {
vi.clearAllMocks();
});
it('should extract characters by position', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello world\nfoo\n');
const result = await cutCommand.execute(['-c', '1,3,5', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('hlo\nfo\n');
expect(result.stderr).toBe('');
});
it('should extract character ranges', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello world\n');
const result = await cutCommand.execute(['-c', '1-5', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('hello\n');
expect(result.stderr).toBe('');
});
it('should extract fields with default tab delimiter', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('name\tage\tcity\nJohn\t25\tNY\n');
const result = await cutCommand.execute(['-f', '1,3', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('name\tcity\nJohn\tNY\n');
expect(result.stderr).toBe('');
});
it('should extract fields with custom delimiter', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('name,age,city\nJohn,25,NY\n');
const result = await cutCommand.execute(['-f', '1,3', '-d', ',', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('name,city\nJohn,NY\n');
expect(result.stderr).toBe('');
});
it('should extract field ranges', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('a,b,c,d,e\n1,2,3,4,5\n');
const result = await cutCommand.execute(['-f', '2-4', '-d', ',', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('b,c,d\n2,3,4\n');
expect(result.stderr).toBe('');
});
it('should handle combined character options', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello world\n');
const result = await cutCommand.execute(['-c1,3,5-7', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('hlo w\n');
expect(result.stderr).toBe('');
});
it('should handle combined field options', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('a,b,c,d,e\n');
const result = await cutCommand.execute(['-f1,3-5', '-d,', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('a,c,d,e\n');
expect(result.stderr).toBe('');
});
it('should handle multiple files', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('hello\n')
.mockResolvedValueOnce('world\n');
const result = await cutCommand.execute(['-c', '1-3', 'file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('hel\nwor\n');
expect(result.stderr).toBe('');
});
it('should error when no list specified', async () => {
const result = await cutCommand.execute(['test.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('you must specify a list');
});
it('should error for non-existent file', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file'));
const result = await cutCommand.execute(['-c', '1', 'nonexistent.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('No such file or directory');
});
it('should error for directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => true, isFile: () => false });
const result = await cutCommand.execute(['-c', '1', 'directory'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('Is a directory');
});
it('should reject absolute paths', async () => {
const result = await cutCommand.execute(['-c', '1', '/absolute/path'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('absolute paths are not supported');
});
it('should return empty output for no files', async () => {
const result = await cutCommand.execute(['-c', '1'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
});
+170
View File
@@ -0,0 +1,170 @@
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'cut' command
* Extract sections from lines
*/
export class CutCommand implements ShellCommand {
name = 'cut';
description = 'Extract sections from lines';
usage = 'cut -c LIST | -f LIST [-d DELIM] [file...]';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
try {
const { options, files } = this.parseArgs(args);
if (!options.characters && !options.fields) {
return createErrorResult(`${this.name}: you must specify a list of bytes, characters, or fields`);
}
const lines: string[] = [];
if (files.length === 0) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
}
// Read all files
for (const file of files) {
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
}
const absolutePath = join(cwd, file);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${file}: Is a directory`);
}
const content = await this.fs.readFile(absolutePath, 'utf8');
const fileLines = content.split('\n');
// Remove the last empty line if the file ends with a newline
if (fileLines.length > 0 && fileLines[fileLines.length - 1] === '') {
fileLines.pop();
}
lines.push(...fileLines);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${file}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${file}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${file}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
}
}
// Process lines
const result = lines.map(line => this.extractFromLine(line, options));
const output = result.length > 0 ? result.join('\n') + '\n' : '';
return createSuccessResult(output);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private extractFromLine(line: string, options: {
characters?: number[];
fields?: number[];
delimiter: string;
}): string {
if (options.characters) {
// Extract characters
const chars = [...line];
const extracted = options.characters
.filter(pos => pos > 0 && pos <= chars.length)
.map(pos => chars[pos - 1]);
return extracted.join('');
} else if (options.fields) {
// Extract fields
const fields = line.split(options.delimiter);
const extracted = options.fields
.filter(pos => pos > 0 && pos <= fields.length)
.map(pos => fields[pos - 1]);
return extracted.join(options.delimiter);
}
return line;
}
private parseList(listStr: string): number[] {
const positions: number[] = [];
const parts = listStr.split(',');
for (const part of parts) {
if (part.includes('-')) {
// Range like "1-3"
const [start, end] = part.split('-').map(Number);
if (!isNaN(start) && !isNaN(end) && start <= end) {
for (let i = start; i <= end; i++) {
positions.push(i);
}
}
} else {
// Single number
const num = Number(part);
if (!isNaN(num)) {
positions.push(num);
}
}
}
return [...new Set(positions)].sort((a, b) => a - b);
}
private parseArgs(args: string[]): {
options: {
characters?: number[];
fields?: number[];
delimiter: string;
};
files: string[]
} {
const options: { characters?: number[]; fields?: number[]; delimiter: string } = {
delimiter: '\t'
};
const files: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-c' && i + 1 < args.length) {
options.characters = this.parseList(args[++i]);
} else if (arg === '-f' && i + 1 < args.length) {
options.fields = this.parseList(args[++i]);
} else if (arg === '-d' && i + 1 < args.length) {
options.delimiter = args[++i];
} else if (arg.startsWith('-c')) {
options.characters = this.parseList(arg.slice(2));
} else if (arg.startsWith('-f')) {
options.fields = this.parseList(arg.slice(2));
} else if (arg.startsWith('-d')) {
options.delimiter = arg.slice(2);
} else if (!arg.startsWith('-')) {
files.push(arg);
}
}
return { options, files };
}
}
+72
View File
@@ -0,0 +1,72 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { DateCommand } from './date';
describe('DateCommand', () => {
const dateCommand = new DateCommand();
beforeEach(() => {
// Mock Date to return consistent values
vi.useFakeTimers();
vi.setSystemTime(new Date('2023-12-25T15:30:45.123Z'));
});
afterEach(() => {
vi.useRealTimers();
});
it('should return current date in default format', async () => {
const result = await dateCommand.execute([], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('2023');
expect(result.stdout).toContain('Dec');
expect(result.stderr).toBe('');
});
it('should format date with custom format string', async () => {
const result = await dateCommand.execute(['+%Y-%m-%d'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('2023-12-25\n');
expect(result.stderr).toBe('');
});
it('should handle time formatting', async () => {
const result = await dateCommand.execute(['+%H:%M:%S'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toMatch(/\d{2}:\d{2}:\d{2}\n/);
expect(result.stderr).toBe('');
});
it('should handle weekday and month names', async () => {
const result = await dateCommand.execute(['+%A %B'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('Monday December\n');
expect(result.stderr).toBe('');
});
it('should handle unix timestamp', async () => {
const result = await dateCommand.execute(['+%s'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toMatch(/\d+\n/);
expect(result.stderr).toBe('');
});
it('should handle percent literal', async () => {
const result = await dateCommand.execute(['+%%'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('%\n');
expect(result.stderr).toBe('');
});
it('should error for invalid format (missing +)', async () => {
const result = await dateCommand.execute(['%Y-%m-%d'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('invalid date');
});
});
+64
View File
@@ -0,0 +1,64 @@
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'date' command
* Display current date and time
*/
export class DateCommand implements ShellCommand {
name = 'date';
description = 'Display current date and time';
usage = 'date [+FORMAT]';
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
try {
const now = new Date();
// Handle format string
if (args.length > 0) {
const format = args[0];
if (format.startsWith('+')) {
const formatStr = format.slice(1);
const formatted = this.formatDate(now, formatStr);
return createSuccessResult(formatted + '\n');
} else {
return createErrorResult(`${this.name}: invalid date '${format}'`);
}
}
// Default format (similar to GNU date)
const defaultFormat = now.toString();
return createSuccessResult(defaultFormat + '\n');
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private formatDate(date: Date, format: string): string {
const formatMap: Record<string, string> = {
// Date formats
'%Y': date.getFullYear().toString(),
'%y': date.getFullYear().toString().slice(-2),
'%m': (date.getMonth() + 1).toString().padStart(2, '0'),
'%d': date.getDate().toString().padStart(2, '0'),
'%H': date.getHours().toString().padStart(2, '0'),
'%M': date.getMinutes().toString().padStart(2, '0'),
'%S': date.getSeconds().toString().padStart(2, '0'),
'%A': date.toLocaleDateString('en-US', { weekday: 'long' }),
'%a': date.toLocaleDateString('en-US', { weekday: 'short' }),
'%B': date.toLocaleDateString('en-US', { month: 'long' }),
'%b': date.toLocaleDateString('en-US', { month: 'short' }),
'%s': Math.floor(date.getTime() / 1000).toString(),
'%%': '%'
};
let result = format;
for (const [pattern, replacement] of Object.entries(formatMap)) {
result = result.replace(new RegExp(pattern, 'g'), replacement);
}
return result;
}
}
+133
View File
@@ -0,0 +1,133 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { DiffCommand } from './diff';
import type { JSRuntimeFS } from '../JSRuntime';
describe('DiffCommand', () => {
const mockFS = {
stat: vi.fn(),
readFile: vi.fn(),
} as unknown as JSRuntimeFS;
const diffCommand = new DiffCommand(mockFS);
beforeEach(() => {
vi.clearAllMocks();
});
it('should return empty output for identical files', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello\nworld\n');
const result = await diffCommand.execute(['file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
it('should show differences in normal format', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('hello\nworld\n')
.mockResolvedValueOnce('hello\nplanet\n');
const result = await diffCommand.execute(['file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('2c2');
expect(result.stderr).toContain('< world');
expect(result.stderr).toContain('> planet');
expect(result.stdout).toBe('');
});
it('should show differences in unified format', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('hello\nworld\n')
.mockResolvedValueOnce('hello\nplanet\n');
const result = await diffCommand.execute(['-u', 'file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('--- file1.txt');
expect(result.stderr).toContain('+++ file2.txt');
expect(result.stderr).toContain('-world');
expect(result.stderr).toContain('+planet');
expect(result.stdout).toBe('');
});
it('should handle added lines', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('hello\n')
.mockResolvedValueOnce('hello\nworld\n');
const result = await diffCommand.execute(['file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('a');
expect(result.stderr).toContain('> world');
expect(result.stdout).toBe('');
});
it('should handle deleted lines', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('hello\nworld\n')
.mockResolvedValueOnce('hello\n');
const result = await diffCommand.execute(['file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('d');
expect(result.stderr).toContain('< world');
expect(result.stdout).toBe('');
});
it('should error when wrong number of arguments', async () => {
const result = await diffCommand.execute(['file1.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('missing operand');
});
it('should error for non-existent file', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file'));
const result = await diffCommand.execute(['nonexistent1.txt', 'nonexistent2.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('No such file or directory');
});
it('should error for directory', async () => {
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false })
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true });
const result = await diffCommand.execute(['directory', 'file.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('Is a directory');
});
it('should reject absolute paths', async () => {
const result = await diffCommand.execute(['/absolute/path1', 'file2.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('absolute paths are not supported');
});
it('should handle empty files', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('')
.mockResolvedValueOnce('');
const result = await diffCommand.execute(['empty1.txt', 'empty2.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
});
+203
View File
@@ -0,0 +1,203 @@
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'diff' command
* Compare files line by line
*/
export class DiffCommand implements ShellCommand {
name = 'diff';
description = 'Compare files line by line';
usage = 'diff [-u] file1 file2';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
try {
const { options, files } = this.parseArgs(args);
if (files.length !== 2) {
return createErrorResult(`${this.name}: missing operand (need exactly 2 files)`);
}
const [file1, file2] = files;
// Read both files
let content1: string, content2: string;
try {
// Handle absolute paths
if (file1.startsWith('/') || file1.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file1)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file1}`);
}
if (file2.startsWith('/') || file2.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file2)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file2}`);
}
const absolutePath1 = join(cwd, file1);
const absolutePath2 = join(cwd, file2);
const stats1 = await this.fs.stat(absolutePath1);
const stats2 = await this.fs.stat(absolutePath2);
if (stats1.isDirectory()) {
return createErrorResult(`${this.name}: ${file1}: Is a directory`);
}
if (stats2.isDirectory()) {
return createErrorResult(`${this.name}: ${file2}: Is a directory`);
}
content1 = await this.fs.readFile(absolutePath1, 'utf8');
content2 = await this.fs.readFile(absolutePath2, 'utf8');
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: Unknown error`);
}
}
// Compare files
if (content1 === content2) {
return createSuccessResult('');
}
// Generate diff output
const lines1 = content1.split('\n');
const lines2 = content2.split('\n');
if (options.unified) {
const diff = this.generateUnifiedDiff(lines1, lines2, file1, file2);
return createErrorResult(diff, 1);
} else {
const diff = this.generateNormalDiff(lines1, lines2);
return createErrorResult(diff, 1);
}
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private generateNormalDiff(lines1: string[], lines2: string[]): string {
const result: string[] = [];
// Find the first difference
let commonPrefix = 0;
const minLen = Math.min(lines1.length, lines2.length);
while (commonPrefix < minLen && lines1[commonPrefix] === lines2[commonPrefix]) {
commonPrefix++;
}
if (lines1.length === lines2.length && commonPrefix === lines1.length) {
// Files are identical
return '';
}
if (lines1.length < lines2.length) {
// Lines added after commonPrefix
const startLine = commonPrefix + 1;
const endLine = lines2.length;
result.push(`${commonPrefix}a${startLine},${endLine}`);
for (let i = commonPrefix; i < lines2.length; i++) {
result.push(`> ${lines2[i]}`);
}
} else if (lines1.length > lines2.length) {
// Lines deleted after commonPrefix
const startLine = commonPrefix + 1;
const endLine = lines1.length;
result.push(`${startLine},${endLine}d${commonPrefix}`);
for (let i = commonPrefix; i < lines1.length; i++) {
result.push(`< ${lines1[i]}`);
}
} else {
// Same length but different content
for (let i = commonPrefix; i < minLen; i++) {
if (lines1[i] !== lines2[i]) {
result.push(`${i + 1}c${i + 1}`);
result.push(`< ${lines1[i]}`);
result.push('---');
result.push(`> ${lines2[i]}`);
}
}
}
return result.join('\n') + (result.length > 0 ? '\n' : '');
}
private generateUnifiedDiff(lines1: string[], lines2: string[], file1: string, file2: string): string {
const result: string[] = [];
result.push(`--- ${file1}`);
result.push(`+++ ${file2}`);
const maxLen = Math.max(lines1.length, lines2.length);
let hasChanges = false;
for (let i = 0; i < maxLen; i++) {
const line1 = i < lines1.length ? lines1[i] : undefined;
const line2 = i < lines2.length ? lines2[i] : undefined;
if (line1 !== line2) {
if (!hasChanges) {
// Start of a change block
const start1 = Math.max(0, i - 3);
const start2 = Math.max(0, i - 3);
result.push(`@@ -${start1 + 1},${lines1.length} +${start2 + 1},${lines2.length} @@`);
// Add context lines before the change
for (let j = Math.max(0, i - 3); j < i; j++) {
if (j < lines1.length) {
result.push(` ${lines1[j]}`);
}
}
hasChanges = true;
}
if (line1 !== undefined) {
result.push(`-${line1}`);
}
if (line2 !== undefined) {
result.push(`+${line2}`);
}
} else if (hasChanges && line1 !== undefined) {
// Context line after a change
result.push(` ${line1}`);
}
}
return result.join('\n') + (result.length > 2 ? '\n' : '');
}
private parseArgs(args: string[]): {
options: { unified: boolean };
files: string[]
} {
const options = { unified: false };
const files: string[] = [];
for (const arg of args) {
if (arg === '-u') {
options.unified = true;
} else if (arg.startsWith('-') && arg.includes('u')) {
options.unified = true;
} else if (!arg.startsWith('-')) {
files.push(arg);
}
}
return { options, files };
}
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, it, expect } from 'vitest';
import { EnvCommand } from './env';
describe('EnvCommand', () => {
const envCommand = new EnvCommand();
it('should display environment variables', async () => {
const result = await envCommand.execute([], '/test/dir');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('HOME=/home/user');
expect(result.stdout).toContain('PATH=/usr/local/bin:/usr/bin:/bin');
expect(result.stdout).toContain('SHELL=/bin/bash');
expect(result.stdout).toContain('USER=user');
expect(result.stdout).toContain('PWD=/test/dir');
expect(result.stdout).toContain('TERM=xterm-256color');
expect(result.stdout).toContain('LANG=en_US.UTF-8');
expect(result.stdout).toContain('NODE_ENV=development');
expect(result.stdout).toContain('EDITOR=nano');
expect(result.stderr).toBe('');
});
it('should show current working directory in PWD', async () => {
const result = await envCommand.execute([], '/different/path');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('PWD=/different/path');
expect(result.stderr).toBe('');
});
it('should error when arguments provided', async () => {
const result = await envCommand.execute(['arg'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('arguments not supported');
});
});
+35
View File
@@ -0,0 +1,35 @@
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'env' command
* Display environment variables
*/
export class EnvCommand implements ShellCommand {
name = 'env';
description = 'Display environment variables';
usage = 'env';
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
// env doesn't accept arguments in this simple implementation
if (args.length > 0) {
return createErrorResult(`${this.name}: arguments not supported in this implementation`);
}
// Simulate common environment variables that would be found in a development environment
const envVars = [
'HOME=/home/user',
'PATH=/usr/local/bin:/usr/bin:/bin',
'SHELL=/bin/bash',
'USER=user',
'PWD=' + cwd,
'TERM=xterm-256color',
'LANG=en_US.UTF-8',
'NODE_ENV=development',
'EDITOR=nano'
];
const output = envVars.join('\n') + '\n';
return createSuccessResult(output);
}
}
+11 -1
View File
@@ -1,8 +1,13 @@
export { type ShellCommand, type ShellCommandResult, createSuccessResult, createErrorResult } from './ShellCommand';
export { CatCommand } from './cat';
export { CdCommand } from './cd';
export { ClearCommand } from './clear';
export { CpCommand } from './cp';
export { CutCommand } from './cut';
export { DateCommand } from './date';
export { DiffCommand } from './diff';
export { EchoCommand } from './echo';
export { EnvCommand } from './env';
export { FindCommand } from './find';
export { GrepCommand } from './grep';
export { HeadCommand } from './head';
@@ -11,6 +16,11 @@ export { MkdirCommand } from './mkdir';
export { MvCommand } from './mv';
export { PwdCommand } from './pwd';
export { RmCommand } from './rm';
export { SortCommand } from './sort';
export { TailCommand } from './tail';
export { TouchCommand } from './touch';
export { WcCommand } from './wc';
export { TrCommand } from './tr';
export { UniqCommand } from './uniq';
export { WcCommand } from './wc';
export { WhoamiCommand } from './whoami';
export { WhichCommand } from './which';
+117
View File
@@ -0,0 +1,117 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { SortCommand } from './sort';
import type { JSRuntimeFS } from '../JSRuntime';
describe('SortCommand', () => {
const mockFS = {
stat: vi.fn(),
readFile: vi.fn(),
} as unknown as JSRuntimeFS;
const sortCommand = new SortCommand(mockFS);
beforeEach(() => {
vi.clearAllMocks();
});
it('should sort lines alphabetically', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('zebra\napple\nbanana\n');
const result = await sortCommand.execute(['test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('apple\nbanana\nzebra\n');
expect(result.stderr).toBe('');
});
it('should sort lines in reverse order', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('apple\nbanana\nzebra\n');
const result = await sortCommand.execute(['-r', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('zebra\nbanana\napple\n');
expect(result.stderr).toBe('');
});
it('should sort numerically', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('10\n2\n1\n20\n');
const result = await sortCommand.execute(['-n', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('1\n2\n10\n20\n');
expect(result.stderr).toBe('');
});
it('should remove duplicates when unique flag is used', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('apple\nbanana\napple\nzebra\nbanana\n');
const result = await sortCommand.execute(['-u', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('apple\nbanana\nzebra\n');
expect(result.stderr).toBe('');
});
it('should combine options', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('10\n2\n10\n1\n20\n2\n');
const result = await sortCommand.execute(['-rnu', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('20\n10\n2\n1\n');
expect(result.stderr).toBe('');
});
it('should handle multiple files', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('zebra\napple\n')
.mockResolvedValueOnce('banana\ngrape\n');
const result = await sortCommand.execute(['file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('apple\nbanana\ngrape\nzebra\n');
expect(result.stderr).toBe('');
});
it('should error for non-existent file', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file'));
const result = await sortCommand.execute(['nonexistent.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('No such file or directory');
});
it('should error for directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => true, isFile: () => false });
const result = await sortCommand.execute(['directory'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('Is a directory');
});
it('should reject absolute paths', async () => {
const result = await sortCommand.execute(['/absolute/path'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('absolute paths are not supported');
});
it('should return empty output for no files', async () => {
const result = await sortCommand.execute([], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
});
+131
View File
@@ -0,0 +1,131 @@
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'sort' command
* Sort lines of text
*/
export class SortCommand implements ShellCommand {
name = 'sort';
description = 'Sort lines of text';
usage = 'sort [-r] [-n] [-u] [file...]';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
try {
const { options, files } = this.parseArgs(args);
let lines: string[] = [];
if (files.length === 0) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
}
// Read all files
for (const file of files) {
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
}
const absolutePath = join(cwd, file);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: read error: ${file}: Is a directory`);
}
const content = await this.fs.readFile(absolutePath, 'utf8');
const fileLines = content.split('\n');
// Remove the last empty line if the file ends with a newline
if (fileLines.length > 0 && fileLines[fileLines.length - 1] === '') {
fileLines.pop();
}
lines.push(...fileLines);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: open failed: ${file}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: open failed: ${file}: Permission denied`);
} else {
return createErrorResult(`${this.name}: open failed: ${file}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: open failed: ${file}: Unknown error`);
}
}
}
// Sort the lines
if (options.numeric) {
lines.sort((a, b) => {
const numA = parseFloat(a) || 0;
const numB = parseFloat(b) || 0;
return options.reverse ? numB - numA : numA - numB;
});
} else {
lines.sort((a, b) => {
const result = a.localeCompare(b);
return options.reverse ? -result : result;
});
}
// Remove duplicates if requested
if (options.unique) {
lines = [...new Set(lines)];
}
const output = lines.length > 0 ? lines.join('\n') + '\n' : '';
return createSuccessResult(output);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private parseArgs(args: string[]): {
options: { reverse: boolean; numeric: boolean; unique: boolean };
files: string[]
} {
const options = { reverse: false, numeric: false, unique: false };
const files: string[] = [];
for (const arg of args) {
if (arg.startsWith('-')) {
// Parse options
for (let i = 1; i < arg.length; i++) {
const char = arg[i];
switch (char) {
case 'r':
options.reverse = true;
break;
case 'n':
options.numeric = true;
break;
case 'u':
options.unique = true;
break;
default:
// Ignore unknown options for now
break;
}
}
} else {
files.push(arg);
}
}
return { options, files };
}
}
+153
View File
@@ -0,0 +1,153 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { TrCommand } from './tr';
import type { JSRuntimeFS } from '../JSRuntime';
describe('TrCommand', () => {
const mockFS = {
stat: vi.fn(),
readFile: vi.fn(),
} as unknown as JSRuntimeFS;
const trCommand = new TrCommand(mockFS);
beforeEach(() => {
vi.clearAllMocks();
});
it('should translate characters', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello world');
const result = await trCommand.execute(['aeiou', 'AEIOU', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('hEllO wOrld');
expect(result.stderr).toBe('');
});
it('should translate character ranges', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello WORLD');
const result = await trCommand.execute(['a-z', 'A-Z', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('HELLO WORLD');
expect(result.stderr).toBe('');
});
it('should delete characters with -d option', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello world!');
const result = await trCommand.execute(['-d', 'aeiou', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('hll wrld!');
expect(result.stderr).toBe('');
});
it('should delete character ranges', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello123world456');
const result = await trCommand.execute(['-d', '0-9', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('helloworld');
expect(result.stderr).toBe('');
});
it('should handle shorter second set by repeating last character', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('abcdef');
const result = await trCommand.execute(['a-f', 'XY', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('XYYYYY');
expect(result.stderr).toBe('');
});
it('should handle multiple files', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('hello')
.mockResolvedValueOnce(' world');
const result = await trCommand.execute(['a-z', 'A-Z', 'file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('HELLO WORLD');
expect(result.stderr).toBe('');
});
it('should handle single character sets', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello');
const result = await trCommand.execute(['l', 'L', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('heLLo');
expect(result.stderr).toBe('');
});
it('should preserve characters not in translation set', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello 123!');
const result = await trCommand.execute(['a-z', 'A-Z', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('HELLO 123!');
expect(result.stderr).toBe('');
});
it('should error when no operands provided', async () => {
const result = await trCommand.execute([], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('missing operand');
});
it('should error when second set missing in translate mode', async () => {
const result = await trCommand.execute(['abc'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('missing operand');
});
it('should error for non-existent file', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file'));
const result = await trCommand.execute(['a', 'A', 'nonexistent.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('No such file or directory');
});
it('should error for directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => true, isFile: () => false });
const result = await trCommand.execute(['a', 'A', 'directory'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('Is a directory');
});
it('should reject absolute paths', async () => {
const result = await trCommand.execute(['a', 'A', '/absolute/path'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('absolute paths are not supported');
});
it('should return empty output for no files', async () => {
const result = await trCommand.execute(['a', 'A'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
});
+170
View File
@@ -0,0 +1,170 @@
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'tr' command
* Translate or delete characters
*/
export class TrCommand implements ShellCommand {
name = 'tr';
description = 'Translate or delete characters';
usage = 'tr [-d] SET1 [SET2] [file...]';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
try {
const { options, sets, files } = this.parseArgs(args);
if (sets.length === 0) {
return createErrorResult(`${this.name}: missing operand`);
}
if (!options.delete && sets.length < 2) {
return createErrorResult(`${this.name}: missing operand after '${sets[0]}'`);
}
let content = '';
if (files.length === 0) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
}
// Read all files
for (const file of files) {
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
}
const absolutePath = join(cwd, file);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${file}: Is a directory`);
}
const fileContent = await this.fs.readFile(absolutePath, 'utf8');
content += fileContent;
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${file}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${file}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${file}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
}
}
// Process content
let result: string;
if (options.delete) {
result = this.deleteCharacters(content, sets[0]);
} else {
result = this.translateCharacters(content, sets[0], sets[1]);
}
return createSuccessResult(result);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private deleteCharacters(content: string, set1: string): string {
const deleteChars = this.expandSet(set1);
const deleteSet = new Set(deleteChars);
return [...content].filter(char => !deleteSet.has(char)).join('');
}
private translateCharacters(content: string, set1: string, set2: string): string {
const fromChars = this.expandSet(set1);
const toChars = this.expandSet(set2);
// Create translation map
const translationMap = new Map<string, string>();
for (let i = 0; i < fromChars.length; i++) {
const toChar = i < toChars.length ? toChars[i] : toChars[toChars.length - 1];
translationMap.set(fromChars[i], toChar);
}
return [...content].map(char => translationMap.get(char) || char).join('');
}
private expandSet(set: string): string[] {
const result: string[] = [];
let i = 0;
while (i < set.length) {
if (i + 2 < set.length && set[i + 1] === '-') {
// Range like 'a-z'
const start = set.charCodeAt(i);
const end = set.charCodeAt(i + 2);
if (start <= end) {
for (let code = start; code <= end; code++) {
result.push(String.fromCharCode(code));
}
} else {
// Invalid range, treat as literal characters
result.push(set[i], set[i + 1], set[i + 2]);
}
i += 3;
} else {
// Single character
result.push(set[i]);
i++;
}
}
return result;
}
private parseArgs(args: string[]): {
options: { delete: boolean };
sets: string[];
files: string[]
} {
const options = { delete: false };
const sets: string[] = [];
const files: string[] = [];
let expectingSet = true;
for (const arg of args) {
if (arg === '-d') {
options.delete = true;
} else if (arg.startsWith('-') && arg !== '-') {
// Parse combined options
for (let i = 1; i < arg.length; i++) {
if (arg[i] === 'd') {
options.delete = true;
}
}
} else if (expectingSet) {
sets.push(arg);
// If delete mode, only expect one set, otherwise expect two
if (options.delete || sets.length === 2) {
expectingSet = false;
}
} else {
files.push(arg);
}
}
return { options, sets, files };
}
}
+137
View File
@@ -0,0 +1,137 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { UniqCommand } from './uniq';
import type { JSRuntimeFS } from '../JSRuntime';
describe('UniqCommand', () => {
const mockFS = {
stat: vi.fn(),
readFile: vi.fn(),
} as unknown as JSRuntimeFS;
const uniqCommand = new UniqCommand(mockFS);
beforeEach(() => {
vi.clearAllMocks();
});
it('should remove consecutive duplicate lines', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('apple\napple\nbanana\nbanana\nbanana\ncherry\n');
const result = await uniqCommand.execute(['test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('apple\nbanana\ncherry\n');
expect(result.stderr).toBe('');
});
it('should show count with -c option', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('apple\napple\nbanana\nbanana\nbanana\ncherry\n');
const result = await uniqCommand.execute(['-c', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(' 2 apple\n 3 banana\n 1 cherry\n');
expect(result.stderr).toBe('');
});
it('should show only duplicates with -d option', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('apple\napple\nbanana\nbanana\nbanana\ncherry\n');
const result = await uniqCommand.execute(['-d', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('apple\nbanana\n');
expect(result.stderr).toBe('');
});
it('should show only unique lines with -u option', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('apple\napple\nbanana\nbanana\nbanana\ncherry\n');
const result = await uniqCommand.execute(['-u', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('cherry\n');
expect(result.stderr).toBe('');
});
it('should combine count and duplicates options', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('apple\napple\nbanana\nbanana\nbanana\ncherry\n');
const result = await uniqCommand.execute(['-cd', 'test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(' 2 apple\n 3 banana\n');
expect(result.stderr).toBe('');
});
it('should handle file with no duplicates', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('apple\nbanana\ncherry\n');
const result = await uniqCommand.execute(['test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('apple\nbanana\ncherry\n');
expect(result.stderr).toBe('');
});
it('should handle empty file', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('');
const result = await uniqCommand.execute(['test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
it('should handle single line file', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('single line\n');
const result = await uniqCommand.execute(['test.txt'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('single line\n');
expect(result.stderr).toBe('');
});
it('should error for non-existent file', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file'));
const result = await uniqCommand.execute(['nonexistent.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('No such file or directory');
});
it('should error for directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => true, isFile: () => false });
const result = await uniqCommand.execute(['directory'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('Is a directory');
});
it('should reject absolute paths', async () => {
const result = await uniqCommand.execute(['/absolute/path'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('absolute paths are not supported');
});
it('should return empty output for no files', async () => {
const result = await uniqCommand.execute([], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
});
+163
View File
@@ -0,0 +1,163 @@
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'uniq' command
* Report or omit repeated lines
*/
export class UniqCommand implements ShellCommand {
name = 'uniq';
description = 'Report or omit repeated lines';
usage = 'uniq [-c] [-d] [-u] [file]';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
try {
const { options, file } = this.parseArgs(args);
let lines: string[] = [];
if (!file) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
}
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
}
const absolutePath = join(cwd, file);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${file}: Is a directory`);
}
const content = await this.fs.readFile(absolutePath, 'utf8');
lines = content.split('\n');
// Remove the last empty line if the file ends with a newline
if (lines.length > 0 && lines[lines.length - 1] === '') {
lines.pop();
}
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${file}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${file}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${file}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
}
// Process lines for uniqueness
const result = this.processLines(lines, options);
const output = result.length > 0 ? result.join('\n') + '\n' : '';
return createSuccessResult(output);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private processLines(
lines: string[],
options: { count: boolean; duplicatesOnly: boolean; uniqueOnly: boolean }
): string[] {
if (lines.length === 0) return [];
const result: string[] = [];
let currentLine = lines[0];
let count = 1;
for (let i = 1; i < lines.length; i++) {
if (lines[i] === currentLine) {
count++;
} else {
// Process the current group
this.addLineToResult(result, currentLine, count, options);
// Start new group
currentLine = lines[i];
count = 1;
}
}
// Process the last group
this.addLineToResult(result, currentLine, count, options);
return result;
}
private addLineToResult(
result: string[],
line: string,
count: number,
options: { count: boolean; duplicatesOnly: boolean; uniqueOnly: boolean }
): void {
const isDuplicate = count > 1;
const isUnique = count === 1;
// Apply filters
if (options.duplicatesOnly && !isDuplicate) return;
if (options.uniqueOnly && !isUnique) return;
// Format output
if (options.count) {
result.push(`${count.toString().padStart(7)} ${line}`);
} else {
result.push(line);
}
}
private parseArgs(args: string[]): {
options: { count: boolean; duplicatesOnly: boolean; uniqueOnly: boolean };
file?: string
} {
const options = { count: false, duplicatesOnly: false, uniqueOnly: false };
let file: string | undefined;
for (const arg of args) {
if (arg.startsWith('-')) {
// Parse options
for (let i = 1; i < arg.length; i++) {
const char = arg[i];
switch (char) {
case 'c':
options.count = true;
break;
case 'd':
options.duplicatesOnly = true;
break;
case 'u':
options.uniqueOnly = true;
break;
default:
// Ignore unknown options for now
break;
}
}
} else {
if (!file) {
file = arg;
}
// uniq typically only accepts one file argument
}
}
return { options, file };
}
}
+53
View File
@@ -0,0 +1,53 @@
import { describe, it, expect } from 'vitest';
import { WhichCommand } from './which';
import { LsCommand } from './ls';
import { CatCommand } from './cat';
import type { JSRuntimeFS } from '../JSRuntime';
describe('WhichCommand', () => {
const mockFS = {} as JSRuntimeFS;
const commands = new Map();
commands.set('ls', new LsCommand(mockFS));
commands.set('cat', new CatCommand(mockFS));
const whichCommand = new WhichCommand(commands);
it('should show path for existing command', async () => {
const result = await whichCommand.execute(['ls'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('/usr/bin/ls\n');
expect(result.stderr).toBe('');
});
it('should handle multiple existing commands', async () => {
const result = await whichCommand.execute(['ls', 'cat'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('/usr/bin/ls\n/usr/bin/cat\n');
expect(result.stderr).toBe('');
});
it('should error for non-existent command', async () => {
const result = await whichCommand.execute(['nonexistent'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toBe('which: no nonexistent in (/usr/bin)\n');
expect(result.stdout).toBe('');
});
it('should handle mix of existing and non-existent commands', async () => {
const result = await whichCommand.execute(['ls', 'nonexistent', 'cat'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toBe('/usr/bin/ls\nwhich: no nonexistent in (/usr/bin)\n/usr/bin/cat\n');
expect(result.stdout).toBe('');
});
it('should error when no arguments provided', async () => {
const result = await whichCommand.execute([], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('missing operand');
});
});
+44
View File
@@ -0,0 +1,44 @@
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'which' command
* Locate a command and show its path
*/
export class WhichCommand implements ShellCommand {
name = 'which';
description = 'Locate a command';
usage = 'which command...';
private commands: Map<string, ShellCommand>;
constructor(commands: Map<string, ShellCommand>) {
this.commands = commands;
}
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing operand`);
}
const results: string[] = [];
let hasError = false;
for (const commandName of args) {
if (this.commands.has(commandName)) {
results.push(`/usr/bin/${commandName}`);
} else {
results.push(`${this.name}: no ${commandName} in (/usr/bin)`);
hasError = true;
}
}
const output = results.join('\n') + (results.length > 0 ? '\n' : '');
if (hasError) {
return createErrorResult(output, 1);
}
return createSuccessResult(output);
}
}
+21
View File
@@ -0,0 +1,21 @@
import { describe, it, expect } from 'vitest';
import { WhoamiCommand } from './whoami';
describe('WhoamiCommand', () => {
const whoamiCommand = new WhoamiCommand();
it('should return current username', async () => {
const result = await whoamiCommand.execute([], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('user\n');
expect(result.stderr).toBe('');
});
it('should error when arguments provided', async () => {
const result = await whoamiCommand.execute(['arg'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('extra operand');
});
});
+21
View File
@@ -0,0 +1,21 @@
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'whoami' command
* Display current username
*/
export class WhoamiCommand implements ShellCommand {
name = 'whoami';
description = 'Display current username';
usage = 'whoami';
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
// whoami doesn't accept any arguments
if (args.length > 0) {
return createErrorResult(`${this.name}: extra operand '${args[0]}'`);
}
return createSuccessResult('user\n');
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ describe('ShellTool', () => {
});
it('should have correct tool properties', () => {
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir');
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear');
expect(shellTool.inputSchema).toBeDefined();
});
+25 -3
View File
@@ -5,8 +5,13 @@ import type { ShellCommand } from "../commands/ShellCommand";
import {
CatCommand,
CdCommand,
ClearCommand,
CpCommand,
CutCommand,
DateCommand,
DiffCommand,
EchoCommand,
EnvCommand,
FindCommand,
GrepCommand,
HeadCommand,
@@ -15,9 +20,14 @@ import {
MvCommand,
PwdCommand,
RmCommand,
SortCommand,
TailCommand,
TouchCommand,
WcCommand
TrCommand,
UniqCommand,
WcCommand,
WhoamiCommand,
WhichCommand
} from "../commands";
interface ShellToolParams {
@@ -32,11 +42,11 @@ export class ShellTool implements Tool<ShellToolParams> {
private cwd: string;
private commands: Map<string, ShellCommand>;
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir";
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear";
readonly inputSchema = z.object({
command: z.string().describe(
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd"'
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2"'
),
});
@@ -48,8 +58,13 @@ export class ShellTool implements Tool<ShellToolParams> {
// Register available commands
this.registerCommand(new CatCommand(fs));
this.registerCommand(new CdCommand(fs));
this.registerCommand(new ClearCommand());
this.registerCommand(new CpCommand(fs));
this.registerCommand(new CutCommand(fs));
this.registerCommand(new DateCommand());
this.registerCommand(new DiffCommand(fs));
this.registerCommand(new EchoCommand());
this.registerCommand(new EnvCommand());
this.registerCommand(new FindCommand(fs));
this.registerCommand(new GrepCommand(fs));
this.registerCommand(new HeadCommand(fs));
@@ -58,9 +73,16 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new MvCommand(fs));
this.registerCommand(new PwdCommand());
this.registerCommand(new RmCommand(fs));
this.registerCommand(new SortCommand(fs));
this.registerCommand(new TailCommand(fs));
this.registerCommand(new TouchCommand(fs));
this.registerCommand(new TrCommand(fs));
this.registerCommand(new UniqCommand(fs));
this.registerCommand(new WcCommand(fs));
this.registerCommand(new WhoamiCommand());
// Register which command last so it has access to all other commands
this.registerCommand(new WhichCommand(this.commands));
}
/**