import { Bash } from "../Bash.js";
import { shellEscape } from "./escape.js";
/**
 * Create a tagged template shell for ergonomic bash execution.
 *
 * @example
 * ```ts
 * const $ = createShell();
 * const result = await $`echo hello ${name}`;
 * console.log(result.stdout); // "hello world\n"
 * ```
 */
export function createShell(options) {
    const bash = new Bash({
        persistState: true,
        ...options,
    });
    const shell = (async (strings, ...values) => {
        let command = strings[0];
        for (let i = 0; i < values.length; i++) {
            command += shellEscape(values[i]);
            command += strings[i + 1];
        }
        return bash.exec(command);
    });
    Object.defineProperty(shell, "bash", {
        get: () => bash,
        enumerable: true,
    });
    shell.cd = async (path) => {
        const result = await bash.exec(`cd ${shellEscape(path)}`);
        if (result.exitCode !== 0) {
            throw new Error(`cd: ${path}: ${result.stderr}`);
        }
    };
    return shell;
}
