mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add "sed" command
This commit is contained in:
5 files changed
+654
-2
No files matched your search
@@ -19,6 +19,7 @@ export { MkdirCommand } from './mkdir';
|
||||
export { MvCommand } from './mv';
|
||||
export { PwdCommand } from './pwd';
|
||||
export { RmCommand } from './rm';
|
||||
export { SedCommand } from './sed';
|
||||
export { SortCommand } from './sort';
|
||||
export { TailCommand } from './tail';
|
||||
export { TouchCommand } from './touch';
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { SedCommand } from './sed';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const mockFS: JSRuntimeFS = {
|
||||
readFile: ((path: string, encoding?: string) => {
|
||||
const files: Record<string, string> = {
|
||||
'/test/hello.txt': 'hello world\nfoo bar\nbaz qux\n',
|
||||
'/test/numbers.txt': '1\n2\n3\n4\n5\n',
|
||||
'/test/mixed.txt': 'apple\nbanana\ncherry\napple pie\n',
|
||||
};
|
||||
|
||||
if (path in files) {
|
||||
if (encoding === 'utf8' || (encoding && encoding !== undefined)) {
|
||||
return Promise.resolve(files[path]);
|
||||
} else {
|
||||
// No encoding specified, return Uint8Array
|
||||
return Promise.resolve(new TextEncoder().encode(files[path]));
|
||||
}
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT: no such file or directory'));
|
||||
}) as JSRuntimeFS['readFile'],
|
||||
|
||||
writeFile: async (_path: string, _data: string | Uint8Array, _encoding?: string) => {
|
||||
// Mock write operation
|
||||
},
|
||||
|
||||
stat: async (_path: string) => ({
|
||||
isFile: () => true,
|
||||
isDirectory: () => false,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
|
||||
lstat: async (_path: string) => ({
|
||||
isFile: () => true,
|
||||
isDirectory: () => false,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
|
||||
readdir: (async (_path: string, _options?: { withFileTypes?: boolean }) => {
|
||||
if (_options?.withFileTypes) {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
}) as JSRuntimeFS['readdir'],
|
||||
mkdir: async () => {},
|
||||
rmdir: async () => {},
|
||||
unlink: async () => {},
|
||||
rename: async () => {},
|
||||
readlink: async () => '',
|
||||
symlink: async () => {},
|
||||
};
|
||||
|
||||
describe('SedCommand', () => {
|
||||
let sedCommand: SedCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
sedCommand = new SedCommand(mockFS);
|
||||
});
|
||||
|
||||
describe('basic functionality', () => {
|
||||
it('should have correct name and description', () => {
|
||||
expect(sedCommand.name).toBe('sed');
|
||||
expect(sedCommand.description).toBe('Stream editor for filtering and transforming text');
|
||||
});
|
||||
|
||||
it('should return error when no script provided', async () => {
|
||||
const result = await sedCommand.execute([], '/test');
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing script');
|
||||
});
|
||||
});
|
||||
|
||||
describe('substitute command', () => {
|
||||
it('should substitute text with s command', async () => {
|
||||
const input = 'hello world\nfoo bar\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi world\nfoo bar\n');
|
||||
});
|
||||
|
||||
it('should substitute globally with g flag', async () => {
|
||||
const input = 'hello hello world\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/g'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi hi world\n');
|
||||
});
|
||||
|
||||
it('should substitute case-insensitively with i flag', async () => {
|
||||
const input = 'Hello HELLO world\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/gi'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi hi world\n');
|
||||
});
|
||||
|
||||
it('should substitute with special characters', async () => {
|
||||
const input = 'test.txt\n';
|
||||
const result = await sedCommand.execute(['s/\\.txt/.bak/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('test.bak\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete command', () => {
|
||||
it('should delete all lines with d command', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('\n');
|
||||
});
|
||||
|
||||
it('should delete specific line with line number', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['2d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline3\n');
|
||||
});
|
||||
|
||||
it('should delete lines matching pattern', async () => {
|
||||
const input = 'keep this\ndelete this line\nkeep this too\n';
|
||||
const result = await sedCommand.execute(['/delete/d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('keep this\nkeep this too\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('print command', () => {
|
||||
it('should print all lines normally without -n', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline1\nline2\nline2\n'); // Each line printed twice (normal + p command)
|
||||
});
|
||||
|
||||
it('should print only specified lines with -n', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['-n', '2p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('quit command', () => {
|
||||
it('should quit after processing specified line', async () => {
|
||||
const input = 'line1\nline2\nline3\nline4\n';
|
||||
const result = await sedCommand.execute(['2q'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline2\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('append, insert, and change commands', () => {
|
||||
it('should append text after line', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['1a\\appended text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nappended text\nline2\n');
|
||||
});
|
||||
|
||||
it('should insert text before line', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['2i\\inserted text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\ninserted text\nline2\n');
|
||||
});
|
||||
|
||||
it('should change line', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['2c\\changed text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nchanged text\nline3\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('file operations', () => {
|
||||
it('should process file content', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', undefined);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle file not found error', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/', 'nonexistent.txt'], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/', '/absolute/path.txt'], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
});
|
||||
});
|
||||
|
||||
describe('option parsing', () => {
|
||||
it('should parse -n option', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['-n', 'p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should parse -e option', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['-e', 's/hello/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi world\n');
|
||||
});
|
||||
|
||||
it('should parse combined options', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['-ne', 'p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('multiple scripts', () => {
|
||||
it('should process multiple scripts in order', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['-e', 's/hello/hi/', '-e', 's/world/universe/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi universe\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle empty input', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', '');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle invalid regex patterns gracefully', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['s/[/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hello world\n'); // Should return original
|
||||
});
|
||||
|
||||
it('should handle invalid script format', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['invalid_script'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Invalid sed script');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,375 @@
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'sed' command
|
||||
* Stream editor for filtering and transforming text
|
||||
*/
|
||||
export class SedCommand implements ShellCommand {
|
||||
name = 'sed';
|
||||
description = 'Stream editor for filtering and transforming text';
|
||||
usage = 'sed [-i] [-n] [-e script] [script] [file...]';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
|
||||
if (args.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing script\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const { options, scripts, files } = this.parseArgs(args);
|
||||
|
||||
if (scripts.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing script\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
let content = '';
|
||||
|
||||
// If input is provided (from pipe), use that input
|
||||
if (input !== undefined) {
|
||||
content = input;
|
||||
} else if (files.length === 0) {
|
||||
// Read from stdin (not implemented in this context, return empty)
|
||||
return createSuccessResult('');
|
||||
} else {
|
||||
// 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 with sed scripts
|
||||
let result = content;
|
||||
for (const script of scripts) {
|
||||
result = await this.processScript(script, result, options);
|
||||
}
|
||||
|
||||
// Handle in-place editing
|
||||
if (options.inPlace && files.length > 0) {
|
||||
for (const file of files) {
|
||||
const absolutePath = join(cwd, file);
|
||||
await this.fs.writeFile(absolutePath, result, 'utf8');
|
||||
}
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
// Handle quiet mode
|
||||
if (options.quiet) {
|
||||
// In quiet mode, only explicitly printed lines are output
|
||||
// For now, we'll return empty unless there are 'p' commands
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(result);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async processScript(script: string, content: string, options: { quiet: boolean; inPlace: boolean }): Promise<string> {
|
||||
// Track if original content ended with newline
|
||||
const originalEndsWithNewline = content.endsWith('\n');
|
||||
|
||||
// Split lines but handle the trailing newline properly
|
||||
let lines = content.split('\n');
|
||||
if (originalEndsWithNewline && lines[lines.length - 1] === '') {
|
||||
lines = lines.slice(0, -1); // Remove the empty line at the end
|
||||
}
|
||||
|
||||
const resultLines: string[] = [];
|
||||
|
||||
// Parse the sed script
|
||||
const command = this.parseScript(script);
|
||||
|
||||
if (!command) {
|
||||
throw new Error(`Invalid sed script: ${script}`);
|
||||
}
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
let processedLine = line;
|
||||
let shouldPrint = !options.quiet;
|
||||
|
||||
switch (command.type) {
|
||||
case 's': {// Substitute
|
||||
const substituted = this.substitute(line, command.pattern!, command.replacement!, command.flags!);
|
||||
processedLine = substituted;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'd': // Delete
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
shouldPrint = false;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'p': // Print
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
if (options.quiet) {
|
||||
shouldPrint = false;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'q': // Quit
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
return this.formatOutput(resultLines, originalEndsWithNewline);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'a': // Append
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
resultLines.push(command.text || '');
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'i': // Insert
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(command.text || '');
|
||||
resultLines.push(processedLine);
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'c': // Change
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(command.text || '');
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (shouldPrint) {
|
||||
resultLines.push(processedLine);
|
||||
}
|
||||
}
|
||||
|
||||
return this.formatOutput(resultLines, originalEndsWithNewline);
|
||||
}
|
||||
|
||||
private formatOutput(lines: string[], originalEndsWithNewline: boolean): string {
|
||||
if (lines.length === 0) {
|
||||
return originalEndsWithNewline ? '\n' : '';
|
||||
}
|
||||
|
||||
const result = lines.join('\n');
|
||||
|
||||
// Only add trailing newline if original content had one
|
||||
return originalEndsWithNewline ? result + '\n' : result;
|
||||
}
|
||||
|
||||
private parseScript(script: string): SedCommandSpec | null {
|
||||
// Handle substitute command: s/pattern/replacement/flags
|
||||
const substituteMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?s\/(.*)\/(.*)\/([gimx]*)$/);
|
||||
if (substituteMatch) {
|
||||
return {
|
||||
type: 's',
|
||||
address: substituteMatch[1] || null,
|
||||
pattern: substituteMatch[2],
|
||||
replacement: substituteMatch[3],
|
||||
flags: substituteMatch[4]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle delete command: d or address d
|
||||
const deleteMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?d$/);
|
||||
if (deleteMatch) {
|
||||
return {
|
||||
type: 'd',
|
||||
address: deleteMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle print command: p or address p
|
||||
const printMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?p$/);
|
||||
if (printMatch) {
|
||||
return {
|
||||
type: 'p',
|
||||
address: printMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle quit command: q or address q
|
||||
const quitMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?q$/);
|
||||
if (quitMatch) {
|
||||
return {
|
||||
type: 'q',
|
||||
address: quitMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle append command: a\text or address a\text
|
||||
const appendMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?a\\(.*)$/);
|
||||
if (appendMatch) {
|
||||
return {
|
||||
type: 'a',
|
||||
address: appendMatch[1] || null,
|
||||
text: appendMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle insert command: i\text or address i\text
|
||||
const insertMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?i\\(.*)$/);
|
||||
if (insertMatch) {
|
||||
return {
|
||||
type: 'i',
|
||||
address: insertMatch[1] || null,
|
||||
text: insertMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle change command: c\text or address c\text
|
||||
const changeMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?c\\(.*)$/);
|
||||
if (changeMatch) {
|
||||
return {
|
||||
type: 'c',
|
||||
address: changeMatch[1] || null,
|
||||
text: changeMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private substitute(line: string, pattern: string, replacement: string, flags: string): string {
|
||||
try {
|
||||
const regexFlags = flags.includes('g') ? 'g' : '';
|
||||
const caseInsensitive = flags.includes('i');
|
||||
|
||||
const regex = new RegExp(pattern, regexFlags + (caseInsensitive ? 'i' : ''));
|
||||
return line.replace(regex, replacement);
|
||||
} catch {
|
||||
// If regex is invalid, return original line
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
private matchesAddress(lineNumber: number, line: string, address: string | null): boolean {
|
||||
if (!address) {
|
||||
return true; // No address means match all lines
|
||||
}
|
||||
|
||||
// Line number address
|
||||
if (/^\d+$/.test(address)) {
|
||||
return lineNumber === parseInt(address);
|
||||
}
|
||||
|
||||
// Last line address
|
||||
if (address === '$') {
|
||||
// This is tricky to implement without knowing total lines
|
||||
// For now, we'll assume it doesn't match
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pattern address /pattern/
|
||||
const patternMatch = address.match(/^\/(.*)\/$/);
|
||||
if (patternMatch) {
|
||||
try {
|
||||
const regex = new RegExp(patternMatch[1]);
|
||||
return regex.test(line);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private parseArgs(args: string[]): {
|
||||
options: { quiet: boolean; inPlace: boolean };
|
||||
scripts: string[];
|
||||
files: string[]
|
||||
} {
|
||||
const options = { quiet: false, inPlace: false };
|
||||
const scripts: string[] = [];
|
||||
const files: string[] = [];
|
||||
let i = 0;
|
||||
let expectingScript = false;
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === '-n') {
|
||||
options.quiet = true;
|
||||
} else if (arg === '-i') {
|
||||
options.inPlace = true;
|
||||
} else if (arg === '-e') {
|
||||
expectingScript = true;
|
||||
} else if (arg.startsWith('-') && arg !== '-') {
|
||||
// Parse combined options
|
||||
for (let j = 1; j < arg.length; j++) {
|
||||
const char = arg[j];
|
||||
switch (char) {
|
||||
case 'n':
|
||||
options.quiet = true;
|
||||
break;
|
||||
case 'i':
|
||||
options.inPlace = true;
|
||||
break;
|
||||
case 'e':
|
||||
expectingScript = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (expectingScript || (scripts.length === 0 && !arg.startsWith('-'))) {
|
||||
scripts.push(arg);
|
||||
expectingScript = false;
|
||||
} else {
|
||||
files.push(arg);
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
return { options, scripts, files };
|
||||
}
|
||||
}
|
||||
|
||||
interface SedCommandSpec {
|
||||
type: 's' | 'd' | 'p' | 'q' | 'a' | 'i' | 'c';
|
||||
address?: string | null;
|
||||
pattern?: string;
|
||||
replacement?: string;
|
||||
flags?: string;
|
||||
text?: string;
|
||||
}
|
||||
@@ -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, hexdump. 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, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators');
|
||||
expect(shellTool.inputSchema).toBeDefined();
|
||||
});
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
MvCommand,
|
||||
PwdCommand,
|
||||
RmCommand,
|
||||
SedCommand,
|
||||
SortCommand,
|
||||
TailCommand,
|
||||
TouchCommand,
|
||||
@@ -48,7 +49,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
private git: Git;
|
||||
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, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. 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, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators";
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
command: z.string().describe(
|
||||
@@ -83,6 +84,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
this.registerCommand(new MvCommand(fs));
|
||||
this.registerCommand(new PwdCommand());
|
||||
this.registerCommand(new RmCommand(fs));
|
||||
this.registerCommand(new SedCommand(fs));
|
||||
this.registerCommand(new SortCommand(fs));
|
||||
this.registerCommand(new TailCommand(fs));
|
||||
this.registerCommand(new TouchCommand(fs));
|
||||
|
||||
Reference in new issue
Block a user