diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index a27da2154e..2886f14caa 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -21,6 +21,7 @@ pub mod scope; pub mod tomcat; mod utf8; pub mod wrap; +pub mod xcode; 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 new file mode 100644 index 0000000000..8c55fb6b9f --- /dev/null +++ b/crates/ide-run/src/xcode.rs @@ -0,0 +1,202 @@ +//! Xcode schemes read straight from the `.xcscheme` files of the `.xcodeproj` / `.xcworkspace` +//! bundles at a project root. `xcodebuild -list` would also know the schemes Xcode autocreates for +//! projects without any, but it takes a second or two, too slow for detection. + +use quick_xml::{Reader, XmlVersion, events::Event}; +use std::fs; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct XcodeScheme { + pub name: String, + /// The `.xcodeproj` or `.xcworkspace` the scheme belongs to. + pub container: PathBuf, + /// False for a scheme only found under `xcuserdata/` (not shared with the team). + pub shared: bool, + pub launch_configuration: Option, + pub test_configuration: Option, + /// The `LaunchAction`'s enabled command-line arguments, each as Xcode stores it (one entry may + /// hold several shell words). + pub arguments: Vec, + /// The `LaunchAction`'s enabled environment variables. + pub environment: Vec<(String, String)>, + /// The `.xctestplan` files the `TestAction` references. + pub test_plans: Vec, + pub default_test_plan: Option, +} + +/// The schemes of every `.xcodeproj` / `.xcworkspace` directly in `root`, sorted by container +/// and then by name. Unreadable or malformed scheme files are skipped. +pub fn schemes(root: &Path) -> Vec { + let Ok(entries) = fs::read_dir(root) else { return Vec::new() }; + let mut containers: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| p.is_dir() && p.extension().is_some_and(|ext| ext == "xcodeproj" || ext == "xcworkspace")) + .collect(); + containers.sort(); + containers.iter().flat_map(|c| container_schemes(c)).collect() +} + +fn container_schemes(container: &Path) -> Vec { + let mut out: Vec = Vec::new(); + let mut add = |dir: PathBuf, shared: bool| { + let Ok(entries) = fs::read_dir(dir) else { return }; + let mut files: Vec = + entries.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "xcscheme")).collect(); + files.sort(); + for file in files { + let Some(name) = file.file_stem().and_then(|s| s.to_str()) else { continue }; + // A shared scheme wins over a personal copy of the same name. + if out.iter().any(|s| s.name == name) { + continue; + } + let Some(xml) = fs::read_to_string(&file).ok() else { continue }; + if let Some(mut scheme) = parse_scheme(&xml, container) { + scheme.name = name.to_owned(); + scheme.shared = shared; + out.push(scheme); + } + } + }; + add(container.join("xcshareddata/xcschemes"), true); + if let Ok(users) = fs::read_dir(container.join("xcuserdata")) { + let mut users: Vec = users.flatten().map(|e| e.path()).collect(); + users.sort(); + for user in users { + add(user.join("xcschemes"), false); + } + } + out.sort_by(|a, b| a.name.cmp(&b.name)); + out +} + +/// Parses one `.xcscheme` file. `name` and `shared` are left for the caller, which knows the file. +pub fn parse_scheme(xml: &str, container: &Path) -> Option { + let mut scheme = XcodeScheme { container: container.to_owned(), ..Default::default() }; + let mut reader = Reader::from_str(xml); + let mut stack: Vec = Vec::new(); + let mut seen_root = false; + loop { + let event = reader.read_event().ok()?; + let empty = matches!(event, Event::Empty(_)); + match event { + Event::Start(tag) | Event::Empty(tag) => { + let name = tag.local_name().as_ref().to_owned(); + if stack.is_empty() { + if seen_root || name != "Scheme" { + return None; + } + seen_root = true; + } + let attr = |key: &str| -> Option { + tag.attributes() + .flatten() + .find(|a| a.key.as_ref() == key) + .and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok().map(|v| v.into_owned())) + }; + let enabled = || attr("isEnabled").as_deref() == Some("YES"); + let action = stack.get(1).map(String::as_str); + match (action, name.as_str()) { + (None, "LaunchAction") => scheme.launch_configuration = attr("buildConfiguration"), + (None, "TestAction") => scheme.test_configuration = attr("buildConfiguration"), + (Some("LaunchAction"), "CommandLineArgument") if enabled() => { + scheme.arguments.extend(attr("argument")); + } + (Some("LaunchAction"), "EnvironmentVariable") if enabled() => { + if let Some(key) = attr("key") { + scheme.environment.push((key, attr("value").unwrap_or_default())); + } + } + (Some("TestAction"), "TestPlanReference") => { + if let Some(plan) = attr("reference").map(|r| resolve(&r, container)) { + if attr("default").as_deref() == Some("YES") { + scheme.default_test_plan = Some(plan.clone()); + } + scheme.test_plans.push(plan); + } + } + _ => {} + } + if !empty { + stack.push(name); + } + } + Event::End(_) => { + stack.pop()?; + } + Event::Eof => return (seen_root && stack.is_empty()).then_some(scheme), + _ => {} + } + } +} + +/// Resolves a scheme file reference such as `container:Tests/All.xctestplan`, which is relative +/// to the folder holding the `.xcodeproj` / `.xcworkspace`. +fn resolve(reference: &str, container: &Path) -> PathBuf { + match reference.split_once(':') { + Some(("absolute", path)) => PathBuf::from(path), + Some((_, path)) => container.parent().unwrap_or(container).join(path), + None => container.parent().unwrap_or(container).join(reference), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/xcode") + } + + #[test] + fn reads_shared_and_personal_schemes_of_each_container() { + let root = fixtures(); + let found = schemes(&root); + let names: Vec<_> = + found.iter().map(|s| (s.container.file_name().unwrap().to_str().unwrap(), &*s.name, s.shared)).collect(); + // `Broken.xcscheme` is skipped; the personal `App` copy loses to the shared one. + assert_eq!( + names, + [ + ("App.xcodeproj", "App", true), + ("App.xcodeproj", "Scratch", false), + ("App.xcworkspace", "Everything", true) + ] + ); + + let app = &found[0]; + assert_eq!(app.container, root.join("App.xcodeproj")); + assert_eq!(app.launch_configuration.as_deref(), Some("Staging")); + assert_eq!(app.test_configuration.as_deref(), Some("Debug")); + // Disabled entries and the TestAction's own arguments are left out; entities are decoded. + assert_eq!(app.arguments, ["-com.apple.CoreData.SQLDebug 1", "--name=\"A & B\""]); + assert_eq!(app.environment, [("API_HOST".to_owned(), "localhost:8080".to_owned())]); + assert_eq!(app.test_plans, [root.join("Tests/Unit.xctestplan"), root.join("Tests/All.xctestplan")]); + assert_eq!(app.default_test_plan, Some(root.join("Tests/All.xctestplan"))); + + let scratch = &found[1]; + assert_eq!(scratch.launch_configuration.as_deref(), Some("Debug")); + assert_eq!(scratch.test_configuration, None); + assert!(scratch.arguments.is_empty() && scratch.test_plans.is_empty()); + + let everything = &found[2]; + assert_eq!(everything.default_test_plan, Some(PathBuf::from("/tmp/Shared.xctestplan"))); + assert_eq!(everything.launch_configuration, None); + } + + #[test] + fn rejects_files_that_are_not_schemes() { + let c = Path::new("A.xcodeproj"); + assert_eq!(parse_scheme("not xml <", c), None); + assert_eq!(parse_scheme("", c), None); + assert_eq!(parse_scheme("", c), None); + assert!(parse_scheme("", c).is_some()); + } + + #[test] + fn a_root_without_xcode_projects_has_no_schemes() { + assert!(schemes(&fixtures().join("App.xcodeproj")).is_empty()); + assert!(schemes(Path::new("/nonexistent")).is_empty()); + } +} diff --git a/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme b/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme new file mode 100644 index 0000000000..2544ab1db4 --- /dev/null +++ b/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcuserdata/dev.xcuserdatad/xcschemes/App.xcscheme b/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcuserdata/dev.xcuserdatad/xcschemes/App.xcscheme new file mode 100644 index 0000000000..1a09a18125 --- /dev/null +++ b/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcuserdata/dev.xcuserdatad/xcschemes/App.xcscheme @@ -0,0 +1,4 @@ + + + + diff --git a/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcuserdata/dev.xcuserdatad/xcschemes/Scratch.xcscheme b/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcuserdata/dev.xcuserdatad/xcschemes/Scratch.xcscheme new file mode 100644 index 0000000000..1a09a18125 --- /dev/null +++ b/crates/ide-run/tests/fixtures/xcode/App.xcodeproj/xcuserdata/dev.xcuserdatad/xcschemes/Scratch.xcscheme @@ -0,0 +1,4 @@ + + + + diff --git a/crates/ide-run/tests/fixtures/xcode/App.xcworkspace/xcshareddata/xcschemes/Broken.xcscheme b/crates/ide-run/tests/fixtures/xcode/App.xcworkspace/xcshareddata/xcschemes/Broken.xcscheme new file mode 100644 index 0000000000..a8243b9a18 --- /dev/null +++ b/crates/ide-run/tests/fixtures/xcode/App.xcworkspace/xcshareddata/xcschemes/Broken.xcscheme @@ -0,0 +1 @@ +not xml < \ No newline at end of file diff --git a/crates/ide-run/tests/fixtures/xcode/App.xcworkspace/xcshareddata/xcschemes/Everything.xcscheme b/crates/ide-run/tests/fixtures/xcode/App.xcworkspace/xcshareddata/xcschemes/Everything.xcscheme new file mode 100644 index 0000000000..81abbca3c4 --- /dev/null +++ b/crates/ide-run/tests/fixtures/xcode/App.xcworkspace/xcshareddata/xcschemes/Everything.xcscheme @@ -0,0 +1,9 @@ + + + + + + + + +