feat(run): run xcode schemes on the ios simulator (#6824)

Xcode projects get one run configuration per scheme (xcode:run:<container>:<scheme>), keeping the scheme's launch build configuration, arguments and environment; a workspace next to the projects is used as the container, and the iOS/macOS host app of a Flutter or React Native project is skipped. At launch the host resolves the simulator and the built .app and bundle id from xcodebuild -showBuildSettings -json, then runs a script that builds with xcodebuild into the project cache's DerivedData, boots the simulator, installs and launches the app with simctl --console-pty, with the environment passed as SIMCTL_CHILD_*. Stop turns the SIGINT into the SIGTERM simctl forwards to the app.

Closes #6795

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-29 17:07:59 +08:00
1 джерело db266643aa
коміт 2b435c8440
7 files changed
+373 -2

No files matched your search

+9
Переглянути файл
@@ -540,6 +540,15 @@ async fn start_inner(
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
}
if config.kind == "xcode" {
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
.blocking(move || {
ide_run::xcode::prepare(&dir, &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
+2
Переглянути файл
@@ -6,6 +6,7 @@
pub(crate) mod cmake;
mod dotnet;
mod swiftpm;
mod xcode;
mod xcode_test;
mod zig;
@@ -97,6 +98,7 @@ pub(crate) fn detect_with_profiles(
detect_projects(root, &["justfile", "Justfile", ".justfile"], detect_just, &mut out);
detect_godot(root, &mut out);
detect_projects(root, &["pubspec.yaml"], detect_flutter, &mut out);
detect_projects_matching(root, xcode::is_project, xcode::detect, &mut out);
detect_unreal(root, &mut out);
crate::external::detect(root, &mut out);
+78
Переглянути файл
@@ -0,0 +1,78 @@
//! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS
//! Simulator (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
//! so its schemes and theirs are built through it.
use super::config;
use crate::RunConfig;
use crate::xcode::{XcodeScheme, schemes};
use std::path::Path;
/// A folder holding an Xcode project or workspace, other than the `ios/` / `macos/` host app
/// of a Flutter or React Native project, which that project's own tooling runs.
pub(super) fn is_project(dir: &Path) -> bool {
let hosted = dir.parent().is_some_and(|p| p.join("pubspec.yaml").is_file() || p.join("package.json").is_file());
!hosted
&& std::fs::read_dir(dir).is_ok_and(|entries| {
entries.flatten().any(|e| e.path().extension().is_some_and(|x| x == "xcodeproj" || x == "xcworkspace"))
})
}
pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let found = schemes(dir);
let workspace = found.iter().map(|s| &s.container).find(|c| c.extension().is_some_and(|x| x == "xcworkspace"));
for scheme in &found {
let container = workspace.unwrap_or(&scheme.container);
let container = container.strip_prefix(dir).unwrap_or(container).to_string_lossy().into_owned();
out.push(scheme_config(scheme, &container));
}
}
fn scheme_config(scheme: &XcodeScheme, container: &str) -> RunConfig {
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
let mut args = vec![flag, container, "-scheme", &scheme.name];
if let Some(configuration) = &scheme.launch_configuration {
args.extend(["-configuration", configuration]);
}
let mut c =
config(format!("xcode:run:{container}:{}", scheme.name), scheme.name.clone(), "xcode", "xcodebuild", &args);
let params = &mut c.extras.params;
params.insert("container".into(), container.to_owned());
params.insert("scheme".into(), scheme.name.clone());
params.extend(scheme.launch_configuration.clone().map(|v| ("configuration".to_owned(), v)));
if !scheme.arguments.is_empty() {
params.insert("arguments".into(), scheme.arguments.join(" "));
}
c.env = scheme.environment.iter().cloned().collect();
c
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_configuration_per_scheme_built_through_the_workspace() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/xcode");
assert!(is_project(&root));
let mut out = Vec::new();
detect(&root, &mut out);
let ids: Vec<_> = out.iter().map(|c| c.id.as_str()).collect();
assert_eq!(
ids,
[
"xcode:run:App.xcworkspace:App",
"xcode:run:App.xcworkspace:Scratch",
"xcode:run:App.xcworkspace:Everything"
]
);
let app = &out[0];
assert_eq!((app.kind.as_str(), app.command.as_str()), ("xcode", "xcodebuild"));
assert_eq!(app.args, ["-workspace", "App.xcworkspace", "-scheme", "App", "-configuration", "Staging"]);
assert_eq!(app.extras.params["container"], "App.xcworkspace");
assert_eq!(app.extras.params["configuration"], "Staging");
assert_eq!(app.extras.params["arguments"], "-com.apple.CoreData.SQLDebug 1 --name=\"A & B\"");
assert_eq!(app.env["API_HOST"], "localhost:8080");
assert!(!app.extras.params.contains_key(crate::xcode::SIMULATOR_PARAM));
}
}
+222 -2
Переглянути файл
@@ -1,8 +1,13 @@
//! 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.
//!
//! A scheme's run configuration builds it for the iOS Simulator and launches the app there with
//! `simctl`; [`prepare`] turns the configuration into that process when it starts.
use ide_core::{IdeError, IdeResult};
use quick_xml::{Reader, XmlVersion, events::Event};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
@@ -173,8 +178,7 @@ pub fn prepare_test(config: &mut crate::RunConfig, bundles: &Path) -> std::io::R
}
/// The booted iOS simulator, otherwise the first iPhone of the newest iOS runtime.
// Local stand-in until the run configurations' simulator choice (#6665 C1/C2) can be shared.
fn default_simulator() -> Option<String> {
pub fn default_simulator() -> Option<String> {
let mut cmd = std::process::Command::new("xcrun");
cmd.args(["simctl", "list", "devices", "available", "-j"]);
let out = ide_core::process::prepare(&mut cmd).output().ok()?;
@@ -202,6 +206,121 @@ fn pick_simulator(json: &str) -> Option<String> {
.filter(|udid| !udid.is_empty())
}
/// The run configuration parameter that holds the simulator's UDID. Empty means
/// [`default_simulator`]: the one place a device selector can feed its choice into.
pub const SIMULATOR_PARAM: &str = "simulator";
/// The `xcodebuild` arguments that pick what is built, and where, for a `kind = "xcode"`
/// configuration: its `container`, `scheme` and `configuration` params and the simulator.
pub fn build_args(params: &BTreeMap<String, String>, udid: &str, derived_data: &Path) -> Result<Vec<String>, 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([
"-destination".to_owned(),
format!("id={udid}"),
"-derivedDataPath".to_owned(),
derived_data.to_string_lossy().into_owned(),
]);
Ok(args)
}
/// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the
/// scheme's first application target.
pub fn built_app(settings: &str) -> Result<(PathBuf, String), String> {
let json: serde_json::Value =
serde_json::from_str(settings).map_err(|e| format!("Unreadable build settings: {e}"))?;
let targets = json.as_array().map(Vec::as_slice).unwrap_or_default();
let apps = || {
targets
.iter()
.map(|t| &t["buildSettings"])
.filter(|b| b["PRODUCT_TYPE"] == "com.apple.product-type.application")
};
let Some(app) = apps().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else {
return Err(match apps().next().and_then(|b| b["PLATFORM_NAME"].as_str()) {
Some("macosx") => "Running macOS apps is not supported yet; only iOS apps run on the Simulator".to_owned(),
Some(platform) => format!("The scheme builds an app for {platform}, not the iOS Simulator"),
None => "The scheme builds no application".to_owned(),
});
};
let get =
|key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}"));
Ok((Path::new(get("TARGET_BUILD_DIR")?).join(get("WRAPPER_NAME")?), get("PRODUCT_BUNDLE_IDENTIFIER")?.to_owned()))
}
/// Quotes `s` as one `sh` word.
fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
/// The script a run executes: build, boot the simulator and show it (Xcode 27 replaced the
/// Simulator app with DeviceHub), install, then launch with the app's output on the console.
/// The app's arguments follow the script as `$@`. `simctl` passes SIGTERM on to the app but not
/// the SIGINT a Stop sends, so the script turns that into a SIGTERM.
pub fn launch_script(build_args: &[String], udid: &str, app: &Path, bundle_id: &str) -> String {
let build: Vec<String> = build_args.iter().map(|a| sh_quote(a)).collect();
let (udid, app, bundle_id) = (sh_quote(udid), sh_quote(&app.to_string_lossy()), sh_quote(bundle_id));
format!(
"set -e\n\
xcodebuild {} build\n\
xcrun simctl bootstatus {udid} -b >/dev/null\n\
open -a Simulator 2>/dev/null || open -a DeviceHub 2>/dev/null || true\n\
xcrun simctl install {udid} {app}\n\
set +e\n\
xcrun simctl launch --console-pty --terminate-running-process {udid} {bundle_id} \"$@\" &\n\
launch=$!\n\
trap 'kill -TERM $launch 2>/dev/null' INT TERM\n\
wait $launch; status=$?\n\
while kill -0 $launch 2>/dev/null; do wait $launch; status=$?; done\n\
exit $status\n",
build.join(" ")
)
}
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
/// its scheme on the simulator. `dir` is the run's working directory; DerivedData goes under
/// `cache_dir`. The configuration's environment reaches the app as `SIMCTL_CHILD_*`.
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
if !cfg!(target_os = "macos") {
return Err(IdeError::unavailable("Xcode schemes run on macOS only"));
}
let output = |program: &str, args: &[String]| -> IdeResult<String> {
let mut cmd = std::process::Command::new(program);
cmd.args(args).current_dir(dir);
let out = ide_core::process::prepare(&mut cmd)
.output()
.map_err(|e| IdeError::unavailable(format!("Cannot run {program}: {e}")))?;
if !out.status.success() {
let err = String::from_utf8_lossy(&out.stderr);
return Err(IdeError::invalid(format!("{program} {} failed:\n{}", args.join(" "), err.trim())));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
};
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"))?,
};
let derived_data = cache_dir.join("xcode/DerivedData");
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)?;
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
config.command = "/bin/sh".into();
config.args = ["-c".to_owned(), launch_script(&args, &udid, &app, &bundle_id), "xcode-run".to_owned()]
.into_iter()
.chain(app_args)
.collect();
config.env = std::mem::take(&mut config.env).into_iter().map(|(k, v)| (format!("SIMCTL_CHILD_{k}"), v)).collect();
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -320,4 +439,105 @@ mod tests {
assert!(schemes(&fixtures().join("App.xcodeproj")).is_empty());
assert!(schemes(Path::new("/nonexistent")).is_empty());
}
#[test]
fn build_args_name_the_container_scheme_configuration_and_simulator() {
let mut params: BTreeMap<String, String> =
[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Staging")]
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.into();
let dd = Path::new("/cache/DerivedData");
assert_eq!(
build_args(&params, "U1", dd).unwrap(),
[
"-workspace",
"App.xcworkspace",
"-scheme",
"App",
"-configuration",
"Staging",
"-destination",
"id=U1",
"-derivedDataPath",
"/cache/DerivedData"
]
);
params.insert("container".into(), "App.xcodeproj".into());
params.remove("configuration");
assert_eq!(
build_args(&params, "U1", dd).unwrap()[..5],
["-project", "App.xcodeproj", "-scheme", "App", "-destination"]
);
params.remove("scheme");
assert_eq!(build_args(&params, "U1", dd).unwrap_err(), "No scheme is set");
}
#[test]
fn built_app_is_the_schemes_simulator_application() {
let settings = |platform: &str| {
format!(
r#"[
{{"target": "AppTests", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.bundle.unit-test", "PLATFORM_NAME": "{platform}"}}}},
{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application", "PLATFORM_NAME": "{platform}",
"TARGET_BUILD_DIR": "/dd/Build/Products/Debug-iphonesimulator", "WRAPPER_NAME": "App.app",
"PRODUCT_BUNDLE_IDENTIFIER": "dev.example.App"}}}}
]"#
)
};
assert_eq!(
built_app(&settings("iphonesimulator")).unwrap(),
(PathBuf::from("/dd/Build/Products/Debug-iphonesimulator/App.app"), "dev.example.App".to_owned())
);
assert!(built_app(&settings("macosx")).unwrap_err().contains("macOS apps is not supported"));
assert_eq!(built_app("[]").unwrap_err(), "The scheme builds no application");
}
/// Runs the script against stub `xcodebuild`, `xcrun` and `open` that log their arguments; the
/// stub `simctl launch` runs until it gets SIGTERM, which a Stop's SIGINT must turn into.
#[cfg(unix)]
#[test]
fn launch_script_builds_installs_launches_and_stops_the_app() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let stub = |tool: &str, then: &str| {
let path = dir.path().join(tool);
let body = format!(
"#!/bin/sh\nprintf '{tool}' >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}"
);
fs::write(&path, body).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
};
stub("xcodebuild", "");
stub("open", "");
stub(
"xcrun",
"[ \"$2\" = launch ] || exit 0\ntrap 'echo terminated >> \"$LOG\"; exit 0' TERM\nwhile :; do sleep 0.05; done\n",
);
let build = ["-project".to_owned(), "My App.xcodeproj".to_owned(), "-scheme".to_owned(), "It's".to_owned()];
let script = launch_script(&build, "U1", Path::new("/dd/My App.app"), "dev.example.App");
let mut child = std::process::Command::new("/bin/sh")
.args(["-c", &script, "xcode-run", "--greeting", "hi there"])
.env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
.env("LOG", &log)
.spawn()
.unwrap();
let launched = || fs::read_to_string(&log).unwrap_or_default().contains("[launch]");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !launched() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(20));
}
std::thread::sleep(std::time::Duration::from_millis(200));
unsafe { libc::kill(child.id() as i32, libc::SIGINT) };
assert!(child.wait().unwrap().success());
assert_eq!(
fs::read_to_string(&log).unwrap(),
"xcodebuild [-project] [My App.xcodeproj] [-scheme] [It's] [build]\n\
xcrun [simctl] [bootstatus] [U1] [-b]\n\
open [-a] [Simulator]\n\
xcrun [simctl] [install] [U1] [/dd/My App.app]\n\
xcrun [simctl] [launch] [--console-pty] [--terminate-running-process] [U1] [dev.example.App] [--greeting] [hi there]\n\
terminated\n"
);
}
}
+2
Переглянути файл
@@ -23,6 +23,7 @@ import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { flutterType } from "./flutterType";
import { xcodeType } from "./xcodeType";
import { tomcatType } from "./tomcat";
import { goBuildType, goTestType } from "./goTypes";
@@ -619,6 +620,7 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [
maven,
godot,
flutterType,
xcodeType,
unreal,
pythonType,
pytest,
+18
Переглянути файл
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { xcodeType } from "./xcodeType";
describe("Xcode run configurations", () => {
it("name what is built the way detection does", () => {
expect(xcodeType.commandLine({ container: "App.xcworkspace", scheme: "App", configuration: "Staging" })).toEqual({
command: "xcodebuild",
args: ["-workspace", "App.xcworkspace", "-scheme", "App", "-configuration", "Staging"],
});
expect(xcodeType.commandLine({ container: "App.xcodeproj", scheme: "App", simulator: "U1" })!.args).toEqual([
"-project",
"App.xcodeproj",
"-scheme",
"App",
]);
expect(xcodeType.commandLine({ container: "App.xcodeproj" })).toBeNull();
});
});
+42
Переглянути файл
@@ -0,0 +1,42 @@
/**
* Xcode schemes run on the iOS Simulator. The host builds, installs and launches the app at
* launch (`ide_run::xcode::prepare`); the command line here names what is built.
*/
import type { RunConfigTypeContribution } from "@/workbench/contributions";
export const xcodeType: RunConfigTypeContribution = {
id: "xcode",
label: "Xcode App",
icon: "file-swift",
description: "Build an Xcode scheme and run it on the iOS Simulator",
fields: [
{
key: "container",
label: "Project or workspace",
mono: true,
browse: "directory",
required: true,
placeholder: "App.xcodeproj",
},
{ key: "scheme", label: "Scheme", required: true },
{ key: "configuration", label: "Build configuration", placeholder: "The scheme's" },
{
key: "simulator",
label: "Simulator",
mono: true,
placeholder: "A booted simulator, else the newest iPhone",
hint: "A simulator UDID (xcrun simctl list devices) pins this configuration to it",
},
{ key: "arguments", label: "Launch arguments", mono: true },
],
commandLine: (p) => {
const container = p.container?.trim() ?? "";
if (!container || !p.scheme?.trim()) return null;
const flag = container.endsWith(".xcworkspace") ? "-workspace" : "-project";
const configuration = p.configuration?.trim();
return {
command: "xcodebuild",
args: [flag, container, "-scheme", p.scheme.trim(), ...(configuration ? ["-configuration", configuration] : [])],
};
},
};