Open History to see the last commit
1import type { EDITORS } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as Path from "effect/Path";
6import * as Stream from "effect/Stream";
7import { ChildProcess, ChildProcessSpawner } from "effect/process";
8
9import * as HostProcess from "./HostProcess.ts";
10import { isCommandAvailable, resolveCommandPath } from "./shell.ts";
11
12type Editor = (typeof EDITORS)[number];
13
14const installNames: Partial<Record<Editor["id"], ReadonlyArray<string>>> = {
15 vscode: ["Visual Studio Code"],
16 "vscode-insiders": ["Visual Studio Code - Insiders"],
17 // `Antigravity.app` is the separate Hub, not the IDE.
18 antigravity: ["Antigravity IDE"],
19 idea: ["IntelliJ IDEA", "IntelliJ IDEA CE", "IntelliJ IDEA Ultimate"],
20 pycharm: ["PyCharm", "PyCharm CE"],
21 rider: ["Rider", "JetBrains Rider"],
22};
23
24// Prefix-only matches could select Insiders when resolving stable VS Code.
25const isVersionedBundle = (entry: string, name: string) => {
26 if (!entry.startsWith(`${name} `) || !entry.endsWith(".app")) return false;
27 return /^\d[\d.]*$/.test(entry.slice(name.length + 1, -".app".length));
28};
29
30// OpenZFS's event daemon is also named zed; it rejects `--version` instead of starting.
31const isZedEditor = Effect.fn("editor.isZedEditor")(
32 function* (command: string) {
33 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
34 const handle = yield* spawner.spawn(
35 ChildProcess.make(command, ["--version"], {
36 stdin: "ignore",
37 stderr: "ignore",
38 forceKillAfter: "1 second",
39 }),
40 );
41 const [stdout, exitCode] = yield* Effect.all(
42 [handle.stdout.pipe(Stream.decodeText(), Stream.runHead), handle.exitCode],
43 { concurrency: "unbounded" },
44 );
45 return exitCode === 0 && Option.getOrElse(stdout, () => "").startsWith("Zed");
46 },
47 Effect.scoped,
48 Effect.timeout("2 seconds"),
49 Effect.catchCause(() => Effect.succeed(false)),
50);
51
52export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(function* (
53 editor: Editor,
54 env: NodeJS.ProcessEnv,
55) {
56 if (editor.commands === null) return Option.none();
57 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
58 const platform = yield* HostProcess.Platform;
59 // Prefer Zed's macOS bundle because OpenZFS also installs a zed executable.
60 const preferBundle = platform === "darwin" && editor.id === "zed";
61 const preferZeditor = platform === "linux" && editor.id === "zed";
62 if (!preferBundle && !preferZeditor) {
63 for (const command of editor.commands) {
64 if (yield* isCommandAvailable(command, { env })) return Option.some({ command, baseArgs });
65 }
66 }
67
68 const path = yield* Path.Path;
69 const fs = yield* FileSystem.FileSystem;
70 const home = env.HOME;
71 const names = installNames[editor.id] ?? [editor.label];
72 const command = editor.commands[0];
73 const jetbrains = editor.launchStyle === "line-column";
74 const candidates: string[] = [];
75 let toolbox: { dir: string; suffix: string } | undefined;
76
77 if (platform === "darwin") {
78 const roots = [...(home ? [path.join(home, "Applications")] : []), "/Applications"];
79 for (const root of roots) {
80 // JetBrains Toolbox appends versions to bundle names; accept exact and versioned names.
81 const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
82 const bundles = new Set(names.map((name) => `${name}.app`));
83 for (const entry of entries) {
84 if (names.some((name) => entry === `${name}.app` || isVersionedBundle(entry, name))) {
85 bundles.add(entry);
86 }
87 }
88 for (const bundle of bundles) {
89 const contents = path.join(root, bundle, "Contents");
90 candidates.push(
91 ...(jetbrains || editor.id === "zed"
92 ? [path.join(contents, "MacOS", editor.id === "zed" ? "cli" : command)]
93 : [
94 path.join(contents, "Resources/app/bin", command),
95 path.join(contents, "Resources/app/bin/code"),
96 ]),
97 );
98 }
99 }
100 if (home && jetbrains) {
101 toolbox = {
102 dir: path.join(home, "Library/Application Support/JetBrains/Toolbox/scripts"),
103 suffix: "",
104 };
105 candidates.push(path.join(toolbox.dir, command));
106 }
107 } else if (platform === "win32") {
108 const roots = [
109 ...(env.LOCALAPPDATA ? [path.join(env.LOCALAPPDATA, "Programs")] : []),
110 ...[env.ProgramFiles, env["ProgramFiles(x86)"], env.ProgramW6432].filter(
111 (root): root is string => !!root,
112 ),
113 ];
114 if (jetbrains) {
115 if (env.LOCALAPPDATA) {
116 toolbox = { dir: path.join(env.LOCALAPPDATA, "JetBrains/Toolbox/scripts"), suffix: ".cmd" };
117 candidates.push(path.join(toolbox.dir, `${command}.cmd`));
118 }
119 for (const directory of roots.flatMap((root) => [root, path.join(root, "JetBrains")])) {
120 const entries = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
121 for (const entry of entries) {
122 if (names.some((name) => entry === name || entry.startsWith(`${name} `))) {
123 candidates.push(path.join(directory, entry, "bin", `${command}64.exe`));
124 candidates.push(path.join(directory, entry, "bin", `${command}.exe`));
125 }
126 }
127 }
128 } else {
129 const name =
130 editor.id === "vscode"
131 ? "Microsoft VS Code"
132 : editor.id === "vscode-insiders"
133 ? "Microsoft VS Code Insiders"
134 : editor.label;
135 for (const root of roots) {
136 candidates.push(
137 path.join(root, name, "resources/app/bin", `${command}.cmd`),
138 path.join(root, name, "resources/app/bin/code.cmd"),
139 path.join(root, name, "bin", `${command}.cmd`),
140 path.join(root, name, "bin/code.cmd"),
141 );
142 if (editor.id === "zed") {
143 candidates.push(
144 path.join(root, name, "bin", "zed.exe"),
145 path.join(root, name, "zed.exe"),
146 );
147 }
148 }
149 }
150 } else if (platform === "linux") {
151 const dirs = [
152 ...(home ? [path.join(home, ".local/bin")] : []),
153 "/usr/local/bin",
154 "/usr/bin",
155 "/snap/bin",
156 ];
157 const dataHome = env.XDG_DATA_HOME || (home ? path.join(home, ".local/share") : undefined);
158 if (jetbrains && dataHome) {
159 toolbox = { dir: path.join(dataHome, "JetBrains/Toolbox/scripts"), suffix: "" };
160 dirs.push(toolbox.dir);
161 }
162 if (preferZeditor) {
163 // Linux packages use zeditor because OpenZFS owns the zed command.
164 for (const name of ["zeditor", "zed"]) {
165 candidates.push(name, ...dirs.map((dir) => path.join(dir, name)));
166 }
167 } else {
168 for (const dir of dirs) {
169 for (const name of editor.commands) candidates.push(path.join(dir, name));
170 }
171 }
172 }
173
174 if (preferBundle) candidates.push(...editor.commands);
175 if (toolbox) {
176 // Toolbox names a launch script `idea1`, `idea2`, ... while `idea` is taken, and keeps that
177 // name after the other install is removed. Try these only after every canonical candidate.
178 const { dir, suffix } = toolbox;
179 const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []));
180 candidates.push(
181 ...entries
182 .filter(
183 (entry) =>
184 entry.startsWith(command) &&
185 entry.endsWith(suffix) &&
186 /^\d+$/.test(entry.slice(command.length, entry.length - suffix.length)),
187 )
188 .sort((a, b) => a.length - b.length || a.localeCompare(b))
189 .map((entry) => path.join(dir, entry)),
190 );
191 }
192 const rejected = new Set<string>();
193 for (const candidate of candidates) {
194 const resolved = yield* resolveCommandPath(candidate, { env });
195 if (resolved === null || rejected.has(resolved)) continue;
196 if (preferZeditor && path.basename(candidate) === "zed" && !(yield* isZedEditor(resolved))) {
197 rejected.add(resolved);
198 continue;
199 }
200 return Option.some({
201 command: candidate,
202 baseArgs:
203 editor.id === "kiro" && (platform === "darwin" || platform === "win32") ? [] : baseArgs,
204 });
205 }
206 return Option.none();
207});