import { execSync } from 'node:child_process';
import type { ExecuteResult } from '../types/common.js';
import { logCommand } from '../utils/logger.js';
export interface ExecuteOptions {
cwd?: string;
env?: Record<string, string>;
timeout?: number;
}
export function execute(
command: string,
args: string[],
options: ExecuteOptions = {}
): ExecuteResult {
logCommand(command, args);
const fullCommand = [command, ...args.map(arg =>
arg.includes(' ') ? `"${arg}"` : arg
)].join(' ');
try {
const stdout = execSync(fullCommand, {
encoding: 'utf-8',
cwd: options.cwd,
env: { ...process.env, ...options.env },
timeout: options.timeout ?? 60000,
stdio: ['pipe', 'pipe', 'pipe'],
});
return {
stdout: stdout.trim(),
stderr: '',
exitCode: 0,
};
} catch (error: unknown) {
const execError = error as {
status?: number;
stdout?: Buffer | string;
stderr?: Buffer | string;
message?: string;
};
const stdout = execError.stdout?.toString().trim() ?? '';
const stderr = execError.stderr?.toString().trim() ?? execError.message ?? '';
const exitCode = execError.status ?? 1;
return {
stdout,
stderr,
exitCode,
};
}
}