Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/activity/windows-executable.ts

Raw
import { stat } from "node:fs/promises";
import { delimiter, extname, isAbsolute, resolve } from "node:path";

const NATIVE_EXTENSIONS = [".exe", ".com"];

function executableNames(command: string): string[] {
	const extension = extname(command).toLowerCase();
	if (extension === ".cmd" || extension === ".bat") {
		throw new Error(
			`Windows terminal command ${JSON.stringify(command)} is a shell script; cmd.exe is not started implicitly. Launch cmd.exe explicitly to run it.`,
		);
	}
	return NATIVE_EXTENSIONS.includes(extension)
		? [command]
		: NATIVE_EXTENSIONS.map((suffix) => command + suffix);
}

async function isFile(path: string): Promise<boolean> {
	try {
		return (await stat(path)).isFile();
	} catch {
		return false;
	}
}

async function existingDirectory(path: string): Promise<boolean> {
	try {
		return (await stat(path)).isDirectory();
	} catch {
		return false;
	}
}

function pathValue(env: NodeJS.ProcessEnv): string | undefined {
	for (const [key, value] of Object.entries(env)) {
		if (key.toLowerCase() === "path") return value;
	}
	return undefined;
}

function pathDirectories(path: string | undefined): string[] {
	if (!path) return [];
	return path.split(delimiter).map((entry) => {
		const trimmed = entry.trim();
		return trimmed.startsWith('"') && trimmed.endsWith('"')
			? trimmed.slice(1, -1)
			: trimmed;
	});
}

/** Resolves only native Win32 executables because terminals never imply a shell. */
export async function resolveWindowsExecutable(
	command: string,
	cwd: string,
	env: NodeJS.ProcessEnv = process.env,
): Promise<string> {
	if (!(await existingDirectory(cwd))) {
		throw new Error(
			`Terminal cwd does not exist or is not a directory: ${cwd}`,
		);
	}
	const names = executableNames(command);
	const explicit =
		isAbsolute(command) ||
		/^[a-z]:/i.test(command) ||
		command.includes("\\") ||
		command.includes("/");
	const directories = explicit ? [cwd] : pathDirectories(pathValue(env));
	for (const directory of directories) {
		for (const name of names) {
			const candidate = resolve(cwd, directory, name);
			if (await isFile(candidate)) return candidate;
		}
	}
	throw new Error(
		`Windows terminal executable was not found: ${command}. Searched ${explicit ? `cwd ${cwd}` : "PATH"} for .exe or .com files.`,
	);
}