Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/intellij/launch.ts

Raw
import { spawn } from "node:child_process";
import { findExecutable } from "./src/pi-ext-executable.ts";

type IdeaLauncher = {
	command: string;
	argsBeforePath: string[];
	script?: string;
};

export function findIdeaLauncher(
	env: NodeJS.ProcessEnv = process.env,
	platform: NodeJS.Platform = process.platform,
): IdeaLauncher | undefined {
	const getEnv = (key: string) =>
		platform === "win32"
			? Object.entries(env).find(
					([candidate]) => candidate.toLowerCase() === key.toLowerCase(),
				)?.[1]
			: env[key];
	const path = getEnv("PATH");
	if (!path) return undefined;
	const host = platform === "win32" ? getEnv("COMSPEC") : undefined;
	const names =
		platform === "win32"
			? host
				? ["idea64.exe", "idea.exe", "idea.cmd", "idea.bat"]
				: ["idea64.exe", "idea.exe"]
			: ["idea"];
	const executable = findExecutable(names, { path, platform });
	if (!executable) return undefined;
	if (/\.(?:cmd|bat)$/iu.test(executable)) {
		if (!host) return undefined;
		return {
			command: host,
			argsBeforePath: ["/d", "/v:off", "/s", "/c"],
			script: executable,
		};
	}
	return { command: executable, argsBeforePath: [] };
}

export async function launchIdea(projectPath: string): Promise<void> {
	const launcher = findIdeaLauncher();
	if (!launcher)
		throw new Error(
			"IntelliJ launcher not found. Add idea (macOS/Linux) or idea64.exe, idea.exe, idea.cmd, or idea.bat (Windows) to PATH.",
		);
	const args = launcher.script
		? [
				...launcher.argsBeforePath,
				`"${quoteCmdPath(launcher.script)} ${quoteCmdPath(projectPath)}"`,
			]
		: [...launcher.argsBeforePath, projectPath];
	await new Promise<void>((resolve, reject) => {
		const child = spawn(launcher.command, args, {
			detached: true,
			stdio: "ignore",
			windowsHide: true,
			windowsVerbatimArguments: launcher.script !== undefined,
		});
		child.once("error", reject);
		child.once("spawn", () => {
			child.unref();
			resolve();
		});
	});
}

function quoteCmdPath(value: string): string {
	// CMD expands percent variables even inside quotes; reject rather than rewrite paths.
	if (/[%!"\r\n\0]/.test(value))
		throw new Error(
			"IntelliJ batch launcher cannot handle this path. Use idea64.exe or idea.exe instead.",
		);
	return `"${value}"`;
}