diff --git a/docs/en/guide/run.mdx b/docs/en/guide/run.mdx index f214cb389..fa64aca9b 100644 --- a/docs/en/guide/run.mdx +++ b/docs/en/guide/run.mdx @@ -112,7 +112,7 @@ The debugger adds attach-only types such as **Remote JVM Debug**, **Go Remote**, ### Common fields - **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Debugging is not available on run targets. See [SSH](/en/guide/remote/ssh). -- **Working directory**: relative to the project root; empty means the project root. +- **Working directory**: relative to the project root; empty means the project root. It may use the path macros `$PROJECT_DIR$`, `$ContentRoot$`, `$MODULE_DIR$`, `$MODULE_WORKING_DIR$` and `$USER_HOME$`, expanded when the configuration starts, so a shared configuration works on every machine. - **Environment variables**: `VAR=value` pairs separated by `;`. The list button opens the **Environment Variables** dialog, where **Include system environment variables** can be turned off. - **Debug adapter**: which debugger **Debug** uses for this configuration (for example `debugpy`, `js-debug`, `codelldb`, `delve`). diff --git a/docs/zh/guide/run.mdx b/docs/zh/guide/run.mdx index 123742294..08673a511 100644 --- a/docs/zh/guide/run.mdx +++ b/docs/zh/guide/run.mdx @@ -108,7 +108,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码, ### 通用字段 - **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上不支持调试。参见 [SSH](/zh/guide/remote/ssh)。 -- **工作目录**:相对于项目根目录,留空即项目根目录。 +- **工作目录**:相对于项目根目录,留空即项目根目录。可以使用路径宏 `$PROJECT_DIR$`、`$ContentRoot$`、`$MODULE_DIR$`、`$MODULE_WORKING_DIR$` 和 `$USER_HOME$`,在配置启动时展开,因此共享的配置在每台机器上都能用。 - **环境变量**:`VAR=value` 形式,用 `;` 分隔。点旁边的列表按钮打开“环境变量”对话框,可以关闭 **包括系统环境变量**。 - **调试适配器**:按“调试”时这个配置使用哪个调试器(如 `debugpy`、`js-debug`、`codelldb`、`delve`)。 diff --git a/src/features/run/cwdMacros.test.ts b/src/features/run/cwdMacros.test.ts new file mode 100644 index 000000000..53d5e5ce2 --- /dev/null +++ b/src/features/run/cwdMacros.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { expandCwd } from "./cwdMacros"; + +const ctx = { root: "/work/app/", module: "services/api", home: "/Users/me" }; + +describe("working directory macros (#4755)", () => { + it("expands the project, module and home folders", () => { + expect(expandCwd("$PROJECT_DIR$/web", ctx)).toEqual({ cwd: "/work/app/web" }); + expect(expandCwd("$ContentRoot$", ctx)).toEqual({ cwd: "/work/app" }); + expect(expandCwd("$MODULE_DIR$/bin", ctx)).toEqual({ cwd: "/work/app/services/api/bin" }); + expect(expandCwd("$MODULE_WORKING_DIR$", ctx)).toEqual({ cwd: "/work/app/services/api" }); + expect(expandCwd("$USER_HOME$/scratch", ctx)).toEqual({ cwd: "/Users/me/scratch" }); + }); + + it("uses the project folder as the module folder when there is no module", () => { + expect(expandCwd("$MODULE_DIR$", { ...ctx, module: null })).toEqual({ cwd: "/work/app" }); + expect(expandCwd("$MODULE_DIR$", { ...ctx, module: "/elsewhere/mod" })).toEqual({ cwd: "/elsewhere/mod" }); + }); + + it("leaves a path without macros as it is", () => { + expect(expandCwd("server", ctx)).toEqual({ cwd: "server" }); + expect(expandCwd("/abs/$dollar", ctx)).toEqual({ cwd: "/abs/$dollar" }); + }); + + it("names an unknown macro and one without a value", () => { + const unknown = expandCwd("$PROJECT_ROOT$/web", ctx); + expect("error" in unknown && unknown.error).toContain("$PROJECT_ROOT$"); + expect("error" in unknown && unknown.error).toContain("$PROJECT_DIR$"); + const remote = expandCwd("$USER_HOME$", { ...ctx, home: null }); + expect(remote).toEqual({ error: "$USER_HOME$ is not available in a remote project." }); + }); +}); diff --git a/src/features/run/cwdMacros.ts b/src/features/run/cwdMacros.ts new file mode 100644 index 000000000..f6569ab71 --- /dev/null +++ b/src/features/run/cwdMacros.ts @@ -0,0 +1,80 @@ +/** + * Path macros in a run configuration's working directory (`$PROJECT_DIR$/web`), expanded when + * it runs or is debugged; the stored value keeps them, so the configuration moves with the project. + */ +import { tx } from "@/platform/i18n"; +import { isTauri, type RunConfig } from "@/platform/ipc"; +import { isRemoteWindow } from "@/platform/remote"; +import { useProject } from "@/platform/project"; +import { notifications } from "@/workbench/contributions"; + +const MACRO = /\$([A-Za-z_][A-Za-z0-9_]*)\$/g; + +/** The macros a working directory may use. */ +export const CWD_MACROS = ["PROJECT_DIR", "ContentRoot", "MODULE_DIR", "MODULE_WORKING_DIR", "USER_HOME"] as const; + +export interface CwdContext { + root: string; + /** The configuration's module directory, absolute or relative to `root`. */ + module?: string | null; + /** The user's home folder; null where it isn't known (a remote project). */ + home: string | null; +} + +const absolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\"); +const trimEnd = (p: string) => p.replace(/[\\/]+$/, ""); +const join = (root: string, p: string) => (absolute(p) ? p : `${trimEnd(root)}/${p.replace(/^\.[\\/]/, "")}`); + +/** `cwd` with its macros replaced; an error names a macro that is unknown or has no value here. */ +export function expandCwd(cwd: string, ctx: CwdContext): { cwd: string } | { error: string } { + let error: string | null = null; + const module = ctx.module ? join(ctx.root, ctx.module) : ctx.root; + const values: Record = { + PROJECT_DIR: ctx.root, + ContentRoot: ctx.root, + MODULE_DIR: module, + MODULE_WORKING_DIR: module, + USER_HOME: ctx.home, + }; + const out = cwd.replace(MACRO, (all, name: string) => { + const value = Object.hasOwn(values, name) ? values[name] : undefined; + if (value) return trimEnd(value); + const supported = CWD_MACROS.map((m) => `$${m}$`).join(", "); + error ??= + value === undefined + ? tx`Unknown macro ${all} in the working directory. Supported: ${supported}.` + : tx`${all} is not available in a remote project.`; + return all; + }); + return error ? { error } : { cwd: out }; +} + +let home: Promise | null = null; +const homeDir = () => + (home ??= isTauri() + ? import("@tauri-apps/api/path").then((m) => m.homeDir()).catch(() => null) + : Promise.resolve(null)); + +/** `config` with the macros of its working directory expanded; throws when one can't be. */ +export async function withExpandedCwd(config: RunConfig): Promise { + const cwd = config.cwd; + if (!cwd?.includes("$")) return config; + const root = useProject.getState().project?.root; + if (!root) return config; + const result = expandCwd(cwd, { + root, + module: config.module, + home: isRemoteWindow() ? null : await homeDir(), + }); + if ("error" in result) throw new Error(result.error); + return { ...config, cwd: result.cwd }; +} + +export function notifyCwdError(config: RunConfig, error: unknown) { + notifications().notify({ + group: "run", + level: "error", + title: tx`Cannot start '${config.name}'`, + body: error instanceof Error ? error.message : String(error), + }); +} diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 56fcac0bb..7e54d82af 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -37,6 +37,7 @@ import { runContextAction, } from "./contextRun"; import { runWithExecutor } from "./executors"; +import { notifyCwdError, withExpandedCwd } from "./cwdMacros"; import { debugWithAgent, jdwpLaunch } from "./javaDebug"; import { attachesToChild, debugAttachingToChild } from "./pluginAttach"; import { RunDialogsOverlay } from "./dialogs"; @@ -184,6 +185,11 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho } async function debugLaunch(config: RunConfig, chain: readonly string[], show?: boolean): Promise { + try { + config = await withExpandedCwd(config); + } catch (e) { + return notifyCwdError(config, e); + } if (!(await prepareLaunch(config, chain, show))) return; if (config.kind === UNITY_CONFIG_KIND) return showUnityAttach(config); // Python on a Docker / Compose target: debugpy in the container, the debugger attaches. diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 627e58990..a55e6572d 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -4,6 +4,7 @@ * per-session `ConsoleModel`, batched per animation frame. */ import { withRunTarget } from "@/platform/runTargetSelection"; +import { notifyCwdError, withExpandedCwd } from "./cwdMacros"; import { create } from "zustand"; import { Channel } from "@tauri-apps/api/core"; import { @@ -847,6 +848,12 @@ async function startRunIn( options: StartRunOptions, ): Promise { config = withRunTarget(config); + try { + config = await withExpandedCwd(config); + } catch (e) { + notifyCwdError(config, e); + return null; + } if (!options.launch && isCMakeBuild(config)) { await buildCMake(config.id, options.show !== false); return null; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7f0c55aae..279848daf 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -910,7 +910,6 @@ "devcontainer up exited with {status}": "devcontainer up exited with {status}", "Select an item to view details": "Select an item to view details", "Select files in the Project view, Commit tool window, or open a file in the editor": "Select files in the Project view, Commit tool window, or open a file in the editor", - "Nothing to show": "Nothing to show", "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory": "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory", "Invalid log stream configuration": "Invalid log stream configuration", @@ -2801,5 +2800,8 @@ "Cannot download to {folder}": "Cannot download to {folder}", "Copy the selected files and folders of a remote project to a folder on this computer": "Copy the selected files and folders of a remote project to a folder on this computer", "{modifier}+Click to only see \"{name}\"": "{modifier}+Click to only see \"{name}\"", - "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C)." + "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).", + "Unknown macro {all} in the working directory. Supported: {supported}.": "Unknown macro {all} in the working directory. Supported: {supported}.", + "{all} is not available in a remote project.": "{all} is not available in a remote project.", + "Cannot start '{name}'": "Cannot start '{name}'" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index c80016ff8..831b2681b 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -5285,7 +5285,6 @@ "Configuration…": "配置…", "No deployment server configured": "未配置部署服务器", "Select files in the Project view, Commit tool window, or open a file in the editor": "请在项目视图或提交工具窗口中选择文件,或在编辑器中打开文件", - "Upload to": "上传到", "Download from": "下载自", "Sync with Deployed to": "与已部署的同步", @@ -9160,5 +9159,8 @@ "Cannot download to {folder}": "无法下载到 {folder}", "Copy the selected files and folders of a remote project to a folder on this computer": "把远程项目中选中的文件和文件夹复制到本机的文件夹", "{modifier}+Click to only see \"{name}\"": "{modifier}+点击仅显示“{name}”", - "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。" + "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。", + "Unknown macro {all} in the working directory. Supported: {supported}.": "工作目录中有未知的宏 {all}。支持:{supported}。", + "{all} is not available in a remote project.": "{all} 在远程项目中不可用。", + "Cannot start '{name}'": "无法启动“{name}”" }