feat(xcode): build in the background for code insight before the first build (#7339)

Opening an Xcode project with no build log builds its first scheme once in the background, so xcode-build-server has compiler arguments and sourcekit-lsp gives cross-target insight before the first Run. The build is cancellable, waits for Xcode's own build database, restarts sourcekit-lsp when it ends, and foreground builds cancel and reap it first. Xcode process execution lives in ide-run.

Closes #7337

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-02 16:32:55 +08:00
1 джерело 75ec6c51a3
коміт 1425bfe8ae
19 files changed
+596 -58

No files matched your search

+4 -1
Переглянути файл
@@ -477,12 +477,15 @@ pub struct BuildSettings {
pub open_tool_window: String,
/// When to focus the Build tool window: `always` | `onError` | `never`.
pub focus_tool_window: String,
/// Build an Xcode project in the background when xcode-build-server has no build log to read
/// yet, so cross-file code insight works before the first Run.
pub xcode_index_build: bool,
}
impl Default for BuildSettings {
fn default() -> Self {
// Builds open the tool window without taking focus.
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
Self { open_tool_window: "always".into(), focus_tool_window: "never".into(), xcode_index_build: true }
}
}
+3
Переглянути файл
@@ -551,6 +551,9 @@ async fn start_inner(
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
}
if matches!(config.kind.as_str(), "xcode" | "xcode-test" | ide_run::xcode_clean::KIND) {
super::xcode_bsp::stop_index_build(&project.root).await;
}
let xcode_container = matches!(config.kind.as_str(), "xcode" | "xcode-test")
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
.flatten();
+132 -21
Переглянути файл
@@ -4,13 +4,20 @@
//! server: when a trusted project has none, it runs the one on `PATH` (xcode-build-server,
//! sourcekit-xcode-bsp) to write the config, keeps the config out of Git through
//! `.git/info/exclude`, then restarts sourcekit-lsp.
//!
//! xcode-build-server reads compiler arguments from the latest build log in DerivedData, so
//! until the project's first build it has none to give. [`xcode_index_build`] runs that build in
//! the background, the way Run would, so cross-file code insight works without pressing Run.
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, TaskId};
use ide_run::xcode_index::{self, XcodeIndexBuild};
use serde::Serialize;
use specta::Type;
use std::path::Path;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{LazyLock, Mutex};
/// The generators, in order of preference, and their arguments for `container`.
const TOOLS: [&str; 2] = ["xcode-build-server", "sourcekit-xcode-bsp"];
@@ -29,23 +36,6 @@ fn tool_args(tool: &str, container: &str, build_root: Option<&Path>) -> Vec<Stri
args
}
/// The DerivedData folder Xcode (and a run) builds `container` in, read from the build settings of
/// the first scheme in `root`'s projects. Without it xcode-build-server reads the build settings of
/// the workspace's first scheme, which may be a package's with none (an `IndexError` on a Tuist
/// workspace whose first scheme is a Swift package). `None` leaves it to xcode-build-server.
fn build_root(root: &Path, container: &str) -> Option<std::path::PathBuf> {
let scheme = ide_run::xcode::schemes(root).into_iter().next()?.name;
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
let mut cmd = Command::new("xcodebuild");
ide_core::process::prepare(&mut cmd)
.args([flag, container, "-scheme", &scheme, "-showBuildSettings", "-json"])
.current_dir(root)
.stdin(Stdio::null())
.stderr(Stdio::null());
let out = cmd.output().ok().filter(|o| o.status.success())?;
ide_run::xcode_clean::derived_data_of(&String::from_utf8_lossy(&out.stdout))
}
/// The config `tool` writes at the project root.
fn config_name(tool: &str) -> &'static str {
if tool == "sourcekit-xcode-bsp" { ".bsp" } else { "buildServer.json" }
@@ -143,7 +133,11 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
let mut cmd = Command::new(exe);
ide_core::process::prepare(&mut cmd)
// An absolute path: with `--build_root` it is written to the config as given.
.args(tool_args(&tool, &root.join(&container).to_string_lossy(), build_root(&root, &container).as_deref()))
.args(tool_args(
&tool,
&root.join(&container).to_string_lossy(),
xcode_index::first_scheme_build_root(&root, &container).as_deref(),
))
.current_dir(&root)
.env("PATH", &search)
.stdin(Stdio::null());
@@ -167,7 +161,111 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
Ok(())
}
ide_command::domain!(xcode_bsp: xcode_bsp_setup, xcode_bsp_generate);
#[derive(Clone)]
struct IndexBuild {
cancel: CancellationToken,
finished: CancellationToken,
}
static RUNNING: LazyLock<Mutex<HashMap<PathBuf, IndexBuild>>> = LazyLock::new(Default::default);
/// Lives in the blocking worker until its Xcode processes have exited and been reaped.
struct RunningIndexBuild {
root: PathBuf,
build: IndexBuild,
}
impl RunningIndexBuild {
fn start(root: PathBuf, cancel: CancellationToken) -> Option<Self> {
let mut running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
if running.contains_key(&root) {
return None;
}
let build = IndexBuild { cancel, finished: CancellationToken::new() };
running.insert(root.clone(), build.clone());
Some(Self { root, build })
}
}
impl Drop for RunningIndexBuild {
fn drop(&mut self) {
RUNNING.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.root);
self.build.finished.cancel();
}
}
/// Stops the project's background build and waits for its processes before Run, Test or Clean.
pub(crate) async fn stop_index_build(root: &Path) {
let build = RUNNING.lock().unwrap_or_else(|e| e.into_inner()).get(root).cloned();
if let Some(build) = build {
build.cancel.cancel();
build.finished.cancelled().await;
}
}
/// Builds what Run builds (its first configuration, for its destination) at low priority
/// (`taskpolicy -c utility`), when the project's xcode-build-server config has no build log to
/// read yet: until then sourcekit-lsp has no compiler arguments, so types from other targets and
/// packages don't resolve. A cancellable background task; it backs off while Xcode uses the build
/// folder. Run later builds incrementally on top of it.
#[command(trust = trusted)]
pub async fn xcode_index_build(host: &Host, window: &str) -> IdeResult<XcodeIndexBuild> {
let project = host.project(window)?;
let root = project.root.clone();
let Some(build_root) = xcode_index::pending_build_root(&root) else { return Ok(XcodeIndexBuild::NotNeeded) };
if !cfg!(target_os = "macos") {
return Ok(XcodeIndexBuild::NotNeeded);
}
let Some(running) = RunningIndexBuild::start(root, project.closed.child_token()) else {
return Ok(XcodeIndexBuild::NotNeeded);
};
let sink = project.sink.clone();
let result = super::blocking(move || {
let result = index_build(&running.root, &build_root, &sink, &running.build.cancel);
drop(running);
result
})
.await?;
if matches!(result, XcodeIndexBuild::Built | XcodeIndexBuild::Failed { .. }) {
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
project.lsp.restart(server.id).await?;
}
}
Ok(result)
}
fn index_build(
root: &Path,
build_root: &Path,
sink: &ide_core::SharedSink,
cancel: &CancellationToken,
) -> IdeResult<XcodeIndexBuild> {
let params = ide_run::xcode::first_run_params(root)
.ok_or_else(|| IdeError::unavailable("The Xcode project has no scheme to build"))?;
let scheme = params.get("scheme").cloned().unwrap_or_default();
let task = TaskId::next();
let _cancel_handle = ide_core::task::on_cancel(task, {
let cancel = cancel.clone();
move || cancel.cancel()
});
let progress = |message: Option<String>, done: bool| {
sink.emit(IdeEvent::Task {
id: task,
title: format!("Building {scheme} for code insight"),
message,
fraction: None,
done,
cancellable: !done,
});
};
progress(Some("Reading build settings…".into()), false);
let result =
xcode_index::build(root, build_root, &params, &|target| progress(Some(target.to_owned()), false), cancel);
progress(None, true);
result
}
ide_command::domain!(xcode_bsp: xcode_bsp_setup, xcode_bsp_generate, xcode_index_build);
#[cfg(test)]
mod tests {
@@ -282,6 +380,19 @@ mod tests {
);
}
#[tokio::test]
async fn a_foreground_run_waits_for_only_its_background_build() {
let (a, b) = (PathBuf::from("/a11-test/App"), PathBuf::from("/a11-test/Other"));
let mine = RunningIndexBuild::start(a.clone(), CancellationToken::new()).unwrap();
let other = RunningIndexBuild::start(b, CancellationToken::new()).unwrap();
let stop = tokio::spawn(async move { stop_index_build(&a).await });
mine.build.cancel.cancelled().await;
assert!(!stop.is_finished(), "foreground waits for the worker to exit");
assert!(!other.build.cancel.is_cancelled());
drop(mine);
stop.await.unwrap();
}
#[test]
fn accepts_only_bundle_names_in_the_root() {
assert!(is_container_name("App.xcworkspace") && is_container_name("App.xcodeproj"));
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@
pub(crate) mod cmake;
mod dotnet;
mod swiftpm;
mod xcode;
pub(crate) mod xcode;
mod xcode_test;
mod zig;
+12 -1
Переглянути файл
@@ -20,7 +20,7 @@ pub(super) fn is_project(dir: &Path) -> bool {
})
}
pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
pub(crate) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let found = schemes(dir);
let workspace = found
.iter()
@@ -58,6 +58,17 @@ fn scheme_config(scheme: &XcodeScheme, container: &str) -> RunConfig {
mod tests {
use super::*;
#[test]
fn the_background_build_builds_what_run_builds_first() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/xcode");
let params = crate::xcode::first_run_params(&root).unwrap();
assert_eq!(
crate::xcode::build_args(&params, None).unwrap(),
["-workspace", "App.xcworkspace", "-scheme", "App", "-configuration", "Staging"]
);
assert_eq!(crate::xcode::first_run_params(&root.join("App.xcodeproj")), None);
}
#[test]
fn one_configuration_per_scheme_built_through_the_workspace() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/xcode");
+1
Переглянути файл
@@ -24,6 +24,7 @@ mod utf8;
pub mod wrap;
pub mod xcode;
pub mod xcode_clean;
pub mod xcode_index;
pub use detect::cmake::cache as cmake_cache;
pub use detect::cmake::presets::{listed as cmake_listed_profiles, load as cmake_presets, profiles as cmake_profiles};
+75 -21
Переглянути файл
@@ -7,12 +7,14 @@
//! macOS app, builds it for the Mac and runs its executable;
//! [`prepare`] turns the configuration into that process when it starts.
use ide_core::{IdeError, IdeResult};
use ide_core::cli_process::{CliTool, Decoding};
use ide_core::{CancellationToken, IdeError, IdeResult};
use quick_xml::{Reader, XmlVersion, events::Event};
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use std::time::Duration;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct XcodeScheme {
@@ -453,17 +455,34 @@ pub fn mac_launch_script(build_args: &[String], executable: &Path) -> String {
pub const MAC_DESTINATION: &str = "platform=macOS";
/// Runs `program` in `dir` and returns its stdout; a failure carries its stderr.
fn output(dir: &Path, program: &str, args: &[String]) -> IdeResult<String> {
pub(crate) fn output(
dir: &Path,
program: &'static str,
args: &[String],
cancel: Option<&CancellationToken>,
) -> 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())));
let (success, stdout, stderr) = if let Some(cancel) = cancel {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let out = CliTool::new(program, Decoding::Utf8Lossy).run(cmd, Duration::from_secs(60 * 60), Some(cancel))?;
(out.success, out.stdout, out.stderr)
} else {
let out = ide_core::process::prepare(&mut cmd)
.output()
.map_err(|e| IdeError::unavailable(format!("Cannot run {program}: {e}")))?;
(
out.status.success(),
String::from_utf8_lossy(&out.stdout).into_owned(),
String::from_utf8_lossy(&out.stderr).into_owned(),
)
};
if !success {
return Err(IdeError::invalid(format!("{program} {} failed:\n{}", args.join(" "), stderr.trim())));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
Ok(stdout)
}
/// Reports a step of [`prepare`] to the run's console while no process is running yet.
@@ -535,7 +554,11 @@ fn build_settings(
params: &BTreeMap<String, String>,
destination: Option<&str>,
progress: Progress,
cancel: Option<&CancellationToken>,
) -> IdeResult<String> {
if cancel.is_some_and(CancellationToken::is_cancelled) {
return Err(IdeError::cancelled());
}
let args = [
build_args(params, destination).map_err(IdeError::invalid)?,
vec!["-showBuildSettings".into(), "-json".into()],
@@ -545,7 +568,7 @@ fn build_settings(
let scheme = params.get("scheme").map_or("", |s| s.trim());
progress(&format!("Reading the build settings of scheme {scheme}…"));
let started = std::time::Instant::now();
let settings = output(dir, "xcodebuild", &args)?;
let settings = output(dir, "xcodebuild", &args, cancel)?;
progress(&format!("Read the build settings in {:.1} s", started.elapsed().as_secs_f64()));
Ok(settings)
})
@@ -557,31 +580,62 @@ fn build_settings(
/// destination. The settings are read once for the simulator or device, which also tells whether
/// the app runs on the Mac instead; only a Mac app, or a scheme without that destination, reads
/// them again.
fn run_target(dir: &Path, params: &BTreeMap<String, String>, progress: Progress) -> IdeResult<(String, String)> {
fn run_target(
dir: &Path,
params: &BTreeMap<String, String>,
progress: Progress,
cancel: Option<&CancellationToken>,
) -> IdeResult<(String, String)> {
let simulator = params.get(SIMULATOR_PARAM).map_or("", String::as_str);
let configured = Some(simulator.trim()).filter(|s| !s.is_empty() && *s != MAC).map(str::to_owned);
let udid = configured.or_else(|| if simulator.trim() == MAC { None } else { default_simulator(dir) });
let default = || {
if cancel.is_some() {
let args = ["simctl", "list", "devices", "available", "-j"].map(String::from);
output(dir, "xcrun", &args, cancel).ok().and_then(|out| pick_simulator(&out))
} else {
default_simulator(dir)
}
};
let udid = configured.or_else(|| (simulator.trim() != MAC).then(default).flatten());
if let Some(udid) = &udid {
let device = format!("id={udid}");
if let Ok(settings) = build_settings(dir, params, Some(&device), progress)
if let Ok(settings) = build_settings(dir, params, Some(&device), progress, cancel)
&& !runs_on_mac(&settings, simulator).map_err(IdeError::invalid)?
{
return Ok((device, settings));
}
}
if runs_on_mac(&build_settings(dir, params, None, progress)?, simulator).map_err(IdeError::invalid)? {
return Ok((MAC_DESTINATION.to_owned(), build_settings(dir, params, Some(MAC_DESTINATION), progress)?));
if runs_on_mac(&build_settings(dir, params, None, progress, cancel)?, simulator).map_err(IdeError::invalid)? {
return Ok((MAC_DESTINATION.to_owned(), build_settings(dir, params, Some(MAC_DESTINATION), progress, cancel)?));
}
let udid = udid
.or_else(|| default_simulator(dir))
.ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?;
let udid = udid.or_else(default);
if cancel.is_some_and(CancellationToken::is_cancelled) {
return Err(IdeError::cancelled());
}
let udid = udid.ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?;
let device = format!("id={udid}");
Ok((device.clone(), build_settings(dir, params, Some(&device), progress)?))
Ok((device.clone(), build_settings(dir, params, Some(&device), progress, cancel)?))
}
/// The params of the configuration Run discovery lists first in `root` (its first scheme, built
/// through the root workspace): what Run builds unless another configuration is picked.
pub fn first_run_params(root: &Path) -> Option<BTreeMap<String, String>> {
let mut out = Vec::new();
crate::detect::xcode::detect(root, &mut out);
out.into_iter().next().map(|c| c.extras.params)
}
/// Where a run of `params` builds ([`run_target`]).
pub fn destination(dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<String> {
Ok(run_target(dir, params, &|_| {})?.0)
Ok(run_target(dir, params, &|_| {}, None)?.0)
}
pub(crate) fn index_destination(
dir: &Path,
params: &BTreeMap<String, String>,
cancel: &CancellationToken,
) -> IdeResult<String> {
Ok(run_target(dir, params, &|_| {}, Some(cancel))?.0)
}
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
@@ -600,7 +654,7 @@ pub fn prepare(dir: &Path, config: &mut crate::RunConfig, progress: Progress) ->
if let Some(reason) = configured.and_then(|u| devices.iter().find(|d| d.udid == u)).and_then(device_unready) {
return Err(IdeError::unavailable(reason));
}
let (destination, settings) = run_target(dir, params, progress)?;
let (destination, settings) = run_target(dir, params, progress, None)?;
if destination == MAC_DESTINATION {
let args = build_args(params, Some(MAC_DESTINATION)).map_err(IdeError::invalid)?;
let executable = mac_executable(&settings).map_err(IdeError::invalid)?;
+244
Переглянути файл
@@ -0,0 +1,244 @@
//! Low-priority Xcode builds for xcode-build-server's initial compiler arguments.
use ide_core::cli_process::{CliTool, Decoding};
use ide_core::error::ErrorKind;
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::Serialize;
use specta::Type;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use crate::xcode;
/// The DerivedData directory of the first scheme, using the selected project or workspace.
/// Used when generating the BSP config so a workspace's package schemes can be skipped.
pub fn first_scheme_build_root(root: &Path, container: &str) -> Option<PathBuf> {
let scheme = xcode::schemes(root).into_iter().next()?.name;
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
let args = [flag, container, "-scheme", &scheme, "-showBuildSettings", "-json"].map(String::from);
let out = xcode::output(root, "xcodebuild", &args, None).ok()?;
crate::xcode_clean::derived_data_of(&out)
}
/// The DerivedData folder an xcode-build-server `buildServer.json` at `root` reads build logs
/// from (`kind: xcode`, `build_root`); `None` for another server's config, or none.
fn xcode_build_root(root: &Path) -> Option<PathBuf> {
let text = std::fs::read_to_string(root.join("buildServer.json")).ok()?;
let config: serde_json::Value = serde_json::from_str(&text).ok()?;
if config.get("kind").and_then(|k| k.as_str()) != Some("xcode") {
return None;
}
config.get("build_root").and_then(|r| r.as_str()).filter(|r| !r.is_empty()).map(PathBuf::from)
}
/// Whether `build_root` has a build log for xcode-build-server to read: a build by Run or Xcode.
fn has_build_log(build_root: &Path) -> bool {
std::fs::read_to_string(build_root.join("Logs/Build/LogStoreManifest.plist"))
.is_ok_and(|manifest| manifest.contains(".xcactivitylog"))
}
/// Xcode's build database in `build_root`. While another process (Xcode's build service) has it
/// open, a second build of the folder fails with "database is locked".
fn build_db(build_root: &Path) -> PathBuf {
build_root.join("Build/Intermediates.noindex/XCBuildData/build.db")
}
/// Whether a process has `file` open (`lsof`), i.e. Xcode is building or has the project open.
fn in_use(file: &Path) -> bool {
if !file.exists() {
return false;
}
let mut cmd = Command::new("lsof");
ide_core::process::prepare(&mut cmd).arg("-t").arg("--").arg(file).stdin(Stdio::null()).stderr(Stdio::null());
cmd.output().is_ok_and(|o| !o.stdout.iter().all(u8::is_ascii_whitespace))
}
/// The target an `xcodebuild` step line names: `SwiftCompile … (in target 'Kit' from project 'App')`.
fn step_target(line: &str) -> Option<&str> {
let rest = &line[line.find("(in target '")? + "(in target '".len()..];
Some(&rest[..rest.find('\'')?])
}
/// What the background build for code insight did.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum XcodeIndexBuild {
/// Nothing to do: no xcode-build-server config, or DerivedData already has a build log.
NotNeeded,
/// Built; sourcekit-lsp restarted to read it.
Built,
/// Xcode is using the build folder: the build it makes (or made) serves instead.
XcodeBusy,
/// Stopped from the task list, or the project closed.
Cancelled,
/// The build failed; what it compiled still serves, sourcekit-lsp restarted.
Failed { message: String },
}
/// The configured build folder when sourcekit-lsp still needs its first build log.
pub fn pending_build_root(root: &Path) -> Option<PathBuf> {
xcode_build_root(root).filter(|build_root| !has_build_log(build_root))
}
/// Builds the same destination as Run and reports the targets as Xcode starts them.
pub fn build(
root: &Path,
build_root: &Path,
params: &BTreeMap<String, String>,
on_target: xcode::Progress,
cancel: &CancellationToken,
) -> IdeResult<XcodeIndexBuild> {
let result = (|| {
let destination = xcode::index_destination(root, params, cancel)?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if in_use(&build_db(build_root)) {
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)
})();
match result {
Err(e) if e.kind == ErrorKind::Cancelled => Ok(XcodeIndexBuild::Cancelled),
outcome => outcome,
}
}
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);
let (success, _) = CliTool::new("xcodebuild", Decoding::Utf8Lossy).stream(cmd, cancel, &mut |_, line| {
if let Some(t) = step_target(&line).filter(|t| *t != target) {
target = t.to_owned();
on_target(&target);
}
locked |= line.contains("database is locked");
if (line.contains(" error: ") || line.starts_with("error: ")) && errors.len() < MAX_ERRORS {
let error = line.trim().to_owned();
if !errors.contains(&error) {
errors.push(error);
}
}
tail.push(line);
let excess = tail.len().saturating_sub(MAX_ERRORS);
tail.drain(..excess);
})?;
Ok(if success {
XcodeIndexBuild::Built
} else if locked {
XcodeIndexBuild::XcodeBusy
} else {
let lines = if errors.is_empty() { tail } else { errors };
XcodeIndexBuild::Failed { message: lines.join("\n") }
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builds_only_for_an_xcode_build_server_config_without_a_build_log() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
assert_eq!(xcode_build_root(root), None);
let dd = root.join("DerivedData/App-abc");
let config =
|kind: &str| format!(r#"{{"name":"xcode build server","kind":"{kind}","build_root":"{}"}}"#, dd.display());
std::fs::write(root.join("buildServer.json"), config("manual")).unwrap();
assert_eq!(xcode_build_root(root), None, "a hand-written .compile config");
std::fs::write(root.join("buildServer.json"), r#"{"name":"sourcekit-xcode-bsp","argv":["x"]}"#).unwrap();
assert_eq!(xcode_build_root(root), None, "another build server prepares targets itself");
std::fs::write(root.join("buildServer.json"), config("xcode")).unwrap();
assert_eq!(xcode_build_root(root), Some(dd.clone()));
assert!(!has_build_log(&dd));
let logs = dd.join("Logs/Build");
std::fs::create_dir_all(&logs).unwrap();
// What a build folder holds after a clean: a manifest without logs.
let manifest = |logs: &str| {
format!(
r#"<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict><key>logFormatVersion</key><integer>11</integer><key>logs</key><dict>{logs}</dict></dict></plist>"#
)
};
std::fs::write(logs.join("LogStoreManifest.plist"), manifest("")).unwrap();
assert!(!has_build_log(&dd));
std::fs::write(
logs.join("LogStoreManifest.plist"),
manifest("<key>F6</key><dict><key>fileName</key><string>F6.xcactivitylog</string></dict>"),
)
.unwrap();
assert!(has_build_log(&dd));
}
#[test]
fn reads_the_target_of_a_build_step() {
assert_eq!(
step_target("SwiftCompile normal arm64 /p/Kit/Greeter.swift (in target 'Kit' from project 'A11Demo')"),
Some("Kit")
);
assert_eq!(step_target(" cd /p"), None);
assert_eq!(step_target("** BUILD SUCCEEDED **"), None);
assert_eq!(step_target("(in target 'Unterminated"), None);
}
#[cfg(target_os = "macos")]
#[test]
fn sees_a_build_database_another_process_has_open() {
let tmp = tempfile::tempdir().unwrap();
let db = build_db(tmp.path());
assert!(!in_use(&db), "no build folder yet");
std::fs::create_dir_all(db.parent().unwrap()).unwrap();
std::fs::write(&db, "").unwrap();
assert!(!in_use(&db));
let open = std::fs::File::open(&db).unwrap();
assert!(in_use(&db));
drop(open);
assert!(!in_use(&db));
}
#[cfg(unix)]
#[test]
fn cancelling_settings_and_build_reaps_the_child() {
use std::time::{Duration, Instant};
for reading_settings in [true, false] {
let tmp = tempfile::tempdir().unwrap();
let pid_file = tmp.path().join("pid");
let args = ["-c", "echo $$ > \"$1\"; while :; do sleep 1; done", "xcodebuild", pid_file.to_str().unwrap()]
.map(String::from);
let cancel = CancellationToken::new();
let canceller = std::thread::spawn({
let cancel = cancel.clone();
move || {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
if let Some(pid) = std::fs::read_to_string(&pid_file).ok().filter(|s| !s.trim().is_empty()) {
cancel.cancel();
break pid;
}
if Instant::now() >= deadline {
cancel.cancel();
panic!("Xcode child did not start");
}
std::thread::sleep(Duration::from_millis(10));
}
}
});
let result = if reading_settings {
xcode::output(tmp.path(), "/bin/sh", &args, Some(&cancel)).map(|_| ())
} else {
let mut cmd = Command::new("/bin/sh");
cmd.args(&args).current_dir(tmp.path());
run_build(cmd, &|_| {}, &cancel).map(|_| ())
};
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
let pid = canceller.join().unwrap();
assert!(!Command::new("/bin/kill").args(["-0", pid.trim()]).output().unwrap().status.success());
}
}
}
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ sourcekit-lsp cannot read `.xcodeproj` or `.xcworkspace` files. Without a build
xcode-build-server config -workspace App.xcworkspace -scheme App
```
Use `-project App.xcodeproj` instead of `-workspace` for a project without a workspace. xcode-build-server takes the compile flags from Xcode's build logs, so build the scheme once in Xcode or with `xcodebuild` first, and build again after adding files or changing build settings.
Use `-project App.xcodeproj` instead of `-workspace` for a project without a workspace. xcode-build-server takes the compile flags from Xcode's build logs, so build the scheme once in Xcode or with `xcodebuild` first, and build again after adding files or changing build settings. When the project has no build log yet, the IDE builds what Run builds once in the background, at low priority (**Building … for code insight** in the status bar, with Cancel), and restarts sourcekit-lsp when it ends; Run then builds on top of it. It skips this while Xcode is using the build folder. Turn it off with **Settings › Build, Execution, Deployment › Compiler › Build Xcode projects in the background for code insight**.
- **[sourcekit-xcode-bsp](https://github.com/slime-studio/sourcekit-xcode-bsp)**: needs Xcode 26 or newer. Install it with `brew install slime-studio/tap/sourcekit-xcode-bsp` and run `sourcekit-xcode-bsp init` in the project root; it finds the `.xcworkspace` or `.xcodeproj` itself and targets the iOS Simulator by default (the `platform` field in `buildServer.json`). It is an early release (0.1.x).
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ sourcekit-lsp 读不了 `.xcodeproj` 和 `.xcworkspace`。没有构建服务器
xcode-build-server config -workspace App.xcworkspace -scheme App
```
没有 workspace 的项目把 `-workspace` 换成 `-project App.xcodeproj`。xcode-build-server 从 Xcode 的构建日志中读取编译参数,所以要先在 Xcode 里或用 `xcodebuild` 构建一次该 scheme;新增文件或修改构建设置后也要重新构建。
没有 workspace 的项目把 `-workspace` 换成 `-project App.xcodeproj`。xcode-build-server 从 Xcode 的构建日志中读取编译参数,所以要先在 Xcode 里或用 `xcodebuild` 构建一次该 scheme;新增文件或修改构建设置后也要重新构建。项目还没有构建日志时,IDE 会在后台以低优先级构建一次运行所构建的内容(状态栏显示 **Building … for code insight**,可取消),结束后重启 sourcekit-lsp;之后的运行在此基础上增量构建。Xcode 正在使用该构建文件夹时会跳过。可在 **设置 › 构建、执行、部署 › 编译器 › 在后台构建 Xcode 项目以提供代码智能** 中关闭。
- **[sourcekit-xcode-bsp](https://github.com/slime-studio/sourcekit-xcode-bsp)**:需要 Xcode 26 及以上版本。用 `brew install slime-studio/tap/sourcekit-xcode-bsp` 安装,然后在项目根目录执行 `sourcekit-xcode-bsp init`;它会自己找到 `.xcworkspace` 或 `.xcodeproj`,默认面向 iOS 模拟器(即 `buildServer.json` 中的 `platform` 字段)。它还处于早期版本(0.1.x)。
+1
Переглянути файл
@@ -1021,3 +1021,4 @@ xcode_bsp_setup trusted project_host bin
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
xcode_index_build trusted project_host bindings async
+26
Переглянути файл
@@ -3003,6 +3003,14 @@ export const commands = {
{ kind: "generated"; dir: string; tool: string } |
/** `files` (file names) are not named in `project`, a classic `.xcodeproj`. */
{ kind: "notInProject"; project: string; files: string[] } | null, IdeError>(__TAURI_INVOKE("xcode_file_sync", { created, removed })),
/**
* Builds what Run builds (its first configuration, for its destination) at low priority
* (`taskpolicy -c utility`), when the project's xcode-build-server config has no build log to
* read yet: until then sourcekit-lsp has no compiler arguments, so types from other targets and
* packages don't resolve. A cancellable background task; it backs off while Xcode uses the build
* folder. Run later builds incrementally on top of it.
*/
xcodeIndexBuild: () => typedError<XcodeIndexBuild, IdeError>(__TAURI_INVOKE("xcode_index_build")),
};
/* Types */
@@ -5888,6 +5896,11 @@ export type BuildSettings = {
openToolWindow?: string,
/** When to focus the Build tool window: `always` | `onError` | `never`. */
focusToolWindow?: string,
/**
* Build an Xcode project in the background when xcode-build-server has no build log to read
* yet, so cross-file code insight works before the first Run.
*/
xcodeIndexBuild?: boolean,
};
export type BuildSystem = "maven" | "gradle" | "cargo" | "go" | "typescript" | "cmake" | "dotnet" |
@@ -18064,6 +18077,19 @@ export type XcodeFileSync =
/** `files` (file names) are not named in `project`, a classic `.xcodeproj`. */
{ kind: "notInProject"; project: string; files: string[] };
/** What the background build for code insight did. */
export type XcodeIndexBuild =
/** Nothing to do: no xcode-build-server config, or DerivedData already has a build log. */
{ kind: "notNeeded" } |
/** Built; sourcekit-lsp restarted to read it. */
{ kind: "built" } |
/** Xcode is using the build folder: the build it makes (or made) serves instead. */
{ kind: "xcodeBusy" } |
/** Stopped from the task list, or the project closed. */
{ kind: "cancelled" } |
/** The build failed; what it compiled still serves, sourcekit-lsp restarted. */
{ kind: "failed"; message: string };
export type ZigSettings = {
/** Directory holding the `zig` executable; empty = the one on `PATH`. */
zig?: string,
+8
Переглянути файл
@@ -204,6 +204,8 @@ export const EXECUTION_PAGES: PageSpec[] = [
"Focus Build tool window",
"automatic build",
"before launch",
"Xcode",
"code insight",
],
sections: [
{
@@ -222,6 +224,12 @@ export const EXECUTION_PAGES: PageSpec[] = [
options: BUILD_WINDOW_WHEN,
hint: "When Build opens, whether it takes keyboard focus from the editor.",
},
{
kind: "toggle",
key: "build.xcodeIndexBuild",
label: "Build Xcode projects in the background for code insight",
hint: "Until an Xcode project's first build, sourcekit-lsp can't resolve types from its other targets. Builds what Run builds, at low priority, once.",
},
],
},
],
+27 -2
Переглянути файл
@@ -1,5 +1,15 @@
import { describe, expect, it } from "vitest";
import { bspStep } from "./xcodeBsp";
import { describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { bspStep, checkXcodeBsp } from "./xcodeBsp";
const { xcodeBspSetup, xcodeIndexBuild } = vi.hoisted(() => ({
xcodeBspSetup: vi.fn(async () => ({ status: "ok", data: null })),
xcodeIndexBuild: vi.fn(async () => ({ status: "ok", data: { kind: "built" } })),
}));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, isTauri: () => true, commands: { ...actual.commands, xcodeBspSetup, xcodeIndexBuild } };
});
describe("Xcode build server config on project open", () => {
const tool = { tool: "xcode-build-server" };
@@ -24,4 +34,19 @@ describe("Xcode build server config on project open", () => {
expect(bspStep(true, tool, true, true)).toBe("generate");
expect(bspStep(true, missing, true, true)).toBe("hint");
});
it("builds after a config was added manually despite a remembered installation hint", async () => {
const root = "/p/xcode";
const key = "openidea.xcodeBsp.v2";
localStorage.setItem(key, JSON.stringify([root]));
useProject.setState({ project: { root, trusted: true } as never });
try {
await checkXcodeBsp();
expect(xcodeBspSetup).toHaveBeenCalledOnce();
expect(xcodeIndexBuild).toHaveBeenCalledOnce();
} finally {
useProject.setState({ project: null });
localStorage.removeItem(key);
}
});
});
+32 -3
Переглянути файл
@@ -5,11 +5,16 @@
* whichever is on PATH; the backend keeps it out of Git (`.git/info/exclude`) and restarts
* sourcekit-lsp. A config that exists is never replaced. With neither tool installed it says,
* once per root, how to install one: the IDE does not install them itself.
*
* xcode-build-server reads compiler arguments from the project's last build, so until then
* cross-file code insight doesn't work. Unless Settings › Build › Compiler turns it off, the
* backend builds what Run builds in the background (`xcodeIndexBuild`) when there is no build yet.
*/
import { registerActions } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
// v2: v1 remembered every root it offered to generate for, which would now skip generating.
@@ -48,6 +53,25 @@ export function bspStep(
return setup.tool ? "generate" : "hint";
}
/** Builds the open project once in the background when its build server has no build to read. */
async function indexBuild(root: string) {
if (!workflowSettings().build.xcodeIndexBuild) return;
let result;
try {
result = await call(commands.xcodeIndexBuild());
} catch (e) {
result = { kind: "failed" as const, message: e instanceof Error ? e.message : String(e) };
}
if (result.kind !== "failed" || useProject.getState().project?.root !== root) return;
notifications().notify({
group: "tools",
level: "warning",
key: hintKey(root),
title: "Background build for code insight failed",
body: `${tx("Code insight reads what it built. Run shows the whole build log.")}\n\n${result.message}`,
});
}
async function generate(root: string, tool: string, container: string) {
const key = hintKey(root);
try {
@@ -57,8 +81,11 @@ async function generate(root: string, tool: string, container: string) {
level: "info",
key,
title: "Build server config generated",
body: tx`Code insight for ${container} reads its last build: Run, or a build in Xcode, refreshes it.`,
body: workflowSettings().build.xcodeIndexBuild
? tx`Code insight for ${container} reads its last build. Without one yet, it is built in the background.`
: tx`Code insight for ${container} reads its last build: Run, or a build in Xcode, refreshes it.`,
});
await indexBuild(root);
} catch (e) {
rememberHint(root);
notifications().notify({
@@ -75,11 +102,13 @@ async function generate(root: string, tool: string, container: string) {
/** Generates the open project's config, or says how to install a generator ([`bspStep`]). */
export async function checkXcodeBsp(again = false) {
const project = useProject.getState().project;
if (!project?.trusted || !isTauri() || (!again && hinted().includes(project.root))) return;
if (!project?.trusted || !isTauri()) return;
const setup = await call(commands.xcodeBspSetup());
if (useProject.getState().project?.root !== project.root) return;
// Configured already (or no Xcode project: the backend does nothing then).
if (!setup) return indexBuild(project.root);
const step = bspStep(project.trusted, setup, hinted().includes(project.root), again);
if (!setup || !step) return;
if (!step) return;
const { container, tool } = setup;
if (step === "generate" && tool) return generate(project.root, tool, container);
rememberHint(project.root);
+6 -1
Переглянути файл
@@ -5119,5 +5119,10 @@
"Cannot find root-relative module \"{rawSpec}\"": "Cannot find root-relative module \"{rawSpec}\"",
"Cannot resolve module \"{rawSpec}\" from {importerPath}": "Cannot resolve module \"{rawSpec}\" from {importerPath}",
"Open External Link?": "Open External Link?",
"This MDX preview wants to open an external URL in your browser:": "This MDX preview wants to open an external URL in your browser:"
"This MDX preview wants to open an external URL in your browser:": "This MDX preview wants to open an external URL in your browser:",
"Build Xcode projects in the background for code insight": "Build Xcode projects in the background for code insight",
"Until an Xcode project's first build, sourcekit-lsp can't resolve types from its other targets. Builds what Run builds, at low priority, once.": "Until an Xcode project's first build, sourcekit-lsp can't resolve types from its other targets. Builds what Run builds, at low priority, once.",
"Code insight for {container} reads its last build. Without one yet, it is built in the background.": "Code insight for {container} reads its last build. Without one yet, it is built in the background.",
"Background build for code insight failed": "Background build for code insight failed",
"Code insight reads what it built. Run shows the whole build log.": "Code insight reads what it built. Run shows the whole build log."
}
+5
Переглянути файл
@@ -11954,6 +11954,11 @@
"Cannot resolve module \"{rawSpec}\" from {importerPath}": "无法从 {importerPath} 解析模块 \"{rawSpec}\"",
"Open External Link?": "打开外部链接?",
"This MDX preview wants to open an external URL in your browser:": "此 MDX 预览请求在浏览器中打开外部链接:",
"Build Xcode projects in the background for code insight": "在后台构建 Xcode 项目以提供代码智能",
"Until an Xcode project's first build, sourcekit-lsp can't resolve types from its other targets. Builds what Run builds, at low priority, once.": "Xcode 项目首次构建之前,sourcekit-lsp 无法解析来自其他 target 的类型。以低优先级构建一次运行所构建的内容。",
"Code insight for {container} reads its last build. Without one yet, it is built in the background.": "{container} 的代码智能读取最近一次构建。尚无构建时,会在后台构建。",
"Background build for code insight failed": "为代码智能进行的后台构建失败",
"Code insight reads what it built. Run shows the whole build log.": "代码智能会读取已构建的部分。运行可查看完整的构建日志。",
"Show list": "显示列表",
"Maven home directory is invalid: its bin folder has no mvn": "Maven 主目录无效:其 bin 文件夹中没有 mvn",
"The directory does not exist": "该目录不存在",
+13 -5
Переглянути файл
@@ -135,14 +135,22 @@ describe("validateWorkflow", () => {
});
it("defaults Build tool window open/focus and rejects unknown values", () => {
expect(DEFAULT_WORKFLOW.build).toEqual({ openToolWindow: "always", focusToolWindow: "never" });
expect(validateWorkflow({ build: { openToolWindow: "onError", focusToolWindow: "always" } }).build).toEqual({
expect(DEFAULT_WORKFLOW.build).toEqual({
openToolWindow: "always",
focusToolWindow: "never",
xcodeIndexBuild: true,
});
expect(
validateWorkflow({ build: { openToolWindow: "onError", focusToolWindow: "always", xcodeIndexBuild: false } })
.build,
).toEqual({
openToolWindow: "onError",
focusToolWindow: "always",
xcodeIndexBuild: false,
});
expect(validateWorkflow({ build: { openToolWindow: "sometimes", focusToolWindow: 1 } }).build).toEqual(
DEFAULT_WORKFLOW.build,
);
expect(
validateWorkflow({ build: { openToolWindow: "sometimes", focusToolWindow: 1, xcodeIndexBuild: "no" } }).build,
).toEqual(DEFAULT_WORKFLOW.build);
});
it("defaults debugger hotSwapAfterCompile to ask and validates enum options", () => {
+4
Переглянути файл
@@ -135,6 +135,8 @@ export interface LogLevelColorsValid {
export interface BuildSettingsValid {
openToolWindow: BuildToolWindowWhen;
focusToolWindow: BuildToolWindowWhen;
/** Build an Xcode project in the background until it has a build log for code insight. */
xcodeIndexBuild: boolean;
}
export interface ConsoleSettingsValid {
@@ -390,6 +392,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
build: {
openToolWindow: "always",
focusToolWindow: "never",
xcodeIndexBuild: true,
},
console: {
softWrap: false,
@@ -608,6 +611,7 @@ export function validateBuild(raw: unknown): BuildSettingsValid {
return {
openToolWindow: oneOf(v.openToolWindow, when, d.openToolWindow),
focusToolWindow: oneOf(v.focusToolWindow, when, d.focusToolWindow),
xcodeIndexBuild: bool(v.xcodeIndexBuild, d.xcodeIndexBuild),
};
}