import process from 'node:process' import { getErrorMessage } from '@internals/utils' import { x } from 'tinyexec' const TOOL_TIMEOUT_MS = 5 * 60_000 const OUTPUT_LINES = 20 export type RunToolOptions = { /** Names the command in a failure reason, such as `kubb add`. */ label: string command: string args: Array cwd: string signal?: AbortSignal } /** * Runs a command without a shell, stdin, or color for up to five minutes, and keeps the last lines of its output, without stack frames. */ export async function runTool({ label, command, args, cwd, signal }: RunToolOptions): Promise<{ failed: boolean; output: string }> { try { const { stdout, stderr, exitCode } = await x(command, args, { signal, timeout: TOOL_TIMEOUT_MS, throwOnError: false, nodeOptions: { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' } }, }) const lines = `${stdout}\n${stderr}`.split('\n').filter((line) => line.trim() && !/^\s+at /.test(line)) return { failed: exitCode !== 0, output: lines.slice(-OUTPUT_LINES).join('\n') || `${label} exited with ${exitCode ?? 'a signal'}` } } catch (error) { // tinyexec still throws when the timeout hits or the process cannot start. return { failed: true, output: `${label} did not run: ${getErrorMessage(error)}` } } }