diff --git a/src/features/run/configSource.test.ts b/src/features/run/configSource.test.ts new file mode 100644 index 000000000..503d007b3 --- /dev/null +++ b/src/features/run/configSource.test.ts @@ -0,0 +1,91 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; + +const files = new Map(); + +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { + ...real, + call: (value: unknown) => value, + commands: { + ...real.commands, + fsReadText: (path: string) => + files.has(path) ? Promise.resolve(files.get(path)) : Promise.reject(new Error("not found")), + findFilesNamed: (name: string) => Promise.resolve([...files.keys()].filter((p) => p.endsWith(`/${name}`))), + }, + }; +}); + +const { configSource, hasSource } = await import("./configSource"); + +const ROOT = "/w/shop"; +const config = (over: Partial): RunConfig => ({ + id: "c", + name: "c", + kind: "shell", + command: "", + args: [], + cwd: ROOT, + env: {}, + detected: false, + isTest: false, + debugAdapter: null, + ...over, +}); + +describe("configSource", () => { + beforeEach(() => { + files.clear(); + useProject.setState({ project: { root: ROOT } as never }); + }); + + it("opens a JVM application's main class, preferring the configuration's module", async () => { + files.set(`${ROOT}/legacy/src/main/java/com/acme/App.java`, "package com.acme;\nclass App {}\n"); + files.set( + `${ROOT}/api/src/main/java/com/acme/App.java`, + "package com.acme;\n\n@SpringBootApplication\npublic class App {\n}\n", + ); + files.set(`${ROOT}/api/src/main/java/org/other/App.java`, "class App {}\n"); + const app = config({ kind: "spring-boot", module: "api", params: { mainClass: "com.acme.App" } }); + expect(await configSource(app)).toEqual({ path: `${ROOT}/api/src/main/java/com/acme/App.java`, line: 3 }); + }); + + it("opens a Kotlin file class at its main function", async () => { + files.set(`${ROOT}/src/main/kotlin/demo/Main.kt`, "package demo\n\nfun main() {}\n"); + const app = config({ kind: "application", params: { mainClass: "demo.MainKt" } }); + expect(await configSource(app)).toEqual({ path: `${ROOT}/src/main/kotlin/demo/Main.kt`, line: 2 }); + }); + + it("opens the script of an npm configuration in package.json", async () => { + files.set(`${ROOT}/web/package.json`, '{\n "scripts": {\n "build": "vite build",\n "dev": "vite"\n }\n}\n'); + const dev = config({ kind: "npm", params: { packageDir: "web", command: "run", script: "dev" } }); + expect(await configSource(dev)).toEqual({ path: `${ROOT}/web/package.json`, line: 3 }); + }); + + it("opens scripts and build files relative to the working directory", async () => { + files.set(`${ROOT}/tools/run.py`, "print(1)\n"); + files.set(`${ROOT}/svc/pom.xml`, "\n"); + files.set(`${ROOT}/build.gradle.kts`, "plugins {}\n"); + expect(await configSource(config({ kind: "python", params: { mode: "script", script: "tools/run.py" } }))).toEqual({ + path: `${ROOT}/tools/run.py`, + line: 0, + }); + expect(await configSource(config({ kind: "maven", params: { projectDir: "svc" } }))).toEqual({ + path: `${ROOT}/svc/pom.xml`, + line: 0, + }); + expect(await configSource(config({ kind: "gradle", params: { projectDir: "" } }))).toEqual({ + path: `${ROOT}/build.gradle.kts`, + line: 0, + }); + }); + + it("has nothing for configurations without a file, or whose file is gone", async () => { + expect(hasSource(config({ kind: "jar-application" }))).toBe(false); + expect(hasSource(config({ kind: "compound" }))).toBe(false); + expect(await configSource(config({ kind: "shell", params: { mode: "script", script: "echo hi" } }))).toBeNull(); + expect(await configSource(config({ kind: "application", params: { mainClass: "com.acme.Gone" } }))).toBeNull(); + }); +}); diff --git a/src/features/run/configSource.ts b/src/features/run/configSource.ts new file mode 100644 index 000000000..58a92b887 --- /dev/null +++ b/src/features/run/configSource.ts @@ -0,0 +1,159 @@ +/** + * Jump to Source for a run configuration: the file it runs, as IDEA's run configuration + * nodes navigate to their main class or script. + */ +import { call, commands, type RunConfig } from "@/platform/ipc"; +import { isJvmApplication, parseJavaArgs } from "@/platform/javaLaunch"; +import { useProject } from "@/platform/project"; +import { tx } from "@/platform/i18n"; +import { editorService, notifications } from "@/workbench/contributions"; +import { joinPath } from "./links"; +import { formParams, typeFor } from "./types"; + +export interface ConfigSource { + path: string; + /** 0-based. */ + line: number; +} + +/** Kinds whose configurations name a file of the project; others (a JAR, a compound) have none. */ +const SOURCE_KINDS = new Set([ + "application", + "spring-boot", + "python", + "pytest", + "ruby", + "shell", + "npm", + "bun", + "gradle", + "maven", + "go", + "go-test", + "dotnet", + "dotnet-test", +]); + +export function hasSource(config: RunConfig): boolean { + return SOURCE_KINDS.has(config.kind) || isJvmApplication(config); +} + +function params(config: RunConfig): Record { + return formParams(config) ?? typeFor(config.kind)?.paramsFrom?.(config) ?? config.params ?? {}; +} + +async function text(path: string): Promise { + return call(commands.fsReadText(path)).catch(() => null); +} + +/** 0-based line of the first match of `pattern` in `source`, else 0. */ +function lineOf(source: string, pattern: RegExp): number { + const m = pattern.exec(source); + return m ? source.slice(0, m.index).split("\n").length - 1 : 0; +} + +async function file(path: string | null, pattern?: RegExp): Promise { + if (!path) return null; + const source = await text(path); + if (source === null) return null; + return { path, line: pattern ? lineOf(source, pattern) : 0 }; +} + +async function firstFile(dir: string, names: string[], pattern?: RegExp): Promise { + for (const name of names) { + const found = await file(joinPath(dir, name), pattern); + if (found) return found; + } + return null; +} + +const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +/** The class's source among the project's files; a Kotlin file class `AppKt` is `App.kt`. */ +async function mainClassSource(mainClass: string, module: string): Promise { + const name = mainClass.trim(); + if (!name) return null; + const dot = name.lastIndexOf("."); + const pkg = dot < 0 ? "" : name.slice(0, dot).replaceAll(".", "/"); + const simple = name.slice(dot + 1).split("$")[0]!; + const fileClass = simple.endsWith("Kt") ? simple.slice(0, -2) : null; + const names = [`${simple}.java`, `${simple}.kt`, ...(fileClass ? [`${fileClass}.kt`] : [])]; + const found = (await Promise.all(names.map((n) => call(commands.findFilesNamed(n)).catch(() => [])))).flat(); + const suffix = (n: string) => (pkg ? `/${pkg}/${n}` : `/${n}`); + const matching = found.filter((p) => names.some((n) => p.replace(/\\/g, "/").endsWith(suffix(n)))); + // Several modules may declare the class: the configuration's module wins. + const inModule = module + ? matching.filter((p) => p.replace(/\\/g, "/").startsWith(`${module.replace(/\/+$/, "")}/`)) + : []; + const path = inModule[0] ?? matching[0]; + if (!path) return null; + const declaration = path.endsWith(`${fileClass}.kt`) + ? /^[ \t]*fun\s+main\b/m + : new RegExp(String.raw`\b(class|interface|enum|record|object)\s+${escape(simple)}\b`); + return file(path, declaration); +} + +/** The file `config` runs (main class, script, package.json script, build file), if any. */ +export async function configSource(config: RunConfig): Promise { + const root = useProject.getState().project?.root ?? ""; + const cwd = config.cwd ?? root; + const p = params(config); + const at = (path: string | undefined, base = cwd) => (path?.trim() ? joinPath(base, path.trim()) : null); + if (isJvmApplication(config)) { + const module = config.module ? joinPath(root, config.module) : ""; + return mainClassSource(p.mainClass || parseJavaArgs(config.args).mainClass || "", module); + } + switch (config.kind) { + case "python": + if (p.mode === "module" && p.module) { + const rel = p.module.replaceAll(".", "/"); + return firstFile(cwd, [`${rel}.py`, `${rel}/__main__.py`]); + } + return file(at(p.script)); + case "pytest": + return file(at(p.target?.split("::")[0])); + case "ruby": + return file(at(p.script)); + case "shell": + return p.mode === "file" ? file(at(p.path)) : null; + case "npm": + case "bun": { + const dir = at(p.packageDir) ?? cwd; + const script = p.script?.trim(); + return file(joinPath(dir, "package.json"), script ? new RegExp(`"${escape(script)}"\\s*:`) : undefined); + } + case "gradle": + return firstFile(at(p.projectDir) ?? cwd, [ + "build.gradle.kts", + "build.gradle", + "settings.gradle.kts", + "settings.gradle", + ]); + case "maven": + return firstFile(at(p.projectDir) ?? cwd, ["pom.xml"]); + case "go": + case "go-test": { + const target = at(p.target); + if (target && /\.go$/.test(target)) return file(target); + return firstFile(target ?? cwd, ["main.go"]); + } + case "dotnet": + case "dotnet-test": + return file(at(p.project)); + default: + return null; + } +} + +export async function jumpToConfigSource(config: RunConfig): Promise { + const source = await configSource(config); + if (!source) { + notifications().notify({ + group: "run", + level: "info", + title: tx`Cannot find the source of ${config.name}`, + }); + return; + } + await editorService().openFile(source.path, { selection: { line: source.line, col: 0 }, focus: true }); +} diff --git a/src/features/run/services.tsx b/src/features/run/services.tsx index 6c2485074..a098b9ad1 100644 --- a/src/features/run/services.tsx +++ b/src/features/run/services.tsx @@ -53,6 +53,7 @@ import { type ServiceSession, } from "./serviceSessions"; import { isDebugOnly } from "./types"; +import { hasSource, jumpToConfigSource } from "./configSource"; import { currentServiceOrder, moveServiceOrder, @@ -755,6 +756,13 @@ function menu(item: ServiceTreeItem): MenuItem[] { run: () => debuggerSession?.show(), }, { label: "Edit Configuration…", icon: "edit", run: () => void executeAction("run.editConfigs", config.id) }, + { + label: "Jump to Source", + icon: "external-link", + shortcut: "F4", + disabled: !hasSource(config), + run: () => void jumpToConfigSource(config), + }, { label: "Remove from Services", icon: "close", @@ -920,6 +928,10 @@ export const runServiceProvider: ServiceProviderContribution = { const r = resolve(item); if (r.config && !(r.session && liveServiceSession(r.session)) && !isDebugOnly(r.config)) run(r); }, + jumpToSource: (item) => { + const { config } = resolve(item); + if (config && hasSource(config)) void jumpToConfigSource(config); + }, detail: RunDetail, addMenu, reorder: { diff --git a/src/features/services/ServicesTree.test.tsx b/src/features/services/ServicesTree.test.tsx index c94b6e3f8..b11af1350 100644 --- a/src/features/services/ServicesTree.test.tsx +++ b/src/features/services/ServicesTree.test.tsx @@ -206,3 +206,19 @@ it("disables dialog entries for a multi-selection", () => { expect(one.disabled).toBeFalsy(); expect(many.disabled).toBe(true); }); + +it("F4 jumps to the source of a provider's node instead of activating it", () => { + const jump = vi.fn(); + const activate = vi.fn(); + const provider = useServiceProviders.getState().providers.get("test")!; + useServiceProviders.setState({ + providers: new Map([ + ["test", { ...provider, activate: (item) => activate(item.key), jumpToSource: (item) => jump(item.key) }], + ]), + }); + const { tree, row } = setup(); + fireEvent.mouseDown(row("two")); + fireEvent.keyDown(tree, { key: "F4" }); + expect(jump.mock.calls).toEqual([["two"]]); + expect(activate).not.toHaveBeenCalled(); +}); diff --git a/src/features/services/ServicesTree.tsx b/src/features/services/ServicesTree.tsx index d3891d861..090949910 100644 --- a/src/features/services/ServicesTree.tsx +++ b/src/features/services/ServicesTree.tsx @@ -259,6 +259,11 @@ export function ServicesTreeView() { const p = index.get(n.key); providers.find((x) => x.id === p?.provider)?.activate?.(n); }} + onJumpToSource={(n) => { + const p = providers.find((x) => x.id === index.get(n.key)?.provider); + if (p?.jumpToSource) p.jumpToSource(n); + else p?.activate?.(n); + }} onContextMenu={(n, keys, e) => { e.preventDefault(); if (!n) { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 6c4f7320f..6bd8d5a5a 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2923,5 +2923,6 @@ "Cursor": "Cursor", "Configure skills for this session": "Configure skills for this session", "No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.", - "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling." + "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.", + "Cannot find the source of {0}": "Cannot find the source of {0}" } diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 69c9c5d11..1ce16f919 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9249,5 +9249,6 @@ "Cursor": "Cursor", "Configure skills for this session": "為此工作階段設定技能", "No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "未在 .agents/skills、.openidea/skills、~/.agents/skills 或 Claude Code、GitHub Copilot、Codex 與 Cursor 的 CLI 資料夾中找到技能。", - "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "該 CLI 會自己發現這個資料夾:關閉只會讓 OpenIDEA 的 / 選單不再提供該技能,並且只在 CLI 支援停用時生效。" + "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "該 CLI 會自己發現這個資料夾:關閉只會讓 OpenIDEA 的 / 選單不再提供該技能,並且只在 CLI 支援停用時生效。", + "Cannot find the source of {0}": "找不到 {0} 的原始碼" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index a3c810b7d..0cbba3f7f 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9252,5 +9252,6 @@ "Cursor": "Cursor", "Configure skills for this session": "为此会话配置技能", "No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "未在 .agents/skills、.openidea/skills、~/.agents/skills 或 Claude Code、GitHub Copilot、Codex 与 Cursor 的 CLI 文件夹中找到技能。", - "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "该 CLI 会自己发现这个文件夹:关闭只会让 OpenIDEA 的 / 菜单不再提供该技能,并且只在 CLI 支持禁用时生效。" + "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "该 CLI 会自己发现这个文件夹:关闭只会让 OpenIDEA 的 / 菜单不再提供该技能,并且只在 CLI 支持禁用时生效。", + "Cannot find the source of {0}": "找不到 {0} 的源代码" } diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index 5e5e4e203..b819dff25 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -288,6 +288,8 @@ export interface ServiceProviderContribution { menu?(item: ServiceTreeItem): MenuItem[]; /** Double click / Enter. */ activate?(item: ServiceTreeItem): void; + /** Jump to Source (F4 / ⌘↓); a provider without it activates the node instead. */ + jumpToSource?(item: ServiceTreeItem): void; /** A node of this provider became the lead selection. */ select?(item: ServiceTreeItem): void; /** A node of this provider was expanded or collapsed. */