Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

editor.ts

265 lines11.1 KB

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, resolveCommandPaths } from "./shell.ts";
11​
12type Editor = (typeof EDITORS)[number];
13​
14// The nearest Zed folder identifies the channel, even below a user named zedpreview.
15const isPrereleaseZedPath = (filePath: string) => {
16 const install = filePath
17 .split(/[\\/]/)
18 .slice(0, -1)
19 .findLast((folder) => folder.toLowerCase().includes("zed"))
20 ?.toLowerCase();
21 return install !== undefined && (install.includes("nightly") || install.includes("preview"));
22};
23​
24const installNames: Partial<Record<Editor["id"], ReadonlyArray<string>>> = {
25 vscode: ["Visual Studio Code"],
26 "vscode-insiders": ["Visual Studio Code - Insiders"],
27 // `Antigravity.app` is the separate Hub, not the IDE.
28 antigravity: ["Antigravity IDE"],
29 idea: ["IntelliJ IDEA", "IntelliJ IDEA CE", "IntelliJ IDEA Ultimate"],
30 pycharm: ["PyCharm", "PyCharm CE"],
31 rider: ["Rider", "JetBrains Rider"],
32};
33​
34// Prefix-only matches could select Insiders when resolving stable VS Code.
35const isVersionedBundle = (entry: string, name: string) => {
36 if (!entry.startsWith(`${name} `) || !entry.endsWith(".app")) return false;
37 return /^\d[\d.]*$/.test(entry.slice(name.length + 1, -".app".length));
38};
39​
40// OpenZFS's event daemon is also named zed, and the Cursor Agent CLI installs a cursor script
41// that fails without an IDE behind it; both reject `--version` instead of starting.
42const isEditorCommand = Effect.fn("editor.isEditorCommand")(
43 function* (command: string, isZed: boolean) {
44 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
45 const handle = yield* spawner.spawn(
46 ChildProcess.make(command, ["--version"], {
47 stdin: "ignore",
48 stderr: "ignore",
49 forceKillAfter: "1 second",
50 }),
51 );
52 const [stdout, exitCode] = yield* Effect.all(
53 [handle.stdout.pipe(Stream.decodeText(), Stream.runHead), handle.exitCode],
54 { concurrency: "unbounded" },
55 );
56 return exitCode === 0 && (!isZed || Option.getOrElse(stdout, () => "").startsWith("Zed"));
57 },
58 Effect.scoped,
59 // A slow first start after an update must not hide a working Cursor.
60 (probe, _command, isZed) =>
61 Effect.timeoutOrElse(probe, { duration: "2 seconds", orElse: () => Effect.succeed(!isZed) }),
62 Effect.catchCause(() => Effect.succeed(false)),
63);
64​
65// The IDE launcher's `bin` sits beside or in `resources/app`; only Kiro's router needs `ide`.
66const isKiroIdeLauncher = Effect.fn("editor.isKiroIdeLauncher")(function* (command: string) {
67 const fs = yield* FileSystem.FileSystem;
68 const path = yield* Path.Path;
69 const real = yield* fs.realPath(command).pipe(Effect.orElseSucceed(() => command));
70 const install = path.dirname(path.dirname(real));
71 if (/[\\/]resources[\\/]app$/i.test(install)) return true;
72 return yield* fs
73 .exists(path.join(install, "resources", "app"))
74 .pipe(Effect.orElseSucceed(() => false));
75});
76​
77export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(function* (
78 editor: Editor,
79 env: NodeJS.ProcessEnv,
80) {
81 if (editor.commands === null) return Option.none();
82 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
83 const platform = yield* HostProcess.Platform;
84 // Prefer Zed's macOS bundle because OpenZFS also installs a zed executable.
85 const preferBundle = platform === "darwin" && editor.id === "zed";
86 const preferZeditor = platform === "linux" && editor.id === "zed";
87 const probeCursor = editor.id === "cursor" && platform !== "win32";
88 if (platform === "win32" && editor.id === "zed") {
89 const isStable = (resolved: string) => !isPrereleaseZedPath(resolved);
90 let firstCommand: string | undefined;
91 for (const command of editor.commands) {
92 const matches = yield* resolveCommandPaths(command, { env, until: isStable });
93 const stable = matches.find(isStable);
94 // Bypass PATH only when stable is behind a prerelease install.
95 if (stable !== undefined) {
96 const isFirst = firstCommand === undefined && stable === matches[0];
97 return Option.some({ command: isFirst ? command : stable, baseArgs });
98 }
99 if (firstCommand === undefined && matches.length > 0) firstCommand = command;
100 }
101 if (firstCommand !== undefined) return Option.some({ command: firstCommand, baseArgs });
102 } else if (!preferBundle && !preferZeditor && !probeCursor) {
103 for (const command of editor.commands) {
104 // Launch the uncached match that was classified, so a newer PATH entry cannot swap it.
105 if (editor.id === "kiro") {
106 const [match] = yield* resolveCommandPaths(command, { env, until: () => true });
107 if (match === undefined) continue;
108 const resolved = (yield* Path.Path).resolve(match);
109 const ide = yield* isKiroIdeLauncher(resolved);
110 return Option.some({ command: resolved, baseArgs: ide ? [] : baseArgs });
111 }
112 if (yield* isCommandAvailable(command, { env })) return Option.some({ command, baseArgs });
113 }
114 }
115​
116 const path = yield* Path.Path;
117 const fs = yield* FileSystem.FileSystem;
118 const home = env.HOME;
119 const names = installNames[editor.id] ?? [editor.label];
120 const command = editor.commands[0];
121 const jetbrains = editor.launchStyle === "line-column";
122 const candidates: string[] = probeCursor ? [...editor.commands] : [];
123 let toolbox: { dir: string; suffix: string } | undefined;
124​
125 if (platform === "darwin") {
126 const roots = [...(home ? [path.join(home, "Applications")] : []), "/Applications"];
127 for (const root of roots) {
128 // JetBrains Toolbox appends versions to bundle names; accept exact and versioned names.
129 const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
130 const bundles = new Set(names.map((name) => `${name}.app`));
131 for (const entry of entries) {
132 if (names.some((name) => entry === `${name}.app` || isVersionedBundle(entry, name))) {
133 bundles.add(entry);
134 }
135 }
136 for (const bundle of bundles) {
137 const contents = path.join(root, bundle, "Contents");
138 candidates.push(
139 ...(jetbrains || editor.id === "zed"
140 ? [path.join(contents, "MacOS", editor.id === "zed" ? "cli" : command)]
141 : [
142 path.join(contents, "Resources/app/bin", command),
143 path.join(contents, "Resources/app/bin/code"),
144 ]),
145 );
146 }
147 }
148 if (home && jetbrains) {
149 toolbox = {
150 dir: path.join(home, "Library/Application Support/JetBrains/Toolbox/scripts"),
151 suffix: "",
152 };
153 candidates.push(path.join(toolbox.dir, command));
154 }
155 } else if (platform === "win32") {
156 const roots = [
157 ...(env.LOCALAPPDATA ? [path.join(env.LOCALAPPDATA, "Programs")] : []),
158 ...[env.ProgramFiles, env["ProgramFiles(x86)"], env.ProgramW6432].filter(
159 (root): root is string => !!root,
160 ),
161 ];
162 if (jetbrains) {
163 if (env.LOCALAPPDATA) {
164 toolbox = { dir: path.join(env.LOCALAPPDATA, "JetBrains/Toolbox/scripts"), suffix: ".cmd" };
165 candidates.push(path.join(toolbox.dir, `${command}.cmd`));
166 }
167 for (const directory of roots.flatMap((root) => [root, path.join(root, "JetBrains")])) {
168 const entries = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
169 for (const entry of entries) {
170 if (names.some((name) => entry === name || entry.startsWith(`${name} `))) {
171 candidates.push(path.join(directory, entry, "bin", `${command}64.exe`));
172 candidates.push(path.join(directory, entry, "bin", `${command}.exe`));
173 }
174 }
175 }
176 } else {
177 const name =
178 editor.id === "vscode"
179 ? "Microsoft VS Code"
180 : editor.id === "vscode-insiders"
181 ? "Microsoft VS Code Insiders"
182 : editor.label;
183 for (const root of roots) {
184 candidates.push(
185 path.join(root, name, "resources/app/bin", `${command}.cmd`),
186 path.join(root, name, "resources/app/bin/code.cmd"),
187 path.join(root, name, "bin", `${command}.cmd`),
188 path.join(root, name, "bin/code.cmd"),
189 );
190 if (editor.id === "zed") {
191 candidates.push(
192 path.join(root, name, "bin", "zed.exe"),
193 path.join(root, name, "zed.exe"),
194 );
195 }
196 }
197 }
198 } else if (platform === "linux") {
199 const dirs = [
200 ...(home ? [path.join(home, ".local/bin")] : []),
201 "/usr/local/bin",
202 "/usr/bin",
203 "/snap/bin",
204 ];
205 const dataHome = env.XDG_DATA_HOME || (home ? path.join(home, ".local/share") : undefined);
206 if (jetbrains && dataHome) {
207 toolbox = { dir: path.join(dataHome, "JetBrains/Toolbox/scripts"), suffix: "" };
208 dirs.push(toolbox.dir);
209 }
210 if (preferZeditor) {
211 // Linux packages use zeditor because OpenZFS owns the zed command.
212 for (const name of ["zeditor", "zed"]) {
213 candidates.push(name, ...dirs.map((dir) => path.join(dir, name)));
214 }
215 } else {
216 for (const dir of dirs) {
217 for (const name of editor.commands) candidates.push(path.join(dir, name));
218 }
219 }
220 }
221​
222 if (preferBundle) candidates.push(...editor.commands);
223 if (toolbox) {
224 // Toolbox names a launch script `idea1`, `idea2`, ... while `idea` is taken, and keeps that
225 // name after the other install is removed. Try these only after every canonical candidate.
226 const { dir, suffix } = toolbox;
227 const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []));
228 candidates.push(
229 ...entries
230 .filter(
231 (entry) =>
232 entry.startsWith(command) &&
233 entry.endsWith(suffix) &&
234 /^\d+$/.test(entry.slice(command.length, entry.length - suffix.length)),
235 )
236 .sort((a, b) => a.length - b.length || a.localeCompare(b))
237 .map((entry) => path.join(dir, entry)),
238 );
239 }
240 const probeZed = editor.id === "zed" && platform !== "win32";
241 const rejected = new Set<string>();
242 for (const candidate of candidates) {
243 // An earlier PATH entry can hold OpenZFS zed or the Cursor Agent CLI's cursor script.
244 const matches =
245 (probeZed || probeCursor) && candidate === command
246 ? yield* resolveCommandPaths(candidate, { env, until: () => false })
247 : [yield* resolveCommandPath(candidate, { env })];
248 for (const resolved of matches) {
249 if (resolved === null || rejected.has(resolved)) continue;
250 const probed = probeCursor || (probeZed && path.basename(candidate) === "zed");
251 if (probed && !(yield* isEditorCommand(resolved, probeZed))) {
252 rejected.add(resolved);
253 continue;
254 }
255 return Option.some({
256 command: resolved === matches[0] ? candidate : resolved,
257 baseArgs:
258 editor.id === "kiro" && (platform !== "linux" || (yield* isKiroIdeLauncher(resolved)))
259 ? []
260 : baseArgs,
261 });
262 }
263 }
264 return Option.none();
265});