From 9d5f575765d1cde53588e4d0dda8ad4a4997884c Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 9 Sep 2025 19:52:41 -0500 Subject: [PATCH] Add a bunch more shell commands --- src/lib/commands/README.md | 169 ++++++++++++++++++++++++ src/lib/commands/find.test.ts | 114 ++++++++++++++++ src/lib/commands/find.ts | 174 +++++++++++++++++++++++++ src/lib/commands/grep.test.ts | 111 ++++++++++++++++ src/lib/commands/grep.ts | 224 ++++++++++++++++++++++++++++++++ src/lib/commands/head.test.ts | 85 ++++++++++++ src/lib/commands/head.ts | 125 ++++++++++++++++++ src/lib/commands/index.ts | 9 +- src/lib/commands/mkdir.test.ts | 95 ++++++++++++++ src/lib/commands/mkdir.ts | 160 +++++++++++++++++++++++ src/lib/commands/tail.test.ts | 85 ++++++++++++ src/lib/commands/tail.ts | 130 ++++++++++++++++++ src/lib/commands/touch.test.ts | 81 ++++++++++++ src/lib/commands/touch.ts | 90 +++++++++++++ src/lib/commands/wc.test.ts | 114 ++++++++++++++++ src/lib/commands/wc.ts | 165 +++++++++++++++++++++++ src/lib/tools/ShellTool.test.ts | 2 +- src/lib/tools/ShellTool.ts | 18 ++- 18 files changed, 1947 insertions(+), 4 deletions(-) create mode 100644 src/lib/commands/find.test.ts create mode 100644 src/lib/commands/find.ts create mode 100644 src/lib/commands/grep.test.ts create mode 100644 src/lib/commands/grep.ts create mode 100644 src/lib/commands/head.test.ts create mode 100644 src/lib/commands/head.ts create mode 100644 src/lib/commands/mkdir.test.ts create mode 100644 src/lib/commands/mkdir.ts create mode 100644 src/lib/commands/tail.test.ts create mode 100644 src/lib/commands/tail.ts create mode 100644 src/lib/commands/touch.test.ts create mode 100644 src/lib/commands/touch.ts create mode 100644 src/lib/commands/wc.test.ts create mode 100644 src/lib/commands/wc.ts diff --git a/src/lib/commands/README.md b/src/lib/commands/README.md index 8997429a..f54d5379 100644 --- a/src/lib/commands/README.md +++ b/src/lib/commands/README.md @@ -24,6 +24,8 @@ Commands return a `ShellCommandResult` object containing: ## Available Commands +The shell supports 15 essential commands for file and directory operations, text processing, and content analysis. + ### cat **Usage:** `cat [file...]` @@ -171,6 +173,173 @@ cp file1.txt file2.txt dest/ # Copy multiple files to directory - Creates target directories as needed - Handles multiple source files +### head + +**Usage:** `head [-n lines] [file...]` + +Display the first lines of files. Shows first 10 lines by default. + +**Options:** +- `-n lines`: Show specific number of lines (e.g., `-n 5` or `-n5`) + +**Examples:** +```bash +head file.txt # Show first 10 lines +head -n 5 file.txt # Show first 5 lines +head -n3 file1.txt file2.txt # Show first 3 lines of multiple files +``` + +**Features:** +- Configurable line count with `-n` option +- Supports multiple files with headers +- Proper error handling for missing files and directories +- Rejects absolute paths for security + +### tail + +**Usage:** `tail [-n lines] [file...]` + +Display the last lines of files. Shows last 10 lines by default. + +**Options:** +- `-n lines`: Show specific number of lines (e.g., `-n 5` or `-n5`) + +**Examples:** +```bash +tail file.txt # Show last 10 lines +tail -n 5 file.txt # Show last 5 lines +tail -n3 file1.txt file2.txt # Show last 3 lines of multiple files +``` + +**Features:** +- Configurable line count with `-n` option +- Supports multiple files with headers +- Handles files with or without trailing newlines +- Proper error handling for missing files and directories + +### grep + +**Usage:** `grep [-i] [-n] [-r] pattern [file...]` + +Search for patterns in files using regular expressions. + +**Options:** +- `-i`: Case-insensitive search +- `-n`: Show line numbers +- `-r`, `-R`: Search directories recursively + +**Examples:** +```bash +grep "error" log.txt # Search for "error" in log.txt +grep -i "hello" file.txt # Case-insensitive search +grep -n "function" *.js # Show line numbers +grep -r "TODO" src/ # Recursive search in directory +``` + +**Features:** +- Regular expression pattern matching +- Case-insensitive search option +- Line number display +- Recursive directory search +- Multiple file support with filename prefixes +- Returns exit code 1 when no matches found (standard grep behavior) + +### find + +**Usage:** `find [path...] [-name pattern] [-type f|d]` + +Search for files and directories by name and type. + +**Options:** +- `-name pattern`: Search by filename pattern (supports * and ? wildcards) +- `-type f`: Find only files +- `-type d`: Find only directories + +**Examples:** +```bash +find . # List all files and directories +find . -name "*.js" # Find all JavaScript files +find . -type d # Find only directories +find src/ -name "test*" -type f # Find files starting with "test" in src/ +``` + +**Features:** +- Recursive directory traversal +- Glob-style pattern matching with * and ? wildcards +- File type filtering (files vs directories) +- Multiple search paths +- Case-insensitive pattern matching + +### wc + +**Usage:** `wc [-l] [-w] [-c] [file...]` + +Count lines, words, and characters in files. + +**Options:** +- `-l`: Count only lines +- `-w`: Count only words +- `-c`: Count only characters +- (no options): Show all counts (lines, words, characters) + +**Examples:** +```bash +wc file.txt # Show lines, words, and characters +wc -l file.txt # Count only lines +wc -w *.txt # Count words in all .txt files +wc file1.txt file2.txt # Show counts and totals for multiple files +``` + +**Features:** +- Line, word, and character counting +- Multiple file support with totals +- Configurable output (lines, words, characters, or all) +- Proper handling of empty files +- Formatted columnar output + +### touch + +**Usage:** `touch file...` + +Create empty files or update timestamps. + +**Examples:** +```bash +touch newfile.txt # Create empty file +touch file1.txt file2.txt # Create multiple files +touch existing.txt # Update timestamp (no-op in this implementation) +``` + +**Features:** +- Creates empty files if they don't exist +- Handles existing files gracefully +- Multiple file support +- Validates parent directory exists +- Prevents touching directories + +### mkdir + +**Usage:** `mkdir [-p] directory...` + +Create directories. + +**Options:** +- `-p`: Create parent directories as needed + +**Examples:** +```bash +mkdir newdir # Create single directory +mkdir dir1 dir2 dir3 # Create multiple directories +mkdir -p deep/nested/path # Create nested directories +``` + +**Features:** +- Single and multiple directory creation +- Recursive directory creation with `-p` option +- Proper error handling for existing files/directories +- Validates parent directory permissions +- Prevents conflicts with existing files + ### mv **Usage:** `mv source... destination` diff --git a/src/lib/commands/find.test.ts b/src/lib/commands/find.test.ts new file mode 100644 index 00000000..30770dcb --- /dev/null +++ b/src/lib/commands/find.test.ts @@ -0,0 +1,114 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { FindCommand } from './find'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const mockFS = { + stat: async (path: string) => { + if (path === '/project/test.txt') { + return { isFile: () => true, isDirectory: () => false }; + } + if (path === '/project' || path === '/project/src') { + return { isFile: () => false, isDirectory: () => true }; + } + throw new Error('ENOENT: not found'); + }, + readdir: async (path: string, _options: { withFileTypes: boolean }) => { + if (path === '/project') { + return [ + { name: 'test.txt', isFile: () => true, isDirectory: () => false }, + { name: 'package.json', isFile: () => true, isDirectory: () => false }, + { name: 'src', isFile: () => false, isDirectory: () => true }, + ]; + } + if (path === '/project/src') { + return [ + { name: 'index.ts', isFile: () => true, isDirectory: () => false }, + { name: 'utils.ts', isFile: () => true, isDirectory: () => false }, + ]; + } + return []; + }, +} as unknown as JSRuntimeFS; + +describe('FindCommand', () => { + let command: FindCommand; + + beforeEach(() => { + command = new FindCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('find'); + expect(command.description).toBe('Search for files and directories'); + expect(command.usage).toBe('find [path...] [-name pattern] [-type f|d]'); + }); + + it('should find all files and directories by default', async () => { + const result = await command.execute(['.'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('.'); + expect(result.stdout).toContain('./test.txt'); + expect(result.stdout).toContain('./package.json'); + expect(result.stdout).toContain('./src'); + expect(result.stdout).toContain('./src/index.ts'); + }); + + it('should filter by file type with -type f', async () => { + const result = await command.execute(['.', '-type', 'f'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('./test.txt'); + expect(result.stdout).toContain('./package.json'); + expect(result.stdout.split('\n')).not.toContain('./src'); + }); + + it('should filter by directory type with -type d', async () => { + const result = await command.execute(['.', '-type', 'd'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('.'); + expect(result.stdout).toContain('./src'); + expect(result.stdout).not.toContain('./test.txt'); + }); + + it('should filter by name pattern', async () => { + const result = await command.execute(['.', '-name', '*.ts'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('./src/index.ts'); + expect(result.stdout).toContain('./src/utils.ts'); + expect(result.stdout).not.toContain('./test.txt'); + }); + + it('should combine name and type filters', async () => { + const result = await command.execute(['.', '-name', '*.ts', '-type', 'f'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('./src/index.ts'); + expect(result.stdout).toContain('./src/utils.ts'); + expect(result.stdout.split('\n')).not.toContain('./src'); + }); + + it('should handle file not found', async () => { + const result = await command.execute(['nonexistent'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should reject absolute paths', async () => { + const result = await command.execute(['/absolute/path'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('absolute paths are not supported'); + }); + + it('should default to current directory when no path specified', async () => { + const result = await command.execute(['-name', '*.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('./test.txt'); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/find.ts b/src/lib/commands/find.ts new file mode 100644 index 00000000..3e68e579 --- /dev/null +++ b/src/lib/commands/find.ts @@ -0,0 +1,174 @@ +import { join, basename } from "@std/path"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'find' command + * Search for files and directories + */ +export class FindCommand implements ShellCommand { + name = 'find'; + description = 'Search for files and directories'; + usage = 'find [path...] [-name pattern] [-type f|d]'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + const { paths, options } = this.parseArgs(args); + const searchPaths = paths.length > 0 ? paths : ['.']; // Default to current directory + + try { + const results: string[] = []; + + for (const searchPath of searchPaths) { + try { + // Handle absolute paths + if (searchPath.startsWith('/') || searchPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(searchPath)) { + return createErrorResult(`${this.name}: absolute paths are not supported: ${searchPath}`); + } + + const absolutePath = join(cwd, searchPath); + + // Check if path exists + const stats = await this.fs.stat(absolutePath); + + if (stats.isFile()) { + // If it's a file, check if it matches the criteria + if (this.matchesFilter(basename(searchPath), 'f', options)) { + results.push(searchPath === '.' ? searchPath : searchPath); + } + } else if (stats.isDirectory()) { + // Search recursively in directory + const matches = await this.searchDirectory(absolutePath, searchPath, options); + results.push(...matches); + } + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('ENOENT') || error.message.includes('not found')) { + return createErrorResult(`${this.name}: ${searchPath}: No such file or directory`); + } else if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${searchPath}: Permission denied`); + } else { + return createErrorResult(`${this.name}: ${searchPath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${searchPath}: Unknown error`); + } + } + } + + return createSuccessResult(results.join('\n') + (results.length > 0 ? '\n' : '')); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async searchDirectory( + dirPath: string, + relativePath: string, + options: { namePattern?: string; type?: 'f' | 'd' } + ): Promise { + try { + const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); + const results: string[] = []; + + // Add the directory itself if it matches + if (this.matchesFilter(basename(relativePath), 'd', options)) { + results.push(relativePath); + } + + for (const entry of entries) { + const entryPath = join(dirPath, entry.name); + let entryRelativePath: string; + + if (relativePath === '.') { + entryRelativePath = `./${entry.name}`; + } else if (relativePath.startsWith('./')) { + entryRelativePath = `${relativePath}/${entry.name}`; + } else { + entryRelativePath = join(relativePath, entry.name); + } + + if (entry.isFile()) { + if (this.matchesFilter(entry.name, 'f', options)) { + results.push(entryRelativePath); + } + } else if (entry.isDirectory()) { + // Recursively search subdirectory + const subResults = await this.searchDirectory(entryPath, entryRelativePath, options); + results.push(...subResults); + } + } + + return results; + } catch { + return []; + } + } + + private matchesFilter( + name: string, + type: 'f' | 'd', + options: { namePattern?: string; type?: 'f' | 'd' } + ): boolean { + // Check type filter + if (options.type && options.type !== type) { + return false; + } + + // Check name pattern (simple glob-style matching) + if (options.namePattern) { + const pattern = options.namePattern + .replace(/\./g, '\\.') // Escape dots + .replace(/\*/g, '.*') // Convert * to .* + .replace(/\?/g, '.'); // Convert ? to . + + const regex = new RegExp(`^${pattern}$`, 'i'); + return regex.test(name); + } + + return true; + } + + private parseArgs(args: string[]): { + paths: string[]; + options: { namePattern?: string; type?: 'f' | 'd' }; + } { + const paths: string[] = []; + const options: { namePattern?: string; type?: 'f' | 'd' } = {}; + let i = 0; + + while (i < args.length) { + const arg = args[i]; + + if (arg === '-name') { + i++; + if (i < args.length) { + options.namePattern = args[i]; + } + } else if (arg === '-type') { + i++; + if (i < args.length) { + const typeArg = args[i]; + if (typeArg === 'f' || typeArg === 'd') { + options.type = typeArg; + } + } + } else if (!arg.startsWith('-')) { + paths.push(arg); + } + // Ignore other options for now + + i++; + } + + return { paths, options }; + } +} \ No newline at end of file diff --git a/src/lib/commands/grep.test.ts b/src/lib/commands/grep.test.ts new file mode 100644 index 00000000..13722baa --- /dev/null +++ b/src/lib/commands/grep.test.ts @@ -0,0 +1,111 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { GrepCommand } from './grep'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const mockFS = { + stat: async (path: string) => { + if (path === '/project/test.txt') { + return { isFile: () => true, isDirectory: () => false }; + } + if (path === '/project/dir') { + return { isFile: () => false, isDirectory: () => true }; + } + throw new Error('ENOENT: not found'); + }, + readFile: async (path: string, _encoding: string) => { + if (path === '/project/test.txt') { + return 'Hello World\nThis is a test\nHELLO again\nAnother line\ntest file'; + } + throw new Error('ENOENT: not found'); + }, + readdir: async (path: string, _options: { withFileTypes: boolean }) => { + if (path === '/project/dir') { + return [ + { name: 'file1.txt', isFile: () => true, isDirectory: () => false }, + { name: 'file2.txt', isFile: () => true, isDirectory: () => false }, + ]; + } + return []; + }, +} as unknown as JSRuntimeFS; + +describe('GrepCommand', () => { + let command: GrepCommand; + + beforeEach(() => { + command = new GrepCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('grep'); + expect(command.description).toBe('Search for patterns in files'); + expect(command.usage).toBe('grep [-i] [-n] [-r] pattern [file...]'); + }); + + it('should search for pattern in file', async () => { + const result = await command.execute(['test', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('This is a test'); + expect(result.stdout).toContain('test file'); + }); + + it('should search case-insensitive with -i', async () => { + const result = await command.execute(['-i', 'hello', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Hello World'); + expect(result.stdout).toContain('HELLO again'); + }); + + it('should show line numbers with -n', async () => { + const result = await command.execute(['-n', 'test', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('2:This is a test'); + expect(result.stdout).toContain('5:test file'); + }); + + it('should return exit code 1 when no matches found', async () => { + const result = await command.execute(['nonexistent', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(''); + }); + + it('should handle file not found', async () => { + const result = await command.execute(['pattern', 'nonexistent.txt'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should handle directory without -r flag', async () => { + const result = await command.execute(['pattern', 'dir'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should require pattern argument', async () => { + const result = await command.execute([], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('missing pattern'); + }); + + it('should reject absolute paths', async () => { + const result = await command.execute(['pattern', '/absolute/path'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('absolute paths are not supported'); + }); + + it('should reject stdin', async () => { + const result = await command.execute(['pattern', '-'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('reading from stdin is not supported'); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/grep.ts b/src/lib/commands/grep.ts new file mode 100644 index 00000000..31253085 --- /dev/null +++ b/src/lib/commands/grep.ts @@ -0,0 +1,224 @@ +import { join } from "@std/path"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'grep' command + * Search for patterns in files + */ +export class GrepCommand implements ShellCommand { + name = 'grep'; + description = 'Search for patterns in files'; + usage = 'grep [-i] [-n] [-r] pattern [file...]'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + if (args.length === 0) { + return createErrorResult(`${this.name}: missing pattern\nUsage: ${this.usage}`); + } + + const { options, pattern, files } = this.parseArgs(args); + + if (!pattern) { + return createErrorResult(`${this.name}: missing pattern\nUsage: ${this.usage}`); + } + + const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files + + try { + const regex = new RegExp(pattern, options.ignoreCase ? 'gi' : 'g'); + const outputs: string[] = []; + let foundMatches = false; + + for (const filePath of targetFiles) { + try { + if (filePath === '-') { + return createErrorResult(`${this.name}: reading from stdin is not supported`); + } + + // Handle absolute paths + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + return createErrorResult(`${this.name}: absolute paths are not supported: ${filePath}`); + } + + const absolutePath = join(cwd, filePath); + + // Check if path exists + const stats = await this.fs.stat(absolutePath); + + if (stats.isDirectory()) { + if (options.recursive) { + // Recursively search directory + const dirMatches = await this.searchDirectory(absolutePath, regex, options, cwd); + if (dirMatches.length > 0) { + outputs.push(...dirMatches); + foundMatches = true; + } + } else { + return createErrorResult(`${this.name}: ${filePath}: Is a directory`); + } + } else { + // Search in file + const fileMatches = await this.searchFile(absolutePath, regex, options, targetFiles.length > 1 ? filePath : null); + if (fileMatches.length > 0) { + outputs.push(...fileMatches); + foundMatches = true; + } + } + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('ENOENT') || error.message.includes('not found')) { + return createErrorResult(`${this.name}: ${filePath}: No such file or directory`); + } else if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${filePath}: Permission denied`); + } else { + return createErrorResult(`${this.name}: ${filePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${filePath}: Unknown error`); + } + } + } + + if (!foundMatches) { + // grep exits with code 1 when no matches found + return { + exitCode: 1, + stdout: '', + stderr: '', + }; + } + + return createSuccessResult(outputs.join('\n') + (outputs.length > 0 ? '\n' : '')); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async searchFile( + filePath: string, + regex: RegExp, + options: { ignoreCase: boolean; showLineNumbers: boolean; recursive: boolean }, + displayName: string | null + ): Promise { + try { + const content = await this.fs.readFile(filePath, 'utf8'); + const lines = content.split('\n'); + const matches: string[] = []; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (regex.test(line)) { + let output = ''; + + if (displayName) { + output += `${displayName}:`; + } + + if (options.showLineNumbers) { + output += `${i + 1}:`; + } + + output += line; + matches.push(output); + } + + // Reset regex lastIndex for global regex + regex.lastIndex = 0; + } + + return matches; + } catch { + return []; + } + } + + private async searchDirectory( + dirPath: string, + regex: RegExp, + options: { ignoreCase: boolean; showLineNumbers: boolean; recursive: boolean }, + baseCwd: string + ): Promise { + try { + const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); + const matches: string[] = []; + + for (const entry of entries) { + const entryPath = join(dirPath, entry.name); + + if (entry.isFile()) { + // Get relative path from base cwd for display + const relativePath = entryPath.startsWith(baseCwd) + ? entryPath.slice(baseCwd.length + 1) + : entryPath; + + const fileMatches = await this.searchFile(entryPath, regex, options, relativePath); + matches.push(...fileMatches); + } else if (entry.isDirectory() && options.recursive) { + const dirMatches = await this.searchDirectory(entryPath, regex, options, baseCwd); + matches.push(...dirMatches); + } + } + + return matches; + } catch { + return []; + } + } + + private parseArgs(args: string[]): { + options: { ignoreCase: boolean; showLineNumbers: boolean; recursive: boolean }; + pattern: string | null; + files: string[] + } { + const options = { ignoreCase: false, showLineNumbers: false, recursive: false }; + const files: string[] = []; + let pattern: string | null = null; + let i = 0; + + while (i < args.length) { + const arg = args[i]; + + if (arg.startsWith('-') && arg !== '-') { + // Parse options + for (let j = 1; j < arg.length; j++) { + const char = arg[j]; + switch (char) { + case 'i': + options.ignoreCase = true; + break; + case 'n': + options.showLineNumbers = true; + break; + case 'r': + case 'R': + options.recursive = true; + break; + default: + // Ignore unknown options + break; + } + } + } else { + // First non-option argument is the pattern + if (pattern === null) { + pattern = arg; + } else { + files.push(arg); + } + } + + i++; + } + + return { options, pattern, files }; + } +} \ No newline at end of file diff --git a/src/lib/commands/head.test.ts b/src/lib/commands/head.test.ts new file mode 100644 index 00000000..8ab15af3 --- /dev/null +++ b/src/lib/commands/head.test.ts @@ -0,0 +1,85 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { HeadCommand } from './head'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const mockFS = { + stat: async (path: string) => { + if (path === '/project/test.txt') { + return { isFile: () => true, isDirectory: () => false }; + } + if (path === '/project/dir') { + return { isFile: () => false, isDirectory: () => true }; + } + throw new Error('ENOENT: not found'); + }, + readFile: async (path: string, _encoding: string) => { + if (path === '/project/test.txt') { + return 'line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\n'; + } + throw new Error('ENOENT: not found'); + }, +} as unknown as JSRuntimeFS; + +describe('HeadCommand', () => { + let command: HeadCommand; + + beforeEach(() => { + command = new HeadCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('head'); + expect(command.description).toBe('Display the first lines of files'); + expect(command.usage).toBe('head [-n lines] [file...]'); + }); + + it('should show first 10 lines by default', async () => { + const result = await command.execute(['test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe('line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\n'); + }); + + it('should show custom number of lines with -n', async () => { + const result = await command.execute(['-n', '3', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe('line 1\nline 2\nline 3\n'); + }); + + it('should show custom number of lines with -n3 format', async () => { + const result = await command.execute(['-n3', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe('line 1\nline 2\nline 3\n'); + }); + + it('should handle file not found', async () => { + const result = await command.execute(['nonexistent.txt'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should handle directory error', async () => { + const result = await command.execute(['dir'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should reject absolute paths', async () => { + const result = await command.execute(['/absolute/path'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('absolute paths are not supported'); + }); + + it('should reject stdin', async () => { + const result = await command.execute(['-'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('reading from stdin is not supported'); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/head.ts b/src/lib/commands/head.ts new file mode 100644 index 00000000..2b71483a --- /dev/null +++ b/src/lib/commands/head.ts @@ -0,0 +1,125 @@ +import { join } from "@std/path"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'head' command + * Display the first lines of files + */ +export class HeadCommand implements ShellCommand { + name = 'head'; + description = 'Display the first lines of files'; + usage = 'head [-n lines] [file...]'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + const { options, files } = this.parseArgs(args); + const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files + + try { + const outputs: string[] = []; + + for (const filePath of targetFiles) { + try { + if (filePath === '-') { + return createErrorResult(`${this.name}: reading from stdin is not supported`); + } + + // Handle absolute paths + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + return createErrorResult(`${this.name}: absolute paths are not supported: ${filePath}`); + } + + const absolutePath = join(cwd, filePath); + + // Check if path exists and is a file + const stats = await this.fs.stat(absolutePath); + + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: ${filePath}: Is a directory`); + } + + // Read file content + const content = await this.fs.readFile(absolutePath, 'utf8'); + const lines = content.split('\n'); + + // Take first n lines (but don't add extra newline if file doesn't end with one) + const selectedLines = lines.slice(0, options.lines); + + // If we're showing multiple files, add a header + if (targetFiles.length > 1) { + outputs.push(`==> ${filePath} <==`); + } + + // Join lines and preserve original line endings + const result = selectedLines.join('\n'); + outputs.push(result); + + // Add separator between files (except for last file) + if (targetFiles.length > 1 && filePath !== targetFiles[targetFiles.length - 1]) { + outputs.push(''); + } + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('ENOENT') || error.message.includes('not found')) { + return createErrorResult(`${this.name}: ${filePath}: No such file or directory`); + } else if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${filePath}: Permission denied`); + } else { + return createErrorResult(`${this.name}: ${filePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${filePath}: Unknown error`); + } + } + } + + return createSuccessResult(outputs.join('\n') + (outputs.length > 0 ? '\n' : '')); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { options: { lines: number }; files: string[] } { + const options = { lines: 10 }; // Default to 10 lines + const files: string[] = []; + let i = 0; + + while (i < args.length) { + const arg = args[i]; + + if (arg === '-n') { + // Next argument should be the number of lines + i++; + if (i < args.length) { + const lineCount = parseInt(args[i], 10); + if (!isNaN(lineCount) && lineCount > 0) { + options.lines = lineCount; + } + } + } else if (arg.startsWith('-n')) { + // -n10 format + const lineCount = parseInt(arg.slice(2), 10); + if (!isNaN(lineCount) && lineCount > 0) { + options.lines = lineCount; + } + } else if (arg.startsWith('-') && arg !== '-') { + // Other options (ignore for now) + } else { + files.push(arg); + } + + i++; + } + + return { options, files }; + } +} \ No newline at end of file diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index b4d46c94..0b07e34b 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -3,7 +3,14 @@ export { CatCommand } from './cat'; export { CdCommand } from './cd'; export { CpCommand } from './cp'; export { EchoCommand } from './echo'; +export { FindCommand } from './find'; +export { GrepCommand } from './grep'; +export { HeadCommand } from './head'; export { LsCommand } from './ls'; +export { MkdirCommand } from './mkdir'; export { MvCommand } from './mv'; export { PwdCommand } from './pwd'; -export { RmCommand } from './rm'; \ No newline at end of file +export { RmCommand } from './rm'; +export { TailCommand } from './tail'; +export { TouchCommand } from './touch'; +export { WcCommand } from './wc'; \ No newline at end of file diff --git a/src/lib/commands/mkdir.test.ts b/src/lib/commands/mkdir.test.ts new file mode 100644 index 00000000..ba167738 --- /dev/null +++ b/src/lib/commands/mkdir.test.ts @@ -0,0 +1,95 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { MkdirCommand } from './mkdir'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const mockFS = { + stat: async (path: string) => { + if (path === '/project/existing') { + return { isFile: () => false, isDirectory: () => true }; + } + if (path === '/project/file.txt') { + return { isFile: () => true, isDirectory: () => false }; + } + if (path === '/project') { + return { isFile: () => false, isDirectory: () => true }; + } + throw new Error('ENOENT: not found'); + }, + mkdir: async (path: string) => { + if (path === '/project/newdir' || path === '/project/deep' || path === '/project/deep/nested') { + return; // Success + } + throw new Error('mkdir failed'); + }, +} as unknown as JSRuntimeFS; + +describe('MkdirCommand', () => { + let command: MkdirCommand; + + beforeEach(() => { + command = new MkdirCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('mkdir'); + expect(command.description).toBe('Create directories'); + expect(command.usage).toBe('mkdir [-p] directory...'); + }); + + it('should create new directory', async () => { + const result = await command.execute(['newdir'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + }); + + it('should handle existing directory error', async () => { + const result = await command.execute(['existing'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('File exists'); + }); + + it('should handle existing file error', async () => { + const result = await command.execute(['file.txt'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('File exists'); + }); + + it('should create parent directories with -p', async () => { + const result = await command.execute(['-p', 'deep/nested'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + }); + + it('should handle missing parent directory without -p', async () => { + const result = await command.execute(['nonexistent/newdir'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should require directory operand', async () => { + const result = await command.execute([], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('missing operand'); + }); + + it('should reject absolute paths', async () => { + const result = await command.execute(['/absolute/path'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('absolute paths are not supported'); + }); + + it('should handle multiple directories', async () => { + const result = await command.execute(['newdir', 'deep'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/mkdir.ts b/src/lib/commands/mkdir.ts new file mode 100644 index 00000000..3f5cb107 --- /dev/null +++ b/src/lib/commands/mkdir.ts @@ -0,0 +1,160 @@ +import { join, dirname } from "@std/path"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'mkdir' command + * Create directories + */ +export class MkdirCommand implements ShellCommand { + name = 'mkdir'; + description = 'Create directories'; + usage = 'mkdir [-p] directory...'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + if (args.length === 0) { + return createErrorResult(`${this.name}: missing operand\nUsage: ${this.usage}`); + } + + const { options, directories } = this.parseArgs(args); + + if (directories.length === 0) { + return createErrorResult(`${this.name}: missing operand\nUsage: ${this.usage}`); + } + + try { + for (const dirPath of directories) { + try { + // Handle absolute paths + if (dirPath.startsWith('/') || dirPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(dirPath)) { + return createErrorResult(`${this.name}: absolute paths are not supported: ${dirPath}`); + } + + const absolutePath = join(cwd, dirPath); + + if (options.parents) { + // Create parent directories as needed (-p option) + await this.createDirectoryRecursive(absolutePath, dirPath); + } else { + // Create only the specified directory + try { + // Check if it already exists + const stats = await this.fs.stat(absolutePath); + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: cannot create directory '${dirPath}': File exists`); + } else { + return createErrorResult(`${this.name}: cannot create directory '${dirPath}': File exists`); + } + } catch (error) { + // Directory doesn't exist, try to create it + if (error instanceof Error && + (error.message.includes('ENOENT') || error.message.includes('not found'))) { + + // Check if parent directory exists + 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`); + } + + // Create the directory + await this.fs.mkdir(absolutePath); + } else { + return createErrorResult(`${this.name}: ${dirPath}: ${error.message}`); + } + } + } + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${dirPath}: Permission denied`); + } else if (error.message.includes('EEXIST') || error.message.includes('exists')) { + if (!options.parents) { + return createErrorResult(`${this.name}: cannot create directory '${dirPath}': File exists`); + } + // With -p, ignore if directory already exists + } else { + return createErrorResult(`${this.name}: ${dirPath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${dirPath}: Unknown error`); + } + } + } + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async createDirectoryRecursive(absolutePath: string, originalPath: string): Promise { + try { + // Check if directory already exists + const stats = await this.fs.stat(absolutePath); + if (stats.isDirectory()) { + return; // Already exists, nothing to do + } else { + throw new Error(`${this.name}: cannot create directory '${originalPath}': File exists`); + } + } catch (error) { + // Directory doesn't exist, try to create it + if (error instanceof Error && + (error.message.includes('ENOENT') || error.message.includes('not found'))) { + + // Try to create parent directory first + const parentDir = dirname(absolutePath); + if (parentDir !== absolutePath) { // Avoid infinite recursion + await this.createDirectoryRecursive(parentDir, dirname(originalPath)); + } + + // Now create this directory + await this.fs.mkdir(absolutePath); + } else { + throw error; + } + } + } + + private parseArgs(args: string[]): { + options: { parents: boolean }; + directories: string[]; + } { + const options = { parents: false }; + const directories: string[] = []; + + for (const arg of args) { + if (arg.startsWith('-') && arg !== '-') { + // Parse options + for (let i = 1; i < arg.length; i++) { + const char = arg[i]; + switch (char) { + case 'p': + options.parents = true; + break; + default: + // Ignore unknown options + break; + } + } + } else { + directories.push(arg); + } + } + + return { options, directories }; + } +} \ No newline at end of file diff --git a/src/lib/commands/tail.test.ts b/src/lib/commands/tail.test.ts new file mode 100644 index 00000000..334c3be6 --- /dev/null +++ b/src/lib/commands/tail.test.ts @@ -0,0 +1,85 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { TailCommand } from './tail'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const mockFS = { + stat: async (path: string) => { + if (path === '/project/test.txt') { + return { isFile: () => true, isDirectory: () => false }; + } + if (path === '/project/dir') { + return { isFile: () => false, isDirectory: () => true }; + } + throw new Error('ENOENT: not found'); + }, + readFile: async (path: string, _encoding: string) => { + if (path === '/project/test.txt') { + return 'line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\n'; + } + throw new Error('ENOENT: not found'); + }, +} as unknown as JSRuntimeFS; + +describe('TailCommand', () => { + let command: TailCommand; + + beforeEach(() => { + command = new TailCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('tail'); + expect(command.description).toBe('Display the last lines of files'); + expect(command.usage).toBe('tail [-n lines] [file...]'); + }); + + it('should show last 10 lines by default', async () => { + const result = await command.execute(['test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe('line 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\n'); + }); + + it('should show custom number of lines with -n', async () => { + const result = await command.execute(['-n', '3', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe('line 10\nline 11\nline 12\n'); + }); + + it('should show custom number of lines with -n3 format', async () => { + const result = await command.execute(['-n3', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe('line 10\nline 11\nline 12\n'); + }); + + it('should handle file not found', async () => { + const result = await command.execute(['nonexistent.txt'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should handle directory error', async () => { + const result = await command.execute(['dir'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should reject absolute paths', async () => { + const result = await command.execute(['/absolute/path'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('absolute paths are not supported'); + }); + + it('should reject stdin', async () => { + const result = await command.execute(['-'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('reading from stdin is not supported'); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/tail.ts b/src/lib/commands/tail.ts new file mode 100644 index 00000000..b115cb95 --- /dev/null +++ b/src/lib/commands/tail.ts @@ -0,0 +1,130 @@ +import { join } from "@std/path"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'tail' command + * Display the last lines of files + */ +export class TailCommand implements ShellCommand { + name = 'tail'; + description = 'Display the last lines of files'; + usage = 'tail [-n lines] [file...]'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + const { options, files } = this.parseArgs(args); + const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files + + try { + const outputs: string[] = []; + + for (const filePath of targetFiles) { + try { + if (filePath === '-') { + return createErrorResult(`${this.name}: reading from stdin is not supported`); + } + + // Handle absolute paths + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + return createErrorResult(`${this.name}: absolute paths are not supported: ${filePath}`); + } + + const absolutePath = join(cwd, filePath); + + // Check if path exists and is a file + const stats = await this.fs.stat(absolutePath); + + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: ${filePath}: Is a directory`); + } + + // Read file content + const content = await this.fs.readFile(absolutePath, 'utf8'); + const 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(); + } + + // Take last n lines + const selectedLines = lines.slice(-options.lines); + + // If we're showing multiple files, add a header + if (targetFiles.length > 1) { + outputs.push(`==> ${filePath} <==`); + } + + // Join lines and add final newline + const result = selectedLines.join('\n'); + outputs.push(result); + + // Add separator between files (except for last file) + if (targetFiles.length > 1 && filePath !== targetFiles[targetFiles.length - 1]) { + outputs.push(''); + } + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('ENOENT') || error.message.includes('not found')) { + return createErrorResult(`${this.name}: ${filePath}: No such file or directory`); + } else if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${filePath}: Permission denied`); + } else { + return createErrorResult(`${this.name}: ${filePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${filePath}: Unknown error`); + } + } + } + + return createSuccessResult(outputs.join('\n') + (outputs.length > 0 ? '\n' : '')); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { options: { lines: number }; files: string[] } { + const options = { lines: 10 }; // Default to 10 lines + const files: string[] = []; + let i = 0; + + while (i < args.length) { + const arg = args[i]; + + if (arg === '-n') { + // Next argument should be the number of lines + i++; + if (i < args.length) { + const lineCount = parseInt(args[i], 10); + if (!isNaN(lineCount) && lineCount > 0) { + options.lines = lineCount; + } + } + } else if (arg.startsWith('-n')) { + // -n10 format + const lineCount = parseInt(arg.slice(2), 10); + if (!isNaN(lineCount) && lineCount > 0) { + options.lines = lineCount; + } + } else if (arg.startsWith('-') && arg !== '-') { + // Other options (ignore for now) + } else { + files.push(arg); + } + + i++; + } + + return { options, files }; + } +} \ No newline at end of file diff --git a/src/lib/commands/touch.test.ts b/src/lib/commands/touch.test.ts new file mode 100644 index 00000000..590f2ef8 --- /dev/null +++ b/src/lib/commands/touch.test.ts @@ -0,0 +1,81 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { TouchCommand } from './touch'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const mockFS = { + stat: async (path: string) => { + if (path === '/project/existing.txt') { + return { isFile: () => true, isDirectory: () => false }; + } + if (path === '/project/dir') { + return { isFile: () => false, isDirectory: () => true }; + } + if (path === '/project') { + return { isFile: () => false, isDirectory: () => true }; + } + throw new Error('ENOENT: not found'); + }, + writeFile: async (path: string, _content: string, _encoding: string) => { + if (path === '/project/newfile.txt') { + return; // Success + } + throw new Error('Write failed'); + }, +} as unknown as JSRuntimeFS; + +describe('TouchCommand', () => { + let command: TouchCommand; + + beforeEach(() => { + command = new TouchCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('touch'); + expect(command.description).toBe('Create empty files or update timestamps'); + expect(command.usage).toBe('touch file...'); + }); + + it('should create new file', async () => { + const result = await command.execute(['newfile.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + }); + + it('should handle existing file (no-op)', async () => { + const result = await command.execute(['existing.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + }); + + it('should handle directory error', async () => { + const result = await command.execute(['dir'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should require file operand', async () => { + const result = await command.execute([], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('missing file operand'); + }); + + it('should reject absolute paths', async () => { + const result = await command.execute(['/absolute/path'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('absolute paths are not supported'); + }); + + it('should handle missing parent directory', async () => { + const result = await command.execute(['nonexistent/file.txt'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/touch.ts b/src/lib/commands/touch.ts new file mode 100644 index 00000000..ea65c796 --- /dev/null +++ b/src/lib/commands/touch.ts @@ -0,0 +1,90 @@ +import { join, dirname } from "@std/path"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'touch' command + * Create empty files or update timestamps + */ +export class TouchCommand implements ShellCommand { + name = 'touch'; + description = 'Create empty files or update timestamps'; + usage = 'touch file...'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + if (args.length === 0) { + return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`); + } + + try { + for (const filePath of args) { + try { + // Handle absolute paths + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + return createErrorResult(`${this.name}: absolute paths are not supported: ${filePath}`); + } + + const absolutePath = join(cwd, filePath); + + try { + // Check if file exists + const stats = await this.fs.stat(absolutePath); + + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: ${filePath}: Is a directory`); + } + + // File exists, update timestamp (in real systems) + // For this implementation, we'll just leave it as is since + // LightningFS doesn't have a direct way to update timestamps + // without modifying the file content + + } catch (error) { + // File doesn't exist, create it + if (error instanceof Error && + (error.message.includes('ENOENT') || error.message.includes('not found'))) { + + // Ensure parent directory exists + const parentDir = dirname(absolutePath); + try { + await this.fs.stat(parentDir); + } catch { + // Parent directory doesn't exist + return createErrorResult(`${this.name}: cannot touch '${filePath}': No such file or directory`); + } + + // Create empty file + await this.fs.writeFile(absolutePath, '', 'utf8'); + } else { + // Other error (permission, etc.) + return createErrorResult(`${this.name}: ${filePath}: ${error.message}`); + } + } + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${filePath}: Permission denied`); + } else { + return createErrorResult(`${this.name}: ${filePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${filePath}: Unknown error`); + } + } + } + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/commands/wc.test.ts b/src/lib/commands/wc.test.ts new file mode 100644 index 00000000..1f159d5c --- /dev/null +++ b/src/lib/commands/wc.test.ts @@ -0,0 +1,114 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { WcCommand } from './wc'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const mockFS = { + stat: async (path: string) => { + if (path === '/project/test.txt') { + return { isFile: () => true, isDirectory: () => false }; + } + if (path === '/project/empty.txt') { + return { isFile: () => true, isDirectory: () => false }; + } + if (path === '/project/dir') { + return { isFile: () => false, isDirectory: () => true }; + } + throw new Error('ENOENT: not found'); + }, + readFile: async (path: string, _encoding: string) => { + if (path === '/project/test.txt') { + return 'Hello world\nThis is a test file\nWith multiple lines\n'; + } + if (path === '/project/empty.txt') { + return ''; + } + throw new Error('ENOENT: not found'); + }, +} as unknown as JSRuntimeFS; + +describe('WcCommand', () => { + let command: WcCommand; + + beforeEach(() => { + command = new WcCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('wc'); + expect(command.description).toBe('Count lines, words, and characters in files'); + expect(command.usage).toBe('wc [-l] [-w] [-c] [file...]'); + }); + + it('should count lines, words, and characters by default', async () => { + const result = await command.execute(['test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toMatch(/\s+3\s+10\s+52 test\.txt/); + }); + + it('should count only lines with -l', async () => { + const result = await command.execute(['-l', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toMatch(/\s+3 test\.txt/); + }); + + it('should count only words with -w', async () => { + const result = await command.execute(['-w', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toMatch(/\s+10 test\.txt/); + }); + + it('should count only characters with -c', async () => { + const result = await command.execute(['-c', 'test.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toMatch(/\s+52 test\.txt/); + }); + + it('should handle empty file', async () => { + const result = await command.execute(['empty.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toMatch(/\s+0\s+0\s+0 empty\.txt/); + }); + + it('should show totals for multiple files', async () => { + const result = await command.execute(['test.txt', 'empty.txt'], '/project'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('test.txt'); + expect(result.stdout).toContain('empty.txt'); + expect(result.stdout).toContain('total'); + }); + + it('should handle file not found', async () => { + const result = await command.execute(['nonexistent.txt'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should handle directory error', async () => { + const result = await command.execute(['dir'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should reject absolute paths', async () => { + const result = await command.execute(['/absolute/path'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('absolute paths are not supported'); + }); + + it('should reject stdin', async () => { + const result = await command.execute(['-'], '/project'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('reading from stdin is not supported'); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/wc.ts b/src/lib/commands/wc.ts new file mode 100644 index 00000000..2b9be9c5 --- /dev/null +++ b/src/lib/commands/wc.ts @@ -0,0 +1,165 @@ +import { join } from "@std/path"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'wc' command + * Count lines, words, and characters in files + */ +export class WcCommand implements ShellCommand { + name = 'wc'; + description = 'Count lines, words, and characters in files'; + usage = 'wc [-l] [-w] [-c] [file...]'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + const { options, files } = this.parseArgs(args); + const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files + + // If no specific options, show all counts + if (!options.lines && !options.words && !options.chars) { + options.lines = true; + options.words = true; + options.chars = true; + } + + try { + const results: Array<{ lines: number; words: number; chars: number; name: string }> = []; + let totalLines = 0; + let totalWords = 0; + let totalChars = 0; + + for (const filePath of targetFiles) { + try { + if (filePath === '-') { + return createErrorResult(`${this.name}: reading from stdin is not supported`); + } + + // Handle absolute paths + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + return createErrorResult(`${this.name}: absolute paths are not supported: ${filePath}`); + } + + const absolutePath = join(cwd, filePath); + + // Check if path exists and is a file + const stats = await this.fs.stat(absolutePath); + + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: ${filePath}: Is a directory`); + } + + // Read file content + const content = await this.fs.readFile(absolutePath, 'utf8'); + + // Count lines, words, and characters + const lines = content === '' ? 0 : content.split('\n').length - (content.endsWith('\n') ? 1 : 0); + const words = content.trim() ? content.trim().split(/\s+/).length : 0; + const chars = content.length; + + results.push({ lines, words, chars, name: filePath }); + totalLines += lines; + totalWords += words; + totalChars += chars; + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('ENOENT') || error.message.includes('not found')) { + return createErrorResult(`${this.name}: ${filePath}: No such file or directory`); + } else if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${filePath}: Permission denied`); + } else { + return createErrorResult(`${this.name}: ${filePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${filePath}: Unknown error`); + } + } + } + + // Format output + const outputs: string[] = []; + + for (const result of results) { + const parts: string[] = []; + + if (options.lines) { + parts.push(result.lines.toString().padStart(8)); + } + if (options.words) { + parts.push(result.words.toString().padStart(8)); + } + if (options.chars) { + parts.push(result.chars.toString().padStart(8)); + } + + parts.push(result.name); + outputs.push(parts.join(' ')); + } + + // Add total line if multiple files + if (results.length > 1) { + const parts: string[] = []; + + if (options.lines) { + parts.push(totalLines.toString().padStart(8)); + } + if (options.words) { + parts.push(totalWords.toString().padStart(8)); + } + if (options.chars) { + parts.push(totalChars.toString().padStart(8)); + } + + parts.push('total'); + outputs.push(parts.join(' ')); + } + + return createSuccessResult(outputs.join('\n') + (outputs.length > 0 ? '\n' : '')); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + options: { lines: boolean; words: boolean; chars: boolean }; + files: string[]; + } { + const options = { lines: false, words: false, chars: false }; + const files: string[] = []; + + for (const arg of args) { + if (arg.startsWith('-') && arg !== '-') { + // Parse options + for (let i = 1; i < arg.length; i++) { + const char = arg[i]; + switch (char) { + case 'l': + options.lines = true; + break; + case 'w': + options.words = true; + break; + case 'c': + options.chars = true; + break; + default: + // Ignore unknown options + break; + } + } + } else { + files.push(arg); + } + } + + return { options, files }; + } +} \ No newline at end of file diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index cefa2589..0cecc78f 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -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'); + 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.inputSchema).toBeDefined(); }); diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index 0c5d2a50..d074f77d 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -7,10 +7,17 @@ import { CdCommand, CpCommand, EchoCommand, + FindCommand, + GrepCommand, + HeadCommand, LsCommand, + MkdirCommand, MvCommand, PwdCommand, - RmCommand + RmCommand, + TailCommand, + TouchCommand, + WcCommand } from "../commands"; interface ShellToolParams { @@ -25,7 +32,7 @@ export class ShellTool implements Tool { private cwd: string; private commands: Map; - readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo"; + readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir"; readonly inputSchema = z.object({ command: z.string().describe( @@ -43,10 +50,17 @@ export class ShellTool implements Tool { this.registerCommand(new CdCommand(fs)); this.registerCommand(new CpCommand(fs)); this.registerCommand(new EchoCommand()); + this.registerCommand(new FindCommand(fs)); + this.registerCommand(new GrepCommand(fs)); + this.registerCommand(new HeadCommand(fs)); this.registerCommand(new LsCommand(fs)); + this.registerCommand(new MkdirCommand(fs)); this.registerCommand(new MvCommand(fs)); this.registerCommand(new PwdCommand()); this.registerCommand(new RmCommand(fs)); + this.registerCommand(new TailCommand(fs)); + this.registerCommand(new TouchCommand(fs)); + this.registerCommand(new WcCommand(fs)); } /**