|
1 | 1 | import type { CliRenderer } from "@opentui/core" |
2 | | -import { existsSync, readdirSync, readFileSync, statSync } from "node:fs" |
| 2 | +import { existsSync, readdirSync, readFileSync, statSync, type Stats } from "node:fs" |
3 | 3 | import { readFile, rm, writeFile } from "node:fs/promises" |
4 | 4 | import os from "node:os" |
5 | 5 | import path from "node:path" |
6 | 6 | import { spawn } from "node:child_process" |
7 | 7 | import type { Stream } from "node:stream" |
| 8 | +import { openPath } from "@opencode/util/open" |
8 | 9 | import { resolveZedDbPath, resolveZedSelection } from "./editor-zed" |
9 | 10 |
|
10 | 11 | export { normalizePromptContent } from "./prompt/content" |
@@ -38,6 +39,308 @@ export async function openEditor(input: { value: string; renderer: CliRenderer; |
38 | 39 | } |
39 | 40 | } |
40 | 41 |
|
| 42 | +const terminalEditors = new Set(["vim", "nvim", "vi", "nano", "micro", "emacs", "kak", "hx", "helix", "joe", "mcedit"]) |
| 43 | +const gotoEditors = new Set(["code", "code-insiders", "codium", "cursor", "windsurf", "trae"]) |
| 44 | +const colonEditors = new Set(["subl", "sublime_text", "atom", "zed", "zeditor", "hx", "helix"]) |
| 45 | + |
| 46 | +export type EditorInvocation = { |
| 47 | + command: string |
| 48 | + args: string[] |
| 49 | + /** The editor owns the terminal, so the renderer must suspend until it exits. */ |
| 50 | + terminal: boolean |
| 51 | + /** Windows command shims (`.cmd`/`.bat`/bare names) need `cmd.exe` to resolve. */ |
| 52 | + shell: boolean |
| 53 | +} |
| 54 | + |
| 55 | +/** Splits `$EDITOR` into a command and arguments without invoking a shell. */ |
| 56 | +export function splitCommand(input: string) { |
| 57 | + const parts: string[] = [] |
| 58 | + let current = "" |
| 59 | + let quote: '"' | "'" | undefined |
| 60 | + for (const char of input) { |
| 61 | + if (quote) { |
| 62 | + if (char === quote) quote = undefined |
| 63 | + else current += char |
| 64 | + continue |
| 65 | + } |
| 66 | + if (char === '"' || char === "'") { |
| 67 | + quote = char |
| 68 | + continue |
| 69 | + } |
| 70 | + if (/\s/.test(char)) { |
| 71 | + if (current) parts.push(current) |
| 72 | + current = "" |
| 73 | + continue |
| 74 | + } |
| 75 | + current += char |
| 76 | + } |
| 77 | + if (current) parts.push(current) |
| 78 | + return parts |
| 79 | +} |
| 80 | + |
| 81 | +export type EditorTarget = { file: string; line?: number; column?: number } |
| 82 | + |
| 83 | +export type EditorBatchInvocation = EditorInvocation & { |
| 84 | + /** Every target opens in one editor process; otherwise launch each target. */ |
| 85 | + batch: boolean |
| 86 | +} |
| 87 | + |
| 88 | +export function buildEditorBatchInvocation(input: { |
| 89 | + editor: string |
| 90 | + files: readonly EditorTarget[] |
| 91 | + platform?: NodeJS.Platform |
| 92 | +}): EditorBatchInvocation { |
| 93 | + const parts = splitCommand(input.editor) |
| 94 | + const command = parts[0] |
| 95 | + if (!command) throw new Error("Set $VISUAL or $EDITOR to open files in an editor") |
| 96 | + const name = editorName(command) |
| 97 | + return { |
| 98 | + command, |
| 99 | + args: [...parts.slice(1), ...targetArgs(name, input.files)], |
| 100 | + terminal: terminalEditors.has(name), |
| 101 | + shell: (input.platform ?? process.platform) === "win32" && !/\.(exe|com)$/i.test(command), |
| 102 | + batch: terminalEditors.has(name) || gotoEditors.has(name) || colonEditors.has(name), |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +function editorName(command: string) { |
| 107 | + return command |
| 108 | + .split(/[\\/]/) |
| 109 | + .pop()! |
| 110 | + .toLowerCase() |
| 111 | + .replace(/\.(exe|cmd|bat|com)$/, "") |
| 112 | +} |
| 113 | + |
| 114 | +function targetArgs(name: string, files: readonly EditorTarget[]) { |
| 115 | + if (!files.length) return [] |
| 116 | + const first = files[0]! |
| 117 | + const paths = files.map((file) => file.file) |
| 118 | + if (gotoEditors.has(name)) { |
| 119 | + if (!files.some((file) => file.line)) return paths |
| 120 | + return ["--goto", ...files.map(locationArg)] |
| 121 | + } |
| 122 | + if (colonEditors.has(name)) return files.map(locationArg) |
| 123 | + if (name === "emacs") |
| 124 | + return first.line ? [`+${first.line}${first.column ? `:${first.column}` : ""}`, ...paths] : paths |
| 125 | + if (name === "nano" || name === "micro" || name === "kak") |
| 126 | + return first.line ? [`+${first.line}${first.column ? `,${first.column}` : ""}`, ...paths] : paths |
| 127 | + if (name === "vim" || name === "nvim" || name === "vi") return first.line ? [`+${first.line}`, ...paths] : paths |
| 128 | + return [first.file] |
| 129 | +} |
| 130 | + |
| 131 | +function locationArg(file: EditorTarget) { |
| 132 | + return file.line ? `${file.file}:${file.line}${file.column ? `:${file.column}` : ""}` : file.file |
| 133 | +} |
| 134 | + |
| 135 | +export type FileLocation = { path: string; line?: number; column?: number } |
| 136 | +export type FileOpenFailure = { path: string; message: string } |
| 137 | +export type FileOpenResult = { opened: number; failures: FileOpenFailure[] } |
| 138 | + |
| 139 | +/** |
| 140 | + * Opens resolved local paths with the user's editor, one process when the |
| 141 | + * editor accepts several targets. Directories open in the system file manager. |
| 142 | + * Without an editor, files open with the OS default handler except launchable |
| 143 | + * types, which would run instead of display. Repeated paths open once with the |
| 144 | + * first location winning. |
| 145 | + */ |
| 146 | +export async function openFilesAtLocation(input: { |
| 147 | + files: readonly FileLocation[] |
| 148 | + renderer: CliRenderer |
| 149 | + cwd?: string |
| 150 | +}): Promise<FileOpenResult> { |
| 151 | + const unique = new Map<string, FileLocation>() |
| 152 | + for (const file of input.files) if (!unique.has(file.path)) unique.set(file.path, file) |
| 153 | + |
| 154 | + const failures: FileOpenFailure[] = [] |
| 155 | + const pending: { file: FileLocation; stat: Stats }[] = [] |
| 156 | + let opened = 0 |
| 157 | + const openedOnce = () => { |
| 158 | + opened++ |
| 159 | + } |
| 160 | + const openFailed = (file: string) => (error: unknown) => { |
| 161 | + failures.push(failure(file, error)) |
| 162 | + } |
| 163 | + |
| 164 | + for (const file of unique.values()) { |
| 165 | + const stat = statSync(file.path, { throwIfNoEntry: false }) |
| 166 | + if (!stat) { |
| 167 | + failures.push({ path: file.path, message: `Path does not exist: ${file.path}` }) |
| 168 | + continue |
| 169 | + } |
| 170 | + if (stat.isDirectory()) { |
| 171 | + // Opening a macOS bundle launches the app; reveal bundles in the file manager instead. |
| 172 | + const target = process.platform === "darwin" && file.path.endsWith(".app") ? path.dirname(file.path) : file.path |
| 173 | + await openPath(target).then(openedOnce, openFailed(file.path)) |
| 174 | + continue |
| 175 | + } |
| 176 | + pending.push({ file, stat }) |
| 177 | + } |
| 178 | + |
| 179 | + if (!pending.length) return { opened, failures } |
| 180 | + const editor = process.env.VISUAL || process.env.EDITOR |
| 181 | + if (!editor) { |
| 182 | + for (const target of pending) { |
| 183 | + if (isLaunchable(target.file.path, target.stat)) { |
| 184 | + failures.push({ path: target.file.path, message: refusal(target.file.path) }) |
| 185 | + continue |
| 186 | + } |
| 187 | + await openPath(target.file.path).then(openedOnce, openFailed(target.file.path)) |
| 188 | + } |
| 189 | + return { opened, failures } |
| 190 | + } |
| 191 | + |
| 192 | + const cwd = input.cwd && existsSync(input.cwd) ? input.cwd : process.cwd() |
| 193 | + const invocation = buildEditorBatchInvocation({ |
| 194 | + editor, |
| 195 | + files: pending.map((target) => ({ file: target.file.path, line: target.file.line, column: target.file.column })), |
| 196 | + }) |
| 197 | + if (invocation.terminal) { |
| 198 | + await input.renderer.suspend() |
| 199 | + try { |
| 200 | + await runTerminalEditor(invocation, cwd) |
| 201 | + opened += pending.length |
| 202 | + } catch (error) { |
| 203 | + failures.push(failure(pending[0]!.file.path, error)) |
| 204 | + } finally { |
| 205 | + await input.renderer.resume() |
| 206 | + } |
| 207 | + return { opened, failures } |
| 208 | + } |
| 209 | + if (!invocation.batch) { |
| 210 | + for (const target of pending) { |
| 211 | + const single = buildEditorBatchInvocation({ |
| 212 | + editor, |
| 213 | + files: [{ file: target.file.path, line: target.file.line, column: target.file.column }], |
| 214 | + }) |
| 215 | + await launchEditor(single, cwd).then(openedOnce, openFailed(target.file.path)) |
| 216 | + } |
| 217 | + return { opened, failures } |
| 218 | + } |
| 219 | + try { |
| 220 | + await launchEditor(invocation, cwd) |
| 221 | + opened += pending.length |
| 222 | + } catch (error) { |
| 223 | + for (const target of pending) { |
| 224 | + if (isLaunchable(target.file.path, target.stat)) { |
| 225 | + failures.push(failure(target.file.path, error)) |
| 226 | + continue |
| 227 | + } |
| 228 | + await openPath(target.file.path).then(openedOnce, openFailed(target.file.path)) |
| 229 | + } |
| 230 | + } |
| 231 | + return { opened, failures } |
| 232 | +} |
| 233 | + |
| 234 | +function failure(file: string, error: unknown): FileOpenFailure { |
| 235 | + return { path: file, message: error instanceof Error ? error.message : String(error) } |
| 236 | +} |
| 237 | + |
| 238 | +function refusal(file: string) { |
| 239 | + return `Refusing to launch ${path.basename(file)}: set $VISUAL or $EDITOR to open it` |
| 240 | +} |
| 241 | + |
| 242 | +/** Opens one resolved path; see `openFilesAtLocation` for the safety rules. */ |
| 243 | +export async function openFileAtLocation(input: { |
| 244 | + path: string |
| 245 | + line?: number |
| 246 | + column?: number |
| 247 | + renderer: CliRenderer |
| 248 | + cwd?: string |
| 249 | +}) { |
| 250 | + const result = await openFilesAtLocation({ |
| 251 | + files: [{ path: input.path, line: input.line, column: input.column }], |
| 252 | + renderer: input.renderer, |
| 253 | + cwd: input.cwd, |
| 254 | + }) |
| 255 | + if (result.opened) return |
| 256 | + throw new Error(result.failures[0]?.message ?? `Could not open ${input.path}`) |
| 257 | +} |
| 258 | + |
| 259 | +// Extensions whose default handler executes the file rather than displaying it. |
| 260 | +const launchableExtensions = new Set([ |
| 261 | + ".app", |
| 262 | + ".appdir", |
| 263 | + ".appref-ms", |
| 264 | + ".bat", |
| 265 | + ".chm", |
| 266 | + ".cmd", |
| 267 | + ".com", |
| 268 | + ".command", |
| 269 | + ".cpl", |
| 270 | + ".desktop", |
| 271 | + ".diagcab", |
| 272 | + ".exe", |
| 273 | + ".hta", |
| 274 | + ".inf", |
| 275 | + ".jar", |
| 276 | + ".js", |
| 277 | + ".jse", |
| 278 | + ".lnk", |
| 279 | + ".msc", |
| 280 | + ".msi", |
| 281 | + ".msix", |
| 282 | + ".pif", |
| 283 | + ".pkg", |
| 284 | + ".ps1", |
| 285 | + ".ps1xml", |
| 286 | + ".psc1", |
| 287 | + ".psc2", |
| 288 | + ".reg", |
| 289 | + ".scf", |
| 290 | + ".scr", |
| 291 | + ".sct", |
| 292 | + ".settingcontent-ms", |
| 293 | + ".shb", |
| 294 | + ".shs", |
| 295 | + ".sys", |
| 296 | + ".terminal", |
| 297 | + ".vb", |
| 298 | + ".vbe", |
| 299 | + ".vbs", |
| 300 | + ".workflow", |
| 301 | + ".ws", |
| 302 | + ".wsc", |
| 303 | + ".wsf", |
| 304 | + ".wsh", |
| 305 | +]) |
| 306 | + |
| 307 | +function isLaunchable(file: string, stat: Stats) { |
| 308 | + if (process.platform !== "win32" && (stat.mode & 0o111) !== 0) return true |
| 309 | + return launchableExtensions.has(path.extname(file).toLowerCase()) |
| 310 | +} |
| 311 | + |
| 312 | +function spawnInvocation(invocation: EditorInvocation, cwd: string) { |
| 313 | + if (!invocation.shell) return spawn(invocation.command, invocation.args, { cwd, stdio: "inherit" }) |
| 314 | + const command = [invocation.command, ...invocation.args].map((part) => `"${part}"`).join(" ") |
| 315 | + return spawn(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", `"${command}"`], { |
| 316 | + cwd, |
| 317 | + stdio: "inherit", |
| 318 | + windowsVerbatimArguments: true, |
| 319 | + }) |
| 320 | +} |
| 321 | + |
| 322 | +function runTerminalEditor(invocation: EditorInvocation, cwd: string) { |
| 323 | + return new Promise<void>((resolve, reject) => { |
| 324 | + const child = spawnInvocation(invocation, cwd) |
| 325 | + child.on("error", reject) |
| 326 | + child.on("exit", (code, signal) => { |
| 327 | + if (code === 0) return resolve() |
| 328 | + reject(new Error(`Editor exited with ${signal ? `signal ${signal}` : `code ${code}`}`)) |
| 329 | + }) |
| 330 | + }) |
| 331 | +} |
| 332 | + |
| 333 | +function launchEditor(invocation: EditorInvocation, cwd: string) { |
| 334 | + return new Promise<void>((resolve, reject) => { |
| 335 | + const child = spawnInvocation(invocation, cwd) |
| 336 | + child.on("error", reject) |
| 337 | + child.on("spawn", () => { |
| 338 | + child.unref() |
| 339 | + resolve() |
| 340 | + }) |
| 341 | + }) |
| 342 | +} |
| 343 | + |
41 | 344 | export function discoverEditorConnection(directory: string) { |
42 | 345 | const root = path.join(os.homedir(), ".claude", "ide") |
43 | 346 | const contains = (parent: string) => { |
|
0 commit comments