diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 742b5fe3a..a006bd1f2 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -503,7 +503,7 @@ impl Host { trusted.clone(), ); documents.add_observer(phpstan.clone()); - let swiftlint = crate::swiftlint::SwiftLint::new(root.clone(), sink.clone(), trusted.clone()); + let swiftlint = crate::swiftlint::SwiftLint::new(root.clone(), settings.clone(), sink.clone(), trusted.clone()); documents.add_observer(swiftlint.clone()); let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone()); documents.add_observer(tsc_watch.clone()); diff --git a/crates/ide-host/src/swiftlint.rs b/crates/ide-host/src/swiftlint.rs index f69de6d19..447a07533 100644 --- a/crates/ide-host/src/swiftlint.rs +++ b/crates/ide-host/src/swiftlint.rs @@ -7,6 +7,7 @@ use ide_core::event::NotifyLevel; use ide_core::output_encoding::decode_tool_output; use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink}; use ide_text::AppliedChange; +use ide_workspace::SettingsStore; use ide_workspace::documents::{DocumentInfo, DocumentObserver}; use parking_lot::Mutex; use serde::Deserialize; @@ -34,6 +35,7 @@ enum Job { pub(crate) struct SwiftLint { root: PathBuf, + settings: Arc, sink: SharedSink, trusted: Arc, lifetime: CancellationToken, @@ -49,9 +51,15 @@ pub(crate) struct SwiftLint { } impl SwiftLint { - pub(crate) fn new(root: PathBuf, sink: SharedSink, trusted: Arc) -> Arc { + pub(crate) fn new( + root: PathBuf, + settings: Arc, + sink: SharedSink, + trusted: Arc, + ) -> Arc { Arc::new(Self { root, + settings, sink, trusted, lifetime: CancellationToken::new(), @@ -72,6 +80,11 @@ impl SwiftLint { self.lifetime.cancel(); } + /// The executable set in Settings (`[tools.swiftlint] path`), else `swiftlint` from PATH. + fn program(&self) -> Option { + self.settings.read_effective(|s| s.tool_path(SOURCE).and_then(|p| ide_sdk::apply::setting_path(&self.root, p))) + } + fn queue(&self, path: &Path, job: Job) { if self.lifetime.is_cancelled() || !path.extension().is_some_and(|e| e == "swift") { return; @@ -143,14 +156,17 @@ impl SwiftLint { Job::Saved => None, Job::Buffer(text) => Some(text.as_str()), }; - let Some(output) = lint(&dir, &path, text, &self.lifetime).await else { return }; + let program = self.program(); + let Some(output) = lint(program.as_deref(), &dir, &path, text, &self.lifetime).await else { return }; // Edited again meanwhile: the newer job's result replaces this one. Restricted // meanwhile: `trust_changed` already cleared the findings. if self.pending.lock().contains_key(&path) || !self.trusted.load(Ordering::Acquire) { continue; } let result = output.map_err(|e| { - if e.kind() == std::io::ErrorKind::NotFound { + if let Some(program) = program.as_deref().filter(|_| e.kind() == std::io::ErrorKind::NotFound) { + format!("The SwiftLint executable set in Settings was not found: {}", program.display()) + } else if e.kind() == std::io::ErrorKind::NotFound { "swiftlint was not found on PATH. Install SwiftLint (brew install swiftlint), \ or from Settings › Languages & Frameworks › Language Servers." .to_string() @@ -243,21 +259,24 @@ fn config_dir(root: &Path, file: &Path) -> Option { .map(Path::to_path_buf) } -/// Runs `swiftlint lint` in `dir` on the saved `file`, or on `text` through stdin; -/// `None` when `cancel` fires first, which kills it. +/// Runs `swiftlint lint` (`program`, else `swiftlint` from PATH) in `dir` on the saved `file`, +/// or on `text` through stdin; `None` when `cancel` fires first, which kills it. async fn lint( + program: Option<&Path>, dir: &Path, file: &Path, text: Option<&str>, cancel: &CancellationToken, ) -> Option> { - let mut cmd = std::process::Command::new("swiftlint"); + let mut cmd = std::process::Command::new(program.unwrap_or(Path::new("swiftlint"))); cmd.args(["lint", "--reporter", "json", "--quiet", "--no-cache"]).current_dir(dir); match text { Some(_) => cmd.arg("--use-stdin"), None => cmd.arg("--force-exclude").arg(file), }; ide_core::process::prepare(&mut cmd); + #[cfg(target_os = "macos")] + command_line_tools_sourcekit(&mut cmd); cmd.stdin(if text.is_some() { Stdio::piped() } else { Stdio::null() }); cmd.stdout(Stdio::piped()).stderr(Stdio::piped()); let mut cmd = tokio::process::Command::from(cmd); @@ -275,6 +294,45 @@ async fn lint( } } +/// SwiftLint loads SourceKit from the default toolchain of the selected Xcode. With only the +/// Command Line Tools selected there is none, so it is given the tools' own SourceKit. +#[cfg(target_os = "macos")] +fn command_line_tools_sourcekit(cmd: &mut std::process::Command) { + let env = |name: &str| { + match cmd.get_envs().find(|(k, _)| *k == name) { + Some((_, value)) => value.map(std::ffi::OsStr::to_owned), + None => std::env::var_os(name), + } + .filter(|v| !v.is_empty()) + }; + if env("TOOLCHAIN_DIR").is_some() || env("XCODE_DEFAULT_TOOLCHAIN_OVERRIDE").is_some() { + return; + } + let developer = env("DEVELOPER_DIR").map(PathBuf::from).or_else(|| selected_developer_dir().clone()); + if let Some(dir) = developer.filter(|d| sourcekit_outside_a_toolchain(d)) { + cmd.env("TOOLCHAIN_DIR", dir); + } +} + +#[cfg(target_os = "macos")] +fn selected_developer_dir() -> &'static Option { + static DIR: std::sync::OnceLock> = std::sync::OnceLock::new(); + DIR.get_or_init(|| { + let mut cmd = std::process::Command::new("/usr/bin/xcode-select"); + cmd.arg("-p").stdin(Stdio::null()).stderr(Stdio::null()); + let out = cmd.output().ok().filter(|o| o.status.success())?; + let dir = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + (!dir.is_empty()).then(|| PathBuf::from(dir)) + }) +} + +#[cfg(any(test, target_os = "macos"))] +/// A developer folder with SourceKit in `usr/lib` but no Xcode default toolchain: the Command Line Tools. +fn sourcekit_outside_a_toolchain(developer: &Path) -> bool { + !developer.join("Toolchains/XcodeDefault.xctoolchain").is_dir() + && developer.join("usr/lib/sourcekitdInProc.framework").is_dir() +} + /// One entry of SwiftLint's JSON report; `line` and `character` are 1-based, the /// character counted in UTF-16 units. #[derive(Debug, Deserialize, PartialEq)] @@ -386,6 +444,47 @@ mod tests { ); } + #[cfg(unix)] + #[tokio::test] + async fn the_executable_set_in_settings_lints() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("p"); + std::fs::create_dir_all(root.join("tools")).unwrap(); + let sink: SharedSink = Arc::new(|_| {}); + let linter = |root: &Path| { + let settings = Arc::new(SettingsStore::load(&dir.path().join("config"), Some(root))); + SwiftLint::new(root.to_path_buf(), settings, sink.clone(), Arc::new(AtomicBool::new(true))) + }; + assert_eq!(linter(&root).program(), None); + + let script = root.join("tools/lint"); + std::fs::write(&script, format!("#!/bin/sh\necho '{}'\n", REPORT.replace('\n', " "))).unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::create_dir_all(root.join(".openidea")).unwrap(); + std::fs::write(root.join(".openidea/settings.toml"), "[tools.swiftlint]\npath = \"tools/lint\"\n").unwrap(); + let program = linter(&root).program(); + assert_eq!(program.as_deref(), Some(script.as_path()), "relative to the project"); + + let file = root.join("A.swift"); + let output = lint(program.as_deref(), &root, &file, None, &CancellationToken::new()).await.unwrap().unwrap(); + let Ok(Report::Violations(violations)) = parse(&String::from_utf8_lossy(&output.stdout), "") else { panic!() }; + assert_eq!(violations.len(), 3); + } + + #[test] + fn only_the_command_line_tools_need_their_sourcekit_named() { + let dir = tempfile::tempdir().unwrap(); + let clt = dir.path().join("CommandLineTools"); + std::fs::create_dir_all(clt.join("usr/lib/sourcekitdInProc.framework")).unwrap(); + assert!(sourcekit_outside_a_toolchain(&clt)); + let xcode = dir.path().join("Xcode.app/Contents/Developer"); + std::fs::create_dir_all(xcode.join("Toolchains/XcodeDefault.xctoolchain/usr/lib")).unwrap(); + std::fs::create_dir_all(xcode.join("usr/lib/sourcekitdInProc.framework")).unwrap(); + assert!(!sourcekit_outside_a_toolchain(&xcode)); + assert!(!sourcekit_outside_a_toolchain(dir.path())); + } + #[test] fn the_nearest_configuration_in_the_project_wins() { let dir = tempfile::tempdir().unwrap();