Files
tsrust/ts/mod_cargo/classes.cargorunner.ts

81 lines
2.3 KiB
TypeScript

import * as plugins from '../plugins.js';
export interface ICargoRunResult {
success: boolean;
exitCode: number;
stdout: string;
}
export class CargoRunner {
private shell: plugins.smartshell.Smartshell;
private rustDir: string;
constructor(rustDir: string) {
this.rustDir = rustDir;
this.shell = new plugins.smartshell.Smartshell({
executor: 'bash',
});
}
public async checkCargoInstalled(): Promise<boolean> {
const result = await this.shell.execSilent('cargo --version');
return result.exitCode === 0;
}
public async getCargoVersion(): Promise<string> {
const result = await this.shell.execSilent('cargo --version');
return result.stdout.trim();
}
public async build(options: { debug?: boolean; clean?: boolean; target?: string } = {}): Promise<ICargoRunResult> {
if (options.clean) {
console.log('Cleaning previous build...');
await this.clean();
}
if (options.target) {
await this.ensureTarget(options.target);
}
const profile = options.debug ? '' : ' --release';
const targetFlag = options.target ? ` --target ${options.target}` : '';
const command = `cd ${this.rustDir} && cargo build${profile}${targetFlag}`;
console.log(`Running: cargo build${profile}${targetFlag}`);
const result = await this.shell.exec(command);
return {
success: result.exitCode === 0,
exitCode: result.exitCode,
stdout: result.stdout,
};
}
/**
* Ensures a rustup target is installed. If not present, installs it via `rustup target add`.
*/
public async ensureTarget(triple: string): Promise<void> {
const listResult = await this.shell.execSilent('rustup target list --installed');
const installedTargets = listResult.stdout.split('\n').map((l) => l.trim());
if (installedTargets.includes(triple)) {
return;
}
console.log(`Installing rustup target: ${triple}`);
const addResult = await this.shell.exec(`rustup target add ${triple}`);
if (addResult.exitCode !== 0) {
throw new Error(`Failed to install rustup target ${triple}`);
}
}
public async clean(): Promise<ICargoRunResult> {
const command = `cd ${this.rustDir} && cargo clean`;
const result = await this.shell.exec(command);
return {
success: result.exitCode === 0,
exitCode: result.exitCode,
stdout: result.stdout,
};
}
}