diff --git a/src/lib/commands/hexdump.test.ts b/src/lib/commands/hexdump.test.ts new file mode 100644 index 00000000..5b5b9f46 --- /dev/null +++ b/src/lib/commands/hexdump.test.ts @@ -0,0 +1,229 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { HexdumpCommand } from './hexdump'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn(), + mkdir: vi.fn(), + stat: vi.fn(), + lstat: vi.fn(), + unlink: vi.fn(), + rmdir: vi.fn(), + rename: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), +}); + +describe('HexdumpCommand', () => { + let mockFS: JSRuntimeFS; + let command: HexdumpCommand; + const testCwd = '/test/dir'; + + beforeEach(() => { + mockFS = createMockFS(); + command = new HexdumpCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('hexdump'); + expect(command.description).toBe('Display file contents in hexadecimal format'); + expect(command.usage).toBe('hexdump [-C] [-n length] [-s skip] [file...]'); + }); + + it('should show error when no file is specified', async () => { + const result = await command.execute([], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('missing file operand'); + }); + + it('should show error for non-existent file', async () => { + vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory')); + + const result = await command.execute(['nonexistent.txt'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should show error for directory', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await command.execute(['testdir'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should display hexdump in default format', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('0000000'); + expect(result.stdout).toContain('000000e'); // Final offset + }); + + it('should display hexdump in canonical format with -C', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('|Hello, World!'); + expect(result.stdout).toContain('|'); // Should have ASCII representation + }); + + it('should handle -n length option', async () => { + const content = 'Hello, World!\nThis is a longer line.'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-n', '5', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('|Hello|'); + expect(result.stdout).not.toContain('World'); + }); + + it('should handle -s skip option', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-s', '7', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000007'); + expect(result.stdout).toContain('|World!'); + expect(result.stdout).not.toContain('Hello'); + }); + + it('should handle -n and -s together', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-s', '7', '-n', '5', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000007'); + expect(result.stdout).toContain('|World|'); + expect(result.stdout).not.toContain('Hello'); + expect(result.stdout).not.toContain('!'); + }); + + it('should show error for invalid -n value', async () => { + const result = await command.execute(['-n', 'invalid'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid length'); + }); + + it('should show error for invalid -s value', async () => { + const result = await command.execute(['-s', 'invalid'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid skip offset'); + }); + + it('should show error for missing -n argument', async () => { + const result = await command.execute(['-n'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('option requires an argument -- n'); + }); + + it('should show error for missing -s argument', async () => { + const result = await command.execute(['-s'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('option requires an argument -- s'); + }); + + it('should show error for invalid option', async () => { + const result = await command.execute(['-x'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid option -- x'); + }); + + it('should handle multiple files', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile) + .mockResolvedValueOnce(Buffer.from('ABC')) + .mockResolvedValueOnce(Buffer.from('XYZ')); + + const result = await command.execute(['-C', 'file1.txt', 'file2.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('==> file1.txt <=='); + expect(result.stdout).toContain('==> file2.txt <=='); + expect(result.stdout).toContain('|ABC|'); + expect(result.stdout).toContain('|XYZ|'); + }); + + it('should handle piped input', async () => { + const input = 'Hello, World!'; + const result = await command.execute(['-C'], testCwd, input); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('|Hello, World!|'); + }); + + it('should handle binary data correctly', async () => { + // Create binary data with non-printable characters + const binaryData = Buffer.from([0x00, 0x01, 0x02, 0x7F, 0x80, 0xFF, 0x41, 0x42, 0x43]); + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(binaryData); + + const result = await command.execute(['-C', 'binary.dat'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('00 01 02 7f 80 ff 41 42 43'); + expect(result.stdout).toContain('|......ABC|'); // Non-printable chars shown as dots + }); + + it('should handle empty file', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('')); + + const result = await command.execute(['-C', 'empty.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); // No output for empty file + }); + + it('should handle skip beyond file length', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('Hi')); + + const result = await command.execute(['-C', '-s', '10', 'short.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); // No output since skip is beyond file + }); +}); \ No newline at end of file diff --git a/src/lib/commands/hexdump.ts b/src/lib/commands/hexdump.ts new file mode 100644 index 00000000..b275a7e5 --- /dev/null +++ b/src/lib/commands/hexdump.ts @@ -0,0 +1,272 @@ +import { join } from "path-browserify"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'hexdump' command + * Display file contents in hexadecimal format + */ +export class HexdumpCommand implements ShellCommand { + name = 'hexdump'; + description = 'Display file contents in hexadecimal format'; + usage = 'hexdump [-C] [-n length] [-s skip] [file...]'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string, input?: string): Promise { + // Parse command line options + const options = this.parseOptions(args); + + if (options.error) { + return createErrorResult(options.error); + } + + // If input is provided (from pipe), process it + if (input !== undefined) { + const buffer = Buffer.from(input, 'utf8'); + const output = this.formatHexdump(buffer, options); + return createSuccessResult(output); + } + + // If no files specified, show usage + if (options.files.length === 0) { + return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`); + } + + try { + const outputs: string[] = []; + + for (const filePath of options.files) { + try { + // Handle both absolute and relative paths + let absolutePath: string; + + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + // It's an absolute path - use it directly + absolutePath = filePath; + } else { + // It's a relative path - resolve it relative to the current working directory + 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 as binary + const content = await this.fs.readFile(absolutePath); + const buffer = Buffer.from(content); + + // Format the hexdump + const hexOutput = this.formatHexdump(buffer, options); + + // Add filename header if multiple files + if (options.files.length > 1) { + outputs.push(`==> ${filePath} <==`); + outputs.push(hexOutput); + } else { + outputs.push(hexOutput); + } + + } catch (error) { + // Handle file not found or permission errors + 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`); + } + } + } + + const result = outputs.join('\n'); + return createSuccessResult(result); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + /** + * Parse command line options + */ + private parseOptions(args: string[]): { + canonical: boolean; + length?: number; + skip: number; + files: string[]; + error?: string; + } { + const options = { + canonical: false, + length: undefined as number | undefined, + skip: 0, + files: [] as string[], + }; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '-C') { + options.canonical = true; + } else if (arg === '-n') { + // Next argument should be the length + if (i + 1 >= args.length) { + return { ...options, error: `${this.name}: option requires an argument -- n` }; + } + const lengthStr = args[++i]; + const length = parseInt(lengthStr, 10); + if (isNaN(length) || length < 0) { + return { ...options, error: `${this.name}: invalid length: ${lengthStr}` }; + } + options.length = length; + } else if (arg === '-s') { + // Next argument should be the skip offset + if (i + 1 >= args.length) { + return { ...options, error: `${this.name}: option requires an argument -- s` }; + } + const skipStr = args[++i]; + const skip = parseInt(skipStr, 10); + if (isNaN(skip) || skip < 0) { + return { ...options, error: `${this.name}: invalid skip offset: ${skipStr}` }; + } + options.skip = skip; + } else if (arg.startsWith('-')) { + return { ...options, error: `${this.name}: invalid option -- ${arg.slice(1)}` }; + } else { + // It's a filename + options.files.push(arg); + } + } + + return options; + } + + /** + * Format buffer content as hexdump + */ + private formatHexdump(buffer: Buffer, options: { + canonical: boolean; + length?: number; + skip: number; + }): string { + const lines: string[] = []; + const bytesPerLine = 16; + + // Apply skip offset + const startOffset = options.skip; + if (startOffset >= buffer.length) { + return ''; // Nothing to display + } + + // Apply length limit + let endOffset = buffer.length; + if (options.length !== undefined) { + endOffset = Math.min(startOffset + options.length, buffer.length); + } + + for (let offset = startOffset; offset < endOffset; offset += bytesPerLine) { + const lineEnd = Math.min(offset + bytesPerLine, endOffset); + const lineBytes = buffer.subarray(offset, lineEnd); + + if (options.canonical) { + // Canonical format (-C): address, hex bytes, ASCII + lines.push(this.formatCanonicalLine(offset, lineBytes)); + } else { + // Default format: address followed by 16-bit words in hex + lines.push(this.formatDefaultLine(offset, lineBytes)); + } + } + + // Add final offset line if we have data + if (endOffset > startOffset) { + const finalOffset = endOffset; + lines.push(this.formatOffsetLine(finalOffset)); + } + + return lines.join('\n'); + } + + /** + * Format a line in canonical format (-C option) + */ + private formatCanonicalLine(offset: number, bytes: Buffer): string { + const addressStr = offset.toString(16).padStart(8, '0'); + + // Format hex bytes (2 groups of 8 bytes each) + const group1: string[] = []; + const group2: string[] = []; + + for (let i = 0; i < 16; i++) { + const hexByte = i < bytes.length + ? bytes[i].toString(16).padStart(2, '0') + : ' '; + + if (i < 8) { + group1.push(hexByte); + } else { + group2.push(hexByte); + } + } + + const hexStr = group1.join(' ') + ' ' + group2.join(' '); + + // Format ASCII representation + let asciiStr = ''; + for (let i = 0; i < bytes.length; i++) { + const byte = bytes[i]; + if (byte >= 32 && byte <= 126) { + // Printable ASCII character + asciiStr += String.fromCharCode(byte); + } else { + // Non-printable character + asciiStr += '.'; + } + } + + return `${addressStr} ${hexStr} |${asciiStr}|`; + } + + /** + * Format a line in default format + */ + private formatDefaultLine(offset: number, bytes: Buffer): string { + const addressStr = offset.toString(16).padStart(7, '0'); + + // Group bytes into 16-bit words (little-endian) + const words: string[] = []; + for (let i = 0; i < bytes.length; i += 2) { + if (i + 1 < bytes.length) { + // Full 16-bit word (little-endian) + const word = (bytes[i + 1] << 8) | bytes[i]; + words.push(word.toString(16).padStart(4, '0')); + } else { + // Partial word (only one byte) + const word = bytes[i]; + words.push(word.toString(16).padStart(2, '0') + ' '); + } + } + + return `${addressStr} ${words.join(' ')}`; + } + + /** + * Format the final offset line + */ + private formatOffsetLine(offset: number): string { + return offset.toString(16).padStart(7, '0'); + } +} \ No newline at end of file diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index 39c52f80..4d7d68d4 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -13,6 +13,7 @@ export { FindCommand } from './find'; export { GitCommand } from './git'; export { GrepCommand } from './grep'; export { HeadCommand } from './head'; +export { HexdumpCommand } from './hexdump'; export { LsCommand } from './ls'; export { MkdirCommand } from './mkdir'; export { MvCommand } from './mv'; diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index adf691fb..e3d50167 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -44,7 +44,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, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip. Supports compound commands with &&, ||, ;, and | operators'); + 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, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators'); expect(shellTool.inputSchema).toBeDefined(); }); diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index dbf991ac..78d1a24e 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -18,6 +18,7 @@ import { GitCommand, GrepCommand, HeadCommand, + HexdumpCommand, LsCommand, MkdirCommand, MvCommand, @@ -47,7 +48,7 @@ export class ShellTool implements Tool { private git: Git; private commands: Map; - 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, git, curl, unzip. Supports compound commands with &&, ||, ;, and | operators"; + 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, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators"; readonly inputSchema = z.object({ command: z.string().describe( @@ -76,6 +77,7 @@ export class ShellTool implements Tool { this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd })); this.registerCommand(new GrepCommand(fs)); this.registerCommand(new HeadCommand(fs)); + this.registerCommand(new HexdumpCommand(fs)); this.registerCommand(new LsCommand(fs)); this.registerCommand(new MkdirCommand(fs)); this.registerCommand(new MvCommand(fs));