perf(xcode): reuse the build description across xcodebuild runs of JSON5 projects (#7530)

In Tuist's JSON5 project format, package product build file GUIDs come from Swift's per-process hash seed, so every xcodebuild process recreated the build description (10-14 s). Runs, tests, Clean and the index build now start xcodebuild with SWIFT_DETERMINISTIC_HASHING=1, so a Rerun with nothing to rebuild reuses the previous description. The launched app does not get the variable.

Closes #7528

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-02 21:41:38 +08:00
1 джерело 8dc1fecc0e
коміт 24588b0975
3 files changed
+62 -12

No files matched your search

+38 -8
Переглянути файл
@@ -196,13 +196,14 @@ fn resolve(reference: &str, container: &Path) -> PathBuf {
/// Completes an `xcodebuild test` launch: a simulator destination unless the configuration names
/// one, and a fresh `-resultBundlePath` under `bundles` (xcodebuild refuses an existing one). The
/// bundles of this configuration's earlier runs are removed. Run with Coverage names the bundle
/// itself in [`RESULT_BUNDLE_PARAM`].
/// itself in [`RESULT_BUNDLE_PARAM`]. `xcodebuild` runs with [`XCODEBUILD_ENV`].
pub fn prepare_test(config: &mut crate::RunConfig, dir: &Path, bundles: &Path) -> std::io::Result<()> {
if !config.args.iter().any(|a| a == "-destination")
&& let Some(udid) = default_simulator(dir)
{
config.args.extend(["-destination".to_owned(), format!("id={udid}")]);
}
set_xcodebuild_env(&mut config.env);
if let Some(at) = config.args.iter().position(|a| a == "-resultBundlePath") {
config.args.drain(at..(at + 2).min(config.args.len()));
}
@@ -336,6 +337,24 @@ pub fn built_app(settings: &str, device: bool) -> Result<(PathBuf, String), Stri
Ok((Path::new(get("TARGET_BUILD_DIR")?).join(get("WRAPPER_NAME")?), get("PRODUCT_BUNDLE_IDENTIFIER")?.to_owned()))
}
/// The environment variable `xcodebuild` runs with, and its value. A project in the JSON5 format
/// (`project.xcproj`, Tuist's `projectFormat: .xcproj`) gets new GUIDs for a target's package
/// product build files in every process, from Swift's per-process hash seed. The build
/// description depends on them, so each `xcodebuild` created it again: 10 s or more of a
/// large workspace's build with nothing to do. A fixed seed lets it reuse the last one, as
/// Xcode's long-lived build service does.
pub const XCODEBUILD_ENV: (&str, &str) = ("SWIFT_DETERMINISTIC_HASHING", "1");
/// Adds [`XCODEBUILD_ENV`] to the environment of a configuration that runs `xcodebuild`.
pub fn set_xcodebuild_env(env: &mut BTreeMap<String, String>) {
env.insert(XCODEBUILD_ENV.0.to_owned(), XCODEBUILD_ENV.1.to_owned());
}
/// `xcodebuild` with [`XCODEBUILD_ENV`] in a script; the app it launches doesn't get it.
fn xcodebuild() -> String {
format!("{}={} xcodebuild", XCODEBUILD_ENV.0, XCODEBUILD_ENV.1)
}
/// Quotes `s` as one `sh` word.
fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
@@ -366,7 +385,7 @@ pub fn launch_script(
format!(
"{watch}\
set -e\n\
xcodebuild {} build\n\
{} {} 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\
@@ -391,6 +410,7 @@ pub fn launch_script(
if [ -n \"$stopped\" ]; then wait $launch 2>/dev/null; s=$?; [ $s -eq 127 ] || status=$s; fi\n\
{report}\
exit $status\n",
xcodebuild(),
build.join(" "),
watch = watch_exits(&udid),
report = report_exit(&bundle_id),
@@ -480,7 +500,7 @@ pub fn device_launch_script(build_args: &[String], udid: &str, name: &str, app:
let hint = sh_quote(&format!("Could not launch the app on {name}. If it is locked, unlock it and run again."));
format!(
"set -e\n\
xcodebuild {} -allowProvisioningUpdates build\n\
{} {} -allowProvisioningUpdates build\n\
xcrun devicectl device install app --device {udid} {app}\n\
set +e\n\
result=$(mktemp)\n\
@@ -492,6 +512,7 @@ pub fn device_launch_script(build_args: &[String], udid: &str, name: &str, app:
if [ -z \"$stopped\" ] && ! grep -q '\"outcome\" *: *\"success\"' \"$result\" 2>/dev/null; then echo {hint} >&2; fi\n\
rm -f \"$result\"\n\
exit $status\n",
xcodebuild(),
build.join(" "),
)
}
@@ -514,7 +535,12 @@ fn device_unready(device: &crate::simulator::IosSimulator) -> Option<String> {
/// reaches the console and a Stop's SIGINT reaches the app. Its arguments follow as `$@`.
pub fn mac_launch_script(build_args: &[String], executable: &Path) -> String {
let build: Vec<String> = build_args.iter().map(|a| sh_quote(a)).collect();
format!("set -e\nxcodebuild {} build\nexec {} \"$@\"\n", build.join(" "), sh_quote(&executable.to_string_lossy()))
format!(
"set -e\n{} {} build\nexec {} \"$@\"\n",
xcodebuild(),
build.join(" "),
sh_quote(&executable.to_string_lossy())
)
}
/// The `-destination` of a run of `params` on a Mac.
@@ -1278,6 +1304,8 @@ mod tests {
};
prepare_test(&mut config, dir.path(), dir.path()).unwrap();
assert_eq!(config.args[..3], ["test", "-destination", "id=X"]);
// The build description is reused across runs of a JSON5 (`project.xcproj`) project.
assert_eq!(config.env.get("SWIFT_DETERMINISTIC_HASHING").map(String::as_str), Some("1"));
assert_eq!(config.args[3], "-resultBundlePath");
assert!(config.args[4].contains("xcode_test_A-") && config.args[4].ends_with(".xcresult"));
assert_eq!(config.args.len(), 5);
@@ -1486,11 +1514,11 @@ mod tests {
fs::write(path, body).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
};
stub(&dir.path().join("xcodebuild"), "");
stub(&dir.path().join("xcodebuild"), "echo \"hashing=$SWIFT_DETERMINISTIC_HASHING\" >> \"$LOG\"\n");
let exe = dir.path().join("My App");
stub(
&exe,
"echo \"GREETING=$GREETING\" >> \"$LOG\"\ntrap 'echo stopped >> \"$LOG\"; exit 0' INT\nwhile :; do sleep 0.05; done\n",
"echo \"GREETING=$GREETING hashing=$SWIFT_DETERMINISTIC_HASHING\" >> \"$LOG\"\ntrap 'echo stopped >> \"$LOG\"; exit 0' INT\nwhile :; do sleep 0.05; done\n",
);
let build = ["-scheme".to_owned(), "It's".to_owned(), "-destination".to_owned(), "platform=macOS".to_owned()];
let mut child = std::process::Command::new("/bin/sh")
@@ -1511,8 +1539,9 @@ mod tests {
assert_eq!(
fs::read_to_string(&log).unwrap(),
"xcodebuild [-scheme] [It's] [-destination] [platform=macOS] [build]\n\
hashing=1\n\
My App [--greeting] [hi there]\n\
GREETING=hello\n\
GREETING=hello hashing=\n\
stopped\n"
);
}
@@ -1533,7 +1562,7 @@ mod tests {
fs::write(&path, body).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
};
stub("xcodebuild", "");
stub("xcodebuild", "echo \"hashing=$SWIFT_DETERMINISTIC_HASHING\" >> \"$LOG\"\n");
stub("open", "");
stub(
"xcrun",
@@ -1567,6 +1596,7 @@ mod tests {
assert_eq!(
fs::read_to_string(&log).unwrap(),
"xcodebuild [-project] [My App.xcodeproj] [-scheme] [It's] [build]\n\
hashing=1\n\
xcrun [simctl] [bootstatus] [U1] [-b]\n\
open [-a] [Simulator]\n\
xcrun [simctl] [install] [U1] [/dd/My App.app]\n\
+2 -1
Переглянути файл
@@ -16,12 +16,13 @@ pub fn ide_derived_data(cache_dir: &Path) -> PathBuf {
/// Turns a [`KIND`] configuration into `xcodebuild clean` of the build its `xcode` configuration
/// runs: the same container, scheme, configuration, destination (the simulator, or the Mac for a
/// macOS app). `dir` is the configuration's working directory.
/// macOS app), and the same environment. `dir` is the configuration's working directory.
pub fn prepare(dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
let params = &config.extras.params;
let destination = destination(dir, params)?;
config.args = clean_args(params, &destination).map_err(IdeError::invalid)?;
config.command = "xcodebuild".into();
crate::xcode::set_xcodebuild_env(&mut config.env);
Ok(())
}
+22 -3
Переглянути файл
@@ -98,9 +98,7 @@ pub fn build(
return Ok(XcodeIndexBuild::XcodeBusy);
}
let args = xcode::build_args(params, Some(&destination)).map_err(IdeError::invalid)?;
let mut cmd = Command::new("taskpolicy");
cmd.args(["-c", "utility", "xcodebuild"]).args(args).arg("build").current_dir(root);
run_build(cmd, on_target, cancel)
run_build(build_command(root, args), on_target, cancel)
})();
match result {
Err(e) if e.kind == ErrorKind::Cancelled => Ok(XcodeIndexBuild::Cancelled),
@@ -108,6 +106,18 @@ pub fn build(
}
}
/// `xcodebuild build` at utility priority, with the environment a Run builds with, so the Run
/// after it reuses its build description.
fn build_command(root: &Path, args: Vec<String>) -> Command {
let mut cmd = Command::new("taskpolicy");
cmd.args(["-c", "utility", "xcodebuild"])
.args(args)
.arg("build")
.current_dir(root)
.env(xcode::XCODEBUILD_ENV.0, xcode::XCODEBUILD_ENV.1);
cmd
}
fn run_build(cmd: Command, on_target: xcode::Progress, cancel: &CancellationToken) -> IdeResult<XcodeIndexBuild> {
const MAX_ERRORS: usize = 5;
let (mut errors, mut tail, mut target, mut locked) = (Vec::new(), Vec::new(), String::new(), false);
@@ -202,6 +212,15 @@ mod tests {
assert!(!in_use(&db));
}
#[test]
fn the_build_runs_with_the_environment_of_a_run() {
let cmd = build_command(Path::new("/p"), vec!["-scheme".into(), "App".into()]);
let env: Vec<_> = cmd.get_envs().collect();
let (key, value) = xcode::XCODEBUILD_ENV;
assert_eq!(env, [(std::ffi::OsStr::new(key), Some(std::ffi::OsStr::new(value)))]);
assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["-c", "utility", "xcodebuild", "-scheme", "App", "build"]);
}
#[cfg(unix)]
#[test]
fn cancelling_settings_and_build_reaps_the_child() {