Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/bash/src/commands/cd/cd.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ export const handler: CommandHandler = async ({ opts, state }: CommandContext) =
return { stdout: '', stderr: `bash: cd: ${targetPath}: No such file or directory`, exitCode: 1 };
}

return { stdout: '', stderr: '', exitCode: 0 };
return { stdout: `Directory changed to ${targetPath} ✔`, stderr: '', exitCode: 0 };
};
6 changes: 3 additions & 3 deletions packages/bash/src/commands/cp/cp.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,20 @@ export const handler: CommandHandler = async ({ state, opts, runtime }: CommandC

await runtime.executeCode(state, `require('fs').copyFileSync('${sourceAbsolutePath}', '${destinationPath}');`);

return { stdout: '', stderr: '', exitCode: 0 };
return { stdout: 'File copied ✔', stderr: '', exitCode: 0 };
}

if(!destinationAbsolutePath && parentDestinationAbsolutePath && !isSourceFolder) {
const destinationFileName = destination.split('/').pop() as string;
const destinationPath = path.join(parentDestinationAbsolutePath, destinationFileName)

await runtime.executeCode(state, `require('fs').copyFileSync('${sourceAbsolutePath}', '${destinationPath}');`);
return { stdout: '', stderr: '', exitCode: 0 };
return { stdout: 'File copied ✔', stderr: '', exitCode: 0 };
}

if(opts.hasFlag('r') && isSourceFolder) {
await runtime.executeCode(state, `(async () => await require('fs').cp('${sourceAbsolutePath}', '${destinationAbsolutePath || destination}', { recursive: true }))()`)
return { stdout: '', stderr: '', exitCode: 0 };
return { stdout: 'Folder copied ✔', stderr: '', exitCode: 0 };
}


