feat(swift): choose the Xcode a project uses and pass it to its tools as DEVELOPER_DIR (#6964)

Settings > Languages > Swift gets an Xcode field (empty = the xcode-select one). For a trusted project the chosen Xcode.app or Contents/Developer becomes DEVELOPER_DIR in the project environment, so sourcekit-lsp, xcodebuild, xcrun, simulators, debug adapters and terminals use it; it overrides a DEVELOPER_DIR from .envrc and is not applied to untrusted projects or LightEdit.

Closes #6963

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-30 20:43:48 +08:00
1 джерело 485d7bf99d
коміт 0cfabdbbbd
28 files changed
+403 -32

No files matched your search

+23
Переглянути файл
@@ -1176,6 +1176,29 @@ mod tests {
set_env_overlay(Vec::new());
}
#[test]
fn a_child_inside_a_project_gets_its_xcode() {
let root = std::path::Path::new("/openidea-test-process/xcode");
let xcode = "/Applications/Xcode-beta.app/Contents/Developer";
crate::project_env::set_developer_dir(root, Some(xcode.into()));
let developer_dir = |cmd: &Command| {
cmd.get_envs().find(|(n, _)| *n == "DEVELOPER_DIR").and_then(|(_, v)| v.map(OsStr::to_owned))
};
// xcodebuild, xcrun, a language server: a `Command` started in the project.
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root.join("App")));
assert_eq!(developer_dir(&tool), Some(xcode.into()));
// A terminal: a PTY applies the fixes itself.
assert!(host_env_fixes_in(root).contains(&("DEVELOPER_DIR".into(), Some(xcode.into()))));
let mut elsewhere = Command::new("xcodebuild");
prepare(elsewhere.current_dir("/openidea-test-process/other"));
assert_eq!(developer_dir(&elsewhere), None);
crate::project_env::set_developer_dir(root, None);
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root));
assert_eq!(developer_dir(&tool), None, "empty: the system default");
}
#[test]
fn a_child_inside_a_project_gets_its_environment() {
let root = std::path::Path::new("/openidea-test-process/project");
+62 -2
Переглянути файл
@@ -16,13 +16,21 @@ struct Entry {
root: PathBuf,
direnv: Vec<(OsString, Option<OsString>)>,
github_token: Option<OsString>,
developer_dir: Option<OsString>,
changes: Changes,
loading: bool,
}
impl Entry {
fn new(root: PathBuf) -> Self {
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
Self {
root,
direnv: Vec::new(),
github_token: None,
developer_dir: None,
changes: Changes::default(),
loading: false,
}
}
fn rebuild(&mut self) {
@@ -33,11 +41,16 @@ impl Entry {
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
combined.extend(self.direnv.iter().cloned());
// The project's chosen Xcode overrides a `DEVELOPER_DIR` from `.envrc`: it is set for this project only.
if let Some(dir) = &self.developer_dir {
combined.retain(|(k, _)| k != DEVELOPER_DIR);
combined.push((DEVELOPER_DIR.into(), Some(dir.clone())));
}
self.changes = Arc::new(combined);
}
fn is_idle_empty(&self) -> bool {
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
!self.loading && self.direnv.is_empty() && self.github_token.is_none() && self.developer_dir.is_none()
}
}
@@ -144,6 +157,31 @@ pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
}
}
const DEVELOPER_DIR: &str = "DEVELOPER_DIR";
/// Sets or clears the `DEVELOPER_DIR` (the Xcode `xcrun`, `xcodebuild` and sourcekit-lsp use)
/// injected for children started in `root`. Returns whether it changed.
pub fn set_developer_dir(root: &Path, dir: Option<OsString>) -> bool {
let dir = dir.filter(|d| !d.is_empty());
let mut entries = entries();
let idx = match entries.iter().position(|e| e.root == root) {
Some(idx) if entries[idx].developer_dir == dir => return false,
Some(idx) => idx,
None if dir.is_none() => return false,
None => {
entries.push(Entry::new(root.to_path_buf()));
entries.len() - 1
}
};
let entry = &mut entries[idx];
entry.developer_dir = dir;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
true
}
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
pub fn github_token(dir: &Path) -> Option<OsString> {
find(&entries(), dir).and_then(|e| e.github_token.clone())
@@ -202,6 +240,28 @@ mod tests {
assert!(for_dir(inner).is_empty());
}
#[test]
fn the_projects_xcode_wins_over_envrc_and_clears() {
let root = Path::new("/openidea-test-env/xcode");
set(root, vec![change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
assert!(set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert!(!set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert_eq!(
*for_dir(&root.join("App")),
[change("A", Some("1")), change("DEVELOPER_DIR", Some("/Applications/Xcode-beta.app/Contents/Developer"))]
);
assert!(set_developer_dir(root, None));
assert_eq!(*for_dir(root), [change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
remove(root);
assert!(for_dir(root).is_empty());
let alone = Path::new("/openidea-test-env/xcode-alone");
assert!(!set_developer_dir(alone, Some("".into())), "empty is the system default");
assert!(set_developer_dir(alone, Some("/X".into())));
assert_eq!(*for_dir(alone), [change("DEVELOPER_DIR", Some("/X"))]);
assert!(set_developer_dir(alone, None));
assert!(entries().iter().all(|e| e.root != alone), "an empty entry is dropped");
}
#[test]
fn waiting_ends_once_the_environment_is_read() {
let root = Path::new("/openidea-test-env/waiting");
+36
Переглянути файл
@@ -1452,6 +1452,7 @@ pub struct LanguagesSettings {
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
pub swift: SwiftSettings,
}
impl Default for LanguagesSettings {
@@ -1485,6 +1486,7 @@ impl Default for LanguagesSettings {
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
swift: SwiftSettings::default(),
}
}
}
@@ -1769,6 +1771,26 @@ pub struct ZigSettings {
pub zig: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SwiftSettings {
/// The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
/// `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
pub xcode: String,
}
impl SwiftSettings {
/// [`Self::xcode`] as a `DEVELOPER_DIR` value (`Xcode.app` gets `/Contents/Developer`); `None` when unset.
pub fn developer_dir(&self) -> Option<std::path::PathBuf> {
let xcode = self.xcode.trim();
if xcode.is_empty() {
return None;
}
let path = std::path::Path::new(xcode);
Some(if path.extension().is_some_and(|e| e == "app") { path.join("Contents/Developer") } else { path.into() })
}
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -2179,6 +2201,20 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn the_xcode_setting_becomes_a_developer_dir() {
let dir = |xcode: &str| SwiftSettings { xcode: xcode.into() }.developer_dir();
assert_eq!(dir(""), None);
assert_eq!(dir(" "), None);
assert_eq!(dir("/Applications/Xcode-beta.app"), Some("/Applications/Xcode-beta.app/Contents/Developer".into()));
assert_eq!(
dir("/Applications/Xcode.app/Contents/Developer"),
Some("/Applications/Xcode.app/Contents/Developer".into())
);
let s: Settings = serde_json::from_str(r#"{"languages":{"swift":{"xcode":"/X.app"}}}"#).unwrap();
assert_eq!(s.languages.swift.xcode, "/X.app");
}
#[test]
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
+7 -4
Переглянути файл
@@ -362,21 +362,24 @@ fn find_binary_in(
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
/// lldb-dap without putting it on `PATH`.
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
find_binary(command, cwd).or_else(|| xcrun_tool(command))
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
}
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
#[cfg(target_os = "macos")]
fn xcrun_tool(command: &str) -> Option<PathBuf> {
fn xcrun_tool(command: &str, cwd: &Path) -> Option<PathBuf> {
if command != "lldb-dap" {
return None;
}
let out = std::process::Command::new("/usr/bin/xcrun").args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let mut cmd = std::process::Command::new("/usr/bin/xcrun");
cmd.current_dir(cwd);
let out = ide_core::process::prepare(&mut cmd).args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let path = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
(out.status.success() && is_executable(&path, false)).then_some(path)
}
#[cfg(not(target_os = "macos"))]
fn xcrun_tool(_command: &str) -> Option<PathBuf> {
fn xcrun_tool(_command: &str, _cwd: &Path) -> Option<PathBuf> {
None
}
+1
Переглянути файл
@@ -31,6 +31,7 @@ pub mod trust;
mod ts_code_style;
mod tsc_watch;
pub mod web_server;
mod xcode_env;
pub use project::{Project, history_retention};
+1 -1
Переглянути файл
@@ -17,7 +17,7 @@ pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<I
if !cfg!(target_os = "macos") || !simulator::is_xcode_project(&root) {
return Ok(None);
}
blocking(simulator::list).await.map(Some)
blocking(move || simulator::list(&root)).await.map(Some)
}
/// Boots a simulator; returns once it is booted.
+6
Переглянути файл
@@ -468,6 +468,12 @@ pub fn set_settings(
}
});
}
if ["languages", "languages.swift", "languages.swift.xcode"].contains(&key) {
// An untrusted project keeps no Xcode of its own (see `xcode_env`).
for project in affected().into_iter().filter(|p| p.is_trusted()) {
host.runtime.spawn(async move { crate::xcode_env::apply_and_restart(&project).await });
}
}
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
for project in affected() {
+2 -1
Переглянути файл
@@ -575,9 +575,10 @@ async fn start_inner(
}
if config.kind == "xcode-test" {
let bundles = project.cache_dir.join("xcresult");
let dir = project.root.clone();
config = host
.blocking(move || {
ide_run::xcode::prepare_test(&mut config, &bundles)?;
ide_run::xcode::prepare_test(&mut config, &dir, &bundles)?;
Ok(config)
})
.await?;
+2
Переглянути файл
@@ -30,6 +30,8 @@ pub async fn run_xcode_test_results(host: &Host, window: &str, bundle: std::path
return Err(IdeError::invalid("Not an Xcode result bundle"));
}
let mut cmd = tokio::process::Command::new("xcrun");
// The project's Xcode reads the bundle its `xcodebuild` wrote.
cmd.current_dir(&host.project(window)?.root);
cmd.args(["xcresulttool", "get", "test-results", "tests", "--compact", "--path"]).arg(&bundle);
ide_core::process::prepare(cmd.as_std_mut());
let out = cmd.output().await?;
+2
Переглянути файл
@@ -773,6 +773,8 @@ impl Host {
let weak = Arc::downgrade(&project);
project.agents.set_git_enabled_hook(Arc::new(move || weak.upgrade().is_some_and(|p| p.git_enabled())));
}
// Before anything starts a language server or a tool in the project; a trusted project only.
crate::xcode_env::apply(&project);
self.insert_project(window, project.clone());
for (key, text, dirty) in &carried {
let _ = project.documents.restore_untitled_buffer(key, text, *dirty);
+2
Переглянути файл
@@ -276,6 +276,8 @@ impl crate::Host {
}
project.lsp.set_execution_allowed(false);
}
// Before anything runs `git` (a `/usr/bin` shim that follows `DEVELOPER_DIR`): set or cleared.
crate::xcode_env::apply(&project);
project.repos();
if trusted {
if let Some(cmd) = self.environment.project_opened(&project.root, &project.sink) {
+49
Переглянути файл
@@ -0,0 +1,49 @@
//! The project's Xcode (`languages.swift.xcode`): every child started in the project gets it as
//! `DEVELOPER_DIR` through [`ide_core::project_env`] — sourcekit-lsp, `xcodebuild` and `xcrun` of
//! runs, tests, coverage and debugging, and terminals.
use crate::project::Project;
use ide_core::settings::SwiftSettings;
use std::path::PathBuf;
/// The `DEVELOPER_DIR` a project's children get. Only a trusted project's: the setting lives in the
/// repository (`.openidea/settings.toml`), and the `/usr/bin` shims (`git`, `xcrun`, `clang`, …)
/// run `$DEVELOPER_DIR/usr/bin/<tool>`, so an untrusted one could point them at its own binaries.
fn developer_dir(trusted: bool, swift: &SwiftSettings) -> Option<PathBuf> {
trusted.then(|| swift.developer_dir()).flatten()
}
/// Applies the project's Xcode to its environment, or clears it for an untrusted project; returns
/// whether it changed.
pub fn apply(project: &Project) -> bool {
let trusted = project.is_trusted() && !project.light;
let dir = developer_dir(trusted, &project.settings.effective().languages.swift).map(Into::into);
let root = ide_core::project_env::set_developer_dir(&project.root, dir.clone());
let worktrees = ide_core::project_env::set_developer_dir(project.agents.worktrees_dir(), dir);
root || worktrees
}
/// [`apply`], then restarts a running sourcekit-lsp when the Xcode changed.
pub async fn apply_and_restart(project: &Project) {
if !apply(project) {
return;
}
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
if let Err(e) = project.lsp.restart(server.id).await {
tracing::warn!("restarting sourcekit-lsp for the new Xcode: {e}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_trusted_project_gets_its_xcode() {
let swift = SwiftSettings { xcode: "./x.app".into() };
assert_eq!(developer_dir(false, &swift), None, "untrusted: the repository's own binaries must not run");
assert_eq!(developer_dir(true, &swift), Some("./x.app/Contents/Developer".into()));
assert_eq!(developer_dir(true, &SwiftSettings::default()), None);
}
}
+11 -6
Переглянути файл
@@ -67,8 +67,12 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
Ok(devices.into_iter().map(|(_, d)| d).collect())
}
fn run(program: &str, args: &[&str]) -> IdeResult<String> {
/// `dir`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult<String> {
let mut cmd = Command::new(program);
if let Some(dir) = dir {
cmd.current_dir(dir);
}
prepare(&mut cmd).args(args);
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("could not run {program}: {e}")))?;
if out.status.success() {
@@ -79,22 +83,23 @@ fn run(program: &str, args: &[&str]) -> IdeResult<String> {
}
/// The available iOS simulators, sorted as [`parse_list`] does.
pub fn list() -> IdeResult<Vec<IosSimulator>> {
parse_list(&run("xcrun", &["simctl", "list", "devices", "available", "--json"])?)
/// The available iOS simulators of the Xcode the project at `root` uses.
pub fn list(root: &Path) -> IdeResult<Vec<IosSimulator>> {
parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)
}
/// Boots a simulator; returns once `simctl` has it booted.
pub fn boot(udid: &str) -> IdeResult<()> {
run("xcrun", &["simctl", "boot", udid]).map(drop)
run_in(None, "xcrun", &["simctl", "boot", udid]).map(drop)
}
pub fn shutdown(udid: &str) -> IdeResult<()> {
run("xcrun", &["simctl", "shutdown", udid]).map(drop)
run_in(None, "xcrun", &["simctl", "shutdown", udid]).map(drop)
}
/// Brings Simulator.app to the front, which shows the booted simulators.
pub fn open_app() -> IdeResult<()> {
run("open", &["-a", "Simulator"]).map(drop)
run_in(None, "open", &["-a", "Simulator"]).map(drop)
}
#[cfg(test)]
+8 -7
Переглянути файл
@@ -156,9 +156,9 @@ 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.
pub fn prepare_test(config: &mut crate::RunConfig, bundles: &Path) -> std::io::Result<()> {
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()
&& let Some(udid) = default_simulator(dir)
{
config.args.extend(["-destination".to_owned(), format!("id={udid}")]);
}
@@ -178,10 +178,11 @@ pub fn prepare_test(config: &mut crate::RunConfig, bundles: &Path) -> std::io::R
Ok(())
}
/// The booted iOS simulator, otherwise the first iPhone of the newest iOS runtime.
pub fn default_simulator() -> Option<String> {
/// The booted iOS simulator, otherwise the first iPhone of the newest iOS runtime. `dir` (inside
/// the project) picks the project's Xcode.
pub fn default_simulator(dir: &Path) -> Option<String> {
let mut cmd = std::process::Command::new("xcrun");
cmd.args(["simctl", "list", "devices", "available", "-j"]);
cmd.args(["simctl", "list", "devices", "available", "-j"]).current_dir(dir);
let out = ide_core::process::prepare(&mut cmd).output().ok()?;
pick_simulator(&String::from_utf8_lossy(&out.stdout))
}
@@ -380,7 +381,7 @@ pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data:
}
let udid = match Some(simulator.trim()).filter(|s| !s.is_empty() && *s != MAC) {
Some(udid) => udid.to_owned(),
None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
None => default_simulator(dir).ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
};
Ok(format!("id={udid}"))
}
@@ -531,7 +532,7 @@ mod tests {
allow_parallel: false,
extras: Default::default(),
};
prepare_test(&mut config, dir.path()).unwrap();
prepare_test(&mut config, dir.path(), dir.path()).unwrap();
assert_eq!(config.args[..3], ["test", "-destination", "id=X"]);
assert_eq!(config.args[3], "-resultBundlePath");
assert!(config.args[4].contains("xcode_test_A-") && config.args[4].ends_with(".xcresult"));
+53 -1
Переглянути файл
@@ -33,6 +33,7 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Zig => zig(),
SdkKind::Dotnet => dotnet(),
SdkKind::Flutter => crate::flutter::detect(),
SdkKind::Xcode => xcode(),
};
if let Some(root) = root {
pinned_first(&mut out, kind, root);
@@ -54,7 +55,8 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
| SdkKind::Rust
| SdkKind::TypeScript
| SdkKind::Dotnet
| SdkKind::Flutter => None,
| SdkKind::Flutter
| SdkKind::Xcode => None,
}
}
@@ -1219,6 +1221,56 @@ fn zig() -> Vec<Sdk> {
})
}
/// Xcodes in `/Applications` and `~/Applications` (any name: `Xcode-beta.app`, `Xcode_16.4.app`),
/// for `languages.swift.xcode`; `path` is the `.app`.
fn xcode() -> Vec<Sdk> {
if !cfg!(target_os = "macos") {
return Vec::new();
}
let dirs = [Some(PathBuf::from("/Applications")), home_dir().map(|h| h.join("Applications"))];
let mut apps: Vec<PathBuf> = dirs
.into_iter()
.flatten()
.flat_map(|d| subdirs(&d))
.filter(|app| app.extension() == Some(OsStr::new("app")))
.filter(|app| app.join("Contents/Developer/usr/bin/xcodebuild").is_file())
.collect();
apps.sort();
apps.into_iter()
.map(|app| {
let version = std::fs::read_to_string(app.join("Contents/version.plist"))
.ok()
.and_then(|plist| plist_string(&plist, "CFBundleShortVersionString"));
let stem = app.file_stem().unwrap_or_default().to_string_lossy().into_owned();
Sdk {
name: match &version {
Some(v) => format!("{stem} {v}"),
None => stem,
},
path: app.clone().into(),
version,
source: "system".to_owned(),
home: Some(app.join("Contents/Developer").into()),
extra: None,
}
})
.collect()
}
/// The `<string>` after `<key>key</key>` of an XML property list.
fn plist_string(plist: &str, key: &str) -> Option<String> {
let rest = &plist[plist.find(&format!("<key>{key}</key>"))?..];
let value = &rest[rest.find("<string>")? + "<string>".len()..];
Some(value[..value.find("</string>")?].trim().to_owned()).filter(|v| !v.is_empty())
}
#[test]
fn reads_xcodes_version_plist() {
let plist = "<dict>\n\t<key>BuildVersion</key>\n\t<string>7</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>26.1</string>\n</dict>";
assert_eq!(plist_string(plist, "CFBundleShortVersionString").as_deref(), Some("26.1"));
assert_eq!(plist_string(plist, "CFBundleVersion"), None);
}
/// The SDKs `dotnet --list-sdks` reports, newest first: only the `dotnet` that runs
/// `dotnet new` can use them.
fn dotnet() -> Vec<Sdk> {
+2
Переглянути файл
@@ -66,6 +66,8 @@ pub enum SdkKind {
Dotnet,
/// Flutter SDK roots.
Flutter,
/// `Xcode.app` bundles.
Xcode,
}
/// One installed interpreter / toolchain.
+4 -4
Переглянути файл
@@ -69,14 +69,14 @@ Open the folder that contains `buildServer.json` (or `.bsp/`) as the project, or
### Several Xcode versions
To run sourcekit-lsp from a specific Xcode, set `DEVELOPER_DIR` in the server's environment: in **Settings › Languages & Frameworks › Language Servers**, select sourcekit-lsp and add it under **Startup › Environment variables**, or in `settings.toml`:
To use a specific Xcode in a project, choose it under **Xcode** in **Settings › Languages & Frameworks › Swift** (the list shows the Xcodes in `/Applications` and `~/Applications`), or in the project's `settings.toml`:
```toml
[languageServers.sourcekit-lsp]
env = { DEVELOPER_DIR = "/Applications/Xcode-beta.app/Contents/Developer" }
[languages.swift]
xcode = "/Applications/Xcode-beta.app"
```
Set it per project to use a different Xcode in each. It applies to sourcekit-lsp only; to build or run with the same Xcode, set `DEVELOPER_DIR` in the run configuration's environment variables too.
Everything the IDE starts in the project gets it as `DEVELOPER_DIR`: sourcekit-lsp, `xcodebuild` (run, test, Clean Build Folder), `simctl`, lldb-dap, coverage reports and new terminals. It also overrides a `DEVELOPER_DIR` from `.envrc`. Changing it restarts sourcekit-lsp. Empty uses the Xcode chosen with `xcode-select`.
## Formatting
+4 -4
Переглянути файл
@@ -69,14 +69,14 @@ sourcekit-lsp 读不了 `.xcodeproj` 和 `.xcworkspace`。没有构建服务器
### 多个 Xcode 版本
要让 sourcekit-lsp 使用某个特定的 Xcode,在服务器的环境中设置 `DEVELOPER_DIR`:在 **设置 › 语言和框架 › 语言服务器** 中选中 sourcekit-lsp,在 **启动 › 环境变量** 中添加;或者写在 `settings.toml` 中:
要让项目使用某个特定的 Xcode,在 **设置 › 语言和框架 › Swift** 的 **Xcode** 中选择(列表显示 `/Applications` 和 `~/Applications` 中的 Xcode),或者写在项目的 `settings.toml` 中:
```toml
[languageServers.sourcekit-lsp]
env = { DEVELOPER_DIR = "/Applications/Xcode-beta.app/Contents/Developer" }
[languages.swift]
xcode = "/Applications/Xcode-beta.app"
```
按项目设置即可让每个项目使用不同的 Xcode。它只对 sourcekit-lsp 生效;要用同一个 Xcode 构建或运行,在运行配置的环境变量里也设置 `DEVELOPER_DIR`。
IDE 在项目中启动的所有进程都会以 `DEVELOPER_DIR` 得到它:sourcekit-lsp、`xcodebuild`(运行、测试、Clean Build Folder)、`simctl`、lldb-dap、覆盖率报告和新开的终端。它也会覆盖 `.envrc` 中的 `DEVELOPER_DIR`。修改后会重启 sourcekit-lsp。留空则使用 `xcode-select` 选择的 Xcode。
## 格式化
+13 -1
Переглянути файл
@@ -10671,6 +10671,7 @@ export type LanguagesSettings_Deserialize = {
arduino?: ArduinoSettings,
zig?: ZigSettings,
flutter?: FlutterSettings,
swift?: SwiftSettings,
};
export type LanguagesSettings_Serialize = {
@@ -10695,6 +10696,7 @@ export type LanguagesSettings_Serialize = {
arduino: ArduinoSettings,
zig: ZigSettings,
flutter: FlutterSettings,
swift: SwiftSettings,
};
export type LargeCommitFile = {
@@ -14510,7 +14512,9 @@ export type SdkKind = "python" | "node" |
/** .NET SDKs of the `dotnet` on the search path; `version` is what `global.json` pins. */
"dotnet" |
/** Flutter SDK roots. */
"flutter";
"flutter" |
/** `Xcode.app` bundles. */
"xcode";
/**
* IDEA's search context: matches anywhere, only in, or outside comments and
@@ -15461,6 +15465,14 @@ export type StubLink = {
export type SubmoduleRollbackSource = "head" | "index";
export type SwiftSettings = {
/**
* The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
* `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
*/
xcode?: string,
};
export type SymbolFilter = "all" |
/** Go to Class (⌘O): classes, interfaces, structs, enums, traits, type aliases. */
"types";
+1
Переглянути файл
@@ -404,6 +404,7 @@ describe("language pages", () => {
"dprint",
"Ruby",
"Rust",
"Swift",
"TypeScript",
"Zig",
]);
+63
Переглянути файл
@@ -0,0 +1,63 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import type { Sdk } from "@/platform/ipc";
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
const xcode = (path: string, name: string): Sdk => ({
path,
name,
version: null,
source: "system",
home: `${path}/Contents/Developer`,
extra: null,
});
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
sdkDetect: (kind: string) =>
ok(
kind === "xcode"
? [xcode("/Applications/Xcode.app", "Xcode 26.1"), xcode("/Applications/Xcode-beta.app", "Xcode-beta 26.2")]
: [],
),
},
};
});
import { PageContext } from "../components/context";
import { SwiftPage } from "../languages/LanguagePages";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openSettings } from "../model/staging";
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe("Swift settings page", () => {
it("lists the installed Xcodes after the xcode-select default", async () => {
const settings = structuredClone(DEFAULT_SETTINGS);
settings.languages.swift.xcode = "/Applications/Xcode-beta.app";
useProject.setState({ settings, project: null });
openSettings("languages.swift");
render(
<PageContext.Provider value={{ pageId: "languages.swift", scope: "project" }}>
<SwiftPage />
</PageContext.Provider>,
);
const combo = screen.getByRole("button", { name: "Xcode" });
await waitFor(() => expect(combo).toHaveTextContent("Xcode-beta 26.2"));
fireEvent.click(combo);
const options = await screen.findAllByRole("option");
expect(options.map((o) => o.textContent)).toEqual([
expect.stringContaining("xcode-select"),
expect.stringContaining("Xcode 26.1"),
expect.stringContaining("Xcode-beta 26.2"),
]);
});
});
+23
Переглянути файл
@@ -908,3 +908,26 @@ export function ZigPage() {
</div>
);
}
// ---------------------------------------------------------------------------
// Swift
export function SwiftPage() {
return (
<div className={styles.page}>
<Section>
<SdkRow
k="languages.swift.xcode"
label="Xcode"
kind="xcode"
emptyLabel="Default"
emptyDetail="xcode-select"
directory
browseTitle="Select Xcode"
aria-label="Xcode"
hint="Xcode whose tools this project uses: sourcekit-lsp, xcodebuild, simctl, lldb-dap and terminals get it as DEVELOPER_DIR. Changing it restarts sourcekit-lsp."
/>
</Section>
</div>
);
}
+12 -1
Переглянути файл
@@ -1,6 +1,6 @@
/**
* PyCharm's top-level "Python" group (Interpreter) and
* Languages & Frameworks › Flutter / Go / Java / Markdown / Node.js / PHP / Rust / TypeScript / Zig. Pages live in
* Languages & Frameworks › Flutter / Go / Java / Markdown / Node.js / PHP / Rust / Swift / TypeScript / Zig. Pages live in
* `../languages/`; settings are `languages.*` / `projectStructure.*`.
*/
import { GO_BUILD_TAG_SECTIONS, GoBuildTagsPage } from "../languages/GoBuildTags";
@@ -50,6 +50,7 @@ const JsonSchemasEditor = lazyPage("languages.jsonSchemas", () =>
import("./JsonSchemasBody").then((m) => m.JsonSchemasEditor),
);
const ZigPage = lazyPage("languages.zig", () => import("../languages/LanguagePages").then((m) => m.ZigPage));
const SwiftPage = lazyPage("languages.swift", () => import("../languages/LanguagePages").then((m) => m.SwiftPage));
export const LANGUAGES_GROUP = "Languages & Frameworks";
@@ -401,6 +402,16 @@ export const LANGUAGE_PAGES: PageSpec[] = [
keywords: ["typescript version", "tsdk", "tsserver", "node_modules", "vtsls", "tsserver log"],
component: TypeScriptPage,
},
{
id: "languages.swift",
projectScope: true,
defaultScope: "project",
title: "Swift",
group: LANGUAGES_GROUP,
order: 404.5,
keywords: ["xcode", "xcode version", "developer_dir", "xcode-select", "sourcekit-lsp", "xcodebuild", "ios"],
component: SwiftPage,
},
{
id: "languages.zig",
projectScope: true,
+2
Переглянути файл
@@ -288,6 +288,8 @@ describe("catalogs", () => {
"fillfactor=70, autovacuum_enabled=false",
// The placeholder of an Xcode run configuration's project or workspace field.
"App.xcodeproj",
// The Swift settings field naming the Xcode a project uses.
"Xcode",
// GitHub's product name, the title of its tool window.
"GitHub Actions",
"Flutter DevTools",
+5
Переглянути файл
@@ -194,6 +194,8 @@ export interface LanguagesValid {
zig: { zig: string };
/** Flutter SDK root; empty = `flutter` / `dart` on PATH. */
flutter: { sdk: string };
/** `Xcode.app` (or its `Contents/Developer`) the project's Apple tools use; empty = `xcode-select`'s. */
swift: { xcode: string };
node: {
runTarget: string;
interpreter: string;
@@ -339,6 +341,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
ruby: { interpreter: "" },
zig: { zig: "" },
flutter: { sdk: "" },
swift: { xcode: "" },
node: { runTarget: "", interpreter: "", packageManager: "", runtime: "" },
php: { runTarget: "", interpreter: "", languageLevel: "", includePaths: [], stubs: [], phpstanConfig: "" },
rust: { toolchain: "", stdlib: "", checkOnSave: true, checkCommand: "check", rustfmtArgs: "" },
@@ -472,6 +475,7 @@ export function validateLanguages(raw: unknown): LanguagesValid {
const ruby = obj(l.ruby);
const zig = obj(l.zig);
const flutter = obj(l.flutter);
const swift = obj(l.swift);
const node = obj(l.node);
const php = obj(l.php);
const rust = obj(l.rust);
@@ -506,6 +510,7 @@ export function validateLanguages(raw: unknown): LanguagesValid {
ruby: { interpreter: text(ruby.interpreter, d.ruby.interpreter) },
zig: { zig: text(zig.zig, d.zig.zig) },
flutter: { sdk: text(flutter.sdk, d.flutter.sdk) },
swift: { xcode: text(swift.xcode, d.swift.xcode) },
node: {
runTarget: text(node.runTarget, ""),
interpreter: text(node.interpreter, d.node.interpreter),
+3
Переглянути файл
@@ -6535,6 +6535,9 @@
"Select Zig Directory": "Выбрать каталог Zig",
"Zig toolchain": "Инструментарий Zig",
"Zig whose standard library and build.zig.zon packages appear under External Libraries. ZLS must match this Zig version. PATH, Homebrew, zvm and mise / asdf installs are detected.": "Zig, стандартная библиотека и пакеты build.zig.zon которого отображаются в разделе «Внешние библиотеки». Версия ZLS должна соответствовать этой версии Zig. Обнаруживаются установки из PATH, Homebrew, zvm и mise / asdf.",
"Xcode": "Xcode",
"Select Xcode": "Выбрать Xcode",
"Xcode whose tools this project uses: sourcekit-lsp, xcodebuild, simctl, lldb-dap and terminals get it as DEVELOPER_DIR. Changing it restarts sourcekit-lsp.": "Xcode, инструменты которого использует проект: sourcekit-lsp, xcodebuild, simctl, lldb-dap и терминалы получают его как DEVELOPER_DIR. При изменении sourcekit-lsp перезапускается.",
"Monospaced": "Моноширинный",
"Proportional": "Пропорциональный",
"Loading system fonts…": "Загрузка системных шрифтов…",
+3
Переглянути файл
@@ -6054,6 +6054,9 @@
"Select Zig Directory": "選擇 Zig 目錄",
"Zig toolchain": "Zig 工具鏈",
"Zig whose standard library and build.zig.zon packages appear under External Libraries. ZLS must match this Zig version. PATH, Homebrew, zvm and mise / asdf installs are detected.": "用於在「外部庫」下列出 Zig 標準庫和 build.zig.zon 依賴的 Zig。ZLS 版本必須與該 Zig 版本符合。可檢測 PATH、Homebrew、zvm 以及 mise / asdf 的安裝。",
"Xcode": "Xcode",
"Select Xcode": "選擇 Xcode",
"Xcode whose tools this project uses: sourcekit-lsp, xcodebuild, simctl, lldb-dap and terminals get it as DEVELOPER_DIR. Changing it restarts sourcekit-lsp.": "此專案使用其工具的 Xcode:sourcekit-lsp、xcodebuild、simctl、lldb-dap 和終端機會以 DEVELOPER_DIR 取得它。修改後會重新啟動 sourcekit-lsp。",
"Monospaced": "等寬",
"Proportional": "非等寬",
"Loading system fonts…": "正在載入系統字型…",
+3
Переглянути файл
@@ -6898,6 +6898,9 @@
"Select Zig Directory": "选择 Zig 目录",
"Zig toolchain": "Zig 工具链",
"Zig whose standard library and build.zig.zon packages appear under External Libraries. ZLS must match this Zig version. PATH, Homebrew, zvm and mise / asdf installs are detected.": "用于在“外部库”下列出 Zig 标准库和 build.zig.zon 依赖的 Zig。ZLS 版本必须与该 Zig 版本匹配。可检测 PATH、Homebrew、zvm 以及 mise / asdf 的安装。",
"Xcode": "Xcode",
"Select Xcode": "选择 Xcode",
"Xcode whose tools this project uses: sourcekit-lsp, xcodebuild, simctl, lldb-dap and terminals get it as DEVELOPER_DIR. Changing it restarts sourcekit-lsp.": "此项目使用其工具的 Xcode:sourcekit-lsp、xcodebuild、simctl、lldb-dap 和终端会以 DEVELOPER_DIR 得到它。修改后会重启 sourcekit-lsp。",
"Monospaced": "等宽",
"Proportional": "非等宽",
"Loading system fonts…": "正在加载系统字体…",