Skip to content
Merged
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
28 changes: 28 additions & 0 deletions packages/bash-types/src/command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { BaseRuntime } from "./runtime";
import { State } from "./state";

/**
* The context of a command execution
*/
export type CommandContext = {
args: string[];
stdin: string;
state: State;
runtime: BaseRuntime;
};

/**
* The handler of a command execution
*/
export type CommandHandler = (ctx: CommandContext) => Promise<CommandResult>;

/**
* The result of a command execution
*/
export type CommandResult = {
stdout: string;
stderr: string;
exitCode: number;
};


1 change: 1 addition & 0 deletions packages/bash-types/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { State } from "./state";
export { BaseRuntime, RuntimeResult } from "./runtime";
export { BashOptions } from "./bash";
export { CommandResult, CommandHandler, CommandContext } from "./command";
8 changes: 4 additions & 4 deletions packages/bash-types/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@ export interface BaseRuntime {
/**
* Execute a code
*/
executeCode(state: State, code: string, language: string): Promise<unknown>;
executeCode(state: State, code: string, language?: string): Promise<unknown>;

/**
* Execute a file
*/
executeFile(state: State, filePath: string, language: string): Promise<unknown>;
executeFile(state: State, filePath: string, language?: string): Promise<unknown>;

/**
* Resolve a directory path
* Resolve a path in the sandbox
*/
resolveDirectoryPath(state: State, directoryPath: string): Promise<string>;
resolvePath(state: State, path: string): Promise<string>;
}

export interface RuntimeResult {
Expand Down
10 changes: 10 additions & 0 deletions packages/bash-types/src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,14 @@ export interface State {
* The return code of the last executed command (ex: 0 for success, 1 for error).
*/
lastExitCode: number;

/**
* Set the exit code of the last executed command
*/
setLastExitCode(code: number): void;

/**
* Set an environment variable
*/
setEnv(key: string, value: string): void;
}
4 changes: 2 additions & 2 deletions packages/bash-wasm/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ export class WasmRuntime implements BaseRuntime {
return result.result as string;
}

async resolveDirectoryPath(state: State, directoryPath: string): Promise<string> {
async resolvePath(state: State, path: string): Promise<string> {
const result = await run({
file: this.jsSandbox,
args: ["RESOLVE_DIRECTORY_PATH", JSON.stringify(state), directoryPath],
args: ["RESOLVE_PATH", JSON.stringify(state), path],
mounts: [`${this.hostWorkspace}::/`],
})

Expand Down
4 changes: 3 additions & 1 deletion packages/bash/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
"license": "Apache-2.0",
"packageManager": "pnpm@10.21.0",
"devDependencies": {
"@types/shell-quote": "^1.7.5",
"tsup": "^8.0.0"
},
"dependencies": {
"@capsule-run/bash-types": "workspace:*"
"@capsule-run/bash-types": "workspace:*",
"shell-quote": "^1.8.3"
}
}
13 changes: 11 additions & 2 deletions packages/bash/src/core/bash.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import type { BaseRuntime, BashOptions } from "@capsule-run/bash-types";
import type { BaseRuntime, BashOptions, CommandResult } from "@capsule-run/bash-types";
import { StateManager } from "./stateManager";
import { Filesystem } from "./filesystem";
import { Parser } from "./parser";
import { Executor } from "./executor";

export class Bash {
private runtime: BaseRuntime;
private filesystem: Filesystem;
private parser: Parser;
private executor: Executor;

public readonly stateManager: StateManager;

Expand All @@ -13,11 +17,16 @@ export class Bash {
this.runtime.hostWorkspace = hostWorkspace;
this.stateManager = new StateManager(runtime, initialCwd);
this.filesystem = new Filesystem(hostWorkspace);
this.parser = new Parser();
this.executor = new Executor(runtime, this.stateManager.state);

this.filesystem.init();
}

run(command: string) {}
async run(command: string): Promise<CommandResult> {
const ast = this.parser.parse(command);
return this.executor.execute(ast);
}

reset() {
this.filesystem.reset();
Expand Down
116 changes: 116 additions & 0 deletions packages/bash/src/core/executor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import path from 'path';
import type { BaseRuntime, CommandHandler, CommandResult, State } from '@capsule-run/bash-types';
import type { ASTNode, CommandNode } from './parser';

export class Executor {

constructor(
private readonly runtime: BaseRuntime,
private readonly state: State,
) {}

async execute(node: ASTNode, stdin = ''): Promise<CommandResult> {
switch (node.type) {
case 'command': return this.executeCommand(node, stdin);
case 'pipeline': return this.executePipeline(node);
case 'and': return this.executeAnd(node);
case 'or': return this.executeOr(node);
case 'sequence': return this.executeSequence(node);
}
}

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

for (const r of node.redirects) {
if (r.op === '<') {
try {
stdin = await this.runtime.executeCode(this.state, `
const fs = require('fs');
const path = require('path');
return fs.readFileSync(path.resolve(${JSON.stringify(r.file)}), 'utf8');
`) as string;
} catch {
return { stdout: '', stderr: `bash: ${r.file}: No such file or directory`, exitCode: 1 };
}
}
}

const handler = await this.searchCommandHandler(name);
let result: CommandResult;

if (handler) {
result = await handler({ args, stdin, state: this.state, runtime: this.runtime });
} else {
result = { stdout: '', stderr: `bash: ${name}: command not found`, exitCode: 127 };
}

for (const r of node.redirects) {
if (r.op === '>' || r.op === '>>') {
try {
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(result.stdout)});
`);

result = { ...result, stdout: '' };
} catch {
return { stdout: '', stderr: `bash: ${r.file}: No such file or directory`, exitCode: 1 };
}
}
}

this.state.setLastExitCode(result.exitCode);
return result;
}

private async executePipeline(node: { type: 'pipeline'; commands: CommandNode[] }): Promise<CommandResult> {
let stdin = '';
let result: CommandResult = { stdout: '', stderr: '', exitCode: 0 };

for (const cmd of node.commands) {
result = await this.executeCommand(cmd, stdin);
stdin = result.stdout;
}

return result;
}


private async executeAnd(node: { type: 'and'; left: ASTNode; right: ASTNode }): Promise<CommandResult> {
const left = await this.execute(node.left);

if (left.exitCode !== 0) return left;

return this.execute(node.right);
}

private async executeOr(node: { type: 'or'; left: ASTNode; right: ASTNode }): Promise<CommandResult> {
const left = await this.execute(node.left);

if (left.exitCode === 0) return left;

return this.execute(node.right);
}

private async executeSequence(node: { type: 'sequence'; left: ASTNode; right: ASTNode }): Promise<CommandResult> {
await this.execute(node.left);
return this.execute(node.right);
}

private async searchCommandHandler(name: string): Promise<CommandHandler | undefined> {
const commandsDir = path.resolve(__dirname, '../commands');
const handlerPath = path.join(commandsDir, name, 'handler');

try {
const mod = require(handlerPath);
return mod.handle as CommandHandler;
} catch {
return undefined;
}
}
}
6 changes: 1 addition & 5 deletions packages/bash/src/core/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@ import fs from 'fs';
import path from 'path';

export class Filesystem {
private workspace: string;

constructor(workspace: string) {
this.workspace = workspace;
}
constructor(private readonly workspace: string) {}

init() {
const directories = ['bin', 'dev', 'etc', 'proc', 'root', 'sys', 'tmp', 'workspace'];
Expand Down
Loading
Loading