Expand Down
42 changes: 30 additions & 12 deletions packages/bash/src/commands/curl/curl.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ function parseRawArgs(raw: string[]): CurlArgs {
}
} else if (arg === '-d' && raw[i + 1]) {
result.body = raw[++i];
// -d implies POST if no -X was given
if (result.method === 'GET') result.method = 'POST';
} else if (!arg.startsWith('-')) {
result.url = arg;
Expand All @@ -83,6 +82,36 @@ export const handler: CommandHandler = async ({ opts, state, runtime }: CommandC
return { stdout: '', stderr: 'bash: curl: no URL specified', exitCode: 1 };
}

if (args.saveToFile) {
const filename = filenameFromUrl(args.url);
const absolutePath = await runtime.resolvePath(state, filename);
const targetPath = absolutePath ?? filename;

const saveResult = await runtime.executeCode(state, `
(async function() {
try {
const response = await fetch(${JSON.stringify(args.url)}, {
method: ${JSON.stringify(args.method)},
headers: ${JSON.stringify(args.headers)},
${args.body !== null ? `body: ${JSON.stringify(args.body)},` : ''}
redirect: ${JSON.stringify(args.followRedirects ? 'follow' : 'manual')},
});
const buffer = await response.arrayBuffer();
require('fs').writeFileSync('${targetPath}', new Uint8Array(buffer));
return { ok: true };
} catch (e) {
return { ok: false, error: String(e) };
}
})()
`) as { ok: boolean; error?: string };

if (!saveResult.ok) {
return { stdout: '', stderr: args.silent ? '' : `bash: curl: ${args.url}: ${saveResult.error}`, exitCode: 1 };
}

return { stdout: 'File downloaded ✔', stderr: '', exitCode: 0 };
}

const result = await runtime.executeCode(state, `
(async function() {
try {
Expand All @@ -92,7 +121,6 @@ export const handler: CommandHandler = async ({ opts, state, runtime }: CommandC
${args.body !== null ? `body: ${JSON.stringify(args.body)},` : ''}
redirect: ${JSON.stringify(args.followRedirects ? 'follow' : 'manual')},
});

const text = await response.text();
return { ok: true, status: response.status, body: text };
} catch (e) {
Expand All @@ -106,15 +134,5 @@ export const handler: CommandHandler = async ({ opts, state, runtime }: CommandC
return { stdout: '', stderr: args.silent ? '' : msg, exitCode: 1 };
}

if (args.saveToFile) {
const filename = filenameFromUrl(args.url);
const absolutePath = await runtime.resolvePath(state, filename);
const targetPath = absolutePath ?? filename;

await runtime.executeCode(state, `require('fs').writeFileSync('${targetPath}', ${JSON.stringify(result.body ?? '')});`);

return { stdout: '', stderr: args.silent ? '' : ` % Total\n100 ${(result.body ?? '').length} Saved to: ${filename}`, exitCode: 0 };
}

return { stdout: result.body ?? '', stderr: '', exitCode: 0 };
};
2 changes: 1 addition & 1 deletion packages/bash/src/commands/echo/echo.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const manual: CommandManual = {
}
};

export const handler: CommandHandler = async ({ opts, state, runtime }: CommandContext) => {
export const handler: CommandHandler = async ({ opts }: CommandContext) => {
const stdout: string[] = [];

await Promise.all(opts.args.map(async (arg) => {
Expand Down
17 changes: 17 additions & 0 deletions packages/bash/src/commands/env/env.handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { CommandContext, CommandHandler, CommandManual } from "@capsule-run/bash-types";

export const manual: CommandManual = {
name: "env",
description: "Display environment variables.",
usage: "env"
};

export const handler: CommandHandler = async ({ opts, state, runtime }: CommandContext) => {
const stdout: string[] = [];

Object.entries(state.env).forEach(([key, value]) => {
stdout.push(`${key}=${value}`);
});

return { stdout: stdout.length > 0 ? stdout.join('\n') : 'No environment variables found.', stderr: '', exitCode: 0 };
};
7 changes: 7 additions & 0 deletions packages/bash/src/commands/env/env.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { describe, it, expect } from "vitest";

describe('echo command', () => {
it('placeholder for real tests', async () => {
expect(0).toBe(0);
})
})
15 changes: 15 additions & 0 deletions packages/bash/src/commands/export/export.handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { CommandContext, CommandHandler, CommandManual } from "@capsule-run/bash-types";

export const manual: CommandManual = {
name: "export",
description: "Set environment variables.",
usage: "export"
};

export const handler: CommandHandler = async ({ opts, state }: CommandContext) => {
for (let i = 0; i < opts.args.length; i += 2) {
state.setEnv(opts.args[i], opts.args[i + 1]);
}

return { stdout: `Environment variables exported ✔`, stderr: '', exitCode: 0 };
};
7 changes: 7 additions & 0 deletions packages/bash/src/commands/export/export.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { describe, it, expect } from "vitest";

describe('echo command', () => {
it('placeholder for real tests', async () => {
expect(0).toBe(0);
})
})
1 change: 0 additions & 1 deletion packages/bash/src/commands/grep/grep.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ export const handler: CommandHandler = async ({ opts, state, runtime, stdin }: C
return;
}

// Single executeCode call: returns { isDirectory, entries?, content? }
const info = await runtime.executeCode(state, `
(function() {
const fs = require('fs');
Expand Down
2 changes: 1 addition & 1 deletion packages/bash/src/commands/mkdir/mkdir.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@ export const handler: CommandHandler = async ({ state, opts, runtime }: CommandC
}))


return { stdout: '', stderr: stderr.join('\n'), exitCode: stderr.length > 0 ? 1 : 0 };
return { stdout: 'Folder created ✔', stderr: stderr.join('\n'), exitCode: stderr.length > 0 ? 1 : 0 };
}
8 changes: 3 additions & 5 deletions packages/bash/src/commands/mv/mv.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ export const handler: CommandHandler = async ({ state, opts, runtime }: CommandC
}

if(isDestinationFolder) {
console.log(sourceAbsolutePath, destinationAbsolutePath)
console.log(isSourceFolder)
await runtime.executeCode(state, `
const fs = require('fs');
(async () => {
Expand All @@ -46,7 +44,7 @@ export const handler: CommandHandler = async ({ state, opts, runtime }: CommandC
fs.rmSync('${sourceAbsolutePath}', ${isSourceFolder ? '{ recursive: true }' : '{}'});
})()
`);
return { stdout: '', stderr: '', exitCode: 0 };
return { stdout: `${isSourceFolder ? 'Folder' : 'File'} moved ✔`, stderr: '', exitCode: 0 };
}

if(!isDestinationFolder && destinationAbsolutePath) {
Expand All @@ -57,14 +55,14 @@ export const handler: CommandHandler = async ({ state, opts, runtime }: CommandC
await fs.rm('${sourceAbsolutePath}');
})()
`);
return { stdout: '', stderr: '', exitCode: 0 };
return { stdout: 'File moved ✔', stderr: '', exitCode: 0 };
}

if(!isDestinationFolder && !destinationAbsolutePath) {
await runtime.executeCode(state, `const fs = require('fs');
fs.renameSync('${sourceAbsolutePath}', '${destination}');
`);
return { stdout: '', stderr: '', exitCode: 0 };
return { stdout: 'File moved ✔', stderr: '', exitCode: 0 };
}

return { stdout: '', stderr: `bash: mv: ${destination}: No such file or directory`, exitCode: 1 };
Expand Down
3 changes: 3 additions & 0 deletions packages/bash/src/commands/rm/rm.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,19 @@ export const handler: CommandHandler = async ({ state, opts, runtime }: CommandC

if(isDirectory && isEmpty && !opts.hasFlag("r")) {
await runtime.executeCode(state, `require('fs').rmdirSync('${targetAbsolutePath}', { recursive: true });`);
stdout.push(`Folder ${target} removed ✔`);
return;
}

if(isDirectory && opts.hasFlag("r") && opts.hasFlag("f")) {
await runtime.executeCode(state, `(async () => { await require('fs').rm('${targetAbsolutePath}', { recursive: true }); })();`);
stdout.push(`Folder ${target} removed ✔`)
return;
}

if(isFile) {
await runtime.executeCode(state, `require('fs').unlinkSync('${targetAbsolutePath}');`);
stdout.push(`File ${target} removed ✔`)
return;
}
}))
Expand Down
2 changes: 1 addition & 1 deletion packages/bash/src/commands/touch/touch.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ export const handler: CommandHandler = async ({ state, opts, runtime }: CommandC
}
}))

return { stdout: '', stderr: stderr.join('\n'), exitCode: stderr.length > 0 ? 1 : 0 };
return { stdout: 'File created ✔', stderr: stderr.join('\n'), exitCode: stderr.length > 0 ? 1 : 0 };
}
59 changes: 54 additions & 5 deletions packages/bash/src/core/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { parsedCommandOptions } from '../helpers/commandOptions';
import { displayCommandManual } from '../helpers/commandManual';

import type { BaseRuntime, CommandHandler, CommandManual, CommandResult, CustomCommand, State } from '@capsule-run/bash-types';
import { Parser } from './parser';
import type { ASTNode, CommandNode } from './parser';


Expand Down Expand Up @@ -72,10 +73,60 @@ export class Executor {
}
}

private async executeScript(filePath: string, scriptArgs: string[]): Promise<CommandResult> {
const absolutePath = await this.runtime.resolvePath(this.state, filePath);
if (!absolutePath) {
return { stdout: '', stderr: `bash: ${filePath}: No such file or directory`, exitCode: 1 };
}

let content: string;
try {
content = await this.runtime.executeCode(this.state, `require('fs').readFileSync('${absolutePath}', 'utf8');`) as string;
} catch {
return { stdout: '', stderr: `bash: sh: ${filePath}: No such file or directory`, exitCode: 1 };
}

const lines = content.split('\n').filter(line => !line.startsWith('#!'));
let script = lines.join('\n');

scriptArgs.forEach((arg, i) => {
script = script.replace(new RegExp(`\\$${i + 1}`, 'g'), arg);
});

script = script.replace(/\$\d+/g, '');

const parser = new Parser();
const stdout: string[] = [];
const stderr: string[] = [];
let exitCode = 0;

for (const line of script.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;

try {
const ast = parser.parse(trimmed);
const result = await this.execute(ast);
if (result.stdout) stdout.push(result.stdout);
if (result.stderr) stderr.push(result.stderr);
exitCode = result.exitCode;
if (exitCode !== 0) break;
} catch {}
}

return { stdout: stdout.join('\n'), stderr: stderr.join('\n'), exitCode };
}

private async executeCommand(node: CommandNode, stdin: string): Promise<CommandResult> {
const [name, ...args] = node.args;
let result: CommandResult;

if (name === 'sh' || name === 'bash') {
const [file, ...scriptArgs] = args;
if (!file) return { stdout: '', stderr: `bash: ${name}: missing script operand`, exitCode: 1 };
return this.executeScript(file, scriptArgs);
}

for (const r of node.redirects) {
if (r.op === '<') {
if (r.file === '/dev/null') {
Expand Down Expand Up @@ -171,20 +222,18 @@ export class Executor {
continue;
}

console.log("writing to file", r.file)

try {
console.log(await this.runtime.executeCode(this.state, `
await this.runtime.executeCode(this.state, `
const fs = require('fs');
const path = require('path');
const filePath = path.resolve(${JSON.stringify(r.file)});

fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.${r.op === '>>' ? 'appendFileSync' : 'writeFileSync'}(filePath, ${JSON.stringify(currentStdout)});
return filePath;
`));
`);

currentStdout = '';
currentStdout = 'File created ✔';
} catch {
return { stdout: '', stderr: `bash: ${r.file}: No such file or directory`, exitCode: 1 };
}
Expand Down
Loading