diff --git a/Cargo.lock b/Cargo.lock index b9cbcc802..0f9331ada 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -252,9 +252,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", @@ -4684,6 +4684,7 @@ dependencies = [ "tree-sitter-make", "tree-sitter-md", "tree-sitter-nix", + "tree-sitter-objc", "tree-sitter-ocaml", "tree-sitter-php", "tree-sitter-prisma-io", @@ -5116,6 +5117,7 @@ dependencies = [ "ide-text", "ide-vfs", "parking_lot 0.12.5", + "quick-xml 0.42.0", "semver", "serde", "serde_json", @@ -10641,6 +10643,16 @@ dependencies = [ "tree-sitter-language", ] +[[package]] +name = "tree-sitter-objc" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ca8bb556423fc176f0535e79d525f783a6684d3c9da81bf9d905303c129e1d2" +dependencies = [ + "cc", + "tree-sitter-language", +] + [[package]] name = "tree-sitter-ocaml" version = "0.26.0" diff --git a/crates/ide-build/src/application_update.rs b/crates/ide-build/src/application_update.rs index 208c280d7..30537d977 100644 --- a/crates/ide-build/src/application_update.rs +++ b/crates/ide-build/src/application_update.rs @@ -85,13 +85,26 @@ gradle.projectsEvaluated {{ pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &str) -> IdeResult<()> { let output = PathBuf::from(fs::read_to_string(cache.join("resource-output.txt"))?.trim()); - if !output.is_absolute() || !output.is_dir() { - return Err(IdeError::invalid("The resource build did not report an output directory")); + let invalid_output = "The resource build did not report an output directory"; + if !output.is_absolute() { + return Err(IdeError::invalid(invalid_output)); } - let output = dunce::canonicalize(output)?; + let output = match fs::metadata(&output) { + Ok(metadata) if metadata.is_dir() => Some(dunce::canonicalize(output)?), + // Gradle's processResources can succeed with NO-SOURCE and never create its destination. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + _ => return Err(IdeError::invalid(invalid_output)), + }; let paths: Vec<_> = class_paths.iter().filter_map(|p| dunce::canonicalize(root.join(p)).ok()).collect(); // A separate resource directory is already on the runtime classpath (e.g. build/resources/main). - if paths.contains(&output) { + if output.as_ref().is_some_and(|dir| paths.contains(dir)) { + return Ok(()); + } + let previous: Vec = fs::read(cache.join("published-resources.json")) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or_default(); + if output.is_none() && previous.is_empty() { return Ok(()); } // jdtls uses bin/main for Gradle, rather than Gradle's build/resources/main. @@ -99,12 +112,10 @@ pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &s let destination = paths.iter().find(|p| p.join(&class_file).is_file()).ok_or_else(|| { IdeError::invalid("Cannot find the running main class output directory; restart the application") })?; - let previous: Vec = fs::read(cache.join("published-resources.json")) - .ok() - .and_then(|bytes| serde_json::from_slice(&bytes).ok()) - .unwrap_or_default(); let mut current = Vec::new(); - copy_resources(&output, &output, destination, &mut current)?; + if let Some(output) = output { + copy_resources(&output, &output, destination, &mut current)?; + } for rel in previous.iter().filter(|p| !current.contains(p)) { let path = destination.join(rel); if path.is_file() { @@ -220,6 +231,39 @@ mod tests { } } + #[test] + fn missing_resource_output_publishes_an_empty_set() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let output = root.join("build/resources/main"); + let cache = root.join("cache"); + let runtime = root.join("bin/main"); + let class_paths = [runtime.to_string_lossy().into_owned()]; + let resource = "application.properties"; + fs::create_dir(&cache).unwrap(); + fs::create_dir_all(runtime.join("example")).unwrap(); + fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap(); + let class = runtime.join("example/Application.class"); + fs::write(&class, "running").unwrap(); + + publish(root, &cache, &class_paths, "example.Application").unwrap(); + assert!(!output.exists()); + + fs::create_dir_all(&output).unwrap(); + fs::write(output.join(resource), "server.port=8081").unwrap(); + publish(root, &cache, &class_paths, "example.Application").unwrap(); + assert!(runtime.join(resource).is_file()); + + fs::remove_file(output.join(resource)).unwrap(); + fs::remove_dir(&output).unwrap(); + publish(root, &cache, &class_paths, "example.Application").unwrap(); + assert!(!runtime.join(resource).exists()); + assert_eq!(fs::read_to_string(class).unwrap(), "running"); + + fs::write(output, "not a directory").unwrap(); + assert!(publish(root, &cache, &class_paths, "example.Application").is_err()); + } + #[test] fn leaves_separate_runtime_resource_directories_in_place_and_rejects_jar_only_runs() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-core/src/process.rs b/crates/ide-core/src/process.rs index 29bf8b60f..ff6b3dbe5 100644 --- a/crates/ide-core/src/process.rs +++ b/crates/ide-core/src/process.rs @@ -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"); diff --git a/crates/ide-core/src/project_env.rs b/crates/ide-core/src/project_env.rs index 2a0ce1aca..8ac54fe78 100644 --- a/crates/ide-core/src/project_env.rs +++ b/crates/ide-core/src/project_env.rs @@ -16,13 +16,21 @@ struct Entry { root: PathBuf, direnv: Vec<(OsString, Option)>, github_token: Option, + developer_dir: Option, 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) -> 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) -> 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 { 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"); diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index a910325d1..2366341d2 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -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 { + 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")] @@ -1975,6 +1997,10 @@ pub struct TypeScriptSettings { /// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the /// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default). pub tsserver_max_memory: u32, + /// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it. + #[serde(deserialize_with = "or_default")] + #[specta(type = TsServerLog)] + pub tsserver_log: TsServerLog, /// Problems › TypeScript project errors: the project's own `tsc --watch` per root /// `tsconfig.json` reports the errors of files that are not open. pub watch_problems: bool, @@ -1982,10 +2008,27 @@ pub struct TypeScriptSettings { impl Default for TypeScriptSettings { fn default() -> Self { - Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false } + Self { + version: "bundled".into(), + tsserver_max_memory: 0, + tsserver_log: TsServerLog::Off, + watch_problems: false, + } } } +/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum TsServerLog { + #[default] + Off, + Terse, + Normal, + RequestTime, + Verbose, +} + /// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -2158,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(); @@ -2168,6 +2225,20 @@ mod tests { assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true); } + #[test] + fn tsserver_log_reads_known_levels_and_drops_anything_else() { + let log = |v: &str| { + let s: Settings = + serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap(); + s.languages.typescript.tsserver_log + }; + assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime); + assert_eq!(log(r#""verbose""#), TsServerLog::Verbose); + assert_eq!(log(r#""--trace""#), TsServerLog::Off); + assert_eq!(log("3"), TsServerLog::Off); + assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime"); + } + #[test] fn python_interpreter_may_name_a_run_target() { let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() }; diff --git a/crates/ide-coverage/Cargo.toml b/crates/ide-coverage/Cargo.toml index be3d3c64c..62a6ad1f1 100644 --- a/crates/ide-coverage/Cargo.toml +++ b/crates/ide-coverage/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ide-coverage" -description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)" +description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo, xcodebuild) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data, xccov)" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ide-coverage/src/goprofile.rs b/crates/ide-coverage/src/goprofile.rs index 842e784af..f2faeb894 100644 --- a/crates/ide-coverage/src/goprofile.rs +++ b/crates/ide-coverage/src/goprofile.rs @@ -59,7 +59,7 @@ pub(crate) fn parse(text: &str, module: &str, module_dir: &Path) -> Accumulator impl Accumulator { /// Removes the branch data of lines whose branches are all taken or all missed. - fn drop_unanimous_branches(&mut self) { + pub(crate) fn drop_unanimous_branches(&mut self) { for lines in self.files.values_mut() { for acc in lines.values_mut() { let taken = acc.branches.values().filter(|t| **t).count(); diff --git a/crates/ide-coverage/src/lib.rs b/crates/ide-coverage/src/lib.rs index c89001414..898f155c5 100644 --- a/crates/ide-coverage/src/lib.rs +++ b/crates/ide-coverage/src/lib.rs @@ -13,6 +13,7 @@ //! | Ruby (rspec, minitest, rake, scripts) | SimpleCov (`coverage/.resultset.json`) | SimpleCov resultset | //! | Go (`go test`) | `-coverprofile` | Go cover profile | //! | Maven / Gradle tests | JaCoCo (plugin goals / an init script) | JaCoCo XML | +//! | Xcode tests (`xcodebuild test`) | `-enableCodeCoverage YES` | the result bundle, read with `xccov` | //! //! Lines in the model are 0-based, like every IPC coordinate. @@ -24,6 +25,7 @@ mod jacoco; mod lcov; mod plan; mod simplecov; +mod xccov; pub use coveragepy::is_data_file; pub use import::{import, import_data}; @@ -94,6 +96,8 @@ pub enum CoverageReportSpec { Jacoco { dir: IpcPath }, /// The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o `). Exported { runner: String, argv: Vec, cwd: IpcPath, env: BTreeMap, lcov: IpcPath }, + /// An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept. + Xccov { bundle: IpcPath, root: IpcPath }, } /// A command line that installs a missing tool (run in the Run tool window). @@ -234,9 +238,31 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult { let text = read_report(lcov)?; Ok(lcov::parse(&text, cwd).finish(runner)) } + CoverageReportSpec::Xccov { bundle, root } => { + if !bundle.exists() { + return Err(IdeError::not_found(format!("the run produced no result bundle ({})", bundle.display()))); + } + let report = xccov_json(&["--report", "--json"], bundle)?; + let archive = xccov_json(&["--archive", "--json"], bundle)?; + Ok(xccov::parse(&report, &archive, root) + .map_err(|e| IdeError::invalid(format!("unexpected xccov output: {e}")))? + .finish("xccov")) + } } } +/// `xcrun xccov view `'s output. +fn xccov_json(args: &[&str], bundle: &Path) -> IdeResult { + let out = ide_core::process::prepare(Command::new("xcrun").args(["xccov", "view"]).args(args).arg(bundle)) + .output() + .map_err(|e| IdeError::unavailable(format!("cannot run xcrun xccov: {e}")))?; + if !out.status.success() { + let text = ide_core::output_encoding::decode_tool_output(&out.stderr).trim().to_owned(); + return Err(IdeError::not_found(format!("the result bundle has no coverage data: {text}"))); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) +} + fn read_report(path: &Path) -> IdeResult { std::fs::read_to_string(path).map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => { diff --git a/crates/ide-coverage/src/plan.rs b/crates/ide-coverage/src/plan.rs index 602fd1e86..4806c8676 100644 --- a/crates/ide-coverage/src/plan.rs +++ b/crates/ide-coverage/src/plan.rs @@ -61,6 +61,9 @@ fn ready( /// data; it must exist (the Gradle init script is written there). Probes tools, /// so call it from a blocking thread. pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared { + if config.kind == "xcode-test" { + return xcode(root, config, out); + } let dir = wrap::run_dir(root, config); let program = program_name(&config.command); let first = config.args.first().map(String::as_str).unwrap_or_default(); @@ -336,6 +339,20 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) - ready("coverage.py", &config, command, args, report) } +/// `xcodebuild test` with coverage on, into a result bundle of its own (`xcode::prepare_test` +/// adds it at launch). +fn xcode(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared { + let mut config = config.clone(); + if let Some(at) = config.args.iter().position(|a| a == "-enableCodeCoverage") { + config.args.drain(at..(at + 2).min(config.args.len())); + } + config.args.extend([s("-enableCodeCoverage"), s("YES")]); + let bundle = out.join("coverage.xcresult"); + config.extras.params.insert(s(ide_run::xcode::RESULT_BUNDLE_PARAM), path(&bundle)); + let report = CoverageReportSpec::Xccov { bundle: bundle.into(), root: root.to_path_buf().into() }; + ready("xccov", &config, config.command.clone(), config.args.clone(), report) +} + #[cfg(test)] mod tests { use super::*; @@ -535,6 +552,23 @@ mod tests { ); } + #[test] + fn xcode_tests_turn_coverage_on_into_their_own_bundle() { + let dir = tempfile::tempdir().unwrap(); + let config = cfg("xcode-test", "xcodebuild", &["test", "-scheme", "App", "-enableCodeCoverage", "NO"]); + let p = prepare(dir.path(), &config, dir.path()); + let (l, report) = launch(&p); + assert_eq!(l.args, ["test", "-scheme", "App", "-enableCodeCoverage", "YES"]); + let bundle = dir.path().join("coverage.xcresult"); + assert_eq!(l.extras.params[ide_run::xcode::RESULT_BUNDLE_PARAM], bundle.to_string_lossy()); + assert!(matches!(report, CoverageReportSpec::Xccov { bundle: b, .. } if (b.as_ref() as &Path) == bundle)); + + // A trailing flag without a value is replaced too. + let config = cfg("xcode-test", "xcodebuild", &["test", "-enableCodeCoverage"]); + let p = prepare(dir.path(), &config, dir.path()); + assert_eq!(launch(&p).0.args, ["test", "-enableCodeCoverage", "YES"]); + } + #[test] fn unknown_commands_are_unsupported() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-coverage/src/xccov.rs b/crates/ide-coverage/src/xccov.rs new file mode 100644 index 000000000..a95dc1f66 --- /dev/null +++ b/crates/ide-coverage/src/xccov.rs @@ -0,0 +1,188 @@ +//! Xcode coverage (`xcodebuild test -enableCodeCoverage YES`), read from the result bundle: +//! +//! - `xcrun xccov view --report --json `: the targets and their files. Files that only +//! test bundles (`*.xctest`) compile are left out. +//! - `xcrun xccov view --archive --json `: `{ "": [{ line, isExecutable, +//! executionCount, subranges? }] }` for every file. A subrange is a region of the line with its +//! own count; a covered line with a missed region is partial. + +use crate::Accumulator; +use serde::Deserialize; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Component, Path, PathBuf}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Report { + #[serde(default)] + targets: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Target { + #[serde(default)] + build_product_path: String, + #[serde(default)] + files: Vec, +} + +#[derive(Deserialize)] +struct ReportFile { + path: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Line { + line: u32, + is_executable: bool, + #[serde(default)] + execution_count: u64, + #[serde(default)] + subranges: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Subrange { + column: u32, + #[serde(default)] + length: u32, + #[serde(default)] + execution_count: u64, +} + +/// `path` inside the project as the project names it: the project and xccov may name it through +/// different symlinks (`/tmp` and `/private/tmp`). `None` outside the project and for DerivedData. +fn in_project(path: &Path, root: &Path, real_root: &Path) -> Option { + let real; + let rel = match path.strip_prefix(root) { + Ok(rel) => rel, + Err(_) => { + real = path.canonicalize().ok()?; + real.strip_prefix(real_root).ok()? + } + }; + let generated = rel.components().any(|c| matches!(c, Component::Normal(n) if n == "DerivedData" || n == ".build")); + (!generated).then(|| root.join(rel)) +} + +pub(crate) fn parse(report: &str, archive: &str, root: &Path) -> Result { + let report: Report = serde_json::from_str(report)?; + let archive: BTreeMap> = serde_json::from_str(archive)?; + // App and framework sources: a file listed by an app or framework target counts even when a test + // bundle compiles it too (sources added to the test target's membership instead of `@testable`). + let is_test_bundle = |t: &Target| { + Path::new(&t.build_product_path) + .components() + .any(|c| matches!(c, Component::Normal(n) if Path::new(n).extension().is_some_and(|e| e == "xctest"))) + }; + let real_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + // Both views go through `in_project`, so they match however each spells the path. + let sources: BTreeSet = report + .targets + .iter() + .filter(|t| !is_test_bundle(t)) + .flat_map(|t| &t.files) + .filter_map(|f| in_project(Path::new(&f.path), root, &real_root)) + .collect(); + let mut acc = Accumulator::default(); + for (file, lines) in &archive { + let Some(path) = in_project(Path::new(file), root, &real_root).filter(|p| sources.contains(p)) else { + continue; + }; + acc.file(&path); + for l in lines.iter().filter(|l| l.is_executable && l.line > 0) { + let n = l.line - 1; + acc.line(&path, n, l.execution_count); + if !l.subranges.is_empty() { + acc.branch(&path, n, "line".into(), l.execution_count > 0); + for r in &l.subranges { + acc.branch(&path, n, format!("{}+{}", r.column, r.length), r.execution_count > 0); + } + } + } + } + // Regions are not branches: keep only the partial marks of lines with mixed regions. + acc.drop_unanimous_branches(); + Ok(acc) +} + +#[cfg(test)] +mod tests { + use super::*; + + // Captured from `xcodebuild test -enableCodeCoverage YES` (Xcode 27.1) on an app with a unit + // test target; paths rewritten to /Users/me. + const REPORT: &str = include_str!("../tests/fixtures/xccov-report.json"); + const ARCHIVE: &str = include_str!("../tests/fixtures/xccov-archive.json"); + + #[test] + fn reads_app_sources_and_leaves_out_test_bundles() { + let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/CovDemo")).unwrap().finish("xccov"); + assert!(!suite.has_branches); + let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect(); + assert_eq!( + names, + [Path::new("/Users/me/CovDemo/CovDemo/App.swift"), Path::new("/Users/me/CovDemo/CovDemo/Calculator.swift")] + ); + // xccov's own totals for Calculator.swift: 14 of 17 lines. + let calc = &suite.files[1]; + assert_eq!((calc.lines_total, calc.lines_covered), (17, 14)); + let at = |n: u32| calc.lines.iter().find(|l| l.line == n).unwrap(); + // `return nil` (line 8) never ran; `if b == 0 {` (line 7) ran with a missed region. + assert_eq!(at(7).hits, 0); + assert!(at(6).partial()); + assert!(!at(1).partial()); + } + + #[test] + fn files_outside_the_project_are_dropped() { + let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/Other")).unwrap().finish("xccov"); + assert!(suite.files.is_empty()); + let report = r#"{"targets":[{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/DerivedData/G.swift"},{"path":"/p/A.swift"}]}]}"#; + let line = r#"[{"line":1,"isExecutable":true,"executionCount":2}]"#; + let archive = format!(r#"{{"/p/DerivedData/G.swift":{line},"/p/A.swift":{line}}}"#); + let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov"); + assert_eq!(suite.files.len(), 1); + assert_eq!(suite.files[0].lines[0].hits, 2); + } + + #[test] + fn a_file_of_an_app_and_a_test_bundle_counts() { + let report = r#"{"targets":[ + {"buildProductPath":"/d/App.app/App","files":[{"path":"/p/A.swift"}]}, + {"buildProductPath":"/d/AppTests.xctest/AppTests","files":[{"path":"/p/A.swift"},{"path":"/p/T.swift"}]}]}"#; + let line = r#"[{"line":1,"isExecutable":true,"executionCount":1}]"#; + let archive = format!(r#"{{"/p/A.swift":{line},"/p/T.swift":{line}}}"#); + let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov"); + let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect(); + assert_eq!(names, [Path::new("/p/A.swift")]); + } + + #[cfg(unix)] + #[test] + fn paths_through_another_symlink_map_to_the_project() { + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().canonicalize().unwrap().join("real"); + std::fs::create_dir_all(&real).unwrap(); + std::fs::write(real.join("A.swift"), "").unwrap(); + let link = dir.path().join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let file = real.join("A.swift").to_string_lossy().into_owned(); + let report = + format!(r#"{{"targets":[{{"buildProductPath":"/d/App.app/App","files":[{{"path":"{file}"}}]}}]}}"#); + let archive = format!(r#"{{"{file}":[{{"line":1,"isExecutable":true,"executionCount":1}}]}}"#); + let suite = parse(&report, &archive, &link).unwrap().finish("xccov"); + assert_eq!(suite.files.len(), 1); + assert_eq!(suite.files[0].path.as_ref() as &Path, link.join("A.swift")); + + // The report names the file through the symlink, the archive by its real path. + let linked = link.join("A.swift").to_string_lossy().into_owned(); + let report = report.replace(&file, &linked); + let suite = parse(&report, &archive, &link).unwrap().finish("xccov"); + assert_eq!(suite.files.len(), 1); + assert_eq!(suite.files[0].lines[0].hits, 1); + } +} diff --git a/crates/ide-coverage/tests/fixtures/xccov-archive.json b/crates/ide-coverage/tests/fixtures/xccov-archive.json new file mode 100644 index 000000000..6b1758b24 --- /dev/null +++ b/crates/ide-coverage/tests/fixtures/xccov-archive.json @@ -0,0 +1,226 @@ +{ + "/Users/me/CovDemo/CovDemo/App.swift": [ + { + "isExecutable": false, + "line": 1 + }, + { + "isExecutable": false, + "line": 2 + }, + { + "isExecutable": false, + "line": 3 + }, + { + "isExecutable": false, + "line": 4 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 5 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 6 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 7 + } + ], + "/Users/me/CovDemo/CovDemo/Calculator.swift": [ + { + "isExecutable": false, + "line": 1 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 2 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 3 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 4 + }, + { + "isExecutable": false, + "line": 5 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 6 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 7, + "subranges": [ + { + "column": 19, + "executionCount": 0, + "length": 0 + } + ] + }, + { + "executionCount": 0, + "isExecutable": true, + "line": 8 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 9, + "subranges": [ + { + "column": 1, + "executionCount": 0, + "length": 9 + } + ] + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 10 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 11 + }, + { + "isExecutable": false, + "line": 12 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 13 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 14, + "subranges": [ + { + "column": 18, + "executionCount": 0, + "length": 0 + } + ] + }, + { + "executionCount": 0, + "isExecutable": true, + "line": 15 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 16, + "subranges": [ + { + "column": 1, + "executionCount": 0, + "length": 9 + }, + { + "column": 26, + "executionCount": 0, + "length": 0 + } + ] + }, + { + "executionCount": 0, + "isExecutable": true, + "line": 17 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 18, + "subranges": [ + { + "column": 1, + "executionCount": 0, + "length": 9 + } + ] + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 19 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 20 + } + ], + "/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift": [ + { + "isExecutable": false, + "line": 1 + }, + { + "isExecutable": false, + "line": 2 + }, + { + "isExecutable": false, + "line": 3 + }, + { + "isExecutable": false, + "line": 4 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 5 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 6 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 7 + }, + { + "isExecutable": false, + "line": 8 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 9 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 10 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 11 + } + ] +} \ No newline at end of file diff --git a/crates/ide-coverage/tests/fixtures/xccov-report.json b/crates/ide-coverage/tests/fixtures/xccov-report.json new file mode 100644 index 000000000..4e308ef19 --- /dev/null +++ b/crates/ide-coverage/tests/fixtures/xccov-report.json @@ -0,0 +1,140 @@ +{ + "coveredLines": 28, + "executableLines": 31, + "lineCoverage": 0.9032258064516129, + "targets": [ + { + "buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/CovDemo", + "coveredLines": 18, + "executableLines": 21, + "files": [ + { + "coveredLines": 14, + "executableLines": 17, + "functions": [ + { + "coveredLines": 3, + "executableLines": 3, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 2, + "name": "Calculator.add(_:_:)" + }, + { + "coveredLines": 5, + "executableLines": 6, + "executionCount": 1, + "lineCoverage": 0.8333333333333334, + "lineNumber": 6, + "name": "Calculator.divide(_:_:)" + }, + { + "coveredLines": 6, + "executableLines": 8, + "executionCount": 1, + "lineCoverage": 0.75, + "lineNumber": 13, + "name": "Calculator.describe(_:)" + } + ], + "lineCoverage": 0.8235294117647058, + "name": "Calculator.swift", + "path": "/Users/me/CovDemo/CovDemo/Calculator.swift" + }, + { + "coveredLines": 4, + "executableLines": 4, + "functions": [ + { + "coveredLines": 3, + "executableLines": 3, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 5, + "name": "CovDemoApp.body.getter" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 6, + "name": "closure #1 in CovDemoApp.body.getter" + } + ], + "lineCoverage": 1, + "name": "App.swift", + "path": "/Users/me/CovDemo/CovDemo/App.swift" + } + ], + "lineCoverage": 0.8571428571428571, + "name": "CovDemo.app" + }, + { + "buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/PlugIns/CovDemoTests.xctest/CovDemoTests", + "coveredLines": 10, + "executableLines": 10, + "files": [ + { + "coveredLines": 10, + "executableLines": 10, + "functions": [ + { + "coveredLines": 3, + "executableLines": 3, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 5, + "name": "CalculatorTests.testAdd()" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 6, + "name": "implicit closure #1 in CalculatorTests.testAdd()" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 6, + "name": "implicit closure #2 in CalculatorTests.testAdd()" + }, + { + "coveredLines": 3, + "executableLines": 3, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 9, + "name": "CalculatorTests.testDivide()" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 10, + "name": "implicit closure #1 in CalculatorTests.testDivide()" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 10, + "name": "implicit closure #2 in CalculatorTests.testDivide()" + } + ], + "lineCoverage": 1, + "name": "CalculatorTests.swift", + "path": "/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift" + } + ], + "lineCoverage": 1, + "name": "CovDemoTests.xctest" + } + ] +} \ No newline at end of file diff --git a/crates/ide-dap/src/adapter.rs b/crates/ide-dap/src/adapter.rs index 47766051e..6167f3ae9 100644 --- a/crates/ide-dap/src/adapter.rs +++ b/crates/ide-dap/src/adapter.rs @@ -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 { - 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 { +fn xcrun_tool(command: &str, cwd: &Path) -> Option { 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 { +fn xcrun_tool(_command: &str, _cwd: &Path) -> Option { None } diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 19f381371..bf29baa13 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -614,6 +614,16 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult`) stay. +/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive. +fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool { + let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0); + reference > 0 && Path::new(path).has_root() && !Path::new(path).exists() +} + /// DAP stack frame → [`StackFrame`] (1-based → 0-based). pub(crate) fn frame_from(f: &Value) -> StackFrame { let source = f.get("source"); @@ -626,7 +636,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame { StackFrame { id: f.get("id").and_then(Value::as_i64).unwrap_or_default(), name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(), - path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into), + path: source + .and_then(|s| s.get("path")) + .and_then(Value::as_str) + .filter(|p| !is_pseudo_path(source, p)) + .map(Into::into), line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1), column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1), presentation_hint: hint, diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index 4b71c289b..6fc6bed78 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -2164,6 +2164,21 @@ fn frames_keep_their_instruction_pointer() { assert!(json.get("instructionPointerReference").is_none()); } +#[test] +fn frames_drop_pseudo_paths_of_referenced_sources() { + let frame = |path: &str, reference: i64| { + frame_from(&json!({"id": 1, "name": "f", "line": 1, + "source": {"path": path, "sourceReference": reference}})) + .path + }; + let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow"; + assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly"); + assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent"); + let here = env!("CARGO_MANIFEST_DIR"); + assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file"); + assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path"); +} + #[tokio::test] async fn smart_step_into_and_reset_frame() { let h = harness(Script::default()); diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index aa42afb77..c28147ae5 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -27,10 +27,12 @@ pub mod relay; mod requests; pub mod rpc; pub mod shell_env; +mod swiftlint; pub mod trust; mod ts_code_style; mod tsc_watch; pub mod web_server; +mod xcode_env; pub use project::{Project, history_retention}; @@ -463,6 +465,9 @@ impl Host { if let Some(phpstan) = &project.phpstan { phpstan.stop(); } + if let Some(swiftlint) = &project.swiftlint { + swiftlint.stop(); + } if let Some(watch) = &project.tsc_watch { watch.stop(); } @@ -703,6 +708,9 @@ impl Host { if let Some(phpstan) = &project.phpstan { phpstan.stop(); } + if let Some(swiftlint) = &project.swiftlint { + swiftlint.stop(); + } if let Some(watch) = &project.tsc_watch { watch.stop(); } diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs index 65eeca548..8c1cdb696 100644 --- a/crates/ide-host/src/menu.rs +++ b/crates/ide-host/src/menu.rs @@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec { act("file.exportSettings", "Export Settings…"), act("file.importSettings", "Import Settings…"), act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"), + act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"), act("file.syncSettings", "Sync Settings Now"), ], ), @@ -484,6 +485,7 @@ pub fn spec(os: Os) -> Vec { act("navigate.declaration", "Declaration or Usages"), act("navigate.implementation", "Implementation(s)"), act("navigate.typeDeclaration", "Type Declaration"), + act("navigate.sourceDefinition", "Source Definition"), act("navigate.superMethod", "Super Method"), act("navigate.gotoTest", "Test"), act("navigate.relatedSymbol", "Related Symbol…"), diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index 4de08ad00..e744a607c 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -1115,11 +1115,16 @@ pub async fn agent_mcp_test(host: &Host, window: &str, id: String) -> IdeResult< let cwd = project.as_ref().map(|p| p.root.clone()).or_else(dirs::home_dir).unwrap_or_else(std::env::temp_dir); match server.transport { McpTransport::Stdio => Ok(ide_agent::mcp::probe_stdio_server(&server, &cwd).await), - McpTransport::Http | McpTransport::Sse => Ok(probe_http_mcp_server(&server).await), + McpTransport::Http | McpTransport::Sse => { + Ok(probe_http_mcp_server(&server, &ide_core::proxy_settings::proxy()).await) + } } } -async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> McpProbeResult { +async fn probe_http_mcp_server( + server: &ide_core::settings::AgentMcpServer, + proxy: &ide_core::proxy_settings::ProxySettings, +) -> McpProbeResult { let started = std::time::Instant::now(); let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX); let Some(url) = server.url.as_deref().map(str::trim).filter(|u| !u.is_empty()) else { @@ -1145,31 +1150,36 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M headers.insert(name, val); } } - let client = - match reqwest::Client::builder().default_headers(headers).timeout(std::time::Duration::from_secs(12)).build() { - Ok(c) => c, - Err(e) => { - return McpProbeResult { - ok: false, - server_name: None, - server_version: None, - protocol_version: None, - tools: Vec::new(), - duration_ms: elapsed_ms(), - error: Some(format!("HTTP client error: {e}")), - }; - } - }; + let client = match ide_http::client::build(proxy) { + Ok(c) => c, + Err(e) => { + return McpProbeResult { + ok: false, + server_name: None, + server_version: None, + protocol_version: None, + tools: Vec::new(), + duration_ms: elapsed_ms(), + error: Some(format!("HTTP client error: {}", e.message)), + }; + } + }; + // The shared client has no MCP headers or 12 s limit of its own. The protocol's headers win over the + // configured ones, as they did over the client's default headers. + let post = |client: &reqwest::Client, url: &str, session_id: Option<&str>| { + let mut headers = headers.clone(); + headers.insert(reqwest::header::CONTENT_TYPE, reqwest::header::HeaderValue::from_static("application/json")); + if let Some(value) = session_id.and_then(|sid| reqwest::header::HeaderValue::from_str(sid).ok()) { + headers.insert("mcp-session-id", value); + } + client.post(url).headers(headers).timeout(std::time::Duration::from_secs(12)) + }; let post_rpc = |session_id: Option, body: serde_json::Value| { let client = client.clone(); let url = url.to_owned(); async move { - let mut req = - client.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string()); - if let Some(sid) = session_id.as_deref() { - req = req.header("Mcp-Session-Id", sid); - } + let req = post(&client, &url, session_id.as_deref()).body(body.to_string()); let resp = req .send() .await @@ -1218,7 +1228,7 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M }; // Best-effort `notifications/initialized` + `tools/list`. - let mut not_req = client.post(url).header(reqwest::header::CONTENT_TYPE, "application/json").body( + let not_req = post(&client, url, session_id.as_deref()).body( serde_json::json!({ "jsonrpc": "2.0", "method": "notifications/initialized", @@ -1226,9 +1236,6 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M }) .to_string(), ); - if let Some(sid) = session_id.as_deref() { - not_req = not_req.header("Mcp-Session-Id", sid); - } let _ = not_req.send().await; let tools_res = post_rpc( @@ -1866,6 +1873,112 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P mod tests { use super::*; + #[tokio::test] + async fn the_mcp_probe_goes_through_the_manual_proxy_and_keeps_its_headers() { + use std::io::{BufRead, BufReader, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let settings = ide_core::proxy_settings::ProxySettings { + mode: ide_core::proxy_settings::ProxyMode::Manual, + host: "127.0.0.1".into(), + port: address.port(), + ..Default::default() + }; + let proxy = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut head = String::new(); + while !head.ends_with("\r\n\r\n") { + if reader.read_line(&mut head).unwrap() == 0 { + break; + } + } + let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + head + }); + let server = ide_core::settings::AgentMcpServer { + transport: McpTransport::Http, + url: Some("http://mcp-target.invalid/mcp".into()), + headers: [("X-Test".to_owned(), "1".to_owned())].into(), + ..Default::default() + }; + let result = probe_http_mcp_server(&server, &settings).await; + assert!(!result.ok); + // A probe that bypassed the proxy leaves it waiting in `accept`; a dummy connection releases it. + let _ = std::net::TcpStream::connect(address); + let head = proxy.join().unwrap().to_ascii_lowercase(); + assert!(head.starts_with("post http://mcp-target.invalid/mcp http/1.1"), "{head}"); + assert!(head.contains("accept: application/json, text/event-stream"), "{head}"); + assert!(head.contains("x-test: 1"), "{head}"); + } + + #[tokio::test] + async fn mcp_protocol_headers_win_over_configured_ones_in_all_three_requests() { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = std::thread::spawn(move || { + let mut heads = Vec::new(); + for reply in [ + r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{},"serverInfo":{"name":"t","version":"1"}}}"#, + "", + r#"{"jsonrpc":"2.0","id":2,"result":{"tools":[]}}"#, + ] { + let (mut stream, _) = listener.accept().unwrap(); + let mut raw = Vec::new(); + let mut byte = [0u8; 1]; + while !raw.ends_with(b"\r\n\r\n") { + stream.read_exact(&mut byte).unwrap(); + raw.push(byte[0]); + } + let head = String::from_utf8(raw).unwrap().to_ascii_lowercase(); + let length = head + .lines() + .find_map(|line| line.strip_prefix("content-length: ")) + .map_or(0, |value| value.trim().parse().unwrap()); + let mut body = vec![0u8; length]; + stream.read_exact(&mut body).unwrap(); + heads.push(head); + let _ = stream.write_all( + format!( + "HTTP/1.1 200 OK\r\nMcp-Session-Id: s1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", + reply.len() + ) + .as_bytes(), + ); + } + heads + }); + let settings = ide_core::proxy_settings::ProxySettings { + mode: ide_core::proxy_settings::ProxyMode::None, + ..Default::default() + }; + let server_config = ide_core::settings::AgentMcpServer { + transport: McpTransport::Http, + url: Some(format!("http://127.0.0.1:{port}/mcp")), + headers: [ + ("Content-Type".to_owned(), "text/plain".to_owned()), + ("Mcp-Session-Id".to_owned(), "configured".to_owned()), + ("Accept".to_owned(), "text/x-configured".to_owned()), + ] + .into(), + ..Default::default() + }; + let result = probe_http_mcp_server(&server_config, &settings).await; + assert!(result.ok, "{:?}", result.error); + let heads = server.join().unwrap(); + let values = |head: &str, name: &str| -> Vec { + head.lines().filter_map(|line| line.strip_prefix(name)).map(|v| v.trim().to_owned()).collect() + }; + for (i, head) in heads.iter().enumerate() { + assert_eq!(values(head, "content-type:"), ["application/json"], "request {i}: {head}"); + assert_eq!(values(head, "accept:"), ["text/x-configured"], "request {i}: {head}"); + // The first request has no session yet, so the configured value stands. + let session = if i == 0 { "configured" } else { "s1" }; + assert_eq!(values(head, "mcp-session-id:"), [session], "request {i}: {head}"); + } + } + #[test] fn an_agent_installs_once_at_a_time() { let first = Installing::begin("test-agent").unwrap(); diff --git a/crates/ide-host/src/ops/ios.rs b/crates/ide-host/src/ops/ios.rs index 64a2fc230..bbae5de3d 100644 --- a/crates/ide-host/src/ops/ios.rs +++ b/crates/ide-host/src/ops/ios.rs @@ -8,16 +8,16 @@ async fn blocking(f: impl FnOnce() -> IdeResult + Send + ' tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))? } -/// The available iOS simulators, booted first; `None` outside macOS or when the project has no -/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has -/// no change feed, and one listing takes a fraction of a second. +/// The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside +/// macOS or when the project has no Xcode project or workspace at its root. Asked again whenever +/// the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second. #[command(trust = trusted)] pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult>> { let root = host.project(window)?.root.clone(); 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. diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index 6cd7ff0ec..97a266227 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -544,38 +544,24 @@ async fn resolve_launch_without_jdtls( let cancel = cancel.clone(); tokio::task::spawn_blocking(move || { let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings); - match from_server { - // The IDE's Java build gave the whole classpath; the server adds its JDK. - Some(server) if by_service => { - info.project_root = server.classpath.project_root; - info.java_home = server.jdk_home.map(Into::into); - } - None if by_service => {} - Some(server) => { - info.project_root = server.classpath.project_root; - info.module_paths = server.classpath.module_paths; - info.java_home = server.jdk_home.map(Into::into); - append_unique_class_paths(&mut class_paths, server.classpath.class_paths); - } - None => { - if !is_maven_module(root, &model, &module) { - return Err(IdeError::unavailable( - "Cannot resolve the classpath: the Java language server does not report it \ - (java-analyzer/projectClasspath), and the module is not a Maven project", - )); - } + let is_maven = is_maven_module(root, &model, &module); + let delegated_maven = !by_service && settings.languages.java.maven.delegate_build && is_maven; + apply_without_jdtls_classpath( + &mut class_paths, + &mut info, + from_server, + by_service, + is_maven, + delegated_maven, + || { let local_repo = ide_sdk::apply::maven_local_repository(root, settings); - let classpath = if aggregator && policy == BuildPolicy::NoBuild { - compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)? + if aggregator && policy == BuildPolicy::NoBuild { + compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel) } else { - compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)? - }; - append_unique_class_paths( - &mut class_paths, - std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()), - ); - } - } + compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel) + } + }, + )?; info.class_paths = class_paths; apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test); finish_launch(&mut info, root, &module, settings, &model, &data_dir); @@ -825,6 +811,59 @@ fn same_entry(a: &str, b: &str, windows: bool) -> bool { a == b || entry_key(a, windows) == entry_key(b, windows) } +/// Resolves the runtime/test classpath for a launch without jdtls (e.g. `java-analyzer` or +/// no Java language server). When `delegated_maven` is true (`delegateBuild = true` on a Maven +/// module), delegates classpath resolution to Maven itself (falling back to the language server's +/// classpath on error, matching the jdtls path) so child POM `` and Maven dependency +/// mediation are respected (#5586). +fn apply_without_jdtls_classpath( + class_paths: &mut Vec, + info: &mut JavaLaunchInfo, + from_server: Option, + by_service: bool, + is_maven: bool, + delegated_maven: bool, + probe_maven: impl FnOnce() -> IdeResult, +) -> IdeResult<()> { + match from_server { + // The IDE's Java build gave the whole classpath; the server adds its JDK. + Some(server) if by_service => { + info.project_root = server.classpath.project_root; + info.java_home = server.jdk_home.map(Into::into); + Ok(()) + } + None if by_service => Ok(()), + Some(server) if delegated_maven => { + info.project_root = server.classpath.project_root; + info.module_paths = server.classpath.module_paths; + info.java_home = server.jdk_home.map(Into::into); + info.class_paths = server.classpath.class_paths; + merge_maven_launch_classpath(class_paths, info, probe_maven(), &[]) + } + Some(server) => { + info.project_root = server.classpath.project_root; + info.module_paths = server.classpath.module_paths; + info.java_home = server.jdk_home.map(Into::into); + append_unique_class_paths(class_paths, server.classpath.class_paths); + Ok(()) + } + None => { + if !is_maven { + return Err(IdeError::unavailable( + "Cannot resolve the classpath: the Java language server does not report it \ + (java-analyzer/projectClasspath), and the module is not a Maven project", + )); + } + let classpath = probe_maven()?; + append_unique_class_paths( + class_paths, + std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()), + ); + Ok(()) + } + } +} + /// Merge the Maven launch classpath without turning a recoverable probe failure into a /// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath /// and leave the reason in the run console. Maven lists the module's and its reactor @@ -1259,6 +1298,55 @@ mod tests { ); } + #[test] + fn delegated_maven_without_jdtls_prefers_maven_classpath_over_server_classpath() { + let server = ide_lsp::java_project::ServerClasspath { + classpath: ide_lsp::jdtls::JavaClasspath { + project_root: Some(PathBuf::from("/work/child").into()), + // Static server resolver kept an excluded parent transitive jar (#5586). + class_paths: vec![ + "/work/child/target/classes".into(), + "/m2/log4j-slf4j-impl-2.12.1.jar".into(), + "/m2/logback-classic.jar".into(), + ], + module_paths: vec![], + }, + jdk_home: Some(PathBuf::from("/jdk8")), + }; + let maven = std::env::join_paths(["/work/child/target/classes", "/m2/logback-classic.jar"]) + .unwrap() + .to_string_lossy() + .into_owned(); + let mut class_paths = vec!["/work/child/target/classes".to_owned()]; + let mut info = JavaLaunchInfo::default(); + apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || Ok(maven)) + .unwrap(); + assert_eq!(class_paths, ["/work/child/target/classes", "/m2/logback-classic.jar"]); + assert_eq!(info.project_root, Some(PathBuf::from("/work/child").into())); + assert_eq!(info.java_home, Some(PathBuf::from("/jdk8").into())); + assert!(info.hints.is_empty(), "{:?}", info.hints); + } + + #[test] + fn delegated_maven_without_jdtls_falls_back_to_server_classpath_on_probe_error() { + let server = ide_lsp::java_project::ServerClasspath { + classpath: ide_lsp::jdtls::JavaClasspath { + project_root: Some(PathBuf::from("/work/child").into()), + class_paths: vec!["/m2/server-fallback.jar".into()], + module_paths: vec![], + }, + jdk_home: None, + }; + let mut class_paths = vec!["/work/child/target/classes".to_owned()]; + let mut info = JavaLaunchInfo::default(); + apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || { + Err(IdeError::internal("maven offline")) + }) + .unwrap(); + assert_eq!(class_paths, ["/work/child/target/classes", "/m2/server-fallback.jar"]); + assert!(info.hints[0].contains("maven offline"), "{:?}", info.hints); + } + #[test] fn cancelled_maven_classpath_probe_propagates_without_fallback() { let mut class_paths = vec!["snapshot.jar".to_owned()]; diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index c8a8d1f2c..0c42b4197 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -336,20 +336,36 @@ pub async fn lsp_inline_completion( let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) { Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => { let cancel = cancel.clone(); - plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten() + plugin_call(move || { + let offered = plugins.offers_inline_completion(&d.language); + (offered, plugins.provide_inline_completion(&d, pos, &cancel).map(|(_, s)| s)) + }) + .await } _ => None, }; host.end_request(request); + inline_items(result, plugin) +} + +/// The plugin's suggestion, else the servers'. When a plugin offers ghost text +/// for the document, "no server supports inline completion" is not returned: +/// the editor would stop asking while typing for 30 s, and a plugin that had +/// nothing this time (cancelled by the next keystroke) may have some next time. +fn inline_items( + servers: IdeResult>, + plugin: Option<(bool, Option)>, +) -> IdeResult> { match plugin { - Some((_, s)) => Ok(vec![InlineCompletionItem { + Some((_, Some(s))) => Ok(vec![InlineCompletionItem { insert_text: s.insert_text, range: s.replace, filter_text: None, command: None, server: PLUGIN_SERVER, }]), - None => result, + Some((true, None)) => provider_server(servers), + _ => servers, } } @@ -659,6 +675,53 @@ pub async fn lsp_switch_source_header( Ok(result?.map(|path| path.to_string_lossy().into_owned())) } +/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos` +/// instead of its `.d.ts`. Cancel with `cancel_request(request)`. +#[command(trust = trusted)] +pub async fn lsp_source_definition( + host: &Host, + window: &str, + request: RequestId, + doc: DocId, + pos: Pos, +) -> IdeResult> { + let lsp = host.project(window)?.lsp.clone(); + let cancel = host.begin_request(request); + let result = tokio::select! { + result = lsp.source_definition(doc, pos, cancel.clone()) => result, + _ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()), + }; + host.end_request(request); + result +} + +/// Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log. +#[command(trust = trusted)] +pub async fn lsp_open_typescript_file(host: &Host, window: &str, doc: DocId, what: TypeScriptFile) -> IdeResult<()> { + let lsp = host.project(window)?.lsp.clone(); + lsp.open_typescript_file(doc, what).await +} + +/// The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with +/// `cancel_request(request)`. +#[command(trust = trusted)] +pub async fn lsp_move_to_file_targets( + host: &Host, + window: &str, + request: RequestId, + doc: DocId, + command: Command, +) -> IdeResult> { + let lsp = host.project(window)?.lsp.clone(); + let cancel = host.begin_request(request); + let result = tokio::select! { + result = lsp.move_to_file_targets(doc, command, cancel.clone()) => result, + _ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()), + }; + host.end_request(request); + Ok(result?.into_iter().map(ide_core::IpcPath::from).collect()) +} + /// Implementations of the symbols at `positions`, one list per position (the /// editor's "is implemented / overridden" gutter markers). Cancel with /// `cancel_request(request)`. @@ -2429,6 +2492,19 @@ pub fn plugin_formatters() -> IdeResult, pub indexing: bool, pub extensions: Vec, + /// In-scope files matching `extensions`; `paths` holds the first + /// `MAX_NAVIGATION_FILES` of them. + pub total: u32, + pub truncated: bool, +} + +/// Discovery offers at most this many files; larger projects get navigation +/// on the first ones instead of none. +const MAX_NAVIGATION_FILES: usize = 20_000; + +/// The first `limit` files `in_scope` accepts, and how many it accepts in all. +fn first_in_scope(files: Vec, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec, usize) { + let mut files: Vec<_> = files.into_iter().filter(in_scope).collect(); + let total = files.len(); + files.truncate(limit); + (files, total) } #[command(trust = trusted)] @@ -24,19 +40,25 @@ pub async fn plugin_navigation_files( blocking(move || { let extensions = plugins.navigation_extensions(&project.root); if extensions.is_empty() { - return Ok(NavigationFiles { paths: vec![], indexing: false, extensions: vec![] }); + return Ok(NavigationFiles { + paths: vec![], + indexing: false, + extensions: vec![], + total: 0, + truncated: false, + }); } let indexing = project.index.status().indexing; - let files = project.index.files_with_extensions(&extensions, 20_001); - if files.len() > 20_000 { - return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files")); - } + let files = project.index.files_with_extensions(&extensions, usize::MAX); // A project window group's members are project scope: their files are // in the group's index (the group root holds none of them). let members = crate::project::workspace_member_roots(&project.root); let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m)); + let (files, total) = first_in_scope(files, in_scope, MAX_NAVIGATION_FILES); Ok(NavigationFiles { - paths: files.into_iter().filter(in_scope).map(Into::into).collect(), + truncated: total > files.len(), + total: u32::try_from(total).unwrap_or(u32::MAX), + paths: files.into_iter().map(Into::into).collect(), indexing, extensions, }) @@ -210,3 +232,19 @@ ide_command::domain!( plugin_navigation_invalidate, plugin_navigation_markers, ); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() { + let files: Vec = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect(); + let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3); + // Out-of-scope files neither take a slot nor count toward the total. + assert_eq!(total, 4); + assert_eq!(kept, ["/p/0/f0.xml", "/p/0/f2.xml", "/p/0/f4.xml"].map(PathBuf::from)); + let (kept, total) = first_in_scope(kept, |_| true, 20_000); + assert_eq!((kept.len(), total), (3, 3)); + } +} diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 3b32ca3ca..01fdec464 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -422,6 +422,10 @@ pub struct PluginHost { initial_load: (Mutex, Condvar), /// `on-startup-finished` has fired. startup_finished: AtomicBool, + /// Language, file and view activation events fired so far (with their project), so a plugin + /// installed or synced afterwards (a remote server gets its packages after the window opened + /// files) still activates for a Twig file that is already open. + fired_activations: Mutex)>>, /// The theme last announced with `ThemeChanged`. announced_theme: Mutex>, /// [`PluginLanguages::revision`] last announced with `LanguagesChanged`. @@ -541,6 +545,7 @@ impl PluginHost { lifecycle: Mutex::new(()), initial_load: (Mutex::new(false), Condvar::new()), startup_finished: AtomicBool::new(false), + fired_activations: Mutex::new(Vec::new()), announced_theme: Mutex::new(None), announced_languages: AtomicU64::new(0), announced_skills: AtomicU64::new(0), @@ -699,6 +704,16 @@ impl PluginHost { /// Fires an activation event from the UI (`on-language:rust`, `on-file:…`, `on-view:…`). pub fn activation_event(&self, event: &ActivationEvent, project: Option<&Path>) { + { + let mut fired = self.fired_activations.lock(); + let entry = (event.clone(), project.map(Path::to_path_buf)); + if !fired.contains(&entry) { + if fired.len() >= MAX_FIRED_ACTIVATIONS { + fired.remove(0); + } + fired.push(entry); + } + } let targets: Vec<_> = self .plugins .read() @@ -3096,8 +3111,12 @@ impl PluginHost { meta.pending = pending; meta.status = if plugin.manifest().wasm.is_some() { PluginStatus::Inactive } else { PluginStatus::Static }; } - let eager = plugin.manifest().activation.contains(&ActivationEvent::StartupFinished) - && self.startup_finished.load(Ordering::Acquire); + let eager = (plugin.manifest().activation.contains(&ActivationEvent::StartupFinished) + && self.startup_finished.load(Ordering::Acquire)) + || self.fired_activations.lock().iter().any(|(event, project)| { + (plugin.dev_root.is_none() || plugin.dev_root == *project) + && plugin.manifest().activation.iter().any(|a| activation_matches(a, event)) + }); if eager { let _ = self.ensure_active(plugin, None); } @@ -3725,6 +3744,9 @@ fn counts(m: &Manifest) -> Vec { m.declaration_counts().into_iter().map(|(point, count)| ContributionCount { point, count }).collect() } +/// How many fired activation events [`PluginHost::activation_event`] remembers (oldest dropped first). +const MAX_FIRED_ACTIVATIONS: usize = 512; + fn activation_matches(declared: &ActivationEvent, fired: &ActivationEvent) -> bool { match (declared, fired) { (ActivationEvent::Language(a), ActivationEvent::Language(b)) => a == b || a == "*", diff --git a/crates/ide-host/src/plugins/providers.rs b/crates/ide-host/src/plugins/providers.rs index 9fe44bf29..bbd51bbe7 100644 --- a/crates/ide-host/src/plugins/providers.rs +++ b/crates/ide-host/src/plugins/providers.rs @@ -653,6 +653,11 @@ impl PluginHost { .collect() } + /// Whether a usable plugin offers ghost text for `language`. + pub fn offers_inline_completion(&self, language: &str) -> bool { + !self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty() + } + /// Ghost text from the first plugin that has some. Not bound by the /// edit-path soft deadline (it may need the network) but by `cancel`: /// the editor cancels a request as soon as the user types on. diff --git a/crates/ide-host/src/plugins/websocket.rs b/crates/ide-host/src/plugins/websocket.rs index f6684fa76..af5aec26c 100644 --- a/crates/ide-host/src/plugins/websocket.rs +++ b/crates/ide-host/src/plugins/websocket.rs @@ -5,6 +5,10 @@ use super::{ network_inbox::{Inbox, Push}, }; use futures::{SinkExt, StreamExt}; +use ide_core::{ + IdeResult, + proxy_settings::{ProxyMode, ProxySettings}, +}; use ide_plugin::WebSocketBatch; use parking_lot::Mutex; use std::{ @@ -17,7 +21,7 @@ use std::{ }; use tokio::sync::{Notify, watch}; use tokio_tungstenite::{ - Connector, connect_async_tls_with_config, + Connector, client_async_tls_with_config, tungstenite::{ Message, client::IntoClientRequest, @@ -128,11 +132,20 @@ impl WebSocketHub { .map(Arc::new) .map(Connector::Rustls) .map_err(|error| ConnectError::Failed(error.message))?; - let (socket, response) = - tokio::time::timeout(timeout, connect_async_tls_with_config(request, Some(config), false, Some(tls))) + let target = reqwest::Url::parse(url).map_err(|_| ConnectError::Invalid("invalid WebSocket URL".into()))?; + // Through the IDE's proxy settings, like the Jupyter kernel channels. + let (socket, response) = tokio::time::timeout(timeout, async { + // The tunnel's reason (a proxy that needs a login, refuses or is unreachable) helps the user. + let stream = open_stream(&target, &ide_core::proxy_settings::proxy()) .await - .map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))? - .map_err(|_| ConnectError::Failed("WebSocket connection failed".into()))?; + .map_err(|error| format!("WebSocket connection failed: {}", error.message))?; + client_async_tls_with_config(request, stream, Some(config), Some(tls)) + .await + .map_err(|_| "WebSocket connection failed".to_owned()) + }) + .await + .map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))? + .map_err(ConnectError::Failed)?; if !subprotocol.is_empty() && response.headers().get("sec-websocket-protocol").and_then(|value| value.to_str().ok()) != Some(subprotocol) @@ -257,14 +270,30 @@ impl WebSocketHub { } } -fn validate_url(url: &str) -> Result<(), String> { - let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?; - // `host_str` keeps an IPv6 address in brackets. - let loopback = parsed.host_str().is_some_and(|host| { +/// `host_str` keeps an IPv6 address in brackets. +fn is_loopback(url: &reqwest::Url) -> bool { + url.host_str().is_some_and(|host| { let host = host.trim_start_matches('[').trim_end_matches(']'); host.eq_ignore_ascii_case("localhost") || host.parse::().is_ok_and(|ip| ip.is_loopback()) - }); - if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && loopback) { + }) +} + +/// The TCP stream to `url` under `settings`. Loopback stays direct in every mode (plaintext `ws://` is +/// loopback-only); a proxy the tunnel cannot speak to (SOCKS) keeps the direct connection plugins had before. +async fn open_stream(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult { + if is_loopback(url) { + return ide_http::tunnel::connect_best_effort( + url, + &ProxySettings { mode: ProxyMode::None, ..Default::default() }, + ) + .await; + } + ide_http::tunnel::connect_best_effort(url, settings).await +} + +fn validate_url(url: &str) -> Result<(), String> { + let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?; + if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && is_loopback(&parsed)) { return Err("WebSocket requires WSS outside loopback".into()); } if !parsed.username().is_empty() || parsed.password().is_some() || parsed.fragment().is_some() { @@ -392,6 +421,84 @@ mod tests { (url, task) } + fn manual(port: u16) -> ProxySettings { + ProxySettings { mode: ProxyMode::Manual, host: "127.0.0.1".into(), port, ..Default::default() } + } + + async fn head_of_first_connection(listener: TcpListener) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let (mut client, _) = listener.accept().await.unwrap(); + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + client.read_exact(&mut byte).await.unwrap(); + head.push(byte[0]); + } + client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await.unwrap(); + String::from_utf8(head).unwrap() + } + + #[tokio::test] + async fn a_manual_proxy_carries_the_connection() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let settings = manual(listener.local_addr().unwrap().port()); + let proxy = tokio::spawn(head_of_first_connection(listener)); + let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap(); + assert!(open_stream(&url, &settings).await.is_err()); + // A connection that bypasses the proxy leaves it waiting, so bound the wait. + let asked = tokio::time::timeout(Duration::from_secs(2), proxy).await.expect("the proxy was never asked"); + assert!(asked.unwrap().starts_with("CONNECT ws-target.invalid:443 HTTP/1.1\r\n")); + } + + #[tokio::test] + async fn loopback_stays_direct_in_every_mode() { + let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy_port = proxy.local_addr().unwrap().port(); + let proxy_task = tokio::spawn(head_of_first_connection(proxy)); + let target = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = + reqwest::Url::parse(&format!("ws://localhost:{}/socket", target.local_addr().unwrap().port())).unwrap(); + let settings = manual(proxy_port); + open_stream(&url, &settings).await.unwrap(); + tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap(); + // Auto mode asks the system proxy, which may be set in the environment: loopback must not. + open_stream(&url, &ProxySettings::default()).await.unwrap(); + tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap(); + assert!(tokio::time::timeout(Duration::from_millis(200), proxy_task).await.is_err(), "the proxy was asked"); + } + + #[tokio::test] + async fn an_ipv6_loopback_websocket_connects() { + let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here + let url = format!("ws://[::1]:{}/socket", listener.local_addr().unwrap().port()); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap(); + socket.send(Message::Binary(vec![7].into())).await.unwrap(); + socket.close(None).await.unwrap(); + }); + let hub = WebSocketHub::default(); + hub.connect("plugin", "/project", &url, &[], "", Duration::from_secs(2)).await.unwrap(); + server.await.unwrap(); + } + + #[tokio::test] + async fn a_refusing_proxy_says_why() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let settings = manual(listener.local_addr().unwrap().port()); + let proxy = tokio::spawn(async move { + use tokio::io::AsyncWriteExt; + let (mut client, _) = listener.accept().await.unwrap(); + client.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").await.unwrap(); + // Keep the socket open until the client has read the reply. + tokio::time::sleep(Duration::from_millis(200)).await; + }); + let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap(); + let error = open_stream(&url, &settings).await.unwrap_err(); + assert!(error.message.contains("needs a login"), "{}", error.message); + proxy.await.unwrap(); + } + #[tokio::test] async fn outbound_message_reaches_the_websocket_server() { let (url, server) = server().await; diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index cc8801c6e..6e503c274 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -77,6 +77,7 @@ pub struct Project { pub(crate) widget_preview: ide_flutter::ToolServer, pub(crate) kotlin_bridge: Option>, pub(crate) phpstan: Option>, + pub(crate) swiftlint: Option>, pub(crate) tsc_watch: Option>, pub(crate) watcher: Arc, /// Watchers of the Project Structure content roots outside the project folder. @@ -419,6 +420,8 @@ impl Host { trusted.clone(), ); documents.add_observer(phpstan.clone()); + let swiftlint = crate::swiftlint::SwiftLint::new(root.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()); let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?)); @@ -441,6 +444,7 @@ impl Host { let window = window.to_owned(); let kotlin_bridge = kotlin_bridge.clone(); let phpstan = phpstan.clone(); + let swiftlint = swiftlint.clone(); let repos = repos.clone(); let git_metadata = git_metadata.clone(); let settings = settings.clone(); @@ -470,6 +474,7 @@ impl Host { index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat()); kotlin_bridge.files_changed(changed.iter().chain(&batch.removed)); phpstan.files_removed(batch.removed.iter()); + swiftlint.files_removed(batch.removed.iter()); lsp.project_files_changed(batch.created.iter().chain(&batch.removed)); lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs); if composer_changed(&root, changed.iter().chain(&batch.removed)) @@ -720,6 +725,7 @@ impl Host { notebooks, kotlin_bridge: Some(kotlin_bridge), phpstan: Some(phpstan), + swiftlint: Some(swiftlint), tsc_watch: Some(tsc_watch), watcher, content_watchers: Mutex::new(content_watchers), @@ -773,6 +779,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); @@ -784,6 +792,9 @@ impl Host { if let Some(phpstan) = &project.phpstan { phpstan.start(&self.runtime); } + if let Some(swiftlint) = &project.swiftlint { + swiftlint.start(&self.runtime); + } if let Some(watch) = &project.tsc_watch { watch.apply(&self.runtime); } @@ -1015,6 +1026,7 @@ impl Host { notebooks, kotlin_bridge: None, phpstan: None, + swiftlint: None, tsc_watch: None, watcher: Arc::new(watcher), content_watchers: Mutex::new(Vec::new()), diff --git a/crates/ide-host/src/swiftlint.rs b/crates/ide-host/src/swiftlint.rs new file mode 100644 index 000000000..f69de6d19 --- /dev/null +++ b/crates/ide-host/src/swiftlint.rs @@ -0,0 +1,404 @@ +//! Swift files below a `.swiftlint.yml` -> `swiftlint lint --reporter json` -> `swiftlint` diagnostics. +//! +//! A file as saved is linted by its path, so the configuration's `excluded` paths and nested +//! configurations apply; an edited buffer is linted through stdin, unless its saved file was excluded. + +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::documents::{DocumentInfo, DocumentObserver}; +use parking_lot::Mutex; +use serde::Deserialize; +use std::collections::{BTreeMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::process::{Output, Stdio}; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; +use std::time::Duration; +use tokio::io::AsyncWriteExt; +use tokio::sync::Notify; + +const DELAY: Duration = Duration::from_millis(400); +const SOURCE: &str = "swiftlint"; +const CONFIG: &str = ".swiftlint.yml"; + +/// What to lint: the saved file, or the text of its edited buffer. +#[derive(Clone, Debug, PartialEq)] +enum Job { + Saved, + Buffer(String), +} + +pub(crate) struct SwiftLint { + root: PathBuf, + sink: SharedSink, + trusted: Arc, + lifetime: CancellationToken, + /// The latest job per file; a newer one replaces it, and its result is dropped. + pending: Mutex>, + changed: Notify, + /// Files with SwiftLint diagnostics, the only ones a clean result or a close clears. + shown: Mutex>, + /// Files the configuration excludes, as found by their last saved-file lint. + excluded: Mutex>, + /// Failures already reported (a missing `swiftlint` included), each once until a run succeeds. + reported: Mutex>, +} + +impl SwiftLint { + pub(crate) fn new(root: PathBuf, sink: SharedSink, trusted: Arc) -> Arc { + Arc::new(Self { + root, + sink, + trusted, + lifetime: CancellationToken::new(), + pending: Mutex::new(BTreeMap::new()), + changed: Notify::new(), + shown: Mutex::new(HashSet::new()), + excluded: Mutex::new(HashSet::new()), + reported: Mutex::new(None), + }) + } + + pub(crate) fn start(self: &Arc, runtime: &tokio::runtime::Handle) { + let linter = self.clone(); + runtime.spawn(async move { linter.run().await }); + } + + pub(crate) fn stop(&self) { + self.lifetime.cancel(); + } + + fn queue(&self, path: &Path, job: Job) { + if self.lifetime.is_cancelled() || !path.extension().is_some_and(|e| e == "swift") { + return; + } + self.pending.lock().insert(path.to_path_buf(), job); + self.changed.notify_one(); + } + + /// Trusting the project lints its open files; Restricted Mode drops what was shown. + pub(crate) fn trust_changed(&self, trusted: bool, open: impl Iterator) { + if trusted { + open.for_each(|info| self.opened(&info)); + } else { + self.pending.lock().clear(); + let shown: Vec = self.shown.lock().iter().cloned().collect(); + for path in shown { + self.publish(path, Vec::new()); + } + } + } + + /// Deleted files and folders lose their diagnostics. + pub(crate) fn files_removed<'a>(&self, removed: impl Iterator) { + let removed: Vec<&PathBuf> = removed.collect(); + self.excluded.lock().retain(|p| !removed.iter().any(|r| p.starts_with(r))); + let gone: Vec = + self.shown.lock().iter().filter(|p| removed.iter().any(|r| p.starts_with(r))).cloned().collect(); + for path in gone { + self.publish(path, Vec::new()); + } + } + + fn publish(&self, path: PathBuf, items: Vec) { + let mut shown = self.shown.lock(); + if items.is_empty() { + if !shown.remove(&path) { + return; + } + } else { + shown.insert(path.clone()); + } + self.sink.emit(IdeEvent::Diagnostics { path: path.into(), source: SOURCE.into(), items }); + } + + async fn run(self: Arc) { + loop { + tokio::select! { + _ = self.lifetime.cancelled() => return, + _ = self.changed.notified() => {}, + } + // Typing keeps replacing the pending job: lint once it pauses. + tokio::select! { + _ = self.lifetime.cancelled() => return, + _ = tokio::time::sleep(DELAY) => {}, + } + loop { + let Some((path, job)) = self.pending.lock().pop_first() else { break }; + if !self.trusted.load(Ordering::Acquire) { + continue; + } + let Some(dir) = config_dir(&self.root, &path) else { + self.publish(path, Vec::new()); + continue; + }; + if job != Job::Saved && self.excluded.lock().contains(&path) { + continue; + } + let text = match &job { + Job::Saved => None, + Job::Buffer(text) => Some(text.as_str()), + }; + let Some(output) = lint(&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 { + "swiftlint was not found on PATH. Install SwiftLint (brew install swiftlint), \ + or from Settings › Languages & Frameworks › Language Servers." + .to_string() + } else { + format!("Cannot run swiftlint: {e}") + } + }); + let result = result.and_then(|o| parse(&decode_tool_output(&o.stdout), &decode_tool_output(&o.stderr))); + match result { + Ok(Report::Excluded) => { + self.excluded.lock().insert(path.clone()); + self.publish(path, Vec::new()); + *self.reported.lock() = None; + } + Ok(Report::Violations(violations)) => { + if job == Job::Saved { + self.excluded.lock().remove(&path); + } + let text = match job { + Job::Buffer(text) => text, + Job::Saved => std::fs::read(&path) + .map(|b| String::from_utf8_lossy(&b).into_owned()) + .unwrap_or_default(), + }; + let items = violations.into_iter().map(|v| diagnostic(v, &text)).collect(); + self.publish(path, items); + *self.reported.lock() = None; + } + Err(text) => { + self.publish(path, Vec::new()); + self.failure(text); + } + } + } + } + } + + fn failure(&self, text: String) { + let mut reported = self.reported.lock(); + if reported.as_ref() == Some(&text) { + return; + } + self.sink.emit(IdeEvent::Notify { + level: NotifyLevel::Error, + title: "SwiftLint check failed".into(), + body: Some(text.clone()), + }); + *reported = Some(text); + } +} + +impl DocumentObserver for SwiftLint { + fn opened(&self, info: &DocumentInfo) { + let path = info.path.to_path_buf(); + self.queue(&path, if info.dirty { Job::Buffer(info.text.clone()) } else { Job::Saved }); + } + + fn changed( + &self, + _doc: ide_core::DocId, + path: &Path, + _version: u32, + _changes: &[AppliedChange], + full_text: &dyn Fn() -> String, + ) { + if path.extension().is_some_and(|e| e == "swift") { + self.queue(path, Job::Buffer(full_text())); + } + } + + fn saved(&self, _doc: ide_core::DocId, path: &Path, _text: &str) { + self.queue(path, Job::Saved); + } + + /// A closed buffer's unsaved text is gone, and with it what its diagnostics described. + fn closed(&self, _doc: ide_core::DocId, path: &Path) { + self.pending.lock().remove(path); + self.publish(path.to_path_buf(), Vec::new()); + } +} + +/// The folder of the `.swiftlint.yml` nearest to `file` within the project, where SwiftLint +/// runs so it finds that configuration. Files outside the project, or below no configuration, +/// are not linted. +fn config_dir(root: &Path, file: &Path) -> Option { + file.ancestors() + .skip(1) + .take_while(|d| d.starts_with(root)) + .find(|d| d.join(CONFIG).is_file()) + .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. +async fn lint( + dir: &Path, + file: &Path, + text: Option<&str>, + cancel: &CancellationToken, +) -> Option> { + let mut cmd = std::process::Command::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); + 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); + cmd.kill_on_drop(true); + let run = async { + let mut child = cmd.spawn()?; + if let (Some(text), Some(mut stdin)) = (text, child.stdin.take()) { + stdin.write_all(text.as_bytes()).await?; + } + child.wait_with_output().await + }; + tokio::select! { + output = run => Some(output), + () = cancel.cancelled() => None, + } +} + +/// One entry of SwiftLint's JSON report; `line` and `character` are 1-based, the +/// character counted in UTF-16 units. +#[derive(Debug, Deserialize, PartialEq)] +struct Violation { + line: Option, + character: Option, + reason: String, + rule_id: String, + severity: String, +} + +#[derive(Debug, PartialEq)] +enum Report { + Violations(Vec), + /// `--force-exclude` dropped the file: the configuration's `excluded` lists it. + Excluded, +} + +/// The `--reporter json` report (SwiftLint exits with 2 when it has errors), or the text +/// to report when there is none. +fn parse(stdout: &str, stderr: &str) -> Result { + if let Ok(violations) = serde_json::from_str::>(stdout.trim()) { + return Ok(Report::Violations(violations)); + } + if stderr.contains("No lintable files found") { + return Ok(Report::Excluded); + } + let lines: Vec<&str> = stderr.lines().chain(stdout.lines()).map(str::trim).filter(|l| !l.is_empty()).collect(); + if lines.is_empty() { + return Err("SwiftLint ended with no report".into()); + } + Err(lines.iter().take(20).copied().collect::>().join("\n")) +} + +fn diagnostic(v: Violation, text: &str) -> Diagnostic { + Diagnostic { + range: range(text, v.line, v.character), + severity: if v.severity.eq_ignore_ascii_case("error") { Severity::Error } else { Severity::Warning }, + message: v.reason, + source: Some("SwiftLint".into()), + server: Some(SOURCE.into()), + code: Some(v.rule_id), + unnecessary: false, + deprecated: false, + } +} + +/// The word at the reported position, or the line from its first non-blank character when +/// SwiftLint gives no column (or the column has no word: a semicolon, a brace). +fn range(text: &str, line: Option, character: Option) -> Range { + let line = line.unwrap_or(1).max(1) - 1; + let content = text.strip_prefix('\u{feff}').unwrap_or(text).split('\n').nth(line as usize).unwrap_or(""); + let content: Vec = content.trim_end().encode_utf16().collect(); + let len = u32::try_from(content.len()).unwrap_or(u32::MAX); + let Some(start) = character.map(|c| c.max(1) - 1).filter(|&c| c < len) else { + let indent = content.iter().take_while(|&&u| u == u16::from(b' ') || u == u16::from(b'\t')).count(); + return Range { start: Pos { line, col: indent as u32 }, end: Pos { line, col: len } }; + }; + let word = |u: &u16| char::from_u32(u32::from(*u)).is_some_and(|c| c.is_alphanumeric() || c == '_'); + let run = content[start as usize..].iter().take_while(|u| word(u)).count() as u32; + Range { start: Pos { line, col: start }, end: Pos { line, col: start + run.max(1) } } +} + +#[cfg(test)] +mod tests { + use super::*; + + const REPORT: &str = r#"[ + {"character": 5, "file": null, "line": 1, "reason": "Variable name 'a_b' should only contain alphanumeric characters", + "rule_id": "identifier_name", "severity": "Error", "type": "Identifier Name"}, + {"character": null, "file": "/p/A.swift", "line": 3, "reason": "Line should be 40 characters or less", + "rule_id": "line_length", "severity": "Warning", "type": "Line Length"}, + {"character": 13, "file": null, "line": 2, "reason": "Lines should not have trailing semicolons", + "rule_id": "trailing_semicolon", "severity": "Warning", "type": "Trailing Semicolon"} + ]"#; + + #[test] + fn violations_map_to_diagnostics() { + let Ok(Report::Violations(violations)) = parse(REPORT, "") else { panic!() }; + let text = "let a_b = 1\nlet 😀x = 1 ;\n let long = 2\n"; + let items: Vec = violations.into_iter().map(|v| diagnostic(v, text)).collect(); + let summary: Vec<_> = items.iter().map(|d| (d.code.as_deref().unwrap(), d.severity, d.range)).collect(); + let r = |line, a, b| Range { start: Pos { line, col: a }, end: Pos { line, col: b } }; + assert_eq!( + summary, + [ + ("identifier_name", Severity::Error, r(0, 4, 7)), + // No column: the line from its first non-blank character. + ("line_length", Severity::Warning, r(2, 4, 16)), + // UTF-16 columns: the emoji takes two, and a semicolon gets one. + ("trailing_semicolon", Severity::Warning, r(1, 12, 13)), + ] + ); + assert_eq!((items[0].source.as_deref(), items[0].server.as_deref()), (Some("SwiftLint"), Some("swiftlint"))); + assert!(items[0].message.starts_with("Variable name 'a_b'")); + } + + #[test] + fn excluded_files_and_failures_are_told_apart() { + assert_eq!(parse("[]\n", ""), Ok(Report::Violations(vec![]))); + let excluded = "Error: No lintable files found at paths: 'Gen/g.swift'\n"; + assert_eq!(parse("", excluded), Ok(Report::Excluded)); + assert_eq!(parse("", "Fatal error: crashed\n\n"), Err("Fatal error: crashed".into())); + assert_eq!(parse("", ""), Err("SwiftLint ended with no report".into())); + // A bad column or line stays on the text. + assert_eq!( + range("x", Some(9), Some(40)), + Range { start: Pos { line: 8, col: 0 }, end: Pos { line: 8, col: 0 } } + ); + } + + #[test] + fn the_nearest_configuration_in_the_project_wins() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("p"); + std::fs::create_dir_all(root.join("Sources/App")).unwrap(); + std::fs::create_dir_all(root.join("Pkg/Sources")).unwrap(); + let file = root.join("Sources/App/A.swift"); + assert_eq!(config_dir(&root, &file), None); + std::fs::write(dir.path().join(CONFIG), "").unwrap(); + assert_eq!(config_dir(&root, &file), None, "a configuration above the project is not the project's"); + std::fs::write(root.join(CONFIG), "").unwrap(); + std::fs::write(root.join("Pkg").join(CONFIG), "").unwrap(); + assert_eq!(config_dir(&root, &file), Some(root.clone())); + assert_eq!(config_dir(&root, &root.join("Pkg/Sources/B.swift")), Some(root.join("Pkg"))); + } +} diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index e954e9575..cdec9ba9b 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -267,6 +267,10 @@ impl crate::Host { if let Some(phpstan) = &project.phpstan { phpstan.interrupt(); } + if let Some(swiftlint) = &project.swiftlint { + let docs = project.documents.open_documents(); + swiftlint.trust_changed(trusted, docs.into_iter().filter_map(|d| project.documents.snapshot(d).ok())); + } if let Some(watch) = &project.tsc_watch { watch.apply(&self.runtime); } @@ -276,6 +280,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) { diff --git a/crates/ide-host/src/xcode_env.rs b/crates/ide-host/src/xcode_env.rs new file mode 100644 index 000000000..a6b1b5b83 --- /dev/null +++ b/crates/ide-host/src/xcode_env.rs @@ -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/`, so an untrusted one could point them at its own binaries. +fn developer_dir(trusted: bool, swift: &SwiftSettings) -> Option { + 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); + } +} diff --git a/crates/ide-host/tests/mcp.rs b/crates/ide-host/tests/mcp.rs index d1b0b8add..9232cb6cc 100644 --- a/crates/ide-host/tests/mcp.rs +++ b/crates/ide-host/tests/mcp.rs @@ -1166,8 +1166,12 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() { assert_eq!(stopped["state"], "stoppedByAgent", "{stopped}"); assert!(stopped.get("interventions").is_none()); - // The user's Stop, rerun and closing the tab are reported with their time. - h.json("run_command", json!({"name": "server", "command": "sleep 30", "timeout": 0})).await; + // The user's Stop, rerun and closing the tab are reported with their time. A stop waits for the command + // itself: a Ctrl+C while the login shell still reads its profile can be taken by a profile command that + // handles it, and the shell then runs the command anyway. + let ready = json!({"name": "server", "command": "echo ready; sleep 30", "pattern": "(?m)^ready", "timeout": 10000}); + let ready = h.json("run_command", ready).await; + assert_eq!((&ready["waitEnded"], &ready["state"]), (&json!("matched"), &json!("running")), "{ready}"); ide_host::ops::run::run_stop(&h.host, "main", agent_process(&h, "_agent_server")).unwrap(); let stop = h.json("wait_for_run", json!({"name": "server", "timeout": 10000})).await; assert!(stop["interventions"][0]["message"].as_str().unwrap().starts_with("The user stopped this command at")); @@ -1217,7 +1221,10 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() { assert_eq!(head["output"], "one\n<<<...content truncated...>>>\n", "{head}"); // Ctrl+C stops the command as stop_run does; terminal keys have no meaning on pipes. - h.json("run_command", json!({"name": "interrupt", "command": "sleep 30", "timeout": 0})).await; + let ready = + json!({"name": "interrupt", "command": "echo ready; sleep 30", "pattern": "(?m)^ready", "timeout": 10000}); + let ready = h.json("run_command", ready).await; + assert_eq!((&ready["waitEnded"], &ready["state"]), (&json!("matched"), &json!("running")), "{ready}"); let key = h.error("send_run_input", json!({"name": "interrupt", "keys": ["Up"]})).await; assert!(key.contains("runs on pipes"), "{key}"); h.json("send_run_input", json!({"name": "interrupt", "keys": ["Ctrl+C"]})).await; diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 620854a29..62dfea064 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -1590,6 +1590,28 @@ fn misbehave_with_language(dir: &Path) -> PathBuf { pkg } +/// A language activation fired before the plugin was there (a remote server gets the desktop's +/// packages after the window opened its files; a plugin installed with such a file open) +/// activates it once it loads; one that never fired doesn't. +#[test] +fn plugins_loaded_after_their_activation_event_fired_activate() { + use ide_extension::ActivationEvent; + let tmp = tempfile::tempdir().unwrap(); + let host = Arc::new( + PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(), + ); + host.load_all(); + host.startup_finished(); + host.activation_event(&ActivationEvent::Language("other".into()), None); + host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap(); + assert_eq!(host.info_of("misbehave").unwrap().status, PluginStatus::Inactive); + host.uninstall("misbehave").unwrap(); + + host.activation_event(&ActivationEvent::Language("mis".into()), None); + host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap(); + assert!(eventually(|| host.info_of("misbehave").is_ok_and(|i| i.status == PluginStatus::Active))); +} + /// Edit-path calls stop waiting at the soft deadline (the result is /// dropped, the instance kept) and are interrupted at the hard one. #[test] @@ -3027,6 +3049,38 @@ fn official_ai_completion_cancels_superseded_requests() { assert!(times[9] < Duration::from_millis(500), "{times:?}"); } +/// Installed with the optional network permission refused (it is not ticked by +/// default), a suggestion request says so in the window instead of failing silently. +#[test] +fn official_ai_completion_explains_a_refused_network_permission() { + let f = fixture(Limits::default()); + f.host.install_from_dir(&official("ai-completion"), &Consent::default()).unwrap(); + let (port, seen) = http_server(r#"{"choices":[{"text":"a + b\n"}]}"#, |_| Duration::ZERO); + f.run("openidea.ai-completion", "set-endpoint", Some(&format!("http://localhost:{port}"))).unwrap(); + f.take_events(); + let doc = ide_plugin::ProviderDocument { + path: f.project.join("src/a.rs"), + language: "rust".into(), + version: 1, + text: "let x = ".into(), + }; + for _ in 0..2 { + assert!(f.host.provide_inline_completion(&doc, ide_core::Pos::new(0, 8), &Default::default()).is_none()); + } + assert!(seen.lock().is_empty(), "denied before connecting"); + let notices: Vec = f + .take_events() + .into_iter() + .filter_map(|(_, e)| match e { + PluginEvent::Notification { level: NotificationLevel::Warning, body, .. } => Some(body), + _ => None, + }) + .collect(); + assert_eq!(notices.len(), 1, "once: {notices:?}"); + assert!(notices[0].contains("Settings › Plugins › AI Completion"), "{notices:?}"); + assert_eq!(f.status("openidea.ai-completion"), PluginStatus::Active, "not a crash"); +} + /// Checkstyle: a save runs the approved `checkstyle` and publishes /// diagnostics; quick fixes come through the code-action provider; saving /// again cancels the check still running. diff --git a/crates/ide-http/src/tunnel.rs b/crates/ide-http/src/tunnel.rs index b6ba7017f..170b1ae7e 100644 --- a/crates/ide-http/src/tunnel.rs +++ b/crates/ide-http/src/tunnel.rs @@ -2,7 +2,8 @@ //! speak (a WebSocket): direct, or through an HTTP proxy's `CONNECT` tunnel. use base64::Engine; -use ide_core::proxy_settings::ProxyRoute; +use hyper_util::client::proxy::matcher::Matcher; +use ide_core::proxy_settings::{ProxyRoute, ProxySettings}; use ide_core::{IdeError, IdeResult}; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -10,32 +11,84 @@ use tokio::net::TcpStream; const CONNECT_TIMEOUT: Duration = Duration::from_secs(30); +/// The PAC lookup of the system proxy settings; none outside macOS. +#[cfg(target_os = "macos")] +const SYSTEM_PAC: fn(&str) -> Option = crate::system_pac_route; +#[cfg(not(target_os = "macos"))] +const SYSTEM_PAC: fn(&str) -> Option = |_| None; + /// A connection to `url`'s host and port, through the proxy System Settings › HTTP Proxy /// (or, in Auto mode, the system) routes that host to. pub async fn connect(url: &reqwest::Url) -> IdeResult { + let route = ide_core::proxy_settings::proxy().route(url.host_str()); + connect_with(url, route, SYSTEM_PAC, Matcher::from_system, false).await +} + +/// [`connect`] under explicit proxy `settings`; a proxy the tunnel cannot speak to (SOCKS) is skipped and +/// the connection goes direct, as it did before the proxy was consulted at all. +pub async fn connect_best_effort(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult { + connect_with(url, settings.route(url.host_str()), SYSTEM_PAC, Matcher::from_system, true).await +} + +/// `host:port`; `host_str` already brackets an IPv6 address (the same rule as `pac.rs`'s `authority`). +fn authority(host: &str, port: u16) -> String { + if host.contains(':') && !host.starts_with('[') { format!("[{host}]:{port}") } else { format!("{host}:{port}") } +} + +/// The URI the system proxy settings are asked about: the scheme reqwest would use (`ws` → `http`). +fn system_uri(url: &reqwest::Url) -> IdeResult { let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?; let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?; - let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; - let proxy = match ide_core::proxy_settings::proxy().route(Some(host)) { + let target = authority(host, port); + let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" }; + format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host")) +} + +/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected; +/// `skip_unusable` sends a route the tunnel cannot speak to direct instead of failing. +async fn connect_with( + url: &reqwest::Url, + route: ProxyRoute, + pac: impl FnOnce(&str) -> Option + Send + 'static, + matcher: impl FnOnce() -> Matcher, + skip_unusable: bool, +) -> IdeResult { + let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?; + let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?; + let target = authority(host, port); + let proxy = match route { ProxyRoute::Direct => None, ProxyRoute::Via(via) => Some(via), ProxyRoute::System => { - // The system proxy of the scheme reqwest would use (`ws` → `http`). - let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" }; - let uri: http::Uri = - format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))?; - hyper_util::client::proxy::matcher::Matcher::from_system().intercept(&uri).map(|intercept| { - let auth = - intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default(); - let uri = intercept.uri(); - format!( - "{}://{auth}{}", - uri.scheme_str().unwrap_or("http"), - uri.authority().map(|a| a.as_str()).unwrap_or_default() - ) - }) + let uri = system_uri(url)?; + // On macOS the resolver may run the PAC script (`dnsResolve`), so it stays off the async threads. A + // script still loading answers with the matcher's route. + let probe = uri.to_string(); + #[cfg(target_os = "macos")] + let pac = tokio::task::spawn_blocking(move || pac(&probe)) + .await + .map_err(|error| IdeError::unavailable(format!("proxy lookup failed: {error}")))?; + // Nothing to evaluate outside macOS: no hop to the blocking pool. + #[cfg(not(target_os = "macos"))] + let pac = pac(&probe); + match pac { + Some(ProxyRoute::Via(via)) if via.starts_with("http://") => Some(via), + Some(ProxyRoute::Direct) => None, + // No PAC applies, or it names a proxy this tunnel cannot speak to (SOCKS): the matcher's route. + _ => matcher().intercept(&uri).map(|intercept| { + let auth = + intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default(); + let uri = intercept.uri(); + format!( + "{}://{auth}{}", + uri.scheme_str().unwrap_or("http"), + uri.authority().map(|a| a.as_str()).unwrap_or_default() + ) + }), + } } }; + let proxy = proxy.filter(|proxy| !skip_unusable || proxy.starts_with("http://")); let connecting = async { let Some(proxy) = proxy else { return TcpStream::connect(&target).await.map_err(|error| reach(&target, &error)); @@ -157,6 +210,93 @@ mod tests { assert!(error.message.contains("needs a login"), "{}", error.message); } + use std::sync::{Arc, Mutex}; + + fn matcher_via(address: &str) -> impl FnOnce() -> Matcher { + let address = address.to_owned(); + move || Matcher::builder().all(format!("http://{address}")).build() + } + + /// The CONNECT line a proxy was asked for, or `None` when nothing connected within a moment. + async fn asked(task: tokio::task::JoinHandle) -> Option { + tokio::time::timeout(Duration::from_millis(300), task).await.ok().map(|head| head.unwrap()) + } + + #[tokio::test] + async fn the_pac_route_wins_over_the_matcher_and_ws_is_looked_up_as_http() { + let (pac_proxy, pac_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await; + let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await; + let seen = Arc::new(Mutex::new(String::new())); + let recorded = Arc::clone(&seen); + let pac = move |probe: &str| { + *recorded.lock().unwrap() = probe.to_owned(); + Some(ProxyRoute::Via(format!("http://{pac_proxy}"))) + }; + let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap(); + connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap(); + assert_eq!(*seen.lock().unwrap(), "http://pac-target.invalid:8080/"); + assert!(asked(pac_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n")); + assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used"); + } + + #[tokio::test] + async fn wss_is_looked_up_as_https() { + let (pac_proxy, _) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await; + let seen = Arc::new(Mutex::new(String::new())); + let recorded = Arc::clone(&seen); + let pac = move |probe: &str| { + *recorded.lock().unwrap() = probe.to_owned(); + Some(ProxyRoute::Via(format!("http://{pac_proxy}"))) + }; + let url = reqwest::Url::parse("wss://pac-target.invalid/s").unwrap(); + connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build(), false).await.unwrap(); + assert_eq!(*seen.lock().unwrap(), "https://pac-target.invalid:443/"); + } + + #[tokio::test] + async fn a_resolved_direct_route_skips_the_matchers_proxy() { + let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap(); + connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy), false) + .await + .unwrap(); + tokio::time::timeout(Duration::from_millis(300), listener.accept()) + .await + .expect("no direct connection") + .unwrap(); + assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used"); + } + + #[tokio::test] + async fn a_socks_pac_route_keeps_the_matchers_route() { + let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await; + let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap(); + let pac = |_: &str| Some(ProxyRoute::Via("socks5h://127.0.0.1:1080".into())); + connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap(); + assert!(asked(matcher_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n")); + } + + #[tokio::test] + async fn an_unusable_proxy_is_skipped_only_when_asked() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap(); + let socks = || ProxyRoute::Via("socks5h://127.0.0.1:1".into()); + let none = || Matcher::builder().build(); + assert!(connect_with(&url, socks(), |_| None, none, false).await.unwrap_err().message.contains("socks5h")); + connect_with(&url, socks(), |_| None, none, true).await.unwrap(); + listener.accept().await.unwrap(); + } + + #[tokio::test] + async fn an_ipv6_literal_is_connected_to() { + let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here + let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap(); + connect_with(&url, ProxyRoute::Direct, |_| None, || Matcher::builder().build(), false).await.unwrap(); + listener.accept().await.unwrap(); + assert_eq!(authority("[::1]", 9), "[::1]:9"); + } + #[test] fn proxy_credentials_are_percent_decoded() { assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c"); diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs index f2860d4e0..83367ab1c 100644 --- a/crates/ide-index/src/lib.rs +++ b/crates/ide-index/src/lib.rs @@ -258,7 +258,8 @@ impl ProjectIndex { } /// Bounded file inventory for background plugin indexers; honors the same - /// project/exclude scope as search and never walks the filesystem. + /// project/exclude scope as search, leaves VCS-ignored files out and never + /// walks the filesystem. pub fn files_with_extensions(&self, extensions: &[String], limit: usize) -> Vec { self.shared .data @@ -266,6 +267,7 @@ impl ProjectIndex { .files .iter() .flatten() + .filter(|f| !f.ignored) .filter(|f| f.path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e))) .take(limit) .map(|f| f.path.clone()) diff --git a/crates/ide-index/src/tests.rs b/crates/ide-index/src/tests.rs index cd067cd26..198ae4962 100644 --- a/crates/ide-index/src/tests.rs +++ b/crates/ide-index/src/tests.rs @@ -895,15 +895,19 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() { } #[test] -fn plugin_inventory_respects_excludes_and_symbols_require_matching_text() { +fn plugin_inventory_respects_excludes_and_ignores_and_symbols_require_matching_text() { let java = "package demo; interface UserMapper { void find(); }"; let f = Fixture::new(&[ ("src/UserMapper.java", java), ("src/mapper.xml", ""), ("target/Generated.java", "class Generated {}"), ("other.txt", "ignored"), + (".gitignore", "gen/\n"), + ("gen/Ignored.java", "class Ignored {}"), ]); let index = f.open(); + // Go to File lists the git-ignored file; plugin navigation leaves it out. + assert_eq!(files(&index, "Ignored"), ["gen/Ignored.java"]); let paths = index.files_with_extensions(&["java".into(), "xml".into()], 100); assert_eq!(paths.len(), 2); assert!(paths.iter().all(|p| p.starts_with(f.root.join("src")))); diff --git a/crates/ide-language/Cargo.toml b/crates/ide-language/Cargo.toml index 278ea7ed0..835cca570 100644 --- a/crates/ide-language/Cargo.toml +++ b/crates/ide-language/Cargo.toml @@ -32,6 +32,7 @@ tree-sitter-java = "0.23.5" tree-sitter-kotlin-ng = "1.1.0" tree-sitter-c = "0.24.2" tree-sitter-cpp = "0.23.4" +tree-sitter-objc = "3.0.2" tree-sitter-c-sharp = "0.23.5" tree-sitter-ruby = "0.23.1" tree-sitter-php = "0.25.1" diff --git a/crates/ide-language/queries/objc/outline.scm b/crates/ide-language/queries/objc/outline.scm new file mode 100644 index 000000000..34ea27437 --- /dev/null +++ b/crates/ide-language/queries/objc/outline.scm @@ -0,0 +1,50 @@ +(class_interface . (identifier) @name category: (identifier) @detail) @def.extension +(class_implementation . (identifier) @name category: (identifier) @detail) @def.extension +(class_interface . (identifier) @name) @def.class +(class_implementation . (identifier) @name) @def.class +(protocol_declaration . (identifier) @name) @def.interface + +(method_declaration ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method +(method_definition ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method +(property_declaration (struct_declaration (struct_declarator [ + (identifier) @name + (pointer_declarator declarator: (identifier) @name) + (function_declarator declarator: (parenthesized_declarator (block_pointer_declarator declarator: (identifier) @name))) +]))) @def.property +(instance_variable (struct_declaration (struct_declarator [ + (identifier) @name + (pointer_declarator declarator: (identifier) @name) +]))) @def.field + +(preproc_call directive: (preproc_directive) @_d argument: (preproc_arg) @name + (#eq? @_d "#pragma") (#match? @name "^mark\\s")) @outline.heading + +(function_definition + declarator: [ + (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail) + (pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)) + (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))) + ]) @def.function +(translation_unit (declaration + declarator: [ + (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail) + (pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)) + ]) @def.function) + +(struct_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct +(union_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct +(enum_specifier name: (type_identifier) @name body: (enumerator_list)) @def.enum +(enumerator name: (identifier) @name) @def.enum_member +(field_declaration_list (field_declaration declarator: [ + (field_identifier) @name + (pointer_declarator declarator: (field_identifier) @name) + (array_declarator declarator: (field_identifier) @name) +]) @def.field) +(type_definition declarator: (type_identifier) @name) @def.type +(preproc_def name: (identifier) @name) @def.macro +(preproc_function_def name: (identifier) @name parameters: (preproc_params) @detail) @def.macro +(translation_unit (declaration declarator: [ + (identifier) @name + (init_declarator declarator: (identifier) @name) + (init_declarator declarator: (pointer_declarator declarator: (identifier) @name)) +]) @def.variable) diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index 099e4c280..2c49c42bd 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -90,6 +90,7 @@ const BUILTIN: &[(&str, &str)] = &[ ("slint", include_str!("../../../languages/slint.toml")), ("sql", include_str!("../../../languages/sql.toml")), ("svelte", include_str!("../../../languages/svelte.toml")), + ("strings", include_str!("../../../languages/strings.toml")), ("swift", include_str!("../../../languages/swift.toml")), ("terraform", include_str!("../../../languages/terraform.toml")), ("terraform-vars", include_str!("../../../languages/terraform-vars.toml")), @@ -98,6 +99,7 @@ const BUILTIN: &[(&str, &str)] = &[ ("typescriptreact", include_str!("../../../languages/typescriptreact.toml")), ("typst", include_str!("../../../languages/typst.toml")), ("vue", include_str!("../../../languages/vue.toml")), + ("xcconfig", include_str!("../../../languages/xcconfig.toml")), ("xml", include_str!("../../../languages/xml.toml")), ("yaml", include_str!("../../../languages/yaml.toml")), ("zig", include_str!("../../../languages/zig.toml")), @@ -1277,6 +1279,11 @@ mod tests { ("P.cs", "csharp"), ("V.swift", "swift"), ("AppDelegate.m", "objective-c"), + ("App.entitlements", "xml"), + ("PrivacyInfo.xcprivacy", "xml"), + ("Localizable.xcstrings", "json"), + ("Debug.xcconfig", "xcconfig"), + ("en.lproj/Localizable.strings", "strings"), ("a.rb", "ruby"), ("Gemfile", "ruby"), ("show.html.erb", "erb"), diff --git a/crates/ide-language/src/syntax/grammars.rs b/crates/ide-language/src/syntax/grammars.rs index f0f75b955..ecab0b530 100644 --- a/crates/ide-language/src/syntax/grammars.rs +++ b/crates/ide-language/src/syntax/grammars.rs @@ -156,6 +156,24 @@ pub(crate) static SPECS: &[Spec] = &[ imports: &["preproc_include", "using_declaration"], constructors: NONE, }, + Spec { + name: "objc", + language: tree_sitter_objc::LANGUAGE, + outline: outline!("objc"), + highlights: None, + // `@interface` / `@implementation` / `@protocol` ... `@end` have no brackets. + fold_nodes: &[ + "class_interface", + "class_implementation", + "protocol_declaration", + "preproc_if", + "preproc_ifdef", + "preproc_function_def", + ], + fold_bodies: NONE, + imports: &["preproc_include", "module_import"], + constructors: NONE, + }, Spec { name: "csharp", language: tree_sitter_c_sharp::LANGUAGE, diff --git a/crates/ide-language/src/syntax/outline.rs b/crates/ide-language/src/syntax/outline.rs index a8edc1ad3..dd9f69c03 100644 --- a/crates/ide-language/src/syntax/outline.rs +++ b/crates/ide-language/src/syntax/outline.rs @@ -180,7 +180,11 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec } names.sort_by_key(|n| n.start_byte()); names.dedup_by_key(|n| n.id()); - let base = names.iter().map(|n| name_text(n, text)).collect::>().join("."); + let mut base = names.iter().map(|n| name_text(n, text)).collect::>().join("."); + // Objective-C selectors: `- (id)initWithName:(id)n age:(int)a` is `initWithName:age:`. + if g.spec.name == "objc" && node.children(&mut node.walk()).any(|c| c.kind() == "method_parameter") { + base = names.iter().map(|n| format!("{}:", name_text(n, text))).collect(); + } if base.is_empty() { continue; } @@ -539,6 +543,12 @@ fn name_text(n: &Node, text: &str) -> String { let t = node_text(n, text); // Ruby / Elixir symbols: `:total` -> `total`. let t = if matches!(n.kind(), "simple_symbol" | "atom") { t.trim_start_matches(':') } else { t }; + // Objective-C `#pragma mark - Lifecycle` -> `Lifecycle` (a bare `mark -` is a separator, so empty). + let t = if n.kind() == "preproc_arg" { + t.trim().trim_start_matches("mark").trim_start().trim_start_matches('-') + } else { + t + }; clean(t, 120) } diff --git a/crates/ide-language/src/syntax/tests.rs b/crates/ide-language/src/syntax/tests.rs index 3a950c73b..f336a6816 100644 --- a/crates/ide-language/src/syntax/tests.rs +++ b/crates/ide-language/src/syntax/tests.rs @@ -546,6 +546,119 @@ int main() { return 0; } assert_eq!(t.iter().filter(|(n, k, _)| n == "draw" && *k == SymbolKind::Method).count(), 2); } +#[test] +fn outline_objc() { + let src = r#"#import +#define MAX 10 +@protocol Greeting +- (NSString *)greet; +@optional +@property (nonatomic) int level; +@end + +@interface Person : NSObject { + int _age; +} +@property (nonatomic, copy) NSString *name; ++ (instancetype)personWithName:(NSString *)name age:(int)age; +- (void)run; +@end + +@interface Person (Extra) +- (void)extra; +@end + +@implementation Person +#pragma mark - Lifecycle ++ (instancetype)personWithName:(NSString *)name age:(int)age { + return nil; +} +- (void)run { +} +@end + +static int helper(int x) { return x; } +"#; + check_outline( + "objective-c", + src, + " + Macro MAX + Interface Greeting + Method greet + Property level + Class Person + Field _age + Property name + Method personWithName:age: + Method run + Namespace Person + Method extra + Class Person + Key Lifecycle + Method personWithName:age: + Method run + Function helper + ", + ); + let t = tags("objective-c", src); + assert!(has_tag(&t, "greet", SymbolKind::Method, Some("Greeting"))); + assert!(has_tag(&t, "personWithName:age:", SymbolKind::Method, Some("Person"))); + assert!(has_tag(&t, "extra", SymbolKind::Method, Some("Person"))); + assert!(has_tag(&t, "name", SymbolKind::Property, Some("Person"))); + assert!(!t.iter().any(|(n, _, _)| n == "Lifecycle")); + let t = tags("objective-c", "@interface A\n@property (copy) void (^onTap)(int i);\n@end\n"); + assert!(has_tag(&t, "onTap", SymbolKind::Property, Some("A")), "{t:?}"); + // `@interface` / `@protocol` / `@implementation` ... `@end` fold like a braced body. + let f = folds("objective-c", src); + for range in [(2, 6), (8, 14), (16, 18), (20, 27), (22, 24)] { + assert!(f.contains(&(range.0, range.1, FoldKind::Region)), "{range:?} not in {f:?}"); + } +} + +#[test] +fn outline_objective_cpp_keeps_the_objc_structure() { + // C++ declarations outside the ObjC blocks are lost to error recovery; the ObjC + // classes and methods, which are why a file is `.mm`, stay. + check_outline( + "objective-cpp", + r#"#import "Bridge.h" +#include +#include + +namespace engine { +class Renderer { +public: + void draw(const std::vector &xs); +}; +} + +@implementation Bridge { + std::unique_ptr _renderer; +} +- (instancetype)init { + self = [super init]; + _renderer = std::make_unique(); + return self; +} +- (void)drawValues:(NSArray *)values { + std::vector xs; + for (NSNumber *n in values) { xs.push_back(n.intValue); } + _renderer->draw(xs); +} +@end + +static std::string helper() { return "x"; } +"#, + " + Class Bridge + Method init + Method drawValues: + Function helper + ", + ); +} + #[test] fn outline_csharp() { check_outline( diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index ef6160a28..b4f67ca42 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -9,7 +9,8 @@ use crate::LspManager; use crate::server::{Running, Server}; use ide_core::error::{ErrorData, ErrorKind}; use ide_core::event::LspRefreshKind; -use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId}; +use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Location, Pos}; +use lsp_types as lsp; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use specta::Type; @@ -20,6 +21,7 @@ use std::time::{Duration, Instant}; pub(crate) const SERVER: &str = "jdtls"; const GENERATED_SOURCES: &str = "openidea.java.generatedSources"; +const METHOD_REFERENCE_DEFINITION: &str = "openidea.java.methodReferenceDefinition"; pub(crate) mod configuration; pub(crate) mod exception_breakpoints; @@ -771,6 +773,19 @@ impl LspManager { } } + /// The declaration of a Java method named by `Type::method` / `expr::method` at `pos`. + /// JDT's selection-based definition can return the functional interface method when the + /// referenced method is inherited; the extension resolves the AST binding instead. + pub(crate) async fn java_method_reference_definition(&self, path: &Path, pos: Pos) -> IdeResult> { + let uri = crate::path_to_uri_string(path); + let value = self + .jdtls_command(path, METHOD_REFERENCE_DEFINITION, vec![json!(uri), json!(pos.line), json!(pos.col)]) + .await?; + let locations: Vec = serde_json::from_value(value).unwrap_or_default(); + let conv = self.conv(crate::text::Encoding::Utf16); + Ok(locations.iter().filter_map(|location| conv.location(location)).collect()) + } + /// The jdtls instance serving `path` (a module directory or source file), /// started if needed and waited for. async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc, Running)> { diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 46faba21d..9581201df 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -327,6 +327,25 @@ fn goto_is_empty(r: &Option) -> bool { } } +/// Whether the caret is on the method name of a Java method reference (`Type::method`). +/// A method reference can name a functional interface's method through JDT's selection-based +/// definition when the referenced method is inherited, so ask the AST binding command instead. +fn java_method_reference_at(text: &DocText, pos: Pos) -> bool { + let line = text.line(pos.line as usize); + let mut utf16 = 0u32; + let mut at = line.len(); + for (i, c) in line.char_indices() { + if utf16 >= pos.col { + at = i; + break; + } + utf16 += c.len_utf16() as u32; + } + let before = line[..at].trim_end(); + let Some(colon) = before.rfind("::") else { return false }; + before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$') +} + fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError { match e { RpcError::Cancelled => IdeError::cancelled(), @@ -1793,7 +1812,31 @@ impl LspManager { } let (method, cap, feature) = goto_method(kind); let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?; - self.goto_in(&snap, &targets, method, pos, None, None).await + let result = self.goto_in(&snap, &targets, method, pos, None, None).await; + // JDT's selection-based definition can name the functional interface method for an + // inherited method reference. Ask the Java binding command when that is what came back, + // when the caret is on a method reference, or when the server found no target at all. + let method_reference = snap.language.as_str() == "java" && java_method_reference_at(&snap.text, pos); + if kind == GotoKind::Definition + && snap.language.as_str() == "java" + && (method_reference + || result.as_ref().is_ok_and(|locs| { + locs.is_empty() + || locs.iter().any(|l| { + let path = l.path.to_string_lossy().replace('\\', "/"); + let uri = l.uri.as_deref().unwrap_or_default(); + path.contains("java/util/function") + || path.contains("java.util.function") + || uri.contains("java/util/function") + || uri.contains("java.util.function") + }) + })) + && let Ok(found) = self.java_method_reference_definition(&snap.path, pos).await + && !found.is_empty() + { + return Ok(found); + } + result } /// Go to Implementation, with the implementations found first passed to `partial` while @@ -2768,6 +2811,79 @@ impl LspManager { Ok(ts_file_moves::file_references(&result)) } + /// Runs vtsls' own `command` for `doc`. typescript-language-server, TypeScript 7 and the + /// Vue / Astro servers have none of these commands: they need vtsls. + async fn vtsls_command( + &self, + doc: DocId, + command: &str, + arguments: impl FnOnce(&DocSnap, &Target) -> Option, + cancel: Option<&CancellationToken>, + ) -> IdeResult<(Target, Value)> { + let snap = self.snapshot(doc)?; + let t = self + .ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == command)) + .await + .into_iter() + .find(|t| t.server.name == "vtsls") + .ok_or_else(|| IdeError::unavailable("This needs the vtsls TypeScript language server"))?; + let arguments = + arguments(&snap, &t).ok_or_else(|| IdeError::invalid(format!("invalid `{command}` arguments")))?; + let params = json!({ "command": command, "arguments": arguments }); + let result = self.call(&t, "workspace/executeCommand", params, cancel, LONG_TIMEOUT).await?; + Ok((t, result)) + } + + /// Go to Source Definition: the JavaScript implementation of what `pos` refers to, not its + /// `.d.ts` declaration (vtsls' `typescript.goToSourceDefinition`). + pub async fn source_definition(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult> { + let (t, result) = self + .vtsls_command( + doc, + "typescript.goToSourceDefinition", + |snap, t| Some(json!([snap.uri, snap.position(t, pos)])), + Some(&cancel), + ) + .await?; + let locs: Vec = serde_json::from_value::>(result) + .map_err(|e| IdeError::internal(format!("typescript.goToSourceDefinition: {e}")))? + .unwrap_or_default(); + let conv = self.conv(t.enc()); + Ok(locs.iter().filter_map(|l| conv.location(l)).collect()) + } + + /// Opens the `tsconfig.json` / `jsconfig.json` of `doc`'s project, or the TS Server log: + /// vtsls answers with `window/showDocument` (or a message when there is none). + pub async fn open_typescript_file(&self, doc: DocId, what: TypeScriptFile) -> IdeResult<()> { + let (command, with_uri) = match what { + TypeScriptFile::ProjectConfig => { + let snap = self.snapshot(doc)?; + let js = snap.language.as_str().starts_with("javascript"); + (if js { "javascript.goToProjectConfig" } else { "typescript.goToProjectConfig" }, true) + } + TypeScriptFile::ServerLog => ("typescript.openTsServerLog", false), + }; + self.vtsls_command(doc, command, |snap, _| Some(if with_uri { json!([snap.uri]) } else { json!([]) }), None) + .await?; + Ok(()) + } + + /// The files tsserver suggests for vtsls' Move to File `command` (from a code action). + pub async fn move_to_file_targets( + &self, + doc: DocId, + command: Command, + cancel: CancellationToken, + ) -> IdeResult> { + let snap = self.snapshot(doc)?; + let request = ts_file_moves::move_to_file_suggestions_request(&snap.path, &command.arguments) + .ok_or_else(|| IdeError::invalid("invalid Move to File command"))?; + let (_, result) = self + .vtsls_command(doc, ts_file_moves::COMMAND, |_, _| request.get("arguments").cloned(), Some(&cancel)) + .await?; + Ok(ts_file_moves::move_to_file_suggestions(&result)) + } + /// Whether a server of `doc` (`server`, when given) provides the command `name`. Code actions /// can carry commands other editors' extensions run themselves after the edit (vtsls' /// `_typescript.didOrganizeImports`): no server provides those. @@ -4677,6 +4793,36 @@ mod code_action_tests { } } +#[cfg(test)] +mod java_method_reference_tests { + use super::java_method_reference_at; + use crate::text::DocText; + use ide_core::Pos; + + #[test] + fn finds_the_method_name_of_a_method_reference() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);"); + let col = "wrapper.set(XbkBtbOutNotice::get".len() as u32; + assert!(java_method_reference_at(&text, Pos::new(0, col))); + } + + #[test] + fn allows_whitespace_around_the_method_reference_operator() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice :: getUpdateTime, now);"); + let col = "wrapper.set(XbkBtbOutNotice :: get".len() as u32; + assert!(java_method_reference_at(&text, Pos::new(0, col))); + } + + #[test] + fn ignores_regular_calls_and_the_referenced_type() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);"); + let type_col = "wrapper.set(XbkBtbOutNotice".len() as u32; + assert!(!java_method_reference_at(&text, Pos::new(0, type_col))); + let call = DocText::new("wrapper.set(getUpdateTime(), now);"); + assert!(!java_method_reference_at(&call, Pos::new(0, "wrapper.set(get".len() as u32))); + } +} + #[cfg(test)] mod did_change_content_tests { use super::*; diff --git a/crates/ide-lsp/src/ts_file_moves.rs b/crates/ide-lsp/src/ts_file_moves.rs index 905be9422..5588bdb5b 100644 --- a/crates/ide-lsp/src/ts_file_moves.rs +++ b/crates/ide-lsp/src/ts_file_moves.rs @@ -87,10 +87,56 @@ pub(crate) fn file_references(result: &Value) -> Vec { .collect() } +/// The `typescript.tsserverRequest` arguments asking where the selection of vtsls' Move to File +/// command (`_typescript.moveToFileRefactoring` with `[action, uri, range]`, run with the target +/// file appended) can go. +pub(crate) fn move_to_file_suggestions_request(file: &std::path::Path, arguments: &[Value]) -> Option { + let range: lsp_types::Range = serde_json::from_value(arguments.get(2)?.clone()).ok()?; + // tsserver: 1-based lines and UTF-16 offsets; vtsls speaks UTF-16. + Some(json!({ + "command": COMMAND, + "arguments": ["getMoveToRefactoringFileSuggestions", { + "file": file, + "startLine": range.start.line + 1, + "startOffset": range.start.character + 1, + "endLine": range.end.line + 1, + "endOffset": range.end.character + 1, + }], + })) +} + +/// The files tsserver suggests in its `getMoveToRefactoringFileSuggestions` answer. +pub(crate) fn move_to_file_suggestions(result: &Value) -> Vec { + let body = result.get("body").unwrap_or(result); + serde_json::from_value(body.get("files").cloned().unwrap_or_default()).unwrap_or_default() +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn asks_tsserver_where_the_move_to_file_selection_can_go() { + let action = json!({ "name": "Move to file", "kind": "refactor.move.file" }); + let range = json!({ "start": { "line": 6, "character": 16 }, "end": { "line": 8, "character": 1 } }); + let request = move_to_file_suggestions_request( + std::path::Path::new("/p/src/util.ts"), + &[action.clone(), json!("file:///p/src/util.ts"), range], + ) + .unwrap(); + assert_eq!( + request["arguments"], + json!(["getMoveToRefactoringFileSuggestions", { + "file": "/p/src/util.ts", "startLine": 7, "startOffset": 17, "endLine": 9, "endOffset": 2, + }]) + ); + assert!(move_to_file_suggestions_request(std::path::Path::new("/p/a.ts"), &[action]).is_none()); + let answer = + json!({ "success": true, "body": { "newFileName": "/p/src/greet.ts", "files": ["/p/src/app.ts"] } }); + assert_eq!(move_to_file_suggestions(&answer), vec![PathBuf::from("/p/src/app.ts")]); + assert!(move_to_file_suggestions(&json!({ "success": false })).is_empty()); + } + #[test] fn converts_tsserver_file_references() { let result = json!({ "success": true, "body": { "symbolName": "\"./Hello.vue\"", "refs": [ diff --git a/crates/ide-lsp/src/types.rs b/crates/ide-lsp/src/types.rs index 2b2118246..cf6103760 100644 --- a/crates/ide-lsp/src/types.rs +++ b/crates/ide-lsp/src/types.rs @@ -109,6 +109,14 @@ pub struct Signature { pub parameters: Vec<(u32, u32)>, } +/// A file vtsls opens for a document: its project's configuration or the TS Server log. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum TypeScriptFile { + ProjectConfig, + ServerLog, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum GotoKind { diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index dfba06ca2..99e76d5cd 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -8824,3 +8824,51 @@ async fn switch_source_header_asks_clangd_and_only_clangd() { assert!(h.launcher.state("mock").requested("textDocument/switchSourceHeader").is_empty()); h.mgr.shutdown_all().await; } + +/// C-family files go to sourcekit-lsp in an Xcode project with a BSP config (`buildServer.json`), +/// which hands them to clangd with the build's flags; elsewhere, and when sourcekit-lsp is missing, +/// to plain clangd. Uses the shipped language definitions. +#[tokio::test(flavor = "multi_thread")] +async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() { + let registry = LanguageRegistry::load(None).unwrap(); + for (language, ext) in [("c", "h"), ("cpp", "cpp"), ("objective-c", "m"), ("objective-cpp", "mm")] { + let shipped = registry.get(&LanguageId::new(language)).unwrap().language_servers; + let names: Vec<_> = shipped.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["sourcekit-lsp", "clangd"], "{language}"); + let servers = [("sourcekit-lsp", incremental_caps()), ("clangd", incremental_caps())]; + let as_shipped = |cfg: &mut LanguageServerConfig| { + let real = shipped.iter().find(|c| c.name == cfg.name).unwrap(); + cfg.root_markers = real.root_markers.clone(); + cfg.require_root_marker = real.require_root_marker; + cfg.replaces = real.replaces.clone(); + }; + let file = format!("Foo.{ext}"); + + // A plain folder, or one with only compile_commands.json: clangd alone. + let h = harness_configured(language, ext, &servers, as_shipped); + std::fs::write(h.root.join("compile_commands.json"), "[]").unwrap(); + h.open(&file, ""); + h.wait_status("clangd", ServerStatus::Ready).await; + assert!(h.statuses("sourcekit-lsp").is_empty(), "{language}"); + h.mgr.shutdown_all().await; + + // An Xcode project with buildServer.json: sourcekit-lsp alone, rooted at the config. + let h = harness_configured(language, ext, &servers, as_shipped); + std::fs::write(h.root.join("buildServer.json"), "{}").unwrap(); + let (_, path) = h.open(&file, ""); + h.wait_status("sourcekit-lsp", ServerStatus::Ready).await; + eventually(|| h.launcher.state("sourcekit-lsp").docs.lock().contains_key(&uri_of(&path))).await; + assert!(h.statuses("clangd").is_empty(), "{language}"); + assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::>(), [h.root.clone()]); + h.mgr.shutdown_all().await; + + // sourcekit-lsp not installed: clangd still serves. + let h = harness_configured(language, ext, &servers, as_shipped); + h.launcher.state("sourcekit-lsp").missing.store(true, Ordering::SeqCst); + std::fs::write(h.root.join("buildServer.json"), "{}").unwrap(); + h.open(&file, ""); + h.wait_status("sourcekit-lsp", ServerStatus::Missing).await; + h.wait_status("clangd", ServerStatus::Ready).await; + h.mgr.shutdown_all().await; + } +} diff --git a/crates/ide-lsp/tests/real_servers.rs b/crates/ide-lsp/tests/real_servers.rs index ad39da005..c5a54794d 100644 --- a/crates/ide-lsp/tests/real_servers.rs +++ b/crates/ide-lsp/tests/real_servers.rs @@ -969,6 +969,135 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() { tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); } +/// vtsls' own commands (#6922): Go to Source Definition opens a library's JavaScript instead +/// of its `.d.ts`, Go to Project Configuration and Open TS Server Log answer with +/// `window/showDocument`, JSDoc `{@link}` in hovers is a `file://…#L1,1` link, and Move to File +/// suggests the project's files and moves a function with its imports in one applied edit. Set +/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/language-server@0.3.0 typescript@6`. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "requires @vtsls/language-server and typescript@6 (OPENIDEA_TEST_NPM_TOOLS)"] +async fn vtsls_commands_open_sources_configs_logs_and_move_to_file() { + let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS")); + let dir = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(dir.path()).unwrap(); + for dir in ["src", "node_modules/greeting"] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + } + let files = [ + ("package.json", "{\"name\":\"app\",\"private\":true}"), + ("tsconfig.json", "{\"files\":[],\"references\":[{\"path\":\"./src/tsconfig.app.json\"}]}"), + ( + "src/tsconfig.app.json", + "{\"compilerOptions\":{\"strict\":true,\"composite\":true,\"module\":\"ESNext\",\"moduleResolution\":\"Bundler\"},\"include\":[\"./**/*.ts\"]}", + ), + ( + "node_modules/greeting/package.json", + "{\"name\":\"greeting\",\"main\":\"index.js\",\"types\":\"index.d.ts\"}", + ), + ("node_modules/greeting/index.d.ts", "export declare function shout(s: string): string;\n"), + ("node_modules/greeting/index.js", "export function shout(s) {\n return s.toUpperCase();\n}\n"), + ( + "src/main.ts", + "import { shout } from \"greeting\";\nimport { greet, Greeter } from \"./util\";\n\n/** Uses {@link Greeter} to say hello. */\nexport function hello(name: string) {\n return shout(greet(name));\n}\n\nexport const g = new Greeter();\n", + ), + ( + "src/util.ts", + "export class Greeter {\n greet(name: string) {\n return `Hello, ${name}`;\n }\n}\n\nexport function greet(name: string) {\n return new Greeter().greet(name);\n}\n", + ), + ("src/strings.ts", "export const upper = (s: string) => s.toUpperCase();\n"), + ("src/app.ts", "import { greet } from \"./util\";\n\nconsole.log(greet(\"app\"));\n"), + ]; + for (path, text) in files { + std::fs::write(root.join(path), text).unwrap(); + } + // The IDE's settings hook: Move to File on, a TypeScript 6 lib, the log on. + let init = serde_json::json!({ + "vtsls": { "enableMoveToFileCodeAction": true, "autoUseWorkspaceTsdk": true }, + "typescript": { + "tsdk": tools.join("node_modules/typescript/lib").to_string_lossy(), + "tsserver": { "log": "verbose" }, + }, + }); + let ts = lang("typescript", "ts", npm_server(&tools, "vtsls", "vtsls", Some(init))); + let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![ts])); + let applied: Arc>> = Arc::default(); + mgr.set_apply_edit_hook(Box::new({ + let applied = applied.clone(); + move |edit| { + applied.lock().push(edit); + true + } + })); + let open = |path: &str| { + let doc = DocId::next(); + let file = root.join(path); + mgr.did_open(doc, &file, &LanguageId::new("typescript"), 1, &std::fs::read_to_string(&file).unwrap()); + doc + }; + let (main, util) = (open("src/main.ts"), open("src/util.ts")); + + // `shout`: Go to Declaration is the `.d.ts`, Go to Source Definition the `.js`. + let at = Pos::new(0, 10); + // The syntax server answers with the import itself until the project is loaded. + let dts = |d: &ide_core::Location| d.path.to_string_lossy().ends_with("greeting/index.d.ts"); + let declaration = retry("declaration", Duration::from_secs(90), || { + let mgr = mgr.clone(); + async move { mgr.goto(main, at, GotoKind::Definition).await.ok().filter(|d| d.iter().any(dts)) } + }) + .await; + assert!(declaration.iter().all(dts), "{declaration:?}"); + let source = mgr.source_definition(main, at, Default::default()).await.unwrap(); + assert_eq!(source.len(), 1, "{source:?}"); + assert_eq!(*source[0].path, *root.join("node_modules/greeting/index.js")); + assert_eq!(source[0].range.start, Pos::new(0, 16)); + + let shown = |events: &Events, suffix: &str| { + events + .lock() + .iter() + .any(|e| matches!(e, IdeEvent::LspShowDocument { path: Some(path), .. } if path.to_string_lossy().ends_with(suffix))) + }; + mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ProjectConfig).await.unwrap(); + retry("tsconfig.app.json shown", Duration::from_secs(10), || { + let found = shown(&events, "src/tsconfig.app.json").then_some(()); + async move { found } + }) + .await; + mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ServerLog).await.unwrap(); + retry("tsserver.log shown", Duration::from_secs(10), || { + let found = shown(&events, "tsserver.log").then_some(()); + async move { found } + }) + .await; + + let hover = mgr.hover(main, Pos::new(4, 17), Default::default()).await.unwrap(); + let hover = format!("{hover:?}"); + assert!(hover.contains("src/util.ts#L1%2C1"), "{hover}"); + + // Move to File on `greet`: tsserver suggests the other files, the move updates the importers. + let caret = Pos::new(6, 16); + let actions = mgr.code_actions(util, Range::new(caret, caret), vec!["refactor.move".into()]).await.unwrap(); + let command = actions + .iter() + .find_map(|a| a.command.clone().filter(|c| c.command == "_typescript.moveToFileRefactoring")) + .unwrap_or_else(|| panic!("no Move to File: {actions:?}")); + let targets = mgr.move_to_file_targets(util, command.clone(), Default::default()).await.unwrap(); + let strings = root.join("src/strings.ts"); + assert!(targets.contains(&strings) && targets.contains(&root.join("src/app.ts")), "{targets:?}"); + let mut moving = command; + moving.arguments.push(serde_json::json!(strings)); + mgr.execute_command(util, moving).await.unwrap(); + let edits = applied.lock().clone(); + assert_eq!(edits.len(), 1, "{edits:?}"); + let edit = format!("{:?}", edits[0]); + for file in ["src/util.ts", "src/strings.ts", "src/app.ts", "src/main.ts"] { + assert!(edit.contains(&*root.join(file).to_string_lossy()), "{file}: {edit}"); + } + assert!(edit.contains("export function greet(name: string)"), "{edit}"); + assert!(edit.contains("import { greet } from \\\"./strings\\\""), "{edit}"); + tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); +} + /// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css` /// files too (`languages: ["css"]`): definition and completion from TSX, references and rename /// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 6306754cf..f6519e668 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -613,11 +613,14 @@ impl PluginEngine { pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result { let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?; let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes))); - if file.is_file() { + // Read into memory rather than `deserialize_file`: that maps the file and makes its pages + // executable, which the hardened runtime of the signed macOS app refuses ("failed to make + // memory executable"), so the cache never hit and every activation compiled again. + if let Ok(precompiled) = std::fs::read(&file) { // SAFETY: the cache directory belongs to the IDE (inside its plugins // directory) and is written only by `store_precompiled` below from // components this engine compiled; a corrupt file fails validation. - match unsafe { Component::deserialize_file(&self.engine, &file) } { + match unsafe { Component::deserialize(&self.engine, &precompiled) } { Ok(component) => return Ok(component), Err(e) => { tracing::info!("discarding precompiled {}: {e}", file.display()); @@ -3035,6 +3038,26 @@ impl Runtime { mod tests { use super::*; + /// The second compile of the same component loads the cached one instead of compiling and + /// writing it again (a failed load deletes and rewrites the file). + #[test] + fn a_precompiled_component_is_loaded_from_the_cache() { + let engine = PluginEngine::new().unwrap(); + let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm"); + let cache = tempfile::tempdir().unwrap(); + engine.compile_cached(&wasm, cache.path()).unwrap(); + let cached = || { + let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect(); + assert_eq!(entries.len(), 1, "{entries:?}"); + let file = entries[0].clone(); + (std::fs::metadata(&file).unwrap().modified().unwrap(), file) + }; + let before = cached(); + std::thread::sleep(std::time::Duration::from_millis(20)); + engine.compile_cached(&wasm, cache.path()).unwrap(); + assert_eq!(cached(), before, "loaded, not compiled and stored again"); + } + #[test] fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() { let fields = [ diff --git a/crates/ide-run/src/detect/xcode.rs b/crates/ide-run/src/detect/xcode.rs index ed1b48b36..7bd966d8d 100644 --- a/crates/ide-run/src/detect/xcode.rs +++ b/crates/ide-run/src/detect/xcode.rs @@ -1,6 +1,6 @@ //! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS //! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all, -//! so its schemes and theirs are built through it. +//! so its schemes and theirs are built through it, as is the workspace of a CocoaPods project. use super::{ConfigExt, config}; use crate::RunConfig; @@ -8,10 +8,12 @@ use crate::xcode::{XcodeScheme, schemes}; use std::path::Path; /// A folder holding an Xcode project or workspace, other than the `ios/` / `macos/` host app -/// of a Flutter or React Native project, which that project's own tooling runs. +/// of a Flutter or React Native project, which that project's own tooling runs, and a CocoaPods +/// `Pods/` folder. pub(super) fn is_project(dir: &Path) -> bool { let hosted = dir.parent().is_some_and(|p| p.join("pubspec.yaml").is_file() || p.join("package.json").is_file()); !hosted + && !crate::xcode::is_pods_dir(dir) && std::fs::read_dir(dir).is_ok_and(|entries| { entries.flatten().any(|e| e.path().extension().is_some_and(|x| x == "xcodeproj" || x == "xcworkspace")) }) @@ -19,9 +21,13 @@ pub(super) fn is_project(dir: &Path) -> bool { pub(super) fn detect(dir: &Path, out: &mut Vec) { let found = schemes(dir); - let workspace = found.iter().map(|s| &s.container).find(|c| c.extension().is_some_and(|x| x == "xcworkspace")); + let workspace = found + .iter() + .map(|s| s.container.clone()) + .find(|c| c.extension().is_some_and(|x| x == "xcworkspace")) + .or_else(|| crate::xcode::pods_workspace(dir)); for scheme in &found { - let container = workspace.unwrap_or(&scheme.container); + let container = workspace.as_ref().unwrap_or(&scheme.container); let container = container.strip_prefix(dir).unwrap_or(container).to_string_lossy().into_owned(); out.push(scheme_config(scheme, &container)); } @@ -77,4 +83,49 @@ mod tests { assert_eq!(app.env["API_HOST"], "localhost:8080"); assert!(!app.extras.params.contains_key(crate::xcode::SIMULATOR_PARAM)); } + + #[test] + fn a_cocoapods_project_builds_and_tests_through_its_workspace() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let scheme = std::fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme"), + ) + .unwrap(); + for dir in ["App.xcodeproj", "Pods/Pods.xcodeproj"] { + let schemes = root.join(dir).join("xcshareddata/xcschemes"); + std::fs::create_dir_all(&schemes).unwrap(); + std::fs::write(schemes.join("App.xcscheme"), &scheme).unwrap(); + } + // `pod install`'s workspace has no schemes of its own. + std::fs::create_dir(root.join("App.xcworkspace")).unwrap(); + + let args = |out: &[RunConfig]| out.iter().map(|c| c.args.join(" ")).collect::>(); + let mut out = Vec::new(); + detect(root, &mut out); + assert_eq!(args(&out), ["-project App.xcodeproj -scheme App -configuration Staging"]); + // Without a Podfile, a `Pods/` folder is just another project. + assert!(is_project(&root.join("Pods"))); + + std::fs::write(root.join("Podfile"), "").unwrap(); + assert!(is_project(root) && !is_project(&root.join("Pods"))); + let mut out = Vec::new(); + detect(root, &mut out); + assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]); + let mut tests = Vec::new(); + super::super::xcode_test::detect(root, &mut tests); + assert_eq!(args(&tests), ["test -workspace App.xcworkspace -scheme App"]); + + // A leftover workspace that sorts first: the one named after the project still wins. + std::fs::create_dir(root.join("Aardvark.xcworkspace")).unwrap(); + let mut out = Vec::new(); + detect(root, &mut out); + assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]); + assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("App.xcworkspace"))); + // Without a workspace named after a project, the first by name. + std::fs::remove_dir(root.join("App.xcworkspace")).unwrap(); + std::fs::create_dir(root.join("Old.xcworkspace")).unwrap(); + assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("Aardvark.xcworkspace"))); + } } diff --git a/crates/ide-run/src/detect/xcode_test.rs b/crates/ide-run/src/detect/xcode_test.rs index e49439eb8..1fe8a2c20 100644 --- a/crates/ide-run/src/detect/xcode_test.rs +++ b/crates/ide-run/src/detect/xcode_test.rs @@ -1,4 +1,5 @@ -//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests. +//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests, +//! through the CocoaPods workspace when the project has one. //! The simulator destination and the result bundle are added at launch (`xcode::prepare_test`). use super::{ConfigExt, config}; @@ -6,11 +7,15 @@ use crate::RunConfig; use std::path::Path; pub(super) fn detect(root: &Path, out: &mut Vec) { + // With a Podfile every scheme is built through the Pods workspace, assuming one app project + // per folder: the workspace `pod install` writes links that project's targets. + let pods = crate::xcode::pods_workspace(root); for scheme in crate::xcode::schemes(root) { if !scheme.has_tests { continue; } - let Some(container) = scheme.container.file_name().and_then(|n| n.to_str()) else { continue }; + let path = pods.as_ref().unwrap_or(&scheme.container); + let Some(container) = path.file_name().and_then(|n| n.to_str()) else { continue }; let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" }; out.push( config( diff --git a/crates/ide-run/src/simulator.rs b/crates/ide-run/src/simulator.rs index c8180e547..2c2137e23 100644 --- a/crates/ide-run/src/simulator.rs +++ b/crates/ide-run/src/simulator.rs @@ -1,4 +1,5 @@ -//! iOS Simulators, through `xcrun simctl` (macOS only): the devices an Xcode project can run on. +//! iOS Simulators, through `xcrun simctl`, and connected iPhones and iPads, through +//! `xcrun devicectl` (macOS only): the devices an Xcode project can run on. //! //! Flutter projects get theirs from `flutter daemon` (`ide-flutter`), so only native Xcode //! projects use this. @@ -11,7 +12,8 @@ use specta::Type; use std::path::Path; use std::process::Command; -/// One simulator `simctl list devices available` reports. +/// One simulator `simctl list devices available` reports, or one physical device +/// `devicectl list devices` knows. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)] #[serde(rename_all = "camelCase")] pub struct IosSimulator { @@ -19,10 +21,18 @@ pub struct IosSimulator { pub name: String, /// The runtime, as Xcode shows it: `iOS 27.0`. pub runtime: String, - /// `Booted`, `Shutdown`, `Booting`, `Shutting Down`. + /// `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`], + /// [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`]. pub state: String, + /// An iPhone or iPad rather than a simulator. + pub physical: bool, } +/// The states of a physical device. +pub const AVAILABLE: &str = "Available"; +pub const UNAVAILABLE: &str = "Unavailable"; +pub const DEVELOPER_MODE_OFF: &str = "Developer Mode Off"; + /// An Xcode project or workspace directly in `root`, outside a Flutter project (whose /// `ios/Runner.xcodeproj` sits one level down and whose devices come from Flutter). pub fn is_xcode_project(root: &Path) -> bool { @@ -54,7 +64,8 @@ pub fn parse_list(json: &str) -> IdeResult> { for d in list.as_array().into_iter().flatten() { let text = |key| d.get(key).and_then(Value::as_str).map(str::to_owned); let (Some(udid), Some(name), Some(state)) = (text("udid"), text("name"), text("state")) else { continue }; - devices.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state })); + devices + .push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state, physical: false })); } } devices.sort_by(|(va, a), (vb, b)| { @@ -67,8 +78,73 @@ pub fn parse_list(json: &str) -> IdeResult> { Ok(devices.into_iter().map(|(_, d)| d).collect()) } -fn run(program: &str, args: &[&str]) -> IdeResult { +/// The physical iOS and iPadOS devices in `devicectl list devices --json-output` output, by name. +/// Reads the fields Xcode 15 and later write, falling back to the `properties` that replace them. +pub fn parse_devices(json: &str) -> IdeResult> { + let value: Value = serde_json::from_str(json).map_err(|e| IdeError::internal(format!("devicectl list: {e}")))?; + let mut devices = Vec::new(); + for d in value.pointer("/result/devices").and_then(Value::as_array).into_iter().flatten() { + let text = |old: &str, new: &str| { + d.pointer(old).or_else(|| d.pointer(new)).and_then(Value::as_str).unwrap_or_default().to_owned() + }; + let reality = text("/hardwareProperties/reality", "/properties/hardware/reality"); + let platform = text("/hardwareProperties/platform", "/properties/hardware/platform"); + let udid = text("/hardwareProperties/udid", "/properties/hardware/udid"); + if reality != "physical" || !matches!(&*platform, "iOS" | "iPadOS") || udid.is_empty() { + continue; + } + let version = d + .pointer("/deviceProperties/osVersionNumber") + .or_else(|| d.pointer("/properties/software/osVersionNumber/stringValue")) + .and_then(Value::as_str) + .unwrap_or_default(); + // `tunnelState` (`connected`, `disconnected`: reachable, connects on use) or `state`. + let connection = text("/connectionProperties/tunnelState", "/properties/connection/state"); + let developer_mode = d + .pointer("/deviceProperties/developerModeStatus") + .and_then(Value::as_str) + .map(str::to_owned) + .or_else(|| d.pointer("/properties/state/developerModeStatus")?.as_object()?.keys().next().cloned()); + let state = if connection == "unavailable" || connection.is_empty() { + UNAVAILABLE + } else if developer_mode.as_deref() == Some("disabled") { + DEVELOPER_MODE_OFF + } else { + AVAILABLE + }; + devices.push(IosSimulator { + udid, + name: text("/deviceProperties/name", "/properties/state/name"), + runtime: format!("{platform} {version}").trim().to_owned(), + state: state.to_owned(), + physical: true, + }); + } + devices.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.udid.cmp(&b.udid))); + Ok(devices) +} + +/// The physical devices paired with this Mac, as [`parse_devices`] reads them; none when +/// `devicectl` (Xcode 15 and later) is missing or fails. `dir` picks the project's Xcode. +pub fn devices(dir: &Path) -> Vec { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos(); + let file = std::env::temp_dir().join(format!("openidea-devicectl-{}-{stamp}.json", std::process::id())); + let path = file.to_string_lossy().into_owned(); + let listed = run_in(Some(dir), "xcrun", &["devicectl", "list", "devices", "--quiet", "--json-output", &path]); + let json = std::fs::read_to_string(&file); + let _ = std::fs::remove_file(&file); + match (listed, json) { + (Ok(_), Ok(json)) => parse_devices(&json).unwrap_or_default(), + _ => Vec::new(), + } +} + +/// `dir`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`). +fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult { 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() { @@ -78,23 +154,26 @@ fn run(program: &str, args: &[&str]) -> IdeResult { Err(IdeError::unavailable(format!("{program} {} failed: {}", args.join(" "), stderr.trim()))) } -/// The available iOS simulators, sorted as [`parse_list`] does. -pub fn list() -> IdeResult> { - parse_list(&run("xcrun", &["simctl", "list", "devices", "available", "--json"])?) +/// The available iOS simulators of the Xcode the project at `root` uses, sorted as +/// [`parse_list`] does, then the physical devices. +pub fn list(root: &Path) -> IdeResult> { + let mut list = parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)?; + list.extend(devices(root)); + Ok(list) } /// 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)] @@ -137,6 +216,42 @@ mod tests { assert_eq!(parse_list("{}").unwrap(), []); } + #[test] + fn lists_physical_devices_by_name_from_old_and_new_fields() { + // Trimmed `devicectl list devices --json-output` (Xcode 27): one device with the + // deprecated fields too, one with `properties` only, a simulator and a Mac. + let json = r#"{"info": {"outcome": "success"}, "result": {"devices": [ + {"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"}, + "deviceProperties": {"name": "Work iPhone", "osVersionNumber": "27.3", "developerModeStatus": "enabled"}, + "connectionProperties": {"tunnelState": "disconnected"}, + "properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"}, + "connection": {"state": "disconnected"}}}, + {"properties": {"hardware": {"reality": "physical", "platform": "iPadOS", "udid": "00008103-BBB"}, + "software": {"osVersionNumber": {"stringValue": "26.1"}}, + "state": {"name": "Test iPad", "developerModeStatus": {"disabled": {"mode": 0}}}, + "connection": {"state": "connected"}}}, + {"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008150-CCC"}, + "state": {"name": "Away iPhone", "developerModeStatus": {"enabled": {"mode": 1}}}, + "connection": {"state": "unavailable"}}}, + {"hardwareProperties": {"reality": "simulated", "platform": "iOS", "udid": "SIM"}, + "connectionProperties": {"tunnelState": "disconnected"}}, + {"hardwareProperties": {"reality": "physical", "platform": "macOS", "udid": "MAC"}, + "connectionProperties": {"tunnelState": "connected"}} + ]}}"#; + let devices = parse_devices(json).unwrap(); + let rows: Vec<_> = devices.iter().map(|d| (&*d.name, &*d.udid, &*d.runtime, &*d.state, d.physical)).collect(); + assert_eq!( + rows, + [ + ("Away iPhone", "00008150-CCC", "iOS", UNAVAILABLE, true), + ("Test iPad", "00008103-BBB", "iPadOS 26.1", DEVELOPER_MODE_OFF, true), + ("Work iPhone", "00008110-AAA", "iOS 27.3", AVAILABLE, true), + ] + ); + assert!(parse_devices("not json").is_err()); + assert_eq!(parse_devices(r#"{"info": {"outcome": "failed"}}"#).unwrap(), []); + } + #[test] fn finds_xcode_projects_at_the_root_only() { let dir = std::env::temp_dir().join(format!("ide-run-simulator-{}", std::process::id())); diff --git a/crates/ide-run/src/xcode.rs b/crates/ide-run/src/xcode.rs index f4640c1ee..3ad97020a 100644 --- a/crates/ide-run/src/xcode.rs +++ b/crates/ide-run/src/xcode.rs @@ -3,7 +3,8 @@ //! projects without any, but it takes a second or two, too slow for detection. //! //! A scheme's run configuration builds it for the iOS Simulator and launches the app there with -//! `simctl`, or, for a macOS app, builds it for the Mac and runs its executable; +//! `simctl`, for a connected iPhone or iPad and launches it there with `devicectl`, or, for a +//! 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}; @@ -46,6 +47,29 @@ pub fn schemes(root: &Path) -> Vec { containers.iter().flat_map(|c| container_schemes(c)).collect() } +/// The `.xcworkspace` `pod install` wrote next to the app's project, when `root` has a `Podfile`: +/// the one named after an `.xcodeproj` in `root`, else the first by name (a leftover workspace +/// may sit beside it). The project alone doesn't link the pods, so its schemes are built through +/// this workspace, which usually has no schemes of its own. The frontend picks the same one +/// (`podsWorkspace` in `src/features/run/cocoapodsActions.ts`). +pub fn pods_workspace(root: &Path) -> Option { + if !root.join("Podfile").is_file() { + return None; + } + let mut dirs: Vec = fs::read_dir(root).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect(); + dirs.sort(); + let has_ext = |p: &Path, ext: &str| p.extension().is_some_and(|e| e == ext); + let projects: Vec<_> = dirs.iter().filter(|p| has_ext(p, "xcodeproj")).filter_map(|p| p.file_stem()).collect(); + let workspaces: Vec<&PathBuf> = dirs.iter().filter(|p| has_ext(p, "xcworkspace")).collect(); + let named = workspaces.iter().find(|w| w.file_stem().is_some_and(|s| projects.contains(&s))); + named.or(workspaces.first()).map(|w| (*w).clone()) +} + +/// The `Pods/` folder of a CocoaPods project: its `Pods.xcodeproj` is generated, not the app. +pub fn is_pods_dir(dir: &Path) -> bool { + dir.file_name().is_some_and(|n| n == "Pods") && dir.parent().is_some_and(|p| p.join("Podfile").is_file()) +} + fn container_schemes(container: &Path) -> Vec { let mut out: Vec = Vec::new(); let mut add = |dir: PathBuf, shared: bool| { @@ -155,16 +179,21 @@ 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<()> { +/// bundles of this configuration's earlier runs are removed. Run with Coverage names the bundle +/// itself in [`RESULT_BUNDLE_PARAM`]. +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}")]); } if let Some(at) = config.args.iter().position(|a| a == "-resultBundlePath") { config.args.drain(at..(at + 2).min(config.args.len())); } + if let Some(bundle) = config.extras.params.get(RESULT_BUNDLE_PARAM).cloned() { + config.args.extend(["-resultBundlePath".to_owned(), bundle]); + return Ok(()); + } let prefix: String = config.id.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect(); fs::create_dir_all(bundles)?; for entry in fs::read_dir(bundles)?.flatten() { @@ -178,10 +207,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 { +/// 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 { 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)) } @@ -211,6 +241,8 @@ fn pick_simulator(json: &str) -> Option { /// [`default_simulator`]: the one place a device selector can feed its choice into. /// [`MAC`] runs an app that supports both on the Mac instead. pub const SIMULATOR_PARAM: &str = "simulator"; +/// The result bundle an `xcodebuild test` launch writes, when the caller reads it afterwards. +pub const RESULT_BUNDLE_PARAM: &str = "resultBundle"; /// Set (to anything but empty) by Debug: the app is launched suspended /// (`simctl launch --wait-for-debugger`) until the debugger attaches to the pid simctl prints. @@ -274,17 +306,32 @@ pub fn mac_executable(settings: &str) -> Result { } /// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the -/// scheme's first application target. -pub fn built_app(settings: &str) -> Result<(PathBuf, String), String> { +/// scheme's first application target for the iOS Simulator, or with `device` for an iPhone or +/// iPad, which runs only an app signed with a development team. +pub fn built_app(settings: &str, device: bool) -> Result<(PathBuf, String), String> { let apps = app_settings(settings)?; - let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else { + let (platform, target) = + if device { ("iphoneos", "an iOS device") } else { ("iphonesimulator", "the iOS Simulator") }; + let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == platform) else { return Err(match apps.first().and_then(|b| b["PLATFORM_NAME"].as_str()) { - Some(platform) => format!("The scheme builds an app for {platform}, not the iOS Simulator"), + Some(platform) => format!("The scheme builds an app for {platform}, not {target}"), None => "The scheme builds no application".to_owned(), }); }; let get = |key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}")); + if device && app["CODE_SIGNING_ALLOWED"] == "NO" { + return Err(format!( + "{} is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps", + get("WRAPPER_NAME")? + )); + } + if device && app["CODE_SIGN_STYLE"] == "Automatic" && get("DEVELOPMENT_TEAM").is_err() { + return Err(format!( + "Signing {} for a device needs a development team: choose one under Signing & Capabilities in Xcode", + get("WRAPPER_NAME")? + )); + } Ok((Path::new(get("TARGET_BUILD_DIR")?).join(get("WRAPPER_NAME")?), get("PRODUCT_BUNDLE_IDENTIFIER")?.to_owned())) } @@ -341,6 +388,49 @@ fn announce_suspended(udid: &str, bundle_id: &str) -> String { ) } +/// The script a run on a physical device executes: build with the project's signing (letting +/// Xcode register the device and fetch profiles, as its own Run does), install, then launch with +/// the app's output on the console. The app's arguments follow the script as `$@`. A Stop's +/// SIGINT becomes a SIGTERM to `devicectl` (a background job ignores SIGINT), which passes it on +/// to the app. When `devicectl` itself fails to launch the app +/// (its JSON outcome is not `success`) and no Stop was asked for, a hint about a locked device +/// follows its error. +pub fn device_launch_script(build_args: &[String], udid: &str, name: &str, app: &Path, bundle_id: &str) -> String { + let build: Vec = build_args.iter().map(|a| sh_quote(a)).collect(); + let (udid, app, bundle_id) = (sh_quote(udid), sh_quote(&app.to_string_lossy()), sh_quote(bundle_id)); + 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\ + xcrun devicectl device install app --device {udid} {app}\n\ + set +e\n\ + result=$(mktemp)\n\ + xcrun devicectl device process launch --console --terminate-existing --json-output \"$result\" --device {udid} {bundle_id} -- \"$@\" &\n\ + launch=$!\n\ + trap 'stopped=1; kill -TERM $launch 2>/dev/null' INT TERM\n\ + wait $launch; status=$?\n\ + while kill -0 $launch 2>/dev/null; do wait $launch; status=$?; done\n\ + if [ -z \"$stopped\" ] && ! grep -q '\"outcome\" *: *\"success\"' \"$result\" 2>/dev/null; then echo {hint} >&2; fi\n\ + rm -f \"$result\"\n\ + exit $status\n", + build.join(" "), + ) +} + +/// Why a run cannot start on `device`, a physical one [`crate::simulator::devices`] listed. +fn device_unready(device: &crate::simulator::IosSimulator) -> Option { + let name = &device.name; + match device.state.as_str() { + crate::simulator::UNAVAILABLE => Some(format!( + "{name} is not connected. Connect it with a cable or to this Mac's network, unlock it, and run again." + )), + crate::simulator::DEVELOPER_MODE_OFF => Some(format!( + "Developer Mode is off on {name}. Turn it on in Settings > Privacy & Security > Developer Mode, restart the device, and run again." + )), + _ => None, + } +} + /// The script a macOS run executes: build, then become the app's executable, so its output /// 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 { @@ -380,13 +470,13 @@ pub fn destination(dir: &Path, params: &BTreeMap, 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}")) } /// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches -/// its scheme on the simulator. `dir` is the run's working directory; DerivedData goes under +/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; DerivedData goes under /// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`. /// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator. pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> { @@ -412,11 +502,32 @@ pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> I return Ok(()); } let udid = destination.trim_start_matches("id=").to_owned(); + let device = crate::simulator::devices(dir).into_iter().find(|d| d.udid == udid); + if let Some(reason) = device.as_ref().and_then(device_unready) { + return Err(IdeError::unavailable(reason)); + } let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?; let settings = show(&args)?; - let (app, bundle_id) = built_app(&settings).map_err(IdeError::invalid)?; + let (app, bundle_id) = built_app(&settings, device.is_some()).map_err(IdeError::invalid)?; let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str)); let wait = params.get(WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty()); + if let Some(device) = device { + if wait { + return Err(IdeError::unavailable("Debugging an app on a physical device is not supported yet")); + } + config.command = "/bin/sh".into(); + config.args = [ + "-c".to_owned(), + device_launch_script(&args, &udid, &device.name, &app, &bundle_id), + "xcode-run".to_owned(), + ] + .into_iter() + .chain(app_args) + .collect(); + let env = std::mem::take(&mut config.env); + config.env = env.into_iter().map(|(k, v)| (format!("DEVICECTL_CHILD_{k}"), v)).collect(); + return Ok(()); + } config.command = "/bin/sh".into(); config.args = ["-c".to_owned(), launch_script(&args, &udid, &app, &bundle_id, wait), "xcode-run".to_owned()] .into_iter() @@ -531,12 +642,16 @@ 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")); assert_eq!(config.args.len(), 5); assert!(!old.exists() && other.exists()); + + config.extras.params.insert(RESULT_BUNDLE_PARAM.into(), "/cov/r.xcresult".into()); + prepare_test(&mut config, dir.path(), dir.path()).unwrap(); + assert_eq!(config.args[3..], ["-resultBundlePath", "/cov/r.xcresult"]); } #[test] @@ -590,14 +705,66 @@ mod tests { ) }; assert_eq!( - built_app(&settings("iphonesimulator")).unwrap(), + built_app(&settings("iphonesimulator"), false).unwrap(), (PathBuf::from("/dd/Build/Products/Debug-iphonesimulator/App.app"), "dev.example.App".to_owned()) ); assert_eq!( - built_app(&settings("macosx")).unwrap_err(), + built_app(&settings("macosx"), false).unwrap_err(), "The scheme builds an app for macosx, not the iOS Simulator" ); - assert_eq!(built_app("[]").unwrap_err(), "The scheme builds no application"); + assert_eq!(built_app("[]", false).unwrap_err(), "The scheme builds no application"); + assert_eq!( + built_app(&settings("iphonesimulator"), true).unwrap_err(), + "The scheme builds an app for iphonesimulator, not an iOS device" + ); + } + + #[test] + fn a_device_app_must_be_signed_with_a_team() { + let settings = |signing: &str| { + format!( + r#"[{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application", + "PLATFORM_NAME": "iphoneos", "TARGET_BUILD_DIR": "/dd/Debug-iphoneos", "WRAPPER_NAME": "App.app", + "PRODUCT_BUNDLE_IDENTIFIER": "dev.example.App", {signing}}}}}]"# + ) + }; + let signed = settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": "ABCDE12345""#); + assert_eq!( + built_app(&signed, true).unwrap(), + (PathBuf::from("/dd/Debug-iphoneos/App.app"), "dev.example.App".to_owned()) + ); + let manual = settings(r#""CODE_SIGN_STYLE": "Manual", "DEVELOPMENT_TEAM": """#); + assert!(built_app(&manual, true).is_ok(), "manual signing names its profile; xcodebuild checks it"); + assert_eq!( + built_app(&settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": """#), true).unwrap_err(), + "Signing App.app for a device needs a development team: choose one under Signing & Capabilities in Xcode" + ); + assert_eq!( + built_app(&settings(r#""CODE_SIGNING_ALLOWED": "NO""#), true).unwrap_err(), + "App.app is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps" + ); + } + + #[test] + fn an_unready_device_says_what_to_do() { + let device = |state: &str| crate::simulator::IosSimulator { + udid: "U".into(), + name: "Test iPhone".into(), + runtime: "iOS 27.3".into(), + state: state.into(), + physical: true, + }; + assert_eq!(device_unready(&device(crate::simulator::AVAILABLE)), None); + assert!( + device_unready(&device(crate::simulator::UNAVAILABLE)) + .unwrap() + .starts_with("Test iPhone is not connected.") + ); + assert!( + device_unready(&device(crate::simulator::DEVELOPER_MODE_OFF)) + .unwrap() + .starts_with("Developer Mode is off on Test iPhone.") + ); } #[test] @@ -737,6 +904,82 @@ mod tests { ); } + /// The device script builds, installs and launches through devicectl, turns a Stop's SIGINT + /// into a SIGTERM to it, and adds the locked-device hint only when devicectl itself failed to launch. + #[cfg(unix)] + #[test] + fn device_launch_script_installs_launches_and_explains_a_failed_launch() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + let stub = |tool: &str, then: &str| { + let path = dir.path().join(tool); + let body = format!( + "#!/bin/sh\nprintf '{tool}' >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}" + ); + fs::write(&path, body).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + }; + stub("xcodebuild", ""); + // `launch` writes its JSON result to the path after `--json-output` ($8), then either + // fails at once or runs until a SIGINT reaches it. + stub( + "xcrun", + "[ \"$4\" = launch ] || exit 0\n\ + printf '{\"info\" : {\"outcome\" : \"%s\"}}' \"$OUTCOME\" > \"$8\"\n\ + [ \"$OUTCOME\" = success ] || { echo 'ERROR: the device was not unlocked' >&2; exit 1; }\n\ + trap 'echo terminated >> \"$LOG\"; exit 0' TERM\n\ + while :; do sleep 0.05; done\n", + ); + let build = ["-project".to_owned(), "App.xcodeproj".to_owned()]; + let script = + device_launch_script(&build, "00008110-AAA", "Test iPhone", Path::new("/dd/My App.app"), "dev.example.App"); + let run = |outcome: &str| { + let _ = fs::remove_file(&log); + std::process::Command::new("/bin/sh") + .args(["-c", &script, "xcode-run", "--greeting", "hi there"]) + .env("PATH", format!("{}:/usr/bin:/bin", dir.path().display())) + .env("LOG", &log) + .env("OUTCOME", outcome) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + }; + + let failed = run("failed").wait_with_output().unwrap(); + assert_eq!(failed.status.code(), Some(1)); + assert_eq!( + String::from_utf8_lossy(&failed.stderr), + "ERROR: the device was not unlocked\n\ + Could not launch the app on Test iPhone. If it is locked, unlock it and run again.\n" + ); + + let child = run("success"); + let launched = || fs::read_to_string(&log).unwrap_or_default().contains("[launch]"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !launched() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + std::thread::sleep(std::time::Duration::from_millis(200)); + unsafe { libc::kill(child.id() as i32, libc::SIGINT) }; + let stopped = child.wait_with_output().unwrap(); + assert!(stopped.status.success()); + assert_eq!(String::from_utf8_lossy(&stopped.stderr), ""); + let log = fs::read_to_string(&log).unwrap(); + let json = log.split("[--json-output] [").nth(1).unwrap().split(']').next().unwrap().to_owned(); + assert_eq!( + log, + format!( + "xcodebuild [-project] [App.xcodeproj] [-allowProvisioningUpdates] [build]\n\ + xcrun [devicectl] [device] [install] [app] [--device] [00008110-AAA] [/dd/My App.app]\n\ + xcrun [devicectl] [device] [process] [launch] [--console] [--terminate-existing] [--json-output] [{json}] \ + [--device] [00008110-AAA] [dev.example.App] [--] [--greeting] [hi there]\n\ + terminated\n" + ) + ); + assert!(!Path::new(&json).exists(), "the launch result file is removed"); + } + /// A debug launch passes `--wait-for-debugger` and prints the pid of the suspended app (not of /// a running copy, nor of a process outside its bundle) right away, while simctl keeps running. #[cfg(unix)] diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index 7947afc50..285421c49 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -6,7 +6,7 @@ use crate::exec::{path_with, search_path, which}; use crate::npm::{has_ts_api, native_typescript, own_typescript}; use crate::{angular, astro, godot, pinned, vue}; use crate::{bin_dir, exe, venv_of}; -use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings}; +use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings, TsServerLog}; use ide_core::version_managers::Tool; use ide_core::{IdeError, IdeResult}; use ide_language::{LanguageConfig, LanguageServerConfig}; @@ -1508,6 +1508,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root if name == "vtsls" && memory > 0 { merge_init_options(cfg, json!({ "typescript": { "tsserver": { "maxTsServerMemory": memory } } })); } + if name == "vtsls" { + // Move to File asks the IDE for the target file (vtsls hides the action by default). + merge_init_options(cfg, json!({ "vtsls": { "enableMoveToFileCodeAction": true } })); + let log = s.languages.typescript.tsserver_log; + if log != TsServerLog::Off { + merge_init_options(cfg, json!({ "typescript": { "tsserver": { "log": log } } })); + } + } if name == "vtsls" && cfg.tsserver_project && !server_root.ancestors().any(|d| d.join("tsconfig.json").is_file() || d.join("jsconfig.json").is_file()) @@ -2778,6 +2786,22 @@ mod maven_linkage_tests { assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144))); } + #[test] + fn vtsls_offers_move_to_file_and_logs_only_when_asked() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = Settings::default(); + let options = |s: &Settings| { + let mut cfg = custom_server("vtsls", &LanguageServerSettings::default()); + configure_server(&mut cfg, tmp.path(), tmp.path(), s); + serde_json::to_value(cfg.initialization_options).unwrap() + }; + let off = options(&s); + assert_eq!(off.pointer("/vtsls/enableMoveToFileCodeAction"), Some(&json!(true))); + assert!(off.pointer("/typescript/tsserver/log").is_none()); + s.languages.typescript.tsserver_log = TsServerLog::Verbose; + assert_eq!(options(&s).pointer("/typescript/tsserver/log"), Some(&json!("verbose"))); + } + #[test] fn vtsls_probes_the_tsconfig_plugins_but_not_its_global_ones() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-sdk/src/discover.rs b/crates/ide-sdk/src/discover.rs index 96592f069..16374b6c8 100644 --- a/crates/ide-sdk/src/discover.rs +++ b/crates/ide-sdk/src/discover.rs @@ -33,6 +33,7 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec { 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 { | SdkKind::Rust | SdkKind::TypeScript | SdkKind::Dotnet - | SdkKind::Flutter => None, + | SdkKind::Flutter + | SdkKind::Xcode => None, } } @@ -1219,6 +1221,56 @@ fn zig() -> Vec { }) } +/// 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 { + 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 = 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 `` after `key` of an XML property list. +fn plist_string(plist: &str, key: &str) -> Option { + let rest = &plist[plist.find(&format!("{key}"))?..]; + let value = &rest[rest.find("")? + "".len()..]; + Some(value[..value.find("")?].trim().to_owned()).filter(|v| !v.is_empty()) +} + +#[test] +fn reads_xcodes_version_plist() { + let plist = "\n\tBuildVersion\n\t7\n\tCFBundleShortVersionString\n\t26.1\n"; + 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 { diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 4bbf32e26..ca3a00a6f 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "java-usages", - "1.19.0", + "1.20.1", include_bytes!("../../../java/java-usages/openidea-java-usages.jar"), ) } diff --git a/crates/ide-sdk/src/lib.rs b/crates/ide-sdk/src/lib.rs index 99f9558f7..13aff5442 100644 --- a/crates/ide-sdk/src/lib.rs +++ b/crates/ide-sdk/src/lib.rs @@ -66,6 +66,8 @@ pub enum SdkKind { Dotnet, /// Flutter SDK roots. Flutter, + /// `Xcode.app` bundles. + Xcode, } /// One installed interpreter / toolchain. diff --git a/crates/ide-sdk/src/php.rs b/crates/ide-sdk/src/php.rs index e0b26119c..c3bab37cb 100644 --- a/crates/ide-sdk/src/php.rs +++ b/crates/ide-sdk/src/php.rs @@ -64,16 +64,25 @@ pub enum ComposerInstall { Outdated, } -/// The Composer project `file` belongs to (the nearest `composer.json` at or below `root`), and -/// whether its dependencies need `composer install`. +/// Whether the nearest enclosing Composer project needs `composer install`. A manifest inside +/// that project's vendor directory belongs to an installed package. pub fn composer_install(file: &Path, root: &Path) -> Option<(PathBuf, ComposerInstall)> { - let dir = file.ancestors().filter(|d| d.starts_with(root)).find(|d| d.join("composer.json").is_file())?; - let composer: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("composer.json")).ok()?).ok()?; - let vendor = dir.join(composer.pointer("/config/vendor-dir").and_then(Value::as_str).unwrap_or("vendor")); + let read = |path: PathBuf| std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::(&t).ok()); + let ancestors: Vec<_> = file.ancestors().take_while(|dir| dir.starts_with(root)).collect(); + let mut project = None; + for dir in ancestors.into_iter().rev() { + let Some(composer) = read(dir.join("composer.json")) else { continue }; + let vendor = dir.join(composer.pointer("/config/vendor-dir").and_then(Value::as_str).unwrap_or("vendor")); + let in_vendor = file.starts_with(&vendor); + project = Some((dir, vendor)); + if in_vendor { + break; + } + } + let (dir, vendor) = project?; if !vendor.join("autoload.php").is_file() { return Some((dir.to_path_buf(), ComposerInstall::Missing)); } - let read = |path: PathBuf| std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::(&t).ok()); let lock = read(dir.join("composer.lock"))?; let installed = read(vendor.join("composer/installed.json")).unwrap_or(Value::Null); // Composer 2 writes `{"packages": [...], "dev": bool}`, Composer 1 the list itself. @@ -352,6 +361,32 @@ mod tests { assert_eq!(composer_install(&root.join("other.php"), root), None, "outside the Composer project"); } + #[test] + fn composer_install_checks_the_owning_project_for_vendor_files() { + for (vendor, manifest) in [("vendor", "{}"), ("deps", r#"{"config":{"vendor-dir":"deps"}}"#)] { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let vendor = root.join(vendor); + let package = vendor.join("symfony/console"); + let nested = root.join("apps/console"); + for dir in [&package, &nested, &vendor.join("composer")] { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(root.join("composer.json"), manifest).unwrap(); + std::fs::write(package.join("composer.json"), "{}").unwrap(); + std::fs::write(nested.join("composer.json"), "{}").unwrap(); + let file = package.join("Application.php"); + assert_eq!(composer_install(&file, root), Some((root.to_path_buf(), ComposerInstall::Missing))); + + std::fs::write(vendor.join("autoload.php"), ", explicit: &str) -> Option { levels(composer, explicit).0.map(|l| l.version) } diff --git a/crates/ide-tools/src/lib.rs b/crates/ide-tools/src/lib.rs index 43ca2142c..b5cab6aff 100644 --- a/crates/ide-tools/src/lib.rs +++ b/crates/ide-tools/src/lib.rs @@ -383,6 +383,9 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap { u.companion = true; } } + for (tool, lang) in registry::LANGUAGE_CLIS { + map.entry(tool.to_string()).or_default().languages.push(lang.to_string()); + } for (plugin, host) in registry::PLUGIN_HOSTS { let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default(); map.entry(plugin.to_string()).or_default().languages = languages; diff --git a/crates/ide-tools/src/registry.rs b/crates/ide-tools/src/registry.rs index 461e17c7a..ca8516f05 100644 --- a/crates/ide-tools/src/registry.rs +++ b/crates/ide-tools/src/registry.rs @@ -210,6 +210,28 @@ pub static TOOLS: &[ToolSpec] = &[ needs: &[], homepage: "https://cli.github.com", }, + // Run by the IDE on Swift files below a `.swiftlint.yml` (not a language server). + ToolSpec { + name: "swiftlint", + display: "SwiftLint", + kind: Cli, + commands: &["swiftlint"], + method: Method::Release { + source: ReleaseSource::GitHub { repo: "realm/SwiftLint" }, + assets: &[ + any_arch(Mac, "portable_swiftlint.zip"), + rule(Linux, X64, "swiftlint_linux_amd64.zip"), + rule(Linux, Arm64, "swiftlint_linux_arm64.zip"), + rule(Windows, X64, "SwiftLint.amd64.zip"), + rule(Windows, Arm64, "SwiftLint.arm64.zip"), + ], + locate: &["swiftlint"], + }, + fallback: None, + version: ver("swiftlint"), + needs: &[], + homepage: "https://realm.github.io/SwiftLint/", + }, ToolSpec { name: "oxfmt", display: "oxfmt", @@ -1410,6 +1432,9 @@ pub static TOOLS: &[ToolSpec] = &[ pub const PLUGIN_HOSTS: &[(&str, &str)] = &[("lombok", "jdtls"), ("css-modules-kit", "vtsls"), ("typescript-styled-plugin", "vtsls")]; +/// Command-line tools the IDE runs on one language's files, listed with that language. +pub const LANGUAGE_CLIS: &[(&str, &str)] = &[("swiftlint", "Swift")]; + pub fn find(name: &str) -> Option<&'static ToolSpec> { TOOLS.iter().find(|t| t.name == name) } diff --git a/crates/ide-tools/src/tests.rs b/crates/ide-tools/src/tests.rs index 70bea5b6c..2a1f30166 100644 --- a/crates/ide-tools/src/tests.rs +++ b/crates/ide-tools/src/tests.rs @@ -1458,6 +1458,15 @@ fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() { assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path())); } +#[test] +fn swiftlint_is_an_installable_tool_of_swift() { + let env = Env::new(); + env.script(&env.sys, "curl", "exit 0"); + let tool = env.tools().info("swiftlint", &[]).unwrap(); + assert_eq!((tool.kind, tool.status, tool.can_install), (ToolKind::Cli, ToolStatus::Missing, true)); + assert_eq!(tool.languages, ["Swift"]); +} + #[test] fn an_npm_tsserver_plugin_is_installed_at_its_pinned_version_only() { let env = Env::new(); diff --git a/crates/ide-vcs/src/history.rs b/crates/ide-vcs/src/history.rs index 803eedb1b..b73b7aa4b 100644 --- a/crates/ide-vcs/src/history.rs +++ b/crates/ide-vcs/src/history.rs @@ -464,11 +464,16 @@ fn renamed_from( Ok(None) } +/// The log index, locked only around reads and writes: Git runs without it, so commit +/// details and one-commit queries need not wait for a long history walk. +fn lock(index: &std::sync::Mutex) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> { + index.lock().unwrap_or_else(|p| p.into_inner()) +} + pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult> { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner()); let result = if q.summary_only { let mut all = q.clone(); all.skip = 0; @@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::>()).unwrap_or_default(); let shallow: HashSet = shallow_vec.iter().copied().collect(); let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?); - let cached = index.views.get(&key).cloned(); + let cached = lock(&r.log_index).views.get(&key).cloned(); let view = if let Some(cached) = cached { cached } else { // Immutable metadata is reused across roots, filters, merges and ref changes. all.request = q.request; - let rows = - std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?)); + let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows( + r, + &all, + cancel, + &r.log_index, + )?)); + let mut index = lock(&r.log_index); if index.views.len() >= 4 { index.views.clear(); } @@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0); let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) }; let total = view.rows.len() as u32; + let mut index = lock(&r.log_index); let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu } Ok(result) } else { - log_indexed(r, q, cancel, &mut index) + log_indexed(r, q, cancel, &r.log_index) }; - index.flush(); + lock(&r.log_index).flush(); result } @@ -640,7 +651,7 @@ fn log_indexed( r: &Repo, q: &LogQuery, cancel: &CancellationToken, - index: &mut crate::log_index::LogIndex, + shared: &std::sync::Mutex, ) -> IdeResult> { let repo = r.gix()?; let shallow: HashSet = @@ -676,6 +687,8 @@ fn log_indexed( && q.since_ms.is_none() && q.until_ms.is_none() { + let mut guard = lock(shared); + let index = &mut *guard; update_head_reachable(&repo, index, cancel)?; let id = tips[0]; let record = index.get(&repo, id)?; @@ -706,7 +719,9 @@ fn log_indexed( commit.message_truncated = false; return Ok(vec![commit]); } - let rows = log_indexed_rows(r, q, cancel, index)?; + let rows = log_indexed_rows(r, q, cancel, shared)?; + let mut guard = lock(shared); + let index = &mut *guard; let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -724,7 +739,7 @@ fn log_indexed_rows( r: &Repo, q: &LogQuery, cancel: &CancellationToken, - index: &mut crate::log_index::LogIndex, + shared: &std::sync::Mutex, ) -> IdeResult> { if cancel.is_cancelled() { return Err(IdeError::cancelled()); @@ -775,7 +790,7 @@ fn log_indexed_rows( } } } - Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?) + Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?) } else { None }; @@ -802,14 +817,17 @@ fn log_indexed_rows( }; let authors: Vec<_> = q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect(); - update_head_reachable(&repo, index, cancel)?; let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::>()); type Walk<'a> = Box> + 'a>; let walk: Walk<'_> = if let Some(ids) = range_ids { Box::new(ids.into_iter().map(Ok)) } else if q.summary_only { - let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?; - Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok)) + // One guard for both: a concurrent query with another shallow set resets `nodes`. + let mut guard = lock(shared); + let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?; + let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?; + drop(guard); + Box::new(sorted.into_iter().map(Ok)) } else if repo.is_shallow().unwrap_or(false) || q.request.is_some() { // The process can be interrupted even during indegree preparation. Git also // respects shallow boundaries while retaining a topological order. @@ -866,7 +884,7 @@ fn log_indexed_rows( LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder, LogOrder::Date => topo::Sorting::DateOrder, }; - let topo = topo::Builder::from_iters(&repo.objects, tips, None::>) + let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::>) .sorting(sorting) .parents(if q.first_parent { Parents::First } else { Parents::All }) .with_commit_graph(graph) @@ -876,11 +894,20 @@ fn log_indexed_rows( }; let walk: Walk<'_> = if q.order == LogOrder::Standard { let ids = walk.collect::>>()?; - Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok)) + Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok)) } else { walk }; let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten(); + let mut guard = lock(shared); + let index = &mut *guard; + // Under the guard that builds the rows: a query run meanwhile (after a branch switch) + // may have moved the shared set to another HEAD. + update_head_reachable(&repo, index, cancel)?; + // A query started before a shallow change may have reset `nodes` to its older set. + if index.shallow != shallow { + index.ensure_nodes(&repo, &tips, &shallow, cancel)?; + } let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -952,6 +979,21 @@ fn log_indexed_rows( Ok(out) } +/// Sorts with the shared nodes only when they were built for this query's shallow set. +fn sort_shared( + repo: &gix::Repository, + ids: Vec, + q: &LogQuery, + shallow: &HashSet, + cancel: &CancellationToken, + shared: &std::sync::Mutex, +) -> IdeResult> { + let guard = lock(shared); + let empty = HashMap::new(); + let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty }; + sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes) +} + /// A ready-node stack gives incoming merge parents priority, while child counts /// prevent an ancestor shared with another branch from moving ahead of its children. fn sort_subset( diff --git a/crates/ide-vcs/src/repo.rs b/crates/ide-vcs/src/repo.rs index 5955b873e..7b23290f1 100644 --- a/crates/ide-vcs/src/repo.rs +++ b/crates/ide-vcs/src/repo.rs @@ -20,7 +20,12 @@ pub(crate) fn gx(e: impl std::fmt::Display) -> IdeError { } pub(crate) struct Cache { - repo: gix::ThreadSafeRepository, + /// `None` after the repository was replaced or went away. gitoxide memory-maps packs, and + /// reading a mapping whose volume was unmounted raises SIGBUS, so that handle is never reused. + repo: Option, + /// The git and common directories `repo` was opened from. + dirs: [PathBuf; 2], + handles: Option, files: [PathBuf; 4], stamp: Vec>, /// `objects/pack` directory and its modification time. An external @@ -49,6 +54,49 @@ fn stamp(files: &[PathBuf]) -> Vec> { .collect() } +/// Tells whether the repository's directories are still the ones its handle was opened from. +/// +/// Comparing paths is not enough: a remounted volume can have the same device, inodes and +/// modification times. A descriptor opened before the unmount stays invalid after it. +#[cfg(unix)] +struct DirHandles([std::fs::File; 2]); + +#[cfg(unix)] +impl DirHandles { + fn open(dirs: &[PathBuf; 2]) -> Option { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + // Any other descriptor makes a normal unmount (Eject) fail because the volume is busy. + #[cfg(target_os = "macos")] + std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_EVTONLY); + Some(Self([options.open(&dirs[0]).ok()?, options.open(&dirs[1]).ok()?])) + } + + fn is_current(&self, dirs: &[PathBuf; 2]) -> bool { + use std::os::unix::fs::MetadataExt; + self.0.iter().zip(dirs).all(|(held, dir)| match (held.metadata(), std::fs::metadata(dir)) { + (Ok(held), Ok(now)) => (held.dev(), held.ino()) == (now.dev(), now.ino()), + _ => false, + }) + } +} + +// ponytail: existence only, because an open directory handle blocks renaming it on Windows. +// A volume that returns between two calls goes unnoticed; compare file ids if that matters. +#[cfg(not(unix))] +struct DirHandles; + +#[cfg(not(unix))] +impl DirHandles { + fn open(dirs: &[PathBuf; 2]) -> Option { + Self.is_current(dirs).then_some(Self) + } + + fn is_current(&self, dirs: &[PathBuf; 2]) -> bool { + dirs.iter().all(|dir| dir.is_dir()) + } +} + /// The pack directory's modification time: adding or removing a pack file /// updates it. `None` when the directory can't be read. fn pack_stamp(pack_dir: &Path) -> Option { @@ -77,7 +125,16 @@ pub(crate) fn discover(path: &Path) -> IdeResult> { let common_dir = absolute(repo.common_dir())?; let files = cache_files(&git_dir, &common_dir); let pack_dir = common_dir.join("objects").join("pack"); - let cache = Cache { stamp: stamp(&files), files, repo: ts, pack_stamp: pack_stamp(&pack_dir), pack_dir }; + let dirs = [git_dir.clone(), common_dir]; + let cache = Cache { + stamp: stamp(&files), + files, + repo: Some(ts), + handles: DirHandles::open(&dirs), + dirs, + pack_stamp: pack_stamp(&pack_dir), + pack_dir, + }; Ok(Some(Repo { execution_allowed: std::sync::atomic::AtomicBool::new(false), git_executable: std::sync::RwLock::new(crate::opening_git_executable()), @@ -141,6 +198,8 @@ impl Repo { /// A thread-local gitoxide handle; reopened when configuration or packed refs change. /// gitoxide's packed-ref snapshot only reloads for a newer mtime, which a replacement may preserve. + /// A volume lost after this returns can still raise SIGBUS in the caller: gitoxide can't read + /// packs without mapping them. pub(crate) fn gix(&self) -> IdeResult { let _scope = self.execution_scope(); self.check_valid()?; @@ -149,12 +208,20 @@ impl Repo { .map_err(gx); } let mut cache = self.inner.lock().unwrap_or_else(|p| p.into_inner()); + if !cache.handles.as_ref().is_some_and(|handles| handles.is_current(&cache.dirs)) { + cache.repo = None; + // Before the repository is opened, so that losing the volume meanwhile is noticed. + cache.handles = DirHandles::open(&cache.dirs); + if cache.handles.is_none() { + return Err(self.stale_error()); + } + } let now = stamp(&cache.files); let pack_now = pack_stamp(&cache.pack_dir); - if now != cache.stamp || pack_now != cache.pack_stamp { + if cache.repo.is_none() || now != cache.stamp || pack_now != cache.pack_stamp { match gix::ThreadSafeRepository::open(&self.git_dir) { Ok(fresh) => { - cache.repo = fresh; + cache.repo = Some(fresh); cache.stamp = now; cache.pack_stamp = pack_now; } @@ -163,11 +230,14 @@ impl Repo { cache.stamp = now; cache.pack_stamp = pack_now; self.check_valid()?; + if cache.repo.is_none() { + return Err(gx(e)); + } tracing::warn!("reopening repository failed: {e}"); } } } - let mut repo = cache.repo.to_thread_local(); + let mut repo = cache.repo.as_ref().ok_or_else(|| self.stale_error())?.to_thread_local(); repo.object_cache_size_if_unset(4 * 1024 * 1024); Ok(repo) } @@ -577,3 +647,44 @@ pub(crate) fn is_ignored(repo: &gix::Repository, rel: &str) -> IdeResult { pub(crate) fn to_string(b: &BStr) -> String { b.to_str_lossy().into_owned() } + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::process::Command; + use std::sync::Arc; + + fn run(cmd: &mut Command) { + assert!(cmd.status().unwrap().success(), "{cmd:?}"); + } + + /// What a remounted volume looks like: every path and modification time is the same, but + /// the files that the old handle mapped are gone. `tests/volume_loss.rs` does it for real. + #[test] + fn a_replaced_repository_is_reopened_even_when_its_stamps_are_the_same() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("repo"); + let copy = tmp.path().join("copy"); + run(Command::new("git").args(["init", "-q"]).arg(&root)); + let repo = discover(&root).unwrap().unwrap(); + repo.set_execution_allowed(true); + let store = || repo.gix().unwrap().objects.store(); + let stamps = || { + let cache = repo.inner.lock().unwrap(); + (stamp(&cache.files), pack_stamp(&cache.pack_dir)) + }; + let (first, before) = (store(), stamps()); + assert!(Arc::ptr_eq(&first, &store()), "an unchanged repository keeps its handle"); + + run(Command::new("cp").arg("-pR").arg(&root).arg(©)); + std::fs::rename(&root, tmp.path().join("old")).unwrap(); + assert!(repo.gix().is_err()); + assert!(repo.gix().is_err()); + std::fs::rename(©, &root).unwrap(); + + assert_eq!(stamps(), before, "the stamps must not be what triggers the reopen"); + let second = store(); + assert!(!Arc::ptr_eq(&first, &second), "the handle to the replaced repository was reused"); + assert!(Arc::ptr_eq(&second, &store()), "it is reopened once"); + } +} diff --git a/crates/ide-vcs/src/status.rs b/crates/ide-vcs/src/status.rs index b6548f17e..5d60e25fd 100644 --- a/crates/ide-vcs/src/status.rs +++ b/crates/ide-vcs/src/status.rs @@ -311,6 +311,22 @@ fn network_args(r: &Repo) -> Vec { NETWORK_STAT_CONFIG.iter().flat_map(|(key, value)| ["-c".to_owned(), format!("{key}={value}")]).collect() } +/// Runs `git status`; when rename detection needs a blob that cannot be fetched (Restricted Mode +/// sets `GIT_NO_LAZY_FETCH`, or the promisor remote is unreachable), retries once without it. +/// The message is stable because `cli::command` pins `LC_ALL=C`. +fn run_status(r: &Repo, mut args: Vec<&str>) -> IdeResult { + let out = crate::cli::run_raw_env(r.root(), &args, None, &read_only())?; + if out.code == Some(0) { + return Ok(out); + } + if String::from_utf8_lossy(&out.stderr).contains("promisor remote") { + let at = args.iter().position(|a| *a == "status").map_or(args.len(), |i| i + 1); + args.insert(at, "--no-renames"); + return crate::cli::run_env(r.root(), &args, None, &read_only()); + } + Err(crate::cli::failure(&args, &out.stderr, &out.stdout, out.code)) +} + /// `git status --porcelain=v2`: what git lists, unreadable directories skipped. /// In Restricted Mode git compares content without the repository's clean/process /// filters and doesn't ask submodules for their own status (which runs their config). @@ -323,7 +339,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult { if !crate::execution_allowed() { args.push("--ignore-submodules=dirty"); } - let out = crate::cli::run_env(r.root(), &args, None, &read_only())?; + let out = run_status(r, args)?; Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored)) } @@ -340,7 +356,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe } args.push("--"); args.extend(paths.iter().map(String::as_str)); - let out = crate::cli::run_env(r.root(), &args, None, &read_only())?; + let out = run_status(r, args)?; Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored)) } diff --git a/crates/ide-vcs/tests/log_lock.rs b/crates/ide-vcs/tests/log_lock.rs new file mode 100644 index 000000000..e14622842 --- /dev/null +++ b/crates/ide-vcs/tests/log_lock.rs @@ -0,0 +1,79 @@ +//! A long file history walk must not hold the log index while Git runs: commit details and +//! one-commit queries (inline blame, the blame popup) share that index. +#![cfg(unix)] + +use ide_vcs::{LogQuery, Repo}; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::Command; +use std::time::{Duration, Instant}; + +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(dir) + .args([ + "-c", + "init.defaultBranch=main", + "-c", + "user.name=T", + "-c", + "user.email=t@e", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .output() + .unwrap(); + assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +#[test] +fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("repo"); + std::fs::create_dir(&dir).unwrap(); + git(&dir, &["init", "-q"]); + for i in 0..3 { + std::fs::write(dir.join("file"), format!("{i}")).unwrap(); + git(&dir, &["add", "-A"]); + git(&dir, &["commit", "-qm", &format!("c{i}")]); + } + // A git whose path-limited history walks take seconds. + let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap(); + let started = tmp.path().join("walk-started"); + let wrapper = tmp.path().join("slow-git"); + std::fs::write( + &wrapper, + format!( + "#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n", + started.display(), + real.trim() + ), + ) + .unwrap(); + std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); + let repo = Repo::discover(&dir).unwrap().unwrap(); + repo.set_execution_allowed(true); + repo.set_git_executable(Some(&wrapper)); + std::thread::scope(|scope| { + let walk = scope.spawn(|| { + repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len() + }); + let deadline = Instant::now() + Duration::from_secs(20); + while !started.exists() { + assert!(Instant::now() < deadline, "the history walk never started"); + std::thread::sleep(Duration::from_millis(20)); + } + let asked = Instant::now(); + let details = repo.log_details("HEAD").unwrap(); + let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap(); + let waited = asked.elapsed(); + println!("queries waited {waited:?}"); + assert_eq!(details.message, "c2"); + assert_eq!(head.len(), 1); + assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing"); + assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk"); + assert_eq!(walk.join().unwrap(), 3); + }); +} diff --git a/crates/ide-vcs/tests/partial_clone.rs b/crates/ide-vcs/tests/partial_clone.rs new file mode 100644 index 000000000..b79c984d1 --- /dev/null +++ b/crates/ide-vcs/tests/partial_clone.rs @@ -0,0 +1,144 @@ +//! Partial clones (`--filter=blob:none`) with a sparse checkout: blobs outside the +//! checkout are never fetched, and gitoxide's status cannot read them. + +use ide_vcs::{ChangeKind, LogQuery, Repos}; +use std::path::Path; +use std::process::Command; + +fn git(dir: &Path, args: &[&str]) { + let out = Command::new("git") + .current_dir(dir) + .args(["-c", "init.defaultBranch=main", "-c", "core.autocrlf=false", "-c", "protocol.file.allow=always"]) + .args(args) + .env("GIT_TERMINAL_PROMPT", "0") + .output() + .expect("git runs"); + assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +fn git_available() -> bool { + Command::new("git").arg("--version").output().is_ok_and(|o| o.status.success()) +} + +fn file_url(path: &Path) -> String { + let path = path.to_string_lossy().replace('\\', "/"); + format!("file:///{}", path.trim_start_matches('/')) +} + +/// A blobless, cone-mode sparse clone of a small source repository; `docs/` and `app/` blobs stay remote. +fn blobless_clone(base: &Path) -> std::path::PathBuf { + let source = base.join("source"); + std::fs::create_dir_all(source.join("docs")).unwrap(); + std::fs::create_dir_all(source.join("app")).unwrap(); + git(&source, &["init", "-q"]); + git(&source, &["config", "user.name", "Test User"]); + git(&source, &["config", "user.email", "test@example.com"]); + git(&source, &["config", "commit.gpgsign", "false"]); + std::fs::write(source.join("README.md"), "hello\n").unwrap(); + let guide: String = (1..=200).map(|i| format!("line {i}\n")).collect(); + std::fs::write(source.join("docs/guide.txt"), &guide).unwrap(); + std::fs::write(source.join("app/main.rs"), "fn main() {}\n").unwrap(); + git(&source, &["add", "-A"]); + git(&source, &["commit", "-q", "-m", "init"]); + + let bare = base.join("bare.git"); + git(base, &["clone", "-q", "--bare", "source", "bare.git"]); + git(&bare, &["config", "uploadpack.allowFilter", "true"]); + git(&bare, &["config", "uploadpack.allowAnySHA1InWant", "true"]); + + let work = base.join("work"); + git(base, &["clone", "-q", "--filter=blob:none", "--sparse", &file_url(&bare), "work"]); + git(&work, &["config", "user.name", "Test User"]); + git(&work, &["config", "user.email", "test@example.com"]); + // A global `status.renames=false` would make the baseline pass without the fix. + git(&work, &["config", "status.renames", "true"]); + assert!(!work.join("app/main.rs").exists(), "app/ is outside the sparse checkout"); + work +} + +#[test] +fn blobless_sparse_clone_keeps_its_repository_and_status() { + if !git_available() { + eprintln!("git is not available; skipping"); + return; + } + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let work = blobless_clone(&base); + let bare = base.join("bare.git"); + + std::fs::write(work.join("README.md"), "hello\nchanged\n").unwrap(); + std::fs::write(work.join("new.txt"), "new\n").unwrap(); + // A staged deletion of a never-fetched blob plus a near-identical addition: rename + // detection would have to fetch the missing blob (`git rm --sparse` needs git 2.35+). + git(&work, &["rm", "-q", "--sparse", "docs/guide.txt"]); + let renamed: String = (1..=199).map(|i| format!("line {i}\n")).collect(); + std::fs::write(work.join("guide2.txt"), renamed).unwrap(); + git(&work, &["add", "guide2.txt"]); + + // The promisor remote is gone: status must not need it. + std::fs::rename(&bare, base.join("gone.git")).unwrap(); + + let repos = Repos::discover(&work, &|_| false).unwrap(); + let repo = repos.primary().expect("the partial clone is a repository"); + assert_eq!(repo.root(), work); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main")); + assert_eq!(repo.log(&LogQuery::default()).unwrap().len(), 1); + + let status = repos.status().expect("status of a partial clone"); + let find = |rel: &str| status.iter().find(|f| f.rel_path == rel); + let readme = find("README.md").expect("README.md listed"); + assert_eq!((readme.staged, readme.unstaged), (None, Some(ChangeKind::Modified))); + let new = find("new.txt").expect("new.txt listed"); + assert_eq!(new.unstaged, Some(ChangeKind::Untracked)); + // Rename detection needs the never-fetched blob, so the retry without it lists an addition. + let moved = find("guide2.txt").expect("guide2.txt listed"); + assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None)); + let removed = find("docs/guide.txt").expect("docs/guide.txt listed"); + assert_eq!(removed.staged, Some(ChangeKind::Deleted)); + // Skip-worktree entries outside the checkout are not missing files. + assert!(find("app/main.rs").is_none(), "{status:?}"); + assert_eq!(status.len(), 4, "{status:?}"); + + // The watcher's scoped refresh (a trusted project's `git status` with a pathspec) retries the + // same way. + repo.set_execution_allowed(true); + let scoped = repo.status_paths(&[work.join("guide2.txt"), work.join("docs/guide.txt")]).expect("scoped status"); + let find = |rel: &str| scoped.iter().find(|f| f.rel_path == rel); + let moved = find("guide2.txt").expect("guide2.txt listed"); + assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None)); + assert_eq!(find("docs/guide.txt").expect("docs/guide.txt listed").staged, Some(ChangeKind::Deleted)); + assert_eq!(scoped.len(), 2, "{scoped:?}"); +} + +#[test] +fn blobless_clone_still_detects_a_rename_between_local_blobs() { + if !git_available() { + eprintln!("git is not available; skipping"); + return; + } + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let work = blobless_clone(&base); + // README.md is inside the cone, so both sides of the rename are local blobs. + git(&work, &["mv", "README.md", "README2.md"]); + + let repos = Repos::discover(&work, &|_| false).unwrap(); + let repo = repos.primary().expect("the partial clone is a repository"); + let status = repos.status().expect("status of a partial clone"); + let moved = status.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed"); + assert_eq!( + (moved.staged, moved.renamed_from.as_deref()), + (Some(ChangeKind::Renamed), Some("README.md")), + "{status:?}" + ); + + repo.set_execution_allowed(true); + let scoped = repo.status_paths(&[work.join("README2.md"), work.join("README.md")]).expect("scoped status"); + let moved = scoped.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed"); + assert_eq!( + (moved.staged, moved.renamed_from.as_deref()), + (Some(ChangeKind::Renamed), Some("README.md")), + "{scoped:?}" + ); +} diff --git a/crates/ide-vcs/tests/volume_loss.rs b/crates/ide-vcs/tests/volume_loss.rs new file mode 100644 index 000000000..b1e469dce --- /dev/null +++ b/crates/ide-vcs/tests/volume_loss.rs @@ -0,0 +1,139 @@ +//! Status after the repository's volume disappears. A stale memory-mapped pack index raises +//! SIGBUS there, which kills the process instead of failing the call. + +#![cfg(target_os = "macos")] + +use ide_vcs::Repo; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +fn run(cmd: &mut Command) { + let out = cmd.output().unwrap(); + assert!(out.status.success(), "{cmd:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +fn git(dir: &Path, args: &[&str]) { + run(Command::new("git") + .current_dir(dir) + .args(["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false"]) + .args(args)); +} + +/// A repository whose objects are all packed, with one staged change so that status has +/// to read the `HEAD` tree. +fn packed_repo(dir: &Path, files: usize) { + std::fs::create_dir_all(dir).unwrap(); + git(dir, &["init", "-q"]); + for i in 0..files { + std::fs::write(dir.join(format!("f{i}")), format!("{i}\n")).unwrap(); + } + git(dir, &["add", "."]); + git(dir, &["commit", "-qm", "init"]); + git(dir, &["repack", "-adq"]); + git(dir, &["pack-refs", "--all"]); + std::fs::write(dir.join("f0"), "changed\n").unwrap(); + git(dir, &["add", "f0"]); +} + +/// An APFS disk image mounted in a temporary directory, detached when dropped. +struct Image { + tmp: tempfile::TempDir, +} + +impl Image { + fn new() -> Self { + let image = Self { tmp: tempfile::tempdir().unwrap() }; + std::fs::create_dir(image.mount()).unwrap(); + run(Command::new("hdiutil") + .args(["create", "-quiet", "-size", "200m", "-fs", "APFS", "-volname", "openidea-test"]) + .arg(image.file())); + image.attach(); + image + } + + fn file(&self) -> PathBuf { + self.tmp.path().join("t.dmg") + } + + fn mount(&self) -> PathBuf { + self.tmp.path().join("mnt") + } + + fn attach(&self) { + run(Command::new("hdiutil") + .args(["attach", "-nobrowse", "-quiet", "-mountpoint"]) + .arg(self.mount()) + .arg(self.file())); + } + + fn force_detach(&self) { + run(Command::new("hdiutil").args(["detach", "-force", "-quiet"]).arg(self.mount())); + } + + /// Unmounts like Eject does: refused while a process keeps the volume busy. + fn unmount(&self) -> Output { + Command::new("diskutil").arg("unmount").arg(self.mount()).output().unwrap() + } +} + +impl Drop for Image { + fn drop(&mut self) { + // After a normal unmount the image is still attached, and only a mounted volume can + // be detached by its path. + let _ = Command::new("hdiutil") + .args(["attach", "-nobrowse", "-quiet", "-mountpoint"]) + .arg(self.mount()) + .arg(self.file()) + .output(); + let _ = Command::new("hdiutil").args(["detach", "-force", "-quiet"]).arg(self.mount()).output(); + } +} + +/// Run with `cargo test -p ide-vcs --test volume_loss -- --ignored`: needs `hdiutil`. +#[test] +#[ignore = "mounts and force-detaches a disk image"] +fn a_force_detached_volume_does_not_crash_status() { + let image = Image::new(); + let root = image.mount().join("repo"); + packed_repo(&root, 5000); + // Start with cold pages, as after a real reconnect. + image.force_detach(); + image.attach(); + + let repo = Repo::discover(&root).unwrap().unwrap(); + repo.set_execution_allowed(true); + assert_eq!(repo.status().unwrap().len(), 1); + + image.force_detach(); + for _ in 0..2 { + assert!(repo.status().is_err()); + assert!(repo.head().is_err()); + } + image.attach(); + assert_eq!(repo.status().unwrap().len(), 1); + + // Gone and back between two calls: same path, same modification times. + image.force_detach(); + image.attach(); + assert_eq!(repo.status().unwrap().len(), 1); + assert!(repo.head().unwrap().1.is_some()); +} + +/// Only the descriptors: this reads nothing, so gitoxide has not mapped any packs yet. +#[test] +#[ignore = "mounts and unmounts a disk image"] +fn the_directory_descriptors_do_not_block_a_normal_unmount() { + let image = Image::new(); + let root = image.mount().join("repo"); + packed_repo(&root, 3); + image.force_detach(); + image.attach(); + + let repo = Repo::discover(&root).unwrap().unwrap(); + repo.set_execution_allowed(true); + let out = image.unmount(); + assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(repo.status().is_err()); + image.attach(); + assert_eq!(repo.status().unwrap().len(), 1); +} diff --git a/crates/ide-workspace/Cargo.toml b/crates/ide-workspace/Cargo.toml index f3e8d275e..f4d324b07 100644 --- a/crates/ide-workspace/Cargo.toml +++ b/crates/ide-workspace/Cargo.toml @@ -24,6 +24,7 @@ globset.workspace = true uuid.workspace = true zip.workspace = true encoding_rs.workspace = true +quick-xml = "0.42" [target.'cfg(windows)'.dependencies] winreg = "0.56" diff --git a/crates/ide-workspace/src/file_moves.rs b/crates/ide-workspace/src/file_moves.rs index 49825af08..be3e5cf93 100644 --- a/crates/ide-workspace/src/file_moves.rs +++ b/crates/ide-workspace/src/file_moves.rs @@ -99,7 +99,9 @@ impl FileMoves { /// Applies `edit` (paths as before the move, as `workspace/willRenameFiles` /// returns them), then performs `moves`. Edited files are snapshotted in - /// Local History first. On failure everything done so far is rolled back. + /// Local History first. `apply_edit` must be transactional: on error it leaves none of + /// its own changes behind, so a rejected edit keeps external changes. A failed + /// file move rolls back the applied edits. /// Returns the id for [`undo`](Self::undo). pub fn perform( &self, @@ -134,11 +136,8 @@ impl FileMoves { } before.push(text); } - if !paths.is_empty() - && let Err(e) = apply_edit(edit) - { - restore(documents, &paths, &before); - return Err(e); + if !paths.is_empty() { + apply_edit(edit)?; } if let Err(e) = crate::file_ops::move_files(moves) { restore(documents, &paths, &before); @@ -305,6 +304,37 @@ mod tests { assert_eq!(fs::read_to_string(root.join("Use.java")).unwrap(), "Bar f; // edited\n"); } + #[test] + fn rejected_reference_edits_preserve_changes_after_the_snapshot() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fs::write(root.join("source.ts"), "source\n").unwrap(); + fs::write(root.join("main.ts"), "old\n").unwrap(); + let docs = documents(); + let mut edit = WorkspaceEdit { + files: vec![FileEdit::Edit { + path: root.join("main.ts").into(), + version: None, + edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "updated".into() }], + }], + ..Default::default() + }; + docs.prepare_workspace_edit(&mut edit).unwrap(); + let apply_edit = |edit: &WorkspaceEdit| { + // An external writer lands after perform captured its rollback text. + fs::write(root.join("main.ts"), "external edit after snapshot\n").unwrap(); + docs.apply_file_move_edits(edit) + }; + let moves = FileMoves::new(); + let mv = vec![FileMove { from: root.join("source.ts").into(), to: root.join("renamed.ts").into() }]; + let error = moves.perform(&docs, None, &mv, &edit, "Move", &apply_edit).unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync); + assert_eq!(fs::read_to_string(root.join("main.ts")).unwrap(), "external edit after snapshot\n"); + assert_eq!(fs::read_to_string(root.join("source.ts")).unwrap(), "source\n"); + assert!(!root.join("renamed.ts").exists()); + assert_eq!(moves.last(), None); + } + #[test] fn moved_paths() { let mv = vec![FileMove { from: "/p/a".into(), to: "/p/b/a".into() }]; diff --git a/crates/ide-workspace/src/recent.rs b/crates/ide-workspace/src/recent.rs index 7db02c3cd..5a027f892 100644 --- a/crates/ide-workspace/src/recent.rs +++ b/crates/ide-workspace/src/recent.rs @@ -162,6 +162,127 @@ fn is_missing(path: &Path) -> bool { path.is_absolute() && !text.contains("://") && !wsl && !path.exists() } +fn folder_name(path: &Path) -> String { + path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string()) +} + +/// What importing a JetBrains IDE's recent projects did (or, as a preview, would do). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct JetBrainsRecentImport { + /// Projects added to the recent projects. + pub imported: u32, + /// Projects left out because their folder no longer exists. + pub missing: u32, + /// Project groups added. + pub groups: u32, +} + +/// A recent project as a JetBrains IDE keeps it in `options/recentProjects.xml`. +#[derive(Debug, Default, PartialEq)] +struct JetBrainsRecent { + path: String, + name: Option, + opened_at_ms: f64, + /// Opened but not listed (LightEdit, a file opened alone): the IDE does not show it. + hidden: bool, +} + +#[derive(Debug, Default, PartialEq)] +struct JetBrainsGroup { + name: String, + paths: Vec, + expanded: bool, +} + +/// The `RecentProjectsManager` state: `additionalInfo` entries (path → `RecentProjectMetaInfo`) and +/// `groups` (`ProjectGroup` with `name`, `expanded` and its `projects`). +fn parse_jetbrains_recent(xml: &str) -> (Vec, Vec) { + use quick_xml::{Reader, XmlVersion, events::Event}; + let mut reader = Reader::from_str(xml); + let (mut projects, mut groups) = (Vec::new(), Vec::new()); + let mut project: Option = None; + let mut group: Option = None; + loop { + let (tag, empty) = match reader.read_event() { + Ok(Event::Start(tag)) => (tag, false), + Ok(Event::Empty(tag)) => (tag, true), + Ok(Event::End(tag)) => { + match tag.local_name().as_ref() { + "entry" => projects.extend(project.take()), + "ProjectGroup" => groups.extend(group.take()), + _ => {} + } + continue; + } + Ok(Event::Eof) | Err(_) => break, + _ => continue, + }; + let attr = |key: &str| { + tag.attributes() + .flatten() + .find(|a| a.key.as_ref() == key) + .and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok().map(|v| v.into_owned())) + }; + match tag.local_name().as_ref() { + "entry" if !empty && group.is_none() => { + project = attr("key").map(|path| JetBrainsRecent { path, ..Default::default() }); + } + "RecentProjectMetaInfo" => { + if let Some(p) = &mut project { + p.hidden = attr("hidden").as_deref() == Some("true"); + } + } + "ProjectGroup" if !empty => group = Some(JetBrainsGroup::default()), + "option" => { + let (name, value) = (attr("name"), attr("value")); + if let Some(g) = &mut group { + match (name.as_deref(), value) { + (Some("name"), Some(v)) => g.name = v, + (Some("expanded"), Some(v)) => g.expanded = v == "true", + // `