diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs index 1d3f1e75a8..65eeca5483 100644 --- a/crates/ide-host/src/menu.rs +++ b/crates/ide-host/src/menu.rs @@ -173,6 +173,21 @@ pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools"; pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild"; /// Id (and `menu.` label key) of the Build › Flutter submenu. pub const FLUTTER_BUILD_MENU: &str = "build.flutter"; +/// Build › Xcode: Clean Build Folder and Delete DerivedData, filled only when the project has +/// Xcode schemes. A submenu after Build › Flutter when it has items, like it. +pub const DYNAMIC_XCODE_BUILD: &str = "xcodeBuild"; +/// Id (and `menu.` label key) of the Build › Xcode submenu. +pub const XCODE_BUILD_MENU: &str = "build.xcode"; + +/// The submenu (id, English label) a dynamic slot is shown as when it has items, followed by a +/// separator; `None`: its items are listed in place. +pub fn dynamic_submenu(slot: &str) -> Option<(&'static str, &'static str)> { + match slot { + DYNAMIC_FLUTTER_BUILD => Some((FLUTTER_BUILD_MENU, "Flutter")), + DYNAMIC_XCODE_BUILD => Some((XCODE_BUILD_MENU, "Xcode")), + _ => None, + } +} /// The menu bar for `os`. Labels are English defaults; the frontend replaces /// them with `menu.` strings from the active locale catalog. @@ -622,6 +637,7 @@ pub fn spec(os: Os) -> Vec { "Build", vec![ Entry::Dynamic(DYNAMIC_FLUTTER_BUILD), + Entry::Dynamic(DYNAMIC_XCODE_BUILD), act("build.buildProject", "Build Project"), act("build.buildModule", "Build Module"), act("build.compileFile", "Recompile"), @@ -1298,12 +1314,12 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec< } })); } - Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => { - let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD); + Entry::Dynamic(slot) if let Some((id, label)) = dynamic_submenu(slot) => { + let items = config.dynamic_items(slot); if !items.is_empty() { out.push(MenuNode::Submenu { - id: FLUTTER_BUILD_MENU.into(), - label: "Flutter".into(), + id: id.into(), + label: label.into(), current: None, children: items.iter().map(DynamicItem::model).collect(), }); diff --git a/crates/ide-host/src/ops/mod.rs b/crates/ide-host/src/ops/mod.rs index 41e0e17d20..40d6fc489c 100644 --- a/crates/ide-host/src/ops/mod.rs +++ b/crates/ide-host/src/ops/mod.rs @@ -52,6 +52,7 @@ pub mod tools; pub mod vcs; pub mod web; pub mod xcode_bsp; +pub mod xcode_clean; pub mod xcode_files; use crate::Host; @@ -141,6 +142,7 @@ ide_command::domains!( vcs_commands: crate::ops::vcs::commands, web: crate::ops::web, xcode_bsp: crate::ops::xcode_bsp, + xcode_clean: crate::ops::xcode_clean, xcode_files: crate::ops::xcode_files, ); diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 72c3807733..0be8084f34 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -552,6 +552,15 @@ async fn start_inner( }) .await?; } + if config.kind == ide_run::xcode_clean::KIND { + let cache = project.cache_dir.clone(); + config = host + .blocking(move || { + ide_run::xcode_clean::prepare(&cache, &mut config)?; + Ok(config) + }) + .await?; + } if config.kind == "go" && config.extras.params.get("scope").is_some_and(|s| s == "file") { let root = project.root.clone(); config = host diff --git a/crates/ide-host/src/ops/xcode_clean.rs b/crates/ide-host/src/ops/xcode_clean.rs new file mode 100644 index 0000000000..ec019dfe3a --- /dev/null +++ b/crates/ide-host/src/ops/xcode_clean.rs @@ -0,0 +1,52 @@ +//! Deleting an Xcode project's DerivedData (#6665 C6). Clean Build Folder is a run of +//! `ide_run::xcode_clean::KIND`; this is the part a run can't do: moving folders to the Trash. +use crate::Host; +use ide_command::command; +use ide_core::IdeResult; +use std::collections::BTreeMap; +use std::path::PathBuf; + +async fn dirs( + host: &Host, + window: &str, + cwd: Option, + params: BTreeMap, +) -> IdeResult> { + let project = host.project(window)?; + let dir = project.root.join(cwd.unwrap_or_default()); + let cache = project.cache_dir.clone(); + super::blocking(move || ide_run::xcode_clean::derived_data_dirs(&dir, &cache, ¶ms)).await +} + +/// The DerivedData folders [`xcode_delete_derived_data`] would delete for an `xcode` +/// configuration (its `cwd` and `params`), for the user to confirm. +#[command(trust = trusted)] +pub async fn xcode_derived_data( + host: &Host, + window: &str, + cwd: Option, + params: BTreeMap, +) -> IdeResult> { + Ok(dirs(host, window, cwd, params).await?.iter().map(|d| d.to_string_lossy().into_owned()).collect()) +} + +/// Moves the configuration's DerivedData folders to the Trash, then restarts sourcekit-lsp: a +/// build server config (xcode-build-server's `build_root`) reads build logs and the index there. +#[command(trust = trusted)] +pub async fn xcode_delete_derived_data( + host: &Host, + window: &str, + cwd: Option, + params: BTreeMap, +) -> IdeResult> { + let found = dirs(host, window, cwd, params).await?; + let deleted = found.clone(); + super::blocking(move || found.iter().try_for_each(|d| ide_vfs::delete(d))).await?; + let project = host.project(window)?; + for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") { + project.lsp.restart(server.id).await?; + } + Ok(deleted.iter().map(|d| d.to_string_lossy().into_owned()).collect()) +} + +ide_command::domain!(xcode_clean: xcode_derived_data, xcode_delete_derived_data); diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index 1e5b144571..109b92eb5c 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -23,6 +23,7 @@ pub mod tomcat; mod utf8; pub mod wrap; pub mod xcode; +pub mod xcode_clean; pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake}; pub use process::{DetachedProcessKills, ProcessManager, StartOptions}; diff --git a/crates/ide-run/src/xcode.rs b/crates/ide-run/src/xcode.rs index db9de66679..843c7b4719 100644 --- a/crates/ide-run/src/xcode.rs +++ b/crates/ide-run/src/xcode.rs @@ -335,7 +335,7 @@ pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> I Some(udid) => udid.to_owned(), None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?, }; - let derived_data = cache_dir.join("xcode/DerivedData"); + let derived_data = crate::xcode_clean::ide_derived_data(cache_dir); let args = build_args(params, &udid, &derived_data).map_err(IdeError::invalid)?; let settings = output("xcodebuild", &[args.as_slice(), &["-showBuildSettings".into(), "-json".into()]].concat())?; let (app, bundle_id) = built_app(&settings).map_err(IdeError::invalid)?; diff --git a/crates/ide-run/src/xcode_clean.rs b/crates/ide-run/src/xcode_clean.rs new file mode 100644 index 0000000000..8b6c282875 --- /dev/null +++ b/crates/ide-run/src/xcode_clean.rs @@ -0,0 +1,139 @@ +//! Product › Clean Build Folder and deleting a project's DerivedData, for the `kind = "xcode"` +//! configurations of `crate::detect::xcode`. +use crate::xcode::{SIMULATOR_PARAM, build_args, default_simulator}; +use ide_core::{IdeError, IdeResult}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// The configuration kind of a Clean Build Folder run; its params are an `xcode` configuration's. +pub const KIND: &str = "xcode-clean"; + +/// Where the IDE's runs of a project build: `xcodebuild -derivedDataPath`, under the project's cache. +pub fn ide_derived_data(cache_dir: &Path) -> PathBuf { + cache_dir.join("xcode/DerivedData") +} + +/// Turns a [`KIND`] configuration into `xcodebuild clean` of the build its `xcode` configuration +/// runs: the same container, scheme, configuration, simulator and DerivedData. +pub fn prepare(cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> { + let params = &config.extras.params; + let udid = match params.get(SIMULATOR_PARAM).map(|s| s.trim()).filter(|s| !s.is_empty()) { + Some(udid) => udid.to_owned(), + None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?, + }; + config.args = clean_args(params, &udid, &ide_derived_data(cache_dir)).map_err(IdeError::invalid)?; + config.command = "xcodebuild".into(); + Ok(()) +} + +fn clean_args(params: &BTreeMap, udid: &str, derived_data: &Path) -> Result, String> { + let mut args = build_args(params, udid, derived_data)?; + args.push("clean".into()); + Ok(args) +} + +/// `xcodebuild -showBuildSettings -json` of the scheme as Xcode builds it: no destination and no +/// `-derivedDataPath`, so the build folder is the one in Xcode's DerivedData location. +fn settings_args(params: &BTreeMap) -> Result, String> { + let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty()); + let container = param("container").ok_or("No Xcode project or workspace is set")?; + let scheme = param("scheme").ok_or("No scheme is set")?; + let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" }; + let mut args = vec![flag.to_owned(), container.to_owned(), "-scheme".to_owned(), scheme.to_owned()]; + if let Some(configuration) = param("configuration") { + args.extend(["-configuration".to_owned(), configuration.to_owned()]); + } + args.extend(["-showBuildSettings".to_owned(), "-json".to_owned()]); + Ok(args) +} + +/// The project's `-` folder in Xcode's DerivedData: the ancestor of the build +/// settings' `BUILD_DIR` (else `OBJROOT`) that sits directly in a `DerivedData` folder. `None` +/// when the build folder is elsewhere (a custom DerivedData location or a legacy `build/`). +pub fn derived_data_of(settings: &str) -> Option { + let json: serde_json::Value = serde_json::from_str(settings).ok()?; + let build = json.as_array()?.iter().find_map(|t| { + let s = &t["buildSettings"]; + s["BUILD_DIR"].as_str().or(s["OBJROOT"].as_str()).filter(|v| !v.is_empty()) + })?; + Path::new(build) + .ancestors() + .find(|dir| dir.parent().and_then(Path::file_name).is_some_and(|name| name == "DerivedData")) + .map(Path::to_path_buf) +} + +/// The existing DerivedData folders of an `xcode` configuration's project: Xcode's +/// `-` one (Xcode's own builds and the scheme's tests) and the IDE's runs' one. +/// `dir` is the configuration's working directory. +pub fn derived_data_dirs(dir: &Path, cache_dir: &Path, params: &BTreeMap) -> IdeResult> { + let args = settings_args(params).map_err(IdeError::invalid)?; + let mut cmd = std::process::Command::new("xcodebuild"); + cmd.args(&args).current_dir(dir); + let out = ide_core::process::prepare(&mut cmd) + .output() + .map_err(|e| IdeError::unavailable(format!("Cannot run xcodebuild: {e}")))?; + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr); + return Err(IdeError::invalid(format!("xcodebuild {} failed:\n{}", args.join(" "), err.trim()))); + } + let xcode = derived_data_of(&String::from_utf8_lossy(&out.stdout)); + Ok(xcode.into_iter().chain([ide_derived_data(cache_dir)]).filter(|d| d.is_dir()).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn params(pairs: &[(&str, &str)]) -> BTreeMap { + pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() + } + + #[test] + fn clean_cleans_the_build_a_run_makes() { + let p = params(&[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Debug")]); + assert_eq!( + clean_args(&p, "UDID", Path::new("/cache/xcode/DerivedData")).unwrap(), + [ + "-workspace", + "App.xcworkspace", + "-scheme", + "App", + "-configuration", + "Debug", + "-destination", + "id=UDID", + "-derivedDataPath", + "/cache/xcode/DerivedData", + "clean" + ] + ); + assert_eq!(ide_derived_data(Path::new("/cache")), Path::new("/cache/xcode/DerivedData")); + } + + #[test] + fn build_settings_are_read_where_xcode_builds() { + let p = params(&[("container", "App.xcodeproj"), ("scheme", "App")]); + assert_eq!( + settings_args(&p).unwrap(), + ["-project", "App.xcodeproj", "-scheme", "App", "-showBuildSettings", "-json"] + ); + assert!(settings_args(¶ms(&[("container", "App.xcodeproj")])).is_err()); + } + + #[test] + fn derived_data_is_the_folder_in_derived_data_that_holds_the_build() { + let settings = |key: &str, dir: &str| format!(r#"[{{"target":"App","buildSettings":{{"{key}":"{dir}"}}}}]"#); + let dd = "/Users/me/Library/Developer/Xcode/DerivedData/App-abcdef"; + assert_eq!(derived_data_of(&settings("BUILD_DIR", &format!("{dd}/Build/Products"))), Some(dd.into())); + assert_eq!( + derived_data_of(&settings("OBJROOT", &format!("{dd}/Build/Intermediates.noindex"))), + Some(dd.into()) + ); + // A custom location or a legacy build folder: nothing to delete. + assert_eq!(derived_data_of(&settings("BUILD_DIR", "/Volumes/Builds/App-abcdef/Build/Products")), None); + assert_eq!(derived_data_of(&settings("BUILD_DIR", "/src/App/build")), None); + // The DerivedData folder itself is never the answer. + assert_eq!(derived_data_of(&settings("BUILD_DIR", "/x/DerivedData")), None); + assert_eq!(derived_data_of("not json"), None); + } +} diff --git a/docs/en/languages/swift.mdx b/docs/en/languages/swift.mdx index e2a69b96ac..f6338403bf 100644 --- a/docs/en/languages/swift.mdx +++ b/docs/en/languages/swift.mdx @@ -57,6 +57,8 @@ Open the folder that contains `buildServer.json` (or `.bsp/`) as the project, or `buildServer.json` holds absolute paths for your machine. Add it to `.gitignore` instead of committing it. +**Clean Build Folder** (**Build › Xcode**, Find Action, or right-click the `.xcodeproj` / `.xcworkspace`) runs `xcodebuild clean` for the selected Xcode scheme in the Run tool window, with the same flags a run uses. **Delete DerivedData** moves this project's DerivedData folder (the one `xcodebuild -showBuildSettings` reports, plus the IDE's own run builds) to the Trash after asking, then restarts sourcekit-lsp. Other projects' DerivedData is left alone. + ### New files in Xcode projects `xcodebuild` compiles only the files a target lists, and the IDE does not edit `project.pbxproj`. What happens to a source file you create, rename or delete depends on how the project lists its files: diff --git a/docs/zh/languages/swift.mdx b/docs/zh/languages/swift.mdx index 1c6e9e7310..8e706cdec7 100644 --- a/docs/zh/languages/swift.mdx +++ b/docs/zh/languages/swift.mdx @@ -57,6 +57,8 @@ sourcekit-lsp 读不了 `.xcodeproj` 和 `.xcworkspace`。没有构建服务器 `buildServer.json` 里是本机的绝对路径。把它加入 `.gitignore`,不要提交。 +**清理构建文件夹**(**构建 › Xcode**、Find Action,或在 `.xcodeproj` / `.xcworkspace` 上右键)会在 Run 工具窗口中对所选 Xcode scheme 运行 `xcodebuild clean`,参数与运行时相同。**删除 DerivedData** 会先询问,再把本项目的 DerivedData 文件夹(`xcodebuild -showBuildSettings` 报告的那个,以及 IDE 自己运行时的构建)移到废纸篓,然后重启 sourcekit-lsp。其他项目的 DerivedData 不受影响。 + ### Xcode 项目中的新文件 `xcodebuild` 只编译 target 中列出的文件,而 IDE 不会修改 `project.pbxproj`。新建、重命名或删除的源文件会怎样,取决于项目如何列出文件: diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 7eb8ea8ba5..6b776ff7d2 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -230,12 +230,12 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) - } })); } - Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => { - let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD); + Entry::Dynamic(slot) if let Some((id, label)) = dynamic_submenu(slot) => { + let items = config.dynamic_items(slot); if !items.is_empty() { out.push(RenderedItem::Submenu { - id: FLUTTER_BUILD_MENU.into(), - title: config.label(FLUTTER_BUILD_MENU, "Flutter"), + id: id.into(), + title: config.label(id, label), current: false, items: items.iter().map(|item| render_dynamic(item, config)).collect(), }); @@ -1402,6 +1402,7 @@ mod tests { DYNAMIC_TOOL_WINDOWS, DYNAMIC_STATUS_BAR_WIDGETS, DYNAMIC_FLUTTER_BUILD, + DYNAMIC_XCODE_BUILD, DYNAMIC_PLUGIN_TOOLS, DYNAMIC_LAYOUTS ], @@ -1595,6 +1596,30 @@ mod tests { ); } + #[test] + fn xcode_build_submenu_follows_flutter_when_filled() { + let mut config = MenuConfig::default(); + config.dynamic.insert( + DYNAMIC_XCODE_BUILD.into(), + vec![ + dynamic_item("xcode.cleanBuildFolder", None, "Clean Build Folder"), + dynamic_item("xcode.deleteDerivedData", None, "Delete DerivedData"), + ], + ); + config.dynamic.insert(DYNAMIC_FLUTTER_BUILD.into(), vec![dynamic_item("flutter.build.ios", None, "Build iOS")]); + let build = render_bar(&spec(Os::Mac), &config, &[]).into_iter().find(|m| m.id == "build").unwrap().items; + let ids: Vec<_> = build + .iter() + .take(4) + .map(|i| match i { + RenderedItem::Submenu { id, title, items, .. } => format!("{id}:{title}:{}", items.len()), + RenderedItem::Separator => "-".into(), + _ => "?".into(), + }) + .collect(); + assert_eq!(ids, ["build.flutter:Flutter:1", "-", "build.xcode:Xcode:2", "-"]); + } + #[test] fn build_menu_lists_recompile_and_patches_its_label() { for os in ALL_OS { diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index a6008b494c..64ec132b17 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -965,4 +965,6 @@ wsl_distros always desktop bin wsl_resolve always desktop bindings sync xcode_bsp_generate trusted project_host bindings async xcode_bsp_setup trusted project_host bindings sync +xcode_delete_derived_data trusted project_host bindings async +xcode_derived_data trusted project_host bindings async xcode_file_sync trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 9e187730c0..6324330b56 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2798,6 +2798,16 @@ export const commands = { /** The generator found on `PATH`; `None`: neither is installed. */ tool: string | null, } | null, IdeError>(__TAURI_INVOKE("xcode_bsp_setup")), + /** + * Moves the configuration's DerivedData folders to the Trash, then restarts sourcekit-lsp: a + * build server config (xcode-build-server's `build_root`) reads build logs and the index there. + */ + xcodeDeleteDerivedData: (cwd: string | null, params: { [key in string]: string }) => typedError(__TAURI_INVOKE("xcode_delete_derived_data", { cwd, params })), + /** + * The DerivedData folders [`xcode_delete_derived_data`] would delete for an `xcode` + * configuration (its `cwd` and `params`), for the user to confirm. + */ + xcodeDerivedData: (cwd: string | null, params: { [key in string]: string }) => typedError(__TAURI_INVOKE("xcode_derived_data", { cwd, params })), /** * What source files created, renamed or deleted in the project need in their Xcode project; * `None` when they are in none, or it picks them up itself. diff --git a/src/features/run/index.ts b/src/features/run/index.ts index aa053d41bf..be789e00c0 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -87,6 +87,7 @@ import { } from "./applicationUpdate"; import { hotReload, hotReloadSession, hotRestart, syncFlutterRunApps } from "./flutterHotReload"; import { registerFlutterBuildActions } from "./flutterBuild"; +import { registerXcodeCleanActions } from "./xcodeClean"; import { npmGutter } from "./npmGutter"; import { launchSettingsGutter } from "./launchSettingsGutter"; import { runGutter } from "./runGutter"; @@ -485,6 +486,7 @@ export function activate(): () => void { registerGoActions(), registerSwiftPackageActions(), registerFlutterBuildActions(), + registerXcodeCleanActions(), registerRunTabActions(), registerComposerInstall(), registerNpmInstall(), diff --git a/src/features/run/xcodeClean.test.ts b/src/features/run/xcodeClean.test.ts new file mode 100644 index 0000000000..b258f1f387 --- /dev/null +++ b/src/features/run/xcodeClean.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; +import { useMenuSlotItems } from "@/workbench/contributions"; +import { useRun } from "./store"; +import { cleanConfig, registerXcodeCleanActions, xcodeConfigFor } from "./xcodeClean"; + +const config = (id: string, kind: string, container: string, scheme = id): RunConfig => ({ + id, + name: scheme, + kind, + command: "xcodebuild", + args: ["-project", container, "-scheme", scheme], + cwd: null, + env: { A: "1" }, + params: { container, scheme, configuration: "Debug" }, + detected: true, + isTest: false, + debugAdapter: null, +}); + +describe("xcode clean", () => { + const configs = [ + config("node", "node", ""), + config("a", "xcode", "App.xcodeproj"), + config("b", "xcode", "App.xcodeproj"), + config("w", "xcode", "Other.xcworkspace"), + ]; + + it("acts on the selected Xcode configuration, else the first", () => { + expect(xcodeConfigFor(configs, "b")?.id).toBe("b"); + expect(xcodeConfigFor(configs, "node")?.id).toBe("a"); + expect(xcodeConfigFor([configs[0]!], "node")).toBeNull(); + }); + + it("acts on a scheme of the right-clicked container", () => { + expect(xcodeConfigFor(configs, "b", "/p/Other.xcworkspace")?.id).toBe("w"); + expect(xcodeConfigFor(configs, "w", "/p/App.xcodeproj/")?.id).toBe("a"); + expect(xcodeConfigFor(configs, "a", "/p/Missing.xcodeproj")).toBeNull(); + }); + + it("cleans with the configuration's params on the chosen simulator", () => { + const clean = cleanConfig(configs[1]!, "UDID"); + expect(clean).toMatchObject({ + id: "xcode:clean:App.xcodeproj:a", + kind: "xcode-clean", + args: [], + env: {}, + params: { container: "App.xcodeproj", scheme: "a", configuration: "Debug", simulator: "UDID" }, + }); + }); + + it("lists Build › Xcode only while the project has an Xcode configuration", () => { + const listed = () => (useMenuSlotItems.getState().slots.xcodeBuild ?? []).map((i) => i.label); + useRun.setState({ configs: [configs[0]!] }); + const dispose = registerXcodeCleanActions(); + expect(listed()).toEqual([]); + useRun.setState({ configs }); + expect(listed()).toEqual(["Clean Build Folder", "Delete DerivedData"]); + useRun.setState({ configs: [configs[0]!] }); + expect(listed()).toEqual([]); + useRun.setState({ configs }); + dispose(); + expect(listed()).toEqual([]); + }); +}); diff --git a/src/features/run/xcodeClean.ts b/src/features/run/xcodeClean.ts new file mode 100644 index 0000000000..bce2bc07ab --- /dev/null +++ b/src/features/run/xcodeClean.ts @@ -0,0 +1,156 @@ +/** + * Xcode's Product › Clean Build Folder and deleting the project's DerivedData (#6665 C6), for the + * selected `xcode` configuration (else the first one), or the right-clicked `.xcodeproj` / + * `.xcworkspace`; in Build › Xcode, Find Action and the Project view's context menu. Clean runs + * `xcodebuild clean` in the Run tool window with the build flags a run uses (host: + * `ide_run::xcode_clean`); Delete DerivedData asks first, then moves Xcode's `-` + * folder and the IDE's run builds to the Trash. + */ +import { registerActions } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { call, commands, type RunConfig } from "@/platform/ipc"; +import { notifications, registerMenuGroup, registerMenuSlotItem } from "@/workbench/contributions"; +import { iosSimulatorFor } from "@/workbench/iosSimulators"; +import { confirm } from "@/workbench/messages"; +import { startRun, useRun } from "./store"; + +const CLEAN = "xcode.cleanBuildFolder"; +const DERIVED_DATA = "xcode.deleteDerivedData"; + +const baseName = (path: string) => path.replace(/\/+$/, "").split("/").pop() ?? ""; + +/** The `xcode` configuration to act on: of the right-clicked container (`arg`), else the selected one, else the first. */ +export function xcodeConfigFor( + configs: readonly RunConfig[], + selectedId: string | null, + arg?: unknown, +): RunConfig | null { + const container = typeof arg === "string" ? baseName(arg) : null; + const xcode = configs.filter( + (c) => c.kind === "xcode" && (!container || baseName(c.params?.container ?? "") === container), + ); + return xcode.find((c) => c.id === selectedId) ?? xcode[0] ?? null; +} + +function target(arg?: unknown): RunConfig | null { + const { configs, selectedId } = useRun.getState(); + return xcodeConfigFor(configs, selectedId, arg); +} + +/** The transient `xcode-clean` run of `config`: its scheme and build flags, on the toolbar's simulator. */ +export function cleanConfig(config: RunConfig, simulator: string | null): RunConfig { + return { + ...config, + id: `xcode:clean:${config.params?.container ?? ""}:${config.params?.scheme ?? ""}`, + name: tx`Clean ${config.name}`, + kind: "xcode-clean", + // The host fills in `xcodebuild … clean`. + args: [], + env: {}, + params: { ...config.params, simulator: simulator ?? "" }, + isTest: false, + debugAdapter: null, + }; +} + +async function cleanBuildFolder(arg?: unknown) { + const config = target(arg); + if (!config) return; + const clean = cleanConfig(config, iosSimulatorFor(config)); + const [applied] = await call(commands.runApplySettings([clean])); + await startRun(applied ?? clean); +} + +function notify(level: "info" | "error", title: string, body?: string) { + notifications().notify({ group: "run", level, key: DERIVED_DATA, title, body }); +} + +async function deleteDerivedData(arg?: unknown) { + const config = target(arg); + if (!config) return; + const at = { cwd: config.cwd ?? null, params: config.params ?? {} }; + try { + const dirs = await call(commands.xcodeDerivedData(at.cwd, at.params)); + if (!dirs.length) return notify("info", tx`No DerivedData to delete`); + const ok = await confirm({ + title: tx`Delete DerivedData`, + message: `${tx`Move the DerivedData of ${config.params?.container ?? config.name} to the Trash? The next build starts from scratch.`}\n\n${dirs.join("\n")}`, + ok: tx`Move to Trash`, + icon: "warning", + }); + if (!ok) return; + const deleted = await call(commands.xcodeDeleteDerivedData(at.cwd, at.params)); + notify("info", tx`DerivedData moved to the Trash`, deleted.join("\n")); + } catch (e) { + notify("error", tx`Could not delete DerivedData`, e instanceof Error ? e.message : String(e)); + } +} + +/** The native Build menu's Xcode submenu (`ide_host::menu::DYNAMIC_XCODE_BUILD`). */ +const XCODE_BUILD_SLOT = "xcodeBuild"; + +/** Lists the actions in Build › Xcode while the project has an `xcode` configuration. */ +function syncBuildMenu(): () => void { + let inMenu: (() => void)[] = []; + const sync = () => { + const xcode = !!target(); + if (xcode === inMenu.length > 0) return; + inMenu.forEach((d) => d()); + inMenu = xcode + ? [ + registerMenuSlotItem(XCODE_BUILD_SLOT, { action: CLEAN, label: "Clean Build Folder" }), + registerMenuSlotItem(XCODE_BUILD_SLOT, { action: DERIVED_DATA, label: "Delete DerivedData" }), + ] + : []; + }; + sync(); + const off = useRun.subscribe((s, old) => { + if (s.configs !== old.configs) sync(); + }); + return () => { + off(); + inMenu.forEach((d) => d()); + }; +} + +const isContainer = (path: string) => /\.(xcodeproj|xcworkspace)\/?$/.test(path); + +export function registerXcodeCleanActions(): () => void { + const disposers = [ + syncBuildMenu(), + registerActions([ + { + id: CLEAN, + title: "Clean Build Folder", + category: "Build", + keywords: ["xcode", "xcodebuild clean"], + when: "projectOpen", + enabled: () => !!target(), + run: ({ arg }) => cleanBuildFolder(arg), + }, + { + id: DERIVED_DATA, + title: "Delete DerivedData", + category: "Build", + keywords: ["xcode", "derived data"], + when: "projectOpen", + enabled: () => !!target(), + run: ({ arg }) => deleteDerivedData(arg), + }, + ]), + registerMenuGroup({ + id: "xcode.clean", + menus: ["projectView"], + order: 45, + items: (_menu, { paths }) => { + const path = paths.length === 1 ? paths[0]! : null; + if (!path || !isContainer(path) || !target(path)) return []; + return [ + { kind: "action", action: CLEAN, arg: path }, + { kind: "action", action: DERIVED_DATA, arg: path }, + ]; + }, + }), + ]; + return () => disposers.reverse().forEach((d) => d()); +} diff --git a/src/platform/locales/en.json b/src/platform/locales/en.json index 5ac15bc980..7fe0a74448 100644 --- a/src/platform/locales/en.json +++ b/src/platform/locales/en.json @@ -440,6 +440,7 @@ "menu.build.rebuildProject": "Rebuild Project", "menu.build.buildArtifacts": "Build Artifacts", "menu.build.flutter": "Flutter", + "menu.build.xcode": "Xcode", "menu.toolwindow.build": "Build", "menu.find.structural": "Search Structurally…", "menu.find.replaceStructural": "Replace Structurally…", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 1597f59d9b..178477430d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4786,6 +4786,14 @@ "Focus Text Filter": "Focus Text Filter", "Maximize Commit Message": "Maximize Commit Message", "Commit Messages": "Commit Messages", + "Clean Build Folder": "Clean Build Folder", + "Delete DerivedData": "Delete DerivedData", + "Clean {name}": "Clean {name}", + "No DerivedData to delete": "No DerivedData to delete", + "Move the DerivedData of {container} to the Trash? The next build starts from scratch.": "Move the DerivedData of {container} to the Trash? The next build starts from scratch.", + "Move to Trash": "Move to Trash", + "DerivedData moved to the Trash": "DerivedData moved to the Trash", + "Could not delete DerivedData": "Could not delete DerivedData", "Regenerate Xcode Project": "Regenerate Xcode Project", "No XcodeGen or Tuist project found": "No XcodeGen or Tuist project found", "Open a file of a project with project.yml or Project.swift.": "Open a file of a project with project.yml or Project.swift.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 9eba73b00f..d84debd98c 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -11437,6 +11437,14 @@ "Focus Text Filter": "聚焦文本过滤器", "Maximize Commit Message": "最大化提交消息", "Commit Messages": "提交消息", + "Clean Build Folder": "清理构建文件夹", + "Delete DerivedData": "删除 DerivedData", + "Clean {name}": "清理 {name}", + "No DerivedData to delete": "没有可删除的 DerivedData", + "Move the DerivedData of {container} to the Trash? The next build starts from scratch.": "将 {container} 的 DerivedData 移到废纸篓?下次构建将从头开始。", + "Move to Trash": "移到废纸篓", + "DerivedData moved to the Trash": "DerivedData 已移到废纸篓", + "Could not delete DerivedData": "无法删除 DerivedData", "Regenerate Xcode Project": "重新生成 Xcode 项目", "No XcodeGen or Tuist project found": "未找到 XcodeGen 或 Tuist 项目", "Open a file of a project with project.yml or Project.swift.": "请打开含 project.yml 或 Project.swift 的项目中的文件。", diff --git a/src/platform/locales/zh.json b/src/platform/locales/zh.json index 77d09c822a..a257a23f37 100644 --- a/src/platform/locales/zh.json +++ b/src/platform/locales/zh.json @@ -440,6 +440,7 @@ "menu.build.rebuildProject": "重新构建项目", "menu.build.buildArtifacts": "构建工件", "menu.build.flutter": "Flutter", + "menu.build.xcode": "Xcode", "menu.toolwindow.build": "构建", "menu.find.structural": "结构化搜索…", "menu.find.replaceStructural": "结构化替换…",