import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; import { findIdeaLauncher, launchIdea } from "../launch.ts"; let root: string | undefined; afterEach(() => { vi.unstubAllEnvs(); if (root) rmSync(root, { recursive: true, force: true }); root = undefined; }); function bin() { root = mkdtempSync(join(tmpdir(), "intellij launch & (test)^-")); return root; } function executable(path: string, content = "") { writeFileSync(path, content); chmodSync(path, 0o755); } it.each(["linux", "darwin"] as const)( "finds executable idea on %s PATH", (platform) => { const directory = bin(); const command = join(directory, "idea"); executable(command); expect(findIdeaLauncher({ PATH: directory }, platform)).toEqual({ command, argsBeforePath: [], }); }, ); it("uses case-insensitive Windows env, quoted PATH entries, and prefers native launchers", () => { const directory = bin(); const script = join(directory, "idea.cmd"); executable(script); const env = { Path: `"${directory}"`, ComSpec: "C:\\Windows\\System32\\cmd.exe", }; expect(findIdeaLauncher(env, "win32")).toEqual({ command: env.ComSpec, argsBeforePath: ["/d", "/v:off", "/s", "/c"], script, }); expect(findIdeaLauncher({ Path: directory }, "win32")).toBeUndefined(); const command = join(directory, "idea64.exe"); executable(command); expect(findIdeaLauncher(env, "win32")).toEqual({ command, argsBeforePath: [], }); }); it("reports missing launchers", async () => { vi.stubEnv("PATH", bin()); await expect(launchIdea("project")).rejects.toThrow( "IntelliJ launcher not found", ); }); it("passes paths with spaces and shell metacharacters unchanged through the real host launcher", async () => { const directory = bin(); const project = join(directory, "project & (nested)^ name"); mkdirSync(project); const output = join(directory, "args.json"); const capture = join(directory, "capture.cjs"); writeFileSync( capture, `require("node:fs").writeFileSync(${JSON.stringify(output)}, JSON.stringify(process.argv.slice(2)));`, ); const windows = process.platform === "win32"; executable( join(directory, windows ? "idea.cmd" : "idea"), windows ? `@echo off\r\n"${process.execPath}" "${capture}" %*\r\n` : `#!/bin/sh\nexec "${process.execPath}" "${capture}" "$@"\n`, ); vi.stubEnv("PATH", directory); await launchIdea(project); await vi.waitFor(() => expect(JSON.parse(readFileSync(output, "utf8"))).toEqual([project]), ); }); it.skipIf(process.platform !== "win32")( "rejects batch expansion characters rather than rewriting paths", async () => { const directory = bin(); executable(join(directory, "idea.cmd")); vi.stubEnv("PATH", directory); for (const project of [ "project%PATH%", "project!", 'project"', "project\n", "project\r", "project\0", ]) await expect(launchIdea(project)).rejects.toThrow( "Use idea64.exe or idea.exe", ); }, );