дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 05:22:23 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
d3feb056aa | ||
|
|
1e00ea5ee2 | ||
|
|
294198a727 | ||
|
|
82b6980a59 | ||
|
|
81e0e8e2d0 | ||
|
|
87b463990c | ||
|
|
046fd37064 | ||
|
|
cacddee19d | ||
|
|
c8cea62eab | ||
|
|
4a2d5c9599 | ||
|
|
059f25f13e | ||
|
|
a765959d48 | ||
|
|
efbb48c3cb | ||
|
|
bb9486c758 | ||
|
|
5c0c3a009c | ||
|
|
ef667f6e21 | ||
|
|
81b43a52b4 | ||
|
|
0bb730039d | ||
|
|
709e1eb855 | ||
|
|
4473324822 | ||
|
|
5d5b3e4791 | ||
|
|
c5b4b71e30 | ||
|
|
0e299ad936 | ||
|
|
5b8e0b9659 | ||
|
|
3d8a6f07b4 | ||
|
|
99b4f8bdf6 | ||
|
|
86f1f666d7 | ||
|
|
be49490153 | ||
|
|
1f5fcb477d | ||
|
|
1bb454bd2f | ||
|
|
f38f63e397 | ||
|
|
08d87c3903 | ||
|
|
1652866769 | ||
|
|
be5a6f62ad | ||
|
|
f5e8d77dcf | ||
|
|
c3ea376899 | ||
|
|
fde075457b | ||
|
|
135723bca6 | ||
|
|
03a660354c | ||
|
|
1572fc36ea | ||
|
|
4f74f22624 | ||
|
|
1309ce10e4 | ||
|
|
49be259232 | ||
|
|
6a8016b888 | ||
|
|
b8f422d451 | ||
|
|
c868ec8b68 | ||
|
|
059a5193ff | ||
|
|
0f7008391c | ||
|
|
c59f93988b | ||
|
|
76d33f0306 | ||
|
|
cd55bc8f7f | ||
|
|
deec86fab9 | ||
|
|
29e89f2525 | ||
|
|
b1bb4a69cd | ||
|
|
ee99b3641f | ||
|
|
19aee5f262 | ||
|
|
acf6931017 | ||
|
|
555ea8901f | ||
|
|
769c1248d6 | ||
|
|
61ab1851fa | ||
|
|
c6a1a36676 | ||
|
|
6165cb0174 | ||
|
|
79f6caeaa8 | ||
|
|
dbfe66a119 | ||
|
|
a66f01ec87 | ||
|
|
bf06ca7832 | ||
|
|
63a03d1c08 | ||
|
|
4be1b152ef | ||
|
|
fe498c4b64 | ||
|
|
5e3e1f939d | ||
|
|
3591b52034 |
No files matched your search
+1
-2
@@ -13,8 +13,7 @@ dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.vscode
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Per-user IDE state
|
||||
/shelf/
|
||||
/changelists.json
|
||||
Vendored
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
|
||||
}
|
||||
Створено
+73
-26
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -3976,7 +3976,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -3991,7 +3991,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"serde",
|
||||
@@ -4003,7 +4003,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4017,7 +4017,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4034,7 +4034,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
@@ -4054,20 +4054,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"tracing",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4081,7 +4082,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4099,7 +4100,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4121,7 +4122,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4136,7 +4137,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4188,7 +4189,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4211,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4229,7 +4230,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4242,12 +4243,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4260,23 +4262,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"ide-run",
|
||||
"ide-vfs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4284,6 +4288,7 @@ dependencies = [
|
||||
"grep-regex",
|
||||
"grep-searcher",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
"insta",
|
||||
"memchr",
|
||||
@@ -4293,9 +4298,21 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"specta",
|
||||
"spellbook",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4310,7 +4327,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4323,7 +4340,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4335,7 +4352,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4355,7 +4372,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"gix",
|
||||
@@ -4372,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4388,11 +4405,28 @@ dependencies = [
|
||||
"tempfile",
|
||||
"tracing",
|
||||
"trash",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4409,6 +4443,7 @@ dependencies = [
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5816,7 +5851,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -5837,12 +5872,14 @@ dependencies = [
|
||||
"ide-run",
|
||||
"ide-sdk",
|
||||
"ide-search",
|
||||
"ide-spell",
|
||||
"ide-syntax",
|
||||
"ide-terminal",
|
||||
"ide-text",
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"ide-web",
|
||||
"ide-workspace",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
@@ -7701,6 +7738,16 @@ dependencies = [
|
||||
"specta",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spellbook"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d204abcbdf8e88729306a8d0ca01a79d8a49969fe1f84696909d6dbc4321c1a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
|
||||
+3
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.1"
|
||||
version = "0.1.14"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -32,6 +32,8 @@ ide-coverage = { path = "crates/ide-coverage" }
|
||||
ide-profiler = { path = "crates/ide-profiler" }
|
||||
ide-http = { path = "crates/ide-http" }
|
||||
ide-db = { path = "crates/ide-db" }
|
||||
ide-web = { path = "crates/ide-web" }
|
||||
ide-spell = { path = "crates/ide-spell" }
|
||||
|
||||
# serialization & IPC typing
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
+29
-1
@@ -9,13 +9,41 @@
|
||||
The IDE you know, rebuilt in Rust.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Download</b></a>
|
||||
·
|
||||
<a href="#benchmark">Benchmark</a>
|
||||
·
|
||||
<a href="#build">Build</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
|
||||
OpenIDEA brings the IntelliJ IDEA way of working — its keymap, its tool windows,
|
||||
its search-everything habits — to a native app with a Rust core.
|
||||
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages.
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
|
||||
## Benchmark
|
||||
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
|
||||
with warm caches, median of 5 runs:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
|---|---|---|
|
||||
| Window with the project | **0.9 s** | 3.1 s |
|
||||
| Ready (CPU settled) | **1.1 s** | 13.2 s |
|
||||
| Memory (USS, all processes) | **169 MB** | 2011 MB |
|
||||
| CPU time until ready | **2.4 s** | 47.9 s |
|
||||
| Idle CPU | **4 %** of a core | 7 % of a core |
|
||||
| Quit | **0.3 s** | 5.9 s |
|
||||
|
||||
A release build of OpenIDEA from `main` and IDEA with default settings and plugins, on
|
||||
Windows 11, 32-core AMD, 62 GB RAM.
|
||||
IDEA analyses Python more deeply, so "ready" doesn't mean the same work on
|
||||
both sides. Both are measured from the outside, the same way: see
|
||||
[`perf/compare`](perf/compare) to run it on your machine and projects.
|
||||
|
||||
## Build
|
||||
|
||||
|
||||
@@ -79,6 +79,15 @@ user's app-data directory only when the user asks; none of them ships with OpenI
|
||||
unmodified, and its source is available from the repository above.
|
||||
- **Eclipse JDT Language Server** (jdtls): EPL-2.0, from download.eclipse.org.
|
||||
|
||||
## en_US Hunspell dictionary
|
||||
|
||||
`crates/ide-spell/src/dict/en_US.{aff,dic}` (the spell checker's bundled dictionary) is the
|
||||
SCOWL-derived en_US Hunspell dictionary (version 2020.12.07, from the `dictionary-en` npm
|
||||
package 4.0.0), copied unmodified. Copyright Kevin Atkinson and the SCOWL / Hunspell
|
||||
dictionary contributors; MIT- and BSD-style licences, full text in
|
||||
`crates/ide-spell/src/dict/LICENSE-en_US`. It is checked with the
|
||||
[spellbook](https://github.com/helix-editor/spellbook) crate (MPL-2.0).
|
||||
|
||||
## nvim-treesitter queries
|
||||
|
||||
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
|
||||
|
||||
@@ -19,7 +19,7 @@ fn main() {
|
||||
eprintln!("synced in {:?}: {r:?}", started.elapsed());
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let model = ide_build::load(&root, &cache);
|
||||
let model = ide_build::load(&root, &cache, None);
|
||||
println!("{}", serde_json::to_string_pretty(&model).unwrap());
|
||||
eprintln!("loaded in {:?}", started.elapsed());
|
||||
}
|
||||
@@ -225,6 +225,7 @@ fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<
|
||||
}
|
||||
let step = |p: &maven::MavenProject, extra: &[String]| {
|
||||
let mut s = BuildStep::new(&p.command, &["-B", "-Dstyle.color=never"], &subdir(root, &p.dir), Format::Maven);
|
||||
s.args.extend(p.options.iter().cloned());
|
||||
s.args.extend(extra.iter().cloned());
|
||||
s.args.extend(goals.iter().map(|g| (*g).to_owned()));
|
||||
s.env = p.env.clone();
|
||||
@@ -583,6 +584,7 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
|
||||
code: m.code.clone(),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
});
|
||||
}
|
||||
out
|
||||
@@ -671,7 +673,7 @@ mod tests {
|
||||
);
|
||||
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
write(&root, "core/src/main/java/A.java", "class A {}");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"));
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
let p = plan(&root, &model, BuildKind::Build, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Maven);
|
||||
assert_eq!(p.title, "demo");
|
||||
@@ -685,7 +687,7 @@ mod tests {
|
||||
let g = tmp.path().join("g");
|
||||
write(&g, "settings.gradle", "include 'app'");
|
||||
write(&g, "app/build.gradle", "apply plugin: 'java'");
|
||||
let model = crate::load(&g, &tmp.path().join("cache2"));
|
||||
let model = crate::load(&g, &tmp.path().join("cache2"), None);
|
||||
let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java"))).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Gradle);
|
||||
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
|
||||
|
||||
@@ -285,6 +285,74 @@ pub fn script_java_version(text: &str) -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Configurations whose dependencies are libraries (`testFixturesImplementation` ends in one).
|
||||
const DEPENDENCY_CONFIGURATIONS: &[&str] = &[
|
||||
"implementation",
|
||||
"api",
|
||||
"compileOnly",
|
||||
"runtimeOnly",
|
||||
"compileOnlyApi",
|
||||
"annotationProcessor",
|
||||
"kapt",
|
||||
"ksp",
|
||||
"compile",
|
||||
"runtime",
|
||||
"testCompile",
|
||||
"testRuntime",
|
||||
"developmentOnly",
|
||||
];
|
||||
|
||||
fn is_dependency_configuration(name: &str) -> bool {
|
||||
DEPENDENCY_CONFIGURATIONS.iter().any(|c| {
|
||||
name == *c || {
|
||||
let mut cap = c.chars();
|
||||
let first = cap.next().map(|f| f.to_ascii_uppercase()).into_iter();
|
||||
let capitalised: String = first.chain(cap).collect();
|
||||
name.len() > c.len() && name.ends_with(&capitalised)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `(group, artifact, version)` of the external dependencies a build script declares:
|
||||
/// `implementation 'g:a:v'`, `api("g:a:v:classifier@jar")`, and the map notation
|
||||
/// `implementation group: 'g', name: 'a', version: 'v'` (Groovy) / `group = "g", …` (Kotlin).
|
||||
/// Versions with interpolations, ranges and catalog aliases (`libs.x`) are skipped.
|
||||
pub fn script_dependencies(text: &str) -> Vec<(String, String, String)> {
|
||||
let text = strip_comments(text);
|
||||
let mut out = Vec::new();
|
||||
for line in text.lines().flat_map(|l| l.split(['{', ';'])) {
|
||||
let line = line.trim_start();
|
||||
let name: String = line.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
|
||||
if name.is_empty() || !is_dependency_configuration(&name) {
|
||||
continue;
|
||||
}
|
||||
let rest = &line[name.len()..];
|
||||
let lits = literals(rest);
|
||||
let map_value = |key: &str| -> Option<String> {
|
||||
let i = rest.find(key)?;
|
||||
let after = rest[i + key.len()..].trim_start().strip_prefix([':', '='])?;
|
||||
literals(after).into_iter().next()
|
||||
};
|
||||
let coordinate = match (map_value("group"), map_value("name"), map_value("version")) {
|
||||
(Some(g), Some(a), Some(v)) => Some((g, a, v)),
|
||||
_ => lits.first().and_then(|l| {
|
||||
let l = l.split('@').next().unwrap_or(l);
|
||||
let mut parts = l.split(':');
|
||||
Some((parts.next()?.to_owned(), parts.next()?.to_owned(), parts.next()?.to_owned()))
|
||||
}),
|
||||
};
|
||||
if let Some((g, a, v)) = coordinate {
|
||||
let plain = |s: &str| {
|
||||
!s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+'))
|
||||
};
|
||||
if plain(&g) && plain(&a) && plain(&v) && !v.contains('+') {
|
||||
out.push((g, a, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every settings and build script of the model (for change detection).
|
||||
pub fn build_files(root: &Path, model: &GradleModel) -> Vec<PathBuf> {
|
||||
let dir = root.join(&model.dir);
|
||||
@@ -333,6 +401,38 @@ pub fn parse_tasks(output: &str) -> Vec<(String, GradleTask)> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn script_dependencies_read_string_and_map_notations() {
|
||||
let script = r#"
|
||||
plugins { id 'java' }
|
||||
dependencies {
|
||||
implementation 'com.google.guava:guava:33.0.0-jre'
|
||||
api("org.slf4j:slf4j-api:2.0.9")
|
||||
testImplementation "junit:junit:4.13.2@jar"
|
||||
// implementation 'commented:out:1.0'
|
||||
compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.30'
|
||||
runtimeOnly(group = "com.h2database", name = "h2", version = "2.2.224")
|
||||
implementation "org.x:dyn:${ver}"
|
||||
implementation 'org.x:range:1.+'
|
||||
implementation libs.okhttp
|
||||
implementation project(':core')
|
||||
classpath 'not:a:library'
|
||||
}
|
||||
"#;
|
||||
let deps = script_dependencies(script);
|
||||
let names: Vec<String> = deps.iter().map(|(g, a, v)| format!("{g}:{a}:{v}")).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"com.google.guava:guava:33.0.0-jre",
|
||||
"org.slf4j:slf4j-api:2.0.9",
|
||||
"junit:junit:4.13.2",
|
||||
"org.projectlombok:lombok:1.18.30",
|
||||
"com.h2database:h2:2.2.224",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -18,7 +18,7 @@ pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -36,9 +36,10 @@ pub struct BuildModel {
|
||||
}
|
||||
|
||||
/// Static model of the builds under `root`, merged with the sync results cached in `cache_dir`.
|
||||
pub fn load(root: &Path, cache_dir: &Path) -> BuildModel {
|
||||
/// Parent POMs are looked up in `maven_repo` (the configured local repository), else the default one.
|
||||
pub fn load(root: &Path, cache_dir: &Path, maven_repo: Option<PathBuf>) -> BuildModel {
|
||||
let maven = maven::is_maven_project(root).then(|| {
|
||||
let mut m = maven::load(root);
|
||||
let mut m = maven::load_with_repo(root, maven_repo.or_else(maven::default_local_repo));
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
m
|
||||
});
|
||||
@@ -49,6 +50,56 @@ pub fn load(root: &Path, cache_dir: &Path) -> BuildModel {
|
||||
BuildModel { maven, gradle }
|
||||
}
|
||||
|
||||
/// A library the project depends on, as `groupId:artifactId:version`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DependencyCoordinate {
|
||||
/// Gradle builds resolve into the Gradle cache, Maven ones into the local repository.
|
||||
pub gradle: bool,
|
||||
pub group_id: String,
|
||||
pub artifact_id: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// The external libraries of `model`, sorted and deduplicated: Maven dependencies
|
||||
/// (with the transitive ones the last sync read), except the build's own modules,
|
||||
/// `pom` imports and `system` scope; dependencies declared in the Gradle build scripts.
|
||||
pub fn dependency_coordinates(root: &Path, model: &BuildModel) -> Vec<DependencyCoordinate> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(m) = &model.maven {
|
||||
let modules: std::collections::HashSet<String> = m.projects.iter().map(MavenProject::key).collect();
|
||||
let mut stack: Vec<&MavenDependency> = m.projects.iter().flat_map(|p| &p.dependencies).collect();
|
||||
while let Some(d) = stack.pop() {
|
||||
stack.extend(&d.children);
|
||||
let Some(version) = d.version.as_deref().filter(|v| !v.is_empty() && !v.contains("${")) else {
|
||||
continue;
|
||||
};
|
||||
if d.kind == "pom" || matches!(d.scope.as_str(), "import" | "system") {
|
||||
continue;
|
||||
}
|
||||
if modules.contains(&format!("{}:{}", d.group_id, d.artifact_id)) {
|
||||
continue;
|
||||
}
|
||||
out.push(DependencyCoordinate {
|
||||
gradle: false,
|
||||
group_id: d.group_id.clone(),
|
||||
artifact_id: d.artifact_id.clone(),
|
||||
version: version.to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(g) = &model.gradle {
|
||||
for script in g.projects.iter().filter_map(|p| p.build_file.as_ref()) {
|
||||
let Ok(text) = std::fs::read_to_string(root.join(script)) else { continue };
|
||||
out.extend(gradle::script_dependencies(&text).into_iter().map(|(group_id, artifact_id, version)| {
|
||||
DependencyCoordinate { gradle: true, group_id, artifact_id, version }
|
||||
}));
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a created / changed / removed project-relative path can change the build model.
|
||||
pub fn affects_build(rel: &Path) -> bool {
|
||||
let Some(name) = rel.file_name().and_then(|n| n.to_str()) else { return false };
|
||||
@@ -68,13 +119,52 @@ mod tests {
|
||||
let cache = tmp.path().join("cache");
|
||||
let root = tmp.path().join("p");
|
||||
std::fs::create_dir_all(root.join("svc")).unwrap();
|
||||
assert_eq!(load(&root, &cache), BuildModel::default());
|
||||
assert_eq!(load(&root, &cache, None), BuildModel::default());
|
||||
std::fs::write(root.join("svc/pom.xml"), "<project><artifactId>svc</artifactId></project>").unwrap();
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let m = load(&root, &cache);
|
||||
let m = load(&root, &cache, None);
|
||||
assert_eq!(m.maven.unwrap().projects[0].pom, "svc/pom.xml");
|
||||
assert_eq!(m.gradle.unwrap().projects[0].path, ":");
|
||||
assert!(affects_build(Path::new("a/pom.xml")) && affects_build(Path::new("settings.gradle.kts")));
|
||||
assert!(!affects_build(Path::new("src/Main.java")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dependency_coordinates_flatten_maven_trees_and_read_gradle_scripts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::write(root.join("build.gradle"), "dependencies { implementation 'org.a:x:1.0' }\n").unwrap();
|
||||
let dep = |g: &str, a: &str, v: Option<&str>, children: Vec<MavenDependency>| MavenDependency {
|
||||
group_id: g.into(),
|
||||
artifact_id: a.into(),
|
||||
version: v.map(Into::into),
|
||||
kind: "jar".into(),
|
||||
scope: "compile".into(),
|
||||
children,
|
||||
..Default::default()
|
||||
};
|
||||
let maven = MavenModel {
|
||||
projects: vec![
|
||||
MavenProject {
|
||||
group_id: "me".into(),
|
||||
artifact_id: "app".into(),
|
||||
dependencies: vec![
|
||||
dep("me", "core", Some("1"), vec![]),
|
||||
dep("org.b", "y", Some("2"), vec![dep("org.c", "z", Some("3"), vec![])]),
|
||||
dep("org.d", "unresolved", Some("${v}"), vec![]),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
MavenProject { group_id: "me".into(), artifact_id: "core".into(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let gradle = gradle::load(root);
|
||||
let model = BuildModel { maven: Some(maven), gradle };
|
||||
let names: Vec<String> = dependency_coordinates(root, &model)
|
||||
.into_iter()
|
||||
.map(|c| format!("{}{}:{}:{}", if c.gradle { "G " } else { "M " }, c.group_id, c.artifact_id, c.version))
|
||||
.collect();
|
||||
assert_eq!(names, ["M org.b:y:2", "M org.c:z:3", "G org.a:x:1.0"]);
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,8 @@ pub struct MavenProject {
|
||||
pub java_version: Option<u32>,
|
||||
/// Maven launcher: the nearest `mvnw` up to the project root (absolute), else `mvn`.
|
||||
pub command: String,
|
||||
/// Options before the goals (`-s`, `-Dmaven.repo.local=`); filled in by the shell from settings.
|
||||
pub options: Vec<String>,
|
||||
/// Environment for runs (`JAVA_HOME` of the matching JDK); filled in by the shell.
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
@@ -410,7 +412,7 @@ struct Resolver {
|
||||
}
|
||||
|
||||
/// `~/.m2/repository`, or `<localRepository>` from `~/.m2/settings.xml`.
|
||||
fn default_local_repo() -> Option<PathBuf> {
|
||||
pub(crate) fn default_local_repo() -> Option<PathBuf> {
|
||||
let m2 = dirs::home_dir()?.join(".m2");
|
||||
if let Some(settings) = std::fs::read_to_string(m2.join("settings.xml")).ok().and_then(|t| xml::parse(&t))
|
||||
&& let Some(repo) = settings.text_of("localRepository")
|
||||
@@ -924,6 +926,7 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
|
||||
profiles: pom.profiles.iter().map(|p| p.id.clone()).collect(),
|
||||
java_version: jv,
|
||||
command: wrapper(root, &dir),
|
||||
options: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
});
|
||||
for m in modules.into_iter().rev() {
|
||||
|
||||
@@ -52,12 +52,7 @@ pub(crate) fn run(
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.process_group(0);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
ide_core::process::no_window(&mut command);
|
||||
let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {program}: {e}")))?;
|
||||
let (tx, rx) = mpsc::channel::<(Stream, String)>();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
|
||||
|
||||
@@ -29,6 +29,10 @@ pub struct SyncOptions {
|
||||
pub profiles: Vec<String>,
|
||||
/// Extra environment (`JAVA_HOME`).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
|
||||
pub maven_command: Option<String>,
|
||||
/// Maven options before the goals (`-s`, `-Dmaven.repo.local=`).
|
||||
pub maven_options: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -184,6 +188,7 @@ pub fn sync_maven(
|
||||
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
|
||||
let _ = std::fs::remove_file(&effective);
|
||||
let mut args: Vec<String> = vec!["-B".into(), "-fae".into(), "-Dstyle.color=never".into()];
|
||||
args.extend(options.maven_options.iter().cloned());
|
||||
if options.offline {
|
||||
args.push("-o".into());
|
||||
}
|
||||
@@ -194,7 +199,8 @@ pub fn sync_maven(
|
||||
args.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
args.push("dependency:tree".into());
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let out = run(&top.command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
if let Some((name, i, total)) = maven_building(line) {
|
||||
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
|
||||
progress(SyncProgress { message: format!("Building model of {name}"), fraction: Some(fraction) });
|
||||
|
||||
@@ -39,7 +39,7 @@ impl Default for EditorGeneralSettings {
|
||||
caret_scroll: "minimize".into(),
|
||||
soft_wrap_files: "*.md; *.txt; *.rst; *.adoc".into(),
|
||||
soft_wrap_indent: true,
|
||||
scroll_past_end: true,
|
||||
scroll_past_end: false,
|
||||
strip_trailing_scope: "modified".into(),
|
||||
keep_trailing_on_caret_line: true,
|
||||
remove_trailing_blank_lines: false,
|
||||
@@ -102,7 +102,7 @@ pub struct BreadcrumbsSettings {
|
||||
|
||||
impl Default for BreadcrumbsSettings {
|
||||
fn default() -> Self {
|
||||
Self { show: false, placement: "bottom".into(), disabled_languages: Vec::new() }
|
||||
Self { show: true, placement: "bottom".into(), disabled_languages: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +117,12 @@ pub struct CompletionSettings {
|
||||
pub auto_popup: bool,
|
||||
/// Insert the selected suggestion by pressing space, dot, or other context-dependent keys.
|
||||
pub insert_on_special_keys: bool,
|
||||
/// Insert a sole suggestion of explicit (⌃Space) completion right away.
|
||||
pub auto_insert_single: bool,
|
||||
/// Sort suggestions by name instead of relevance.
|
||||
pub sort_alphabetically: bool,
|
||||
/// Add `()` after function and method suggestions.
|
||||
pub insert_parentheses: bool,
|
||||
pub show_documentation: bool,
|
||||
pub documentation_delay: u32,
|
||||
pub parameter_info: bool,
|
||||
@@ -130,10 +136,13 @@ impl Default for CompletionSettings {
|
||||
case_sensitivity: "first".into(),
|
||||
auto_popup: true,
|
||||
insert_on_special_keys: false,
|
||||
show_documentation: true,
|
||||
auto_insert_single: true,
|
||||
sort_alphabetically: false,
|
||||
insert_parentheses: true,
|
||||
show_documentation: false,
|
||||
documentation_delay: 500,
|
||||
parameter_info: true,
|
||||
parameter_info_delay: 300,
|
||||
parameter_info_delay: 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,13 +175,22 @@ impl Default for FoldingSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct EditorTabsSettings {
|
||||
/// `top` | `none`.
|
||||
/// `top` | `bottom` | `none`.
|
||||
pub placement: String,
|
||||
pub multiple_rows: bool,
|
||||
/// One row that doesn't fit: `scroll` the tabs panel | `squeeze` the tabs.
|
||||
pub one_row_overflow: String,
|
||||
pub pinned_separate_row: bool,
|
||||
pub show_file_icon: bool,
|
||||
pub show_extension: bool,
|
||||
pub show_directory_for_non_unique: bool,
|
||||
/// Mark modified tabs with an asterisk.
|
||||
pub mark_modified: bool,
|
||||
pub show_full_path_on_hover: bool,
|
||||
pub show_close_button: bool,
|
||||
/// `right` | `left` (with `show_close_button`).
|
||||
pub close_button_position: String,
|
||||
pub sort_alphabetically: bool,
|
||||
pub preview_tab: bool,
|
||||
pub open_at_end: bool,
|
||||
pub tab_limit: u32,
|
||||
@@ -187,14 +205,21 @@ impl Default for EditorTabsSettings {
|
||||
Self {
|
||||
placement: "top".into(),
|
||||
multiple_rows: false,
|
||||
one_row_overflow: "scroll".into(),
|
||||
pinned_separate_row: false,
|
||||
show_file_icon: true,
|
||||
show_extension: true,
|
||||
show_directory_for_non_unique: true,
|
||||
mark_modified: false,
|
||||
show_full_path_on_hover: true,
|
||||
show_close_button: true,
|
||||
close_button_position: "right".into(),
|
||||
sort_alphabetically: false,
|
||||
preview_tab: true,
|
||||
open_at_end: false,
|
||||
tab_limit: 10,
|
||||
closing_policy: "unchanged".into(),
|
||||
activate_on_close: "mru".into(),
|
||||
tab_limit: 30,
|
||||
closing_policy: "lru".into(),
|
||||
activate_on_close: "left".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,7 +239,7 @@ pub struct SmartKeysSettings {
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
pub reformat_on_paste: String,
|
||||
pub smart_indent: bool,
|
||||
/// Backspace › Unindent: `nearest` indent position | `none`.
|
||||
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
|
||||
pub backspace_unindent: String,
|
||||
}
|
||||
|
||||
@@ -226,10 +251,10 @@ impl Default for SmartKeysSettings {
|
||||
pair_brackets: true,
|
||||
pair_quotes: true,
|
||||
surround_selection: true,
|
||||
tab_out_of_pair: false,
|
||||
reformat_on_paste: "indentBlock".into(),
|
||||
tab_out_of_pair: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
smart_indent: true,
|
||||
backspace_unindent: "nearest".into(),
|
||||
backspace_unindent: "autoindent".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -275,11 +300,38 @@ pub struct InlayHintsSettings {
|
||||
pub disabled_languages: Vec<String>,
|
||||
/// Code vision: usages above declarations.
|
||||
pub code_vision_usages: bool,
|
||||
/// Code vision: last author of a declaration (VCS blame) beside its usages.
|
||||
pub code_vision_author: bool,
|
||||
}
|
||||
|
||||
impl Default for InlayHintsSettings {
|
||||
fn default() -> Self {
|
||||
Self { types: true, parameters: true, other: true, disabled_languages: Vec::new(), code_vision_usages: true }
|
||||
Self {
|
||||
types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
disabled_languages: Vec::new(),
|
||||
code_vision_usages: true,
|
||||
code_vision_author: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Editor › General › Inline Completion: ghost text from language servers that
|
||||
/// support `textDocument/inlineCompletion` (LSP 3.18).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct InlineCompletionSettings {
|
||||
pub enabled: bool,
|
||||
/// Ask only once typing has paused for `pause_ms`, instead of right after each change.
|
||||
pub only_on_pause: bool,
|
||||
pub pause_ms: u32,
|
||||
pub disabled_languages: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for InlineCompletionSettings {
|
||||
fn default() -> Self {
|
||||
Self { enabled: true, only_on_pause: false, pause_ms: 500, disabled_languages: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,6 +366,12 @@ pub struct LanguageCodeStyle {
|
||||
pub indent: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub hard_wrap_at: Option<u32>,
|
||||
/// Comment Code › Line comment at first column.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub line_comment_at_first_column: Option<bool>,
|
||||
/// Comment Code › Add a space at line comment start.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub line_comment_add_space: Option<bool>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -329,6 +387,14 @@ pub struct CodeStyleSettings {
|
||||
/// Enable EditorConfig support.
|
||||
pub editorconfig: bool,
|
||||
pub languages: BTreeMap<String, LanguageCodeStyle>,
|
||||
/// Formatter › Do not format: globs (`*.min.js`, `generated/**`) Reformat Code skips.
|
||||
pub do_not_format: Vec<String>,
|
||||
/// Formatter › Turn formatter on/off with markers in code comments.
|
||||
pub formatter_tags_enabled: bool,
|
||||
pub formatter_off_tag: String,
|
||||
pub formatter_on_tag: String,
|
||||
/// The markers are regular expressions.
|
||||
pub formatter_tags_regexp: bool,
|
||||
}
|
||||
|
||||
impl Default for CodeStyleSettings {
|
||||
@@ -340,6 +406,11 @@ impl Default for CodeStyleSettings {
|
||||
detect_indents: true,
|
||||
editorconfig: true,
|
||||
languages: BTreeMap::new(),
|
||||
do_not_format: Vec::new(),
|
||||
formatter_tags_enabled: false,
|
||||
formatter_off_tag: "@formatter:off".into(),
|
||||
formatter_on_tag: "@formatter:on".into(),
|
||||
formatter_tags_regexp: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,11 @@ pub enum IdeEvent {
|
||||
doc: DocId,
|
||||
dirty: bool,
|
||||
},
|
||||
/// An open document's language changed (Settings › File Types, Override File Type).
|
||||
DocLanguage {
|
||||
doc: DocId,
|
||||
language: crate::LanguageId,
|
||||
},
|
||||
/// Full replacement of diagnostics for one file from one producer.
|
||||
Diagnostics {
|
||||
path: crate::IpcPath,
|
||||
@@ -106,6 +111,9 @@ pub enum ServerStatus {
|
||||
Crashed,
|
||||
Stopped,
|
||||
Missing,
|
||||
/// Not started: its configuration can't launch it (e.g. no JDK new enough);
|
||||
/// the message says what to change, and a settings change retries.
|
||||
Misconfigured,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! "Ignored Files and Folders" (IDEA: Settings › File Types): file names the IDE
|
||||
//! treats as nonexistent — hidden from the project view and navigation, never
|
||||
//! indexed or searched, never offered as unversioned changes.
|
||||
|
||||
/// IDEA's default list, plus `.jj` and the Windows shell files.
|
||||
pub const DEFAULT_IGNORED_NAMES: &[&str] = &[
|
||||
"*.pyc",
|
||||
"*.pyo",
|
||||
"*.rbc",
|
||||
"*.yarb",
|
||||
"*~",
|
||||
".DS_Store",
|
||||
".git",
|
||||
".hg",
|
||||
".jj",
|
||||
".svn",
|
||||
"CVS",
|
||||
"__pycache__",
|
||||
"_svn",
|
||||
"vssver.scc",
|
||||
"vssver2.scc",
|
||||
"Thumbs.db",
|
||||
"desktop.ini",
|
||||
];
|
||||
|
||||
/// Matches single path segments against name patterns (`*` and `?` wildcards).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct IgnoredNames {
|
||||
exact: Vec<String>,
|
||||
wildcards: Vec<String>,
|
||||
}
|
||||
|
||||
impl IgnoredNames {
|
||||
pub fn new(patterns: &[String]) -> Self {
|
||||
let mut out = Self::default();
|
||||
for p in patterns.iter().map(|p| p.trim()).filter(|p| !p.is_empty() && !p.contains('/')) {
|
||||
if p.contains(['*', '?']) {
|
||||
out.wildcards.push(p.to_owned());
|
||||
} else {
|
||||
out.exact.push(p.to_owned());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn is_ignored_name(&self, name: &str) -> bool {
|
||||
self.exact.iter().any(|e| e == name) || self.wildcards.iter().any(|w| wildcard(w.as_bytes(), name.as_bytes()))
|
||||
}
|
||||
|
||||
/// Whether any segment of a `/`-separated relative path is ignored.
|
||||
pub fn is_ignored_path(&self, rel: &str) -> bool {
|
||||
rel.split('/').any(|seg| !seg.is_empty() && self.is_ignored_name(seg))
|
||||
}
|
||||
}
|
||||
|
||||
fn wildcard(p: &[u8], s: &[u8]) -> bool {
|
||||
let (mut pi, mut si, mut star, mut mark) = (0, 0, None, 0);
|
||||
while si < s.len() {
|
||||
if pi < p.len() && (p[pi] == b'?' || p[pi] == s[si]) {
|
||||
pi += 1;
|
||||
si += 1;
|
||||
} else if pi < p.len() && p[pi] == b'*' {
|
||||
star = Some(pi);
|
||||
pi += 1;
|
||||
mark = si;
|
||||
} else if let Some(st) = star {
|
||||
pi = st + 1;
|
||||
mark += 1;
|
||||
si = mark;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
p[pi..].iter().all(|&c| c == b'*')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn defaults() -> IgnoredNames {
|
||||
IgnoredNames::new(&DEFAULT_IGNORED_NAMES.iter().map(|s| s.to_string()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_names_and_wildcards() {
|
||||
let m = defaults();
|
||||
for name in [".DS_Store", "__pycache__", "a.pyc", "notes.txt~", "Thumbs.db"] {
|
||||
assert!(m.is_ignored_name(name), "{name}");
|
||||
}
|
||||
for name in ["DS_Store", "a.py", "pyc", "src", ".gitignore"] {
|
||||
assert!(!m.is_ignored_name(name), "{name}");
|
||||
}
|
||||
assert!(wildcard(b"a?c*", b"abcdef"));
|
||||
assert!(!wildcard(b"a?c", b"abcd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_any_path_segment() {
|
||||
let m = defaults();
|
||||
assert!(m.is_ignored_path("src/.DS_Store"));
|
||||
assert!(m.is_ignored_path("pkg/__pycache__/"));
|
||||
assert!(m.is_ignored_path("pkg/__pycache__/mod.cpython-312.pyc"));
|
||||
assert!(!m.is_ignored_path("src/main.rs"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Settings › Editor › Inspections: inspection profiles. `Default` and the
|
||||
//! user's IDE-level copies live in the IDE (global) settings, `Project Default`
|
||||
//! and project-level copies in the project's; the project picks which one is in
|
||||
//! effect. The UI applies the profile to diagnostics. Also Editor › Natural
|
||||
//! Languages › Spelling (the Typo inspection's dictionaries).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct InspectionSettings {
|
||||
/// Profile in effect for the project: `default`, `project`, or a copy
|
||||
/// as `ide:<key>` / `project:<key>`.
|
||||
pub profile: String,
|
||||
/// The `Default` profile (IDE level): inspection id → override.
|
||||
pub default: BTreeMap<String, InspectionOverride>,
|
||||
/// The `Project Default` profile (stored with the project).
|
||||
pub project: BTreeMap<String, InspectionOverride>,
|
||||
/// Profiles copied at IDE level (global settings), by key.
|
||||
pub ide_profiles: BTreeMap<String, CustomInspectionProfile>,
|
||||
/// Profiles copied at project level (project settings), by key.
|
||||
pub project_profiles: BTreeMap<String, CustomInspectionProfile>,
|
||||
}
|
||||
|
||||
impl Default for InspectionSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
profile: "default".into(),
|
||||
default: BTreeMap::new(),
|
||||
project: BTreeMap::new(),
|
||||
ide_profiles: BTreeMap::new(),
|
||||
project_profiles: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A named profile made with Copy.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CustomInspectionProfile {
|
||||
pub name: String,
|
||||
pub overrides: BTreeMap<String, InspectionOverride>,
|
||||
}
|
||||
|
||||
/// Editor › Natural Languages › Spelling.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SpellingSettings {
|
||||
/// Application-level dictionary: accepted words (IDE settings).
|
||||
pub ide_words: Vec<String>,
|
||||
/// Project-level dictionary: accepted words (project settings).
|
||||
pub project_words: Vec<String>,
|
||||
/// Custom dictionaries: plain word lists or Hunspell `.dic` files.
|
||||
pub custom_dictionaries: Vec<String>,
|
||||
}
|
||||
|
||||
/// Changes to one inspection; absent fields keep the inspection's defaults.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct InspectionOverride {
|
||||
#[specta(optional)]
|
||||
pub enabled: Option<bool>,
|
||||
#[specta(optional)]
|
||||
pub severity: Option<InspectionLevel>,
|
||||
}
|
||||
|
||||
/// IDEA's highlighting levels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum InspectionLevel {
|
||||
Error,
|
||||
Warning,
|
||||
WeakWarning,
|
||||
ServerProblem,
|
||||
Typo,
|
||||
/// Reported (Problems, Inspect Code) but not highlighted in the editor.
|
||||
None,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn overrides_parse_partially() {
|
||||
let s: InspectionSettings = serde_json::from_str(
|
||||
r#"{"default":{"lsp:ruff":{"enabled":false},"lsp:ruff:F401":{"severity":"weakWarning"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(s.profile, "default");
|
||||
assert_eq!(s.default["lsp:ruff"].enabled, Some(false));
|
||||
assert_eq!(s.default["lsp:ruff:F401"].severity, Some(InspectionLevel::WeakWarning));
|
||||
assert!(s.project.is_empty());
|
||||
assert!(s.ide_profiles.is_empty());
|
||||
let s: InspectionSettings = serde_json::from_str(
|
||||
r#"{"profile":"ide:strict","ideProfiles":{"strict":{"name":"Strict","overrides":{"lsp:ruff":{"severity":"error"}}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(s.ide_profiles["strict"].name, "Strict");
|
||||
assert_eq!(s.ide_profiles["strict"].overrides["lsp:ruff"].severity, Some(InspectionLevel::Error));
|
||||
assert!(serde_json::from_str::<InspectionSettings>(r#"{"default":{"x":{"severity":"loud"}}}"#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,10 @@ pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
pub mod ids;
|
||||
pub mod ignored;
|
||||
pub mod inspection_settings;
|
||||
pub mod ipc_path;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
pub mod settings;
|
||||
pub mod text;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Child-process helpers shared by every crate that spawns tools.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
|
||||
/// with other flags. Prefer [`no_window`] otherwise.
|
||||
pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
|
||||
/// Keeps a console child (java, node, curl, a language server, ...) from
|
||||
/// opening its own console window on Windows. Release builds use the GUI
|
||||
/// subsystem, so without this every spawn flashes a `cmd` window. A no-op
|
||||
/// elsewhere. For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
|
||||
pub fn no_window(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub use crate::editor_settings::*;
|
||||
pub use crate::inspection_settings::*;
|
||||
pub use crate::workflow_settings::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -37,6 +38,27 @@ pub struct Settings {
|
||||
pub terminal: TerminalSettings,
|
||||
pub actions_on_save: ActionsOnSaveSettings,
|
||||
pub external_tools: Vec<ExternalTool>,
|
||||
/// Language servers / debug adapters at a user-chosen location, by the
|
||||
/// command the language definition launches (`elixir-ls`, `codelldb`).
|
||||
pub tools: BTreeMap<String, ToolSettings>,
|
||||
/// Editor › Inspections profiles.
|
||||
pub inspections: InspectionSettings,
|
||||
/// Editor › Natural Languages › Spelling.
|
||||
pub spelling: SpellingSettings,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolSettings {
|
||||
/// Executable to launch instead of the managed / `PATH` one; empty = auto-detect.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// The configured executable for `command`, if any (`~/` not yet expanded).
|
||||
pub fn tool_path(&self, command: &str) -> Option<&str> {
|
||||
self.tools.get(command).map(|t| t.path.trim()).filter(|p| !p.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -59,6 +81,9 @@ impl Default for Settings {
|
||||
terminal: TerminalSettings::default(),
|
||||
actions_on_save: ActionsOnSaveSettings::default(),
|
||||
external_tools: Vec::new(),
|
||||
tools: BTreeMap::new(),
|
||||
inspections: InspectionSettings::default(),
|
||||
spelling: SpellingSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,6 +116,11 @@ pub struct GeneralSettings {
|
||||
pub save_on_idle: bool,
|
||||
pub idle_seconds: u32,
|
||||
pub date_format: DateFormatSettings,
|
||||
/// File › Power Save Mode: no automatic popups (completion, parameter info,
|
||||
/// quick documentation) or background highlighting (usages, code vision).
|
||||
pub power_save_mode: bool,
|
||||
/// File › Rename Project… (project layer): the name shown for the project; empty = its folder name.
|
||||
pub project_name: String,
|
||||
}
|
||||
|
||||
impl Default for GeneralSettings {
|
||||
@@ -103,6 +133,8 @@ impl Default for GeneralSettings {
|
||||
save_on_idle: false,
|
||||
idle_seconds: 15,
|
||||
date_format: DateFormatSettings::default(),
|
||||
power_save_mode: false,
|
||||
project_name: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,6 +224,20 @@ pub struct AppearanceSettings {
|
||||
/// Status bar widgets shown (`true`) or hidden (`false`) by the user
|
||||
/// (status bar context menu); widgets not listed use their default.
|
||||
pub status_bar_widgets: BTreeMap<String, bool>,
|
||||
/// Customize Main Toolbar; `None` = the default toolbar.
|
||||
pub main_toolbar: Option<MainToolbarSettings>,
|
||||
}
|
||||
|
||||
/// Main toolbar entries per side, in order: title widget ids (`project`,
|
||||
/// `vcs.branch`…) or `action:<id>`. Widgets in neither list nor `hidden`
|
||||
/// (registered later) keep their default place.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MainToolbarSettings {
|
||||
pub left: Vec<String>,
|
||||
pub right: Vec<String>,
|
||||
/// Widgets the user removed.
|
||||
pub hidden: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for AppearanceSettings {
|
||||
@@ -221,6 +267,7 @@ impl Default for AppearanceSettings {
|
||||
show_tool_window_names: true,
|
||||
widescreen_tool_windows: false,
|
||||
status_bar_widgets: BTreeMap::new(),
|
||||
main_toolbar: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -255,6 +302,7 @@ pub struct EditorSettings {
|
||||
pub smart_keys: SmartKeysSettings,
|
||||
pub code_editing: CodeEditingSettings,
|
||||
pub inlay: InlayHintsSettings,
|
||||
pub inline_completion: InlineCompletionSettings,
|
||||
/// Gutter icon groups turned off (`run`, `breakpoints`, `bookmarks`, `vcs`, `blame`).
|
||||
pub gutter_icons_disabled: Vec<String>,
|
||||
pub show_gutter_icons: bool,
|
||||
@@ -289,6 +337,7 @@ impl Default for EditorSettings {
|
||||
smart_keys: SmartKeysSettings::default(),
|
||||
code_editing: CodeEditingSettings::default(),
|
||||
inlay: InlayHintsSettings::default(),
|
||||
inline_completion: InlineCompletionSettings::default(),
|
||||
gutter_icons_disabled: Vec::new(),
|
||||
show_gutter_icons: true,
|
||||
code_style: CodeStyleSettings::default(),
|
||||
@@ -303,12 +352,30 @@ pub struct FileSettings {
|
||||
/// Save on focus loss / tab switch, like IDEA.
|
||||
pub auto_save: bool,
|
||||
pub exclude: Vec<String>,
|
||||
/// Ignored Files and Folders: name patterns hidden everywhere; see [`crate::ignored`].
|
||||
pub ignored_names: Vec<String>,
|
||||
pub trim_trailing_whitespace: bool,
|
||||
pub ensure_final_newline: bool,
|
||||
/// Local History keeps changes from this many working days (days with changes), like IDEA.
|
||||
pub local_history_days: u32,
|
||||
/// Upper bound for a project's Local History in MB; the oldest revisions go first.
|
||||
pub local_history_max_mb: u32,
|
||||
/// File Types › Recognized File Types: the user's changes, by language id.
|
||||
pub file_types: BTreeMap<String, FileTypeAssociation>,
|
||||
/// Override File Type: file (project-relative and `/`-separated, or absolute) → language id.
|
||||
pub file_type_overrides: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// One language's file name and hashbang patterns on top of its definition.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FileTypeAssociation {
|
||||
/// Added file name patterns: `*.foo`, `Jenkinsfile`, `Dockerfile.*` (`*` and `?` wildcards).
|
||||
pub patterns: Vec<String>,
|
||||
/// Patterns of the definition (`*.ext`, file names) the user removed.
|
||||
pub removed_patterns: Vec<String>,
|
||||
/// Interpreters run by a `#!` first line, e.g. `node` for `#!/usr/bin/env node`.
|
||||
pub hashbangs: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for FileSettings {
|
||||
@@ -316,10 +383,13 @@ impl Default for FileSettings {
|
||||
Self {
|
||||
auto_save: true,
|
||||
exclude: vec!["**/.git".into(), "**/node_modules".into(), "**/target".into()],
|
||||
ignored_names: crate::ignored::DEFAULT_IGNORED_NAMES.iter().map(|s| (*s).into()).collect(),
|
||||
trim_trailing_whitespace: true,
|
||||
ensure_final_newline: true,
|
||||
local_history_days: 5,
|
||||
local_history_max_mb: 512,
|
||||
file_types: BTreeMap::new(),
|
||||
file_type_overrides: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -332,6 +402,7 @@ pub struct LanguagesSettings {
|
||||
pub rust: RustSettings,
|
||||
pub go: GoSettings,
|
||||
pub typescript: TypeScriptSettings,
|
||||
pub java: JavaSettings,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -394,6 +465,35 @@ pub struct GoSettings {
|
||||
pub gopath: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct JavaSettings {
|
||||
/// Project JDK home; empty = per module, the installed JDK matching the
|
||||
/// Java version it targets.
|
||||
pub jdk: String,
|
||||
/// JDK home the Java language server (jdtls) runs on, apart from the project
|
||||
/// JDK (IDEA's "JDK for importer"); empty = the project JDK when new enough,
|
||||
/// else the first installed one that is.
|
||||
pub jdtls_jdk: String,
|
||||
/// Extra JVM options for the Java language server (jdtls), space-separated
|
||||
/// (VS Code's `java.jdt.ls.vmargs`).
|
||||
pub jdtls_vm_args: String,
|
||||
/// Build Tools › Maven.
|
||||
pub maven: MavenSettings,
|
||||
}
|
||||
|
||||
/// Build Tools › Maven.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MavenSettings {
|
||||
/// Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`.
|
||||
pub home: String,
|
||||
/// User `settings.xml` (`-s`); empty = `~/.m2/settings.xml`.
|
||||
pub user_settings: String,
|
||||
/// Local repository (`-Dmaven.repo.local`); empty = from `settings.xml`.
|
||||
pub local_repository: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct TypeScriptSettings {
|
||||
@@ -420,12 +520,23 @@ pub struct ProjectStructureSettings {
|
||||
pub excluded: Vec<String>,
|
||||
/// Auto-detected roots (from `pom.xml`, `build.gradle`, `Cargo.toml`, …) the user unmarked.
|
||||
pub unmarked: Vec<String>,
|
||||
/// Content roots besides the project folder (absolute paths), shown and searched with it.
|
||||
pub content_roots: Vec<String>,
|
||||
/// "Exclude files": `;`-separated name patterns (`*.log;tmp*`) excluded at any depth.
|
||||
pub exclude_files: String,
|
||||
}
|
||||
|
||||
impl ProjectStructureSettings {
|
||||
/// The "Exclude files" name patterns.
|
||||
pub fn exclude_file_patterns(&self) -> Vec<String> {
|
||||
self.exclude_files.split(';').map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// `files.exclude` plus the Project Structure excluded folders as globs.
|
||||
/// `files.exclude`, the ignored names and the Project Structure excluded folders as globs.
|
||||
pub fn exclude_globs(&self) -> Vec<String> {
|
||||
let mut out = self.files.exclude.clone();
|
||||
let mut out = self.file_excludes();
|
||||
for dir in &self.project_structure.excluded {
|
||||
let dir = dir.trim().trim_matches('/');
|
||||
if !dir.is_empty() {
|
||||
@@ -434,6 +545,19 @@ impl Settings {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `files.exclude`, `files.ignoredNames` and the Project Structure "Exclude files"
|
||||
/// patterns (a bare name matches at any depth).
|
||||
pub fn file_excludes(&self) -> Vec<String> {
|
||||
let mut out = self.files.exclude.clone();
|
||||
out.extend(self.files.ignored_names.iter().filter(|n| !n.trim().is_empty()).cloned());
|
||||
out.extend(self.project_structure.exclude_file_patterns().into_iter().filter(|p| !p.contains('/')));
|
||||
out
|
||||
}
|
||||
|
||||
pub fn ignored_names(&self) -> crate::ignored::IgnoredNames {
|
||||
crate::ignored::IgnoredNames::new(&self.files.ignored_names)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -462,4 +586,15 @@ mod tests {
|
||||
assert!(k.overrides["file.save"].is_empty());
|
||||
assert_eq!(serde_json::to_value(Settings::default()).unwrap()["customKeymaps"], serde_json::json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclude_files_patterns_join_the_file_excludes() {
|
||||
let s: Settings = serde_json::from_str(
|
||||
r#"{"files":{"exclude":[],"ignoredNames":[]},"projectStructure":{"excludeFiles":" *.log ; tmp*;;"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(s.project_structure.exclude_file_patterns(), vec!["*.log", "tmp*"]);
|
||||
assert_eq!(s.file_excludes(), vec!["*.log", "tmp*"]);
|
||||
assert!(Settings::default().files.file_types.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,11 @@ pub struct Diagnostic {
|
||||
pub unnecessary: bool,
|
||||
#[serde(default)]
|
||||
pub deprecated: bool,
|
||||
/// Language server (or tool) that reported it, e.g. `basedpyright`; `source`
|
||||
/// is what the producer calls itself. Inspection profiles key on this.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub server: Option<String>,
|
||||
}
|
||||
|
||||
/// Symbol kinds, a stable subset of LSP `SymbolKind`.
|
||||
@@ -168,6 +173,17 @@ impl SymbolKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// Declared (or conventional) visibility of an outline symbol.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Visibility {
|
||||
Public,
|
||||
Protected,
|
||||
/// Package / module / assembly scope (Java default, `internal`, `pub(crate)`, Go unexported).
|
||||
Package,
|
||||
Private,
|
||||
}
|
||||
|
||||
/// A node of a document outline (Structure tool window, breadcrumbs).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct OutlineItem {
|
||||
@@ -179,6 +195,10 @@ pub struct OutlineItem {
|
||||
/// The identifier itself; where navigation lands.
|
||||
pub selection_range: Range,
|
||||
pub children: Vec<OutlineItem>,
|
||||
/// Unknown (`None`) for language-server symbols and languages without the notion.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub visibility: Option<Visibility>,
|
||||
}
|
||||
|
||||
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
|
||||
|
||||
@@ -24,7 +24,8 @@ pub struct VcsSettings {
|
||||
impl Default for VcsSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
show_dirty_directories: true,
|
||||
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
|
||||
show_dirty_directories: false,
|
||||
limit_history: true,
|
||||
history_limit: 1000,
|
||||
git: GitSettings::default(),
|
||||
@@ -211,6 +212,8 @@ impl Default for PythonDebuggerSettings {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct RunSettings {
|
||||
pub confirm_rerun: bool,
|
||||
/// Ask before closing a Run tab whose process is still running.
|
||||
pub confirm_terminate: bool,
|
||||
pub show_on_start: bool,
|
||||
/// Grace period between interrupt and kill when stopping a process.
|
||||
pub termination_timeout_ms: u32,
|
||||
@@ -218,7 +221,7 @@ pub struct RunSettings {
|
||||
|
||||
impl Default for RunSettings {
|
||||
fn default() -> Self {
|
||||
Self { confirm_rerun: true, show_on_start: true, termination_timeout_ms: 3000 }
|
||||
Self { confirm_rerun: true, confirm_terminate: true, show_on_start: true, termination_timeout_ms: 3000 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,6 +244,8 @@ pub struct TerminalSettings {
|
||||
pub shell_integration: bool,
|
||||
pub highlight_hyperlinks: bool,
|
||||
pub option_as_meta: bool,
|
||||
/// Escape moves focus to the editor instead of reaching the shell.
|
||||
pub escape_to_editor: bool,
|
||||
/// `block` | `underline` | `bar`.
|
||||
pub cursor_shape: String,
|
||||
pub cursor_blink: bool,
|
||||
@@ -249,6 +254,10 @@ pub struct TerminalSettings {
|
||||
pub font_size: f32,
|
||||
/// Multiple of the cell height.
|
||||
pub line_height: f32,
|
||||
/// Font tried for glyphs the main font lacks; empty = none.
|
||||
pub fallback_font_family: String,
|
||||
/// Multiple of the cell width.
|
||||
pub column_width: f32,
|
||||
}
|
||||
|
||||
impl Default for TerminalSettings {
|
||||
@@ -267,12 +276,15 @@ impl Default for TerminalSettings {
|
||||
shell_integration: true,
|
||||
highlight_hyperlinks: true,
|
||||
option_as_meta: false,
|
||||
escape_to_editor: false,
|
||||
cursor_shape: "block".into(),
|
||||
cursor_blink: true,
|
||||
use_editor_font: true,
|
||||
font_family: "JetBrains Mono".into(),
|
||||
font_size: 13.0,
|
||||
line_height: 1.0,
|
||||
fallback_font_family: String::new(),
|
||||
column_width: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
//! "Import a report collected in CI from disk": the format is sniffed from the
|
||||
//! content (lcov, Go cover profile, JaCoCo XML) and paths recorded on another
|
||||
//! machine are mapped into the project by their longest existing suffix.
|
||||
|
||||
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Format {
|
||||
Lcov,
|
||||
GoProfile,
|
||||
Jacoco,
|
||||
}
|
||||
|
||||
pub(crate) fn detect(text: &str) -> Option<Format> {
|
||||
let head = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if head.starts_with('<') {
|
||||
return head.contains("<report").then_some(Format::Jacoco);
|
||||
}
|
||||
let first = head.lines().next().unwrap_or_default();
|
||||
if first.starts_with("mode:") {
|
||||
return Some(Format::GoProfile);
|
||||
}
|
||||
head.lines().any(|l| l.trim_start().starts_with("SF:")).then_some(Format::Lcov)
|
||||
}
|
||||
|
||||
/// Reads the report at `path` for the project at `root`. Blocking.
|
||||
pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
let text = std::fs::read_to_string(path)?;
|
||||
let mut suite = match detect(&text) {
|
||||
Some(Format::Lcov) => lcov::parse(&text, root).finish("lcov"),
|
||||
Some(Format::GoProfile) => {
|
||||
let (module, module_dir) = go_module_for(root, &text);
|
||||
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
|
||||
}
|
||||
Some(Format::Jacoco) => {
|
||||
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
|
||||
let module = jacoco::module_dir(path);
|
||||
let module =
|
||||
if path.starts_with(root) && module.starts_with(root) && module != path.parent().unwrap_or(path) {
|
||||
module
|
||||
} else {
|
||||
root.to_path_buf()
|
||||
};
|
||||
let mut acc = Accumulator { has_branches: true, ..Default::default() };
|
||||
jacoco::parse_into(&text, &module, &mut acc)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
acc.finish("JaCoCo")
|
||||
}
|
||||
None => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is not an lcov tracefile, Go cover profile or JaCoCo XML report",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
for f in &mut suite.files {
|
||||
let p: &Path = f.path.as_ref();
|
||||
if !p.exists()
|
||||
&& let Some(found) = relocate(p, root)
|
||||
{
|
||||
f.path = found.into();
|
||||
}
|
||||
}
|
||||
suite.files.sort_by(|a, b| (a.path.as_ref() as &Path).cmp(b.path.as_ref()));
|
||||
Ok(suite)
|
||||
}
|
||||
|
||||
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
|
||||
/// `path` that exists under `root`.
|
||||
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
|
||||
let parts: Vec<&std::ffi::OsStr> = path
|
||||
.components()
|
||||
.filter_map(|c| match c {
|
||||
Component::Normal(s) => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
(0..parts.len()).find_map(|skip| {
|
||||
let candidate = parts[skip..].iter().fold(root.to_path_buf(), |p, s| p.join(s));
|
||||
candidate.is_file().then_some(candidate)
|
||||
})
|
||||
}
|
||||
|
||||
/// The Go module the profile's import paths belong to: the project's `go.mod`, else one
|
||||
/// a level or two down whose module path prefixes the profile's files.
|
||||
fn go_module_for(root: &Path, profile: &str) -> (String, PathBuf) {
|
||||
let first = profile
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|l| !l.is_empty() && !l.starts_with("mode:"))
|
||||
.and_then(|l| l.rsplit_once(':').map(|(f, _)| f.to_owned()))
|
||||
.unwrap_or_default();
|
||||
let matches = |module: &str| !module.is_empty() && (first == module || first.starts_with(&format!("{module}/")));
|
||||
let read = |dir: &Path| -> Option<String> {
|
||||
let text = std::fs::read_to_string(dir.join("go.mod")).ok()?;
|
||||
text.lines().find_map(|l| l.trim().strip_prefix("module")).map(|m| m.trim().trim_matches('"').to_owned())
|
||||
};
|
||||
let mut candidates = vec![root.to_path_buf()];
|
||||
for dir in std::fs::read_dir(root).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
|
||||
candidates
|
||||
.extend(std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()));
|
||||
candidates.push(dir);
|
||||
}
|
||||
let found: Vec<(String, PathBuf)> = candidates.into_iter().filter_map(|d| read(&d).map(|m| (m, d))).collect();
|
||||
found
|
||||
.iter()
|
||||
.find(|(m, _)| matches(m))
|
||||
.or_else(|| found.iter().find(|(_, d)| d == root))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| (String::new(), root.to_path_buf()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_formats() {
|
||||
assert_eq!(detect("TN:\nSF:a.rs\nDA:1,1\nend_of_record\n"), Some(Format::Lcov));
|
||||
assert_eq!(detect("mode: atomic\nm/a.go:1.1,2.2 1 0\n"), Some(Format::GoProfile));
|
||||
assert_eq!(
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
|
||||
Some(Format::Jacoco)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
|
||||
assert_eq!(detect("hello"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_ci_lcov_with_foreign_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::write(root.join("src/lib.rs"), "").unwrap();
|
||||
let report = tmp.path().join("lcov.info");
|
||||
std::fs::write(&report, "SF:/home/runner/work/app/app/src/lib.rs\nDA:1,1\nDA:2,0\nend_of_record\n").unwrap();
|
||||
let suite = import(&report, &root).unwrap();
|
||||
assert_eq!(suite.runner, "lcov");
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, root.join("src/lib.rs"));
|
||||
assert_eq!(suite.files[0].lines_covered, 1);
|
||||
assert!(import(&tmp.path().join("missing"), &root).is_err());
|
||||
std::fs::write(&report, "nothing").unwrap();
|
||||
assert!(import(&report, &root).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_go_profiles_of_nested_modules() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("svc/calc")).unwrap();
|
||||
std::fs::write(root.join("svc/go.mod"), "module example.com/svc\n").unwrap();
|
||||
let report = root.join("cover.out");
|
||||
std::fs::write(&report, "mode: set\nexample.com/svc/calc/calc.go:3.1,4.2 1 1\n").unwrap();
|
||||
let suite = import(&report, root).unwrap();
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, root.join("svc/calc/calc.go"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_jacoco_against_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("p");
|
||||
std::fs::create_dir_all(root.join("src/main/java/com/x")).unwrap();
|
||||
std::fs::write(root.join("src/main/java/com/x/A.java"), "").unwrap();
|
||||
let report = tmp.path().join("jacoco.xml");
|
||||
let xml = r#"<report name="p"><package name="com/x"><sourcefile name="A.java"><line nr="2" mi="0" ci="1" mb="0" cb="0"/></sourcefile></package></report>"#;
|
||||
std::fs::write(&report, xml).unwrap();
|
||||
let suite = import(&report, &root).unwrap();
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, root.join("src/main/java/com/x/A.java"));
|
||||
assert!(suite.has_branches);
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,12 @@
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
mod lcov;
|
||||
mod plan;
|
||||
|
||||
pub use import::import;
|
||||
pub use plan::prepare;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
@@ -204,7 +206,7 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
|
||||
let (program, args) =
|
||||
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
|
||||
let out = Command::new(program)
|
||||
let out = ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.envs(env)
|
||||
|
||||
@@ -287,6 +287,8 @@ mod tests {
|
||||
detected: true,
|
||||
is_test: true,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -233,7 +233,9 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
|
||||
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
|
||||
return Ok(()); // Reported as a missing adapter when it is started.
|
||||
};
|
||||
let probe = Command::new(&python)
|
||||
let mut probe = Command::new(&python);
|
||||
ide_core::process::no_window(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.args(["-c", "import debugpy.adapter"])
|
||||
.current_dir(&spec.cwd)
|
||||
.stdin(Stdio::null())
|
||||
@@ -335,6 +337,7 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
None => spec.args.clone(),
|
||||
};
|
||||
let mut cmd = Command::new(&binary);
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(&args)
|
||||
.envs(spec.env.iter().map(|(k, v)| (k, v)))
|
||||
.current_dir(&spec.cwd)
|
||||
|
||||
@@ -55,6 +55,7 @@ pub async fn build(
|
||||
) -> IdeResult<PathBuf> {
|
||||
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
|
||||
let mut cmd = tokio::process::Command::new(cargo);
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.arg("--message-format=json-render-diagnostics")
|
||||
.current_dir(cwd)
|
||||
|
||||
@@ -522,6 +522,17 @@ impl DebugManager {
|
||||
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
|
||||
/// Events of the session (including cargo build output) go to `owner` only.
|
||||
pub async fn start(&self, config: LaunchConfig, owner: SessionOwner) -> IdeResult<DebugSessionId> {
|
||||
self.start_with(config, owner, |_| None).await
|
||||
}
|
||||
|
||||
/// [`start`](Self::start) with the adapter executable chosen by `custom_command`
|
||||
/// (the configured command → a user-chosen executable, from settings).
|
||||
pub async fn start_with(
|
||||
&self,
|
||||
config: LaunchConfig,
|
||||
owner: SessionOwner,
|
||||
custom_command: impl FnOnce(&str) -> Option<String>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let mut arguments = launch_arguments(&config)?;
|
||||
let cwd = config
|
||||
.cwd
|
||||
@@ -531,6 +542,9 @@ impl DebugManager {
|
||||
let dbg = adapter::find_config(&self.languages, &config.adapter)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("unknown debug adapter `{}`", config.adapter)))?;
|
||||
let mut spec = adapter::resolve(&dbg, cwd.clone());
|
||||
if let Some(command) = custom_command(&spec.command) {
|
||||
spec.command = command;
|
||||
}
|
||||
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy).
|
||||
if config.adapter == "debugpy" {
|
||||
let python = match arguments.get("python") {
|
||||
|
||||
@@ -390,6 +390,7 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
return Err("runInTerminal without args".into());
|
||||
};
|
||||
let mut cmd = tokio::process::Command::new(program);
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(rest).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
if let Some(cwd) = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()) {
|
||||
cmd.current_dir(cwd);
|
||||
|
||||
@@ -15,7 +15,8 @@ use sqlx::{
|
||||
postgres::{PgConnectOptions, PgPool, PgPoolOptions, PgSslMode},
|
||||
sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions},
|
||||
};
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -184,6 +185,90 @@ fn looks_like_query(sql: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
fn file_setting(path: &str) -> Option<PathBuf> {
|
||||
let path = path.trim();
|
||||
(!path.is_empty()).then(|| crate::tunnel::expand(path))
|
||||
}
|
||||
|
||||
fn is_identifier(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
|
||||
}
|
||||
|
||||
/// A MySQL `SET` value: numbers and keywords as they are, anything else quoted.
|
||||
fn mysql_value(v: &str) -> String {
|
||||
let keyword = ["ON", "OFF", "TRUE", "FALSE", "DEFAULT"].iter().any(|k| k.eq_ignore_ascii_case(v));
|
||||
if keyword || v.parse::<f64>().is_ok() {
|
||||
v.to_owned()
|
||||
} else {
|
||||
format!("'{}'", v.replace('\\', "\\\\").replace('\'', "''"))
|
||||
}
|
||||
}
|
||||
|
||||
/// How the Options and Advanced tabs reach a connection.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Setup {
|
||||
/// PostgreSQL run-time parameters (startup `options`), SQLite pragmas.
|
||||
pub params: Vec<(String, String)>,
|
||||
/// Run on every new connection: MySQL session settings, then the startup script.
|
||||
pub statements: Vec<String>,
|
||||
pub application_name: Option<String>,
|
||||
pub charset: Option<String>,
|
||||
pub collation: Option<String>,
|
||||
pub statement_cache: Option<usize>,
|
||||
pub connect_timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
impl Setup {
|
||||
pub fn of(source: &DataSource) -> IdeResult<Self> {
|
||||
let mut s = Setup::default();
|
||||
let o = &source.options;
|
||||
match source.driver {
|
||||
DbDriver::Postgres => {
|
||||
if source.read_only {
|
||||
s.params.push(("default_transaction_read_only".into(), "on".into()));
|
||||
}
|
||||
if !o.default_schema.trim().is_empty() {
|
||||
s.params.push(("search_path".into(), o.default_schema.trim().into()));
|
||||
}
|
||||
if !o.time_zone.trim().is_empty() {
|
||||
s.params.push(("TimeZone".into(), o.time_zone.trim().into()));
|
||||
}
|
||||
}
|
||||
DbDriver::Mysql if source.read_only => s.statements.push("SET SESSION TRANSACTION READ ONLY".into()),
|
||||
_ => {}
|
||||
}
|
||||
for p in &source.properties {
|
||||
let value = p.value.trim();
|
||||
let name = p.name.trim().replace('-', "_");
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !is_identifier(&name) {
|
||||
return Err(IdeError::invalid(format!("invalid driver property name: {}", p.name.trim())));
|
||||
}
|
||||
let number = |what: &str| {
|
||||
value.parse::<u64>().map_err(|_| IdeError::invalid(format!("{what} must be a whole number: {value}")))
|
||||
};
|
||||
match (source.driver, name.to_ascii_lowercase().as_str()) {
|
||||
(_, "statement_cache_capacity") => s.statement_cache = Some(number(&name)? as usize),
|
||||
(_, "connect_timeout") => s.connect_timeout = Some(Duration::from_secs(number(&name)?)),
|
||||
(DbDriver::Postgres, "application_name") => s.application_name = Some(value.to_owned()),
|
||||
(DbDriver::Mysql, "charset") => s.charset = Some(value.to_owned()),
|
||||
(DbDriver::Mysql, "collation") => s.collation = Some(value.to_owned()),
|
||||
(DbDriver::Mysql, _) => s.statements.push(format!("SET SESSION {name} = {}", mysql_value(value))),
|
||||
_ => s.params.push((name, value.to_owned())),
|
||||
}
|
||||
}
|
||||
let script = o.startup_script.trim();
|
||||
if !script.is_empty() {
|
||||
s.statements.extend(crate::split::split(script, source.driver).into_iter().map(|st| st.text));
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
pub fn driver(&self) -> DbDriver {
|
||||
match self {
|
||||
@@ -196,7 +281,24 @@ impl Pool {
|
||||
/// Opens a pool and one connection (so bad settings fail here).
|
||||
pub async fn connect(source: &DataSource, password: Option<&str>, root: Option<&Path>) -> IdeResult<Self> {
|
||||
const MAX: u32 = 4;
|
||||
let timeout = Duration::from_secs(30);
|
||||
let setup = Setup::of(source)?;
|
||||
let timeout = setup.connect_timeout.unwrap_or(Duration::from_secs(30));
|
||||
let init = Arc::new(setup.statements);
|
||||
// Runs the session statements (startup script…) on every new connection.
|
||||
macro_rules! after_connect {
|
||||
() => {{
|
||||
let init = init.clone();
|
||||
move |conn, _| {
|
||||
let init = init.clone();
|
||||
Box::pin(async move {
|
||||
for sql in init.iter() {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}};
|
||||
}
|
||||
match source.driver {
|
||||
DbDriver::Sqlite => {
|
||||
let file = source.file.as_deref().ok_or_else(|| IdeError::invalid("no database file"))?;
|
||||
@@ -204,11 +306,18 @@ impl Pool {
|
||||
Some(r) if file.is_relative() => r.join(file),
|
||||
_ => file.to_path_buf(),
|
||||
};
|
||||
let opts =
|
||||
let mut opts =
|
||||
SqliteConnectOptions::new().filename(&file).create_if_missing(false).read_only(source.read_only);
|
||||
for (k, v) in setup.params {
|
||||
opts = opts.pragma(k, v);
|
||||
}
|
||||
if let Some(n) = setup.statement_cache {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
@@ -219,24 +328,39 @@ impl Pool {
|
||||
.host(&source.host)
|
||||
.port(source.port.unwrap_or(5432))
|
||||
.username(&source.user)
|
||||
.application_name("OpenIDEA")
|
||||
.application_name(setup.application_name.as_deref().unwrap_or("OpenIDEA"))
|
||||
.ssl_mode(match source.ssl {
|
||||
DbSslMode::Disable => PgSslMode::Disable,
|
||||
DbSslMode::Prefer => PgSslMode::Prefer,
|
||||
DbSslMode::Require => PgSslMode::Require,
|
||||
DbSslMode::VerifyCa => PgSslMode::VerifyCa,
|
||||
DbSslMode::VerifyFull => PgSslMode::VerifyFull,
|
||||
});
|
||||
if let Some(f) = file_setting(&source.ssl_ca_file) {
|
||||
opts = opts.ssl_root_cert(f);
|
||||
}
|
||||
if let Some(f) = file_setting(&source.ssl_cert_file) {
|
||||
opts = opts.ssl_client_cert(f);
|
||||
}
|
||||
if let Some(f) = file_setting(&source.ssl_key_file) {
|
||||
opts = opts.ssl_client_key(f);
|
||||
}
|
||||
if !source.database.is_empty() {
|
||||
opts = opts.database(&source.database);
|
||||
}
|
||||
if let Some(p) = password {
|
||||
opts = opts.password(p);
|
||||
}
|
||||
if source.read_only {
|
||||
opts = opts.options([("default_transaction_read_only", "on")]);
|
||||
if !setup.params.is_empty() {
|
||||
opts = opts.options(setup.params);
|
||||
}
|
||||
if let Some(n) = setup.statement_cache {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
@@ -251,25 +375,41 @@ impl Pool {
|
||||
DbSslMode::Disable => MySqlSslMode::Disabled,
|
||||
DbSslMode::Prefer => MySqlSslMode::Preferred,
|
||||
DbSslMode::Require => MySqlSslMode::Required,
|
||||
DbSslMode::VerifyCa => MySqlSslMode::VerifyCa,
|
||||
DbSslMode::VerifyFull => MySqlSslMode::VerifyIdentity,
|
||||
});
|
||||
if let Some(f) = file_setting(&source.ssl_ca_file) {
|
||||
opts = opts.ssl_ca(f);
|
||||
}
|
||||
if let Some(f) = file_setting(&source.ssl_cert_file) {
|
||||
opts = opts.ssl_client_cert(f);
|
||||
}
|
||||
if let Some(f) = file_setting(&source.ssl_key_file) {
|
||||
opts = opts.ssl_client_key(f);
|
||||
}
|
||||
if !source.database.is_empty() {
|
||||
opts = opts.database(&source.database);
|
||||
}
|
||||
if let Some(p) = password {
|
||||
opts = opts.password(p);
|
||||
}
|
||||
let read_only = source.read_only;
|
||||
if let Some(c) = &setup.charset {
|
||||
opts = opts.charset(c);
|
||||
}
|
||||
if let Some(c) = &setup.collation {
|
||||
opts = opts.collation(c);
|
||||
}
|
||||
if let Some(n) = setup.statement_cache {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let tz = source.options.time_zone.trim();
|
||||
if !tz.is_empty() {
|
||||
opts = opts.timezone(Some(tz.to_owned()));
|
||||
}
|
||||
let pool = MySqlPoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(move |conn, _| {
|
||||
Box::pin(async move {
|
||||
if read_only {
|
||||
conn.execute("SET SESSION TRANSACTION READ ONLY").await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
@@ -282,6 +422,10 @@ impl Pool {
|
||||
with_pool!(self, p => p.close().await)
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
with_pool!(self, p => p.is_closed())
|
||||
}
|
||||
|
||||
/// Runs `sql` (no row limit beyond `max`), for introspection.
|
||||
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
let fetched: IdeResult<Fetched> = with_pool!(self, p => fetch!(p, sql, max));
|
||||
@@ -434,3 +578,68 @@ fn statement_columns<S: sqlx::Statement>(s: &S) -> Vec<ResultColumn> {
|
||||
.map(|c| ResultColumn { name: c.name().to_owned(), type_name: c.type_info().name().to_owned() })
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::source::{DbOptions, DbProperty};
|
||||
|
||||
fn prop(name: &str, value: &str) -> DbProperty {
|
||||
DbProperty { name: name.into(), value: value.into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_options_become_runtime_parameters() {
|
||||
let s = DataSource {
|
||||
driver: DbDriver::Postgres,
|
||||
read_only: true,
|
||||
options: DbOptions {
|
||||
default_schema: "app, public".into(),
|
||||
time_zone: "Europe/Paris".into(),
|
||||
startup_script: "SET work_mem = '64MB'; select 1;".into(),
|
||||
..Default::default()
|
||||
},
|
||||
properties: vec![prop("statement_timeout", "5s"), prop("application_name", "me"), prop("", "x")],
|
||||
..Default::default()
|
||||
};
|
||||
let setup = Setup::of(&s).unwrap();
|
||||
let names: Vec<_> = setup.params.iter().map(|(k, _)| k.as_str()).collect();
|
||||
assert_eq!(names, ["default_transaction_read_only", "search_path", "TimeZone", "statement_timeout"]);
|
||||
assert_eq!(setup.application_name.as_deref(), Some("me"));
|
||||
assert_eq!(setup.statements, ["SET work_mem = '64MB'", "select 1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_properties_become_session_variables() {
|
||||
let s = DataSource {
|
||||
driver: DbDriver::Mysql,
|
||||
read_only: true,
|
||||
properties: vec![
|
||||
prop("sql_mode", "ANSI_QUOTES"),
|
||||
prop("max_execution_time", "1000"),
|
||||
prop("charset", "utf8mb4"),
|
||||
prop("connect-timeout", "5"),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let setup = Setup::of(&s).unwrap();
|
||||
assert_eq!(
|
||||
setup.statements,
|
||||
[
|
||||
"SET SESSION TRANSACTION READ ONLY",
|
||||
"SET SESSION sql_mode = 'ANSI_QUOTES'",
|
||||
"SET SESSION max_execution_time = 1000"
|
||||
]
|
||||
);
|
||||
assert_eq!(setup.charset.as_deref(), Some("utf8mb4"));
|
||||
assert_eq!(setup.connect_timeout, Some(Duration::from_secs(5)));
|
||||
assert!(Setup::of(&DataSource { properties: vec![prop("a; drop", "1")], ..s.clone() }).is_err());
|
||||
assert!(Setup::of(&DataSource { properties: vec![prop("connect_timeout", "soon")], ..s }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_properties_become_pragmas() {
|
||||
let s = DataSource { properties: vec![prop("cache_size", "-2000")], ..Default::default() };
|
||||
assert_eq!(Setup::of(&s).unwrap().params, [("cache_size".to_owned(), "-2000".to_owned())]);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,9 @@ pub mod sql;
|
||||
pub mod tunnel;
|
||||
|
||||
pub use conn::{Held, Pool, QueryResult, ResultColumn};
|
||||
pub use source::{DataSource, DbDriver, DbSsh, DbSshAuth, DbSslMode};
|
||||
pub use source::{
|
||||
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
@@ -21,6 +23,7 @@ use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tunnel::{OpenError, Tunnel, TunnelSpec, UnknownHostKey};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -219,6 +222,24 @@ fn through_tunnel(e: IdeError, source: &DataSource, tunneled: bool) -> IdeError
|
||||
)
|
||||
}
|
||||
|
||||
/// Options › Run keep-alive query: pings the pool until it is closed or dropped
|
||||
/// (a dropped SSH tunnel or an idle-killing proxy stays alive meanwhile).
|
||||
fn keep_alive(pool: &Arc<Pool>, every: Duration) {
|
||||
let pool = Arc::downgrade(pool);
|
||||
tokio::spawn(async move {
|
||||
let mut tick = tokio::time::interval(every);
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
tick.tick().await;
|
||||
loop {
|
||||
tick.tick().await;
|
||||
let Some(p) = pool.upgrade().filter(|p| !p.is_closed()) else { break };
|
||||
if let Err(e) = p.rows("SELECT 1", 1).await {
|
||||
tracing::debug!("keep-alive: {}", e.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Rolls back a session's transaction and releases its connection.
|
||||
async fn end_session(session: &Session) {
|
||||
let held = session.lock().await.take();
|
||||
@@ -261,14 +282,16 @@ impl DbManager {
|
||||
source::load(&self.root)
|
||||
}
|
||||
|
||||
/// The data source of connection target `target`, with its database for `<id>:<database>`.
|
||||
/// The connection settings of target `target` ([`DataSource::resolved`]), with
|
||||
/// its database for `<id>:<database>`.
|
||||
pub fn source(&self, target: &str) -> IdeResult<DataSource> {
|
||||
let (id, database) = split_target(target);
|
||||
let mut source = self
|
||||
.sources()?
|
||||
.into_iter()
|
||||
.find(|s| s.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?;
|
||||
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?
|
||||
.resolved()?;
|
||||
if let Some(db) = database {
|
||||
source.database = db.to_owned();
|
||||
}
|
||||
@@ -341,7 +364,10 @@ impl DbManager {
|
||||
}
|
||||
|
||||
async fn password(&self, source: &DataSource) -> Option<String> {
|
||||
self.secret(source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await
|
||||
match self.secret(source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await {
|
||||
Some(p) => Some(p),
|
||||
None => source.url_password(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Trusts the host key that failed the last connection of `id` (adds it to `known_hosts`).
|
||||
@@ -411,6 +437,7 @@ impl DbManager {
|
||||
password: Option<String>,
|
||||
ssh_secret: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let source = &source.resolved()?;
|
||||
let password = match password {
|
||||
Some(p) => Some(p),
|
||||
None => self.password(source).await,
|
||||
@@ -458,9 +485,14 @@ impl DbManager {
|
||||
return Err(through_tunnel(e, &source, tunnel.is_some()));
|
||||
}
|
||||
};
|
||||
let mut pools = self.pools.lock();
|
||||
// Another caller may have connected meanwhile; keep theirs.
|
||||
Ok(pools.entry(id.to_owned()).or_insert(pool).clone())
|
||||
let kept = self.pools.lock().entry(id.to_owned()).or_insert_with(|| pool.clone()).clone();
|
||||
if Arc::ptr_eq(&kept, &pool)
|
||||
&& let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0)
|
||||
{
|
||||
keep_alive(&pool, Duration::from_secs(secs.into()));
|
||||
}
|
||||
Ok(kept)
|
||||
}
|
||||
|
||||
/// Closes the tunnel of `source_id` once none of its targets is connected.
|
||||
@@ -496,24 +528,29 @@ impl DbManager {
|
||||
|
||||
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
|
||||
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
|
||||
let pool = self.pool(split_target(id).0).await?;
|
||||
let id = split_target(id).0;
|
||||
let system = self.source(id)?.introspection.show_system;
|
||||
let pool = self.pool(id).await?;
|
||||
if pool.driver() != DbDriver::Postgres {
|
||||
return Err(IdeError::invalid("only PostgreSQL data sources list databases"));
|
||||
}
|
||||
let first = |rows: Vec<Vec<Option<String>>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten());
|
||||
let current = first(pool.rows("SELECT current_database()", 1).await?).next().unwrap_or_default();
|
||||
let rows = pool.rows(sql::DATABASES, MAX_META_ROWS).await?;
|
||||
let rows = pool.rows(sql::databases(system), MAX_META_ROWS).await?;
|
||||
let mut names: Vec<String> =
|
||||
first(rows).filter(|n| *n == current || !sql::INTERNAL_DATABASES.contains(&n.as_str())).collect();
|
||||
first(rows).filter(|n| system || *n == current || !sql::INTERNAL_DATABASES.contains(&n.as_str())).collect();
|
||||
if !names.contains(¤t) {
|
||||
names.insert(0, current.clone());
|
||||
}
|
||||
Ok(Databases { current, names })
|
||||
}
|
||||
|
||||
/// Every schema (the Schemas tab picks the ones the tree shows); system schemas
|
||||
/// only with [`DbIntrospection::show_system`].
|
||||
pub async fn schemas(&self, id: &str) -> IdeResult<Vec<String>> {
|
||||
let system = self.source(id)?.introspection.show_system;
|
||||
let pool = self.pool(id).await?;
|
||||
let rows = pool.rows(sql::schemas(pool.driver()), MAX_META_ROWS).await?;
|
||||
let rows = pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?;
|
||||
Ok(rows.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect())
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,76 @@ pub enum DbSslMode {
|
||||
#[default]
|
||||
Prefer,
|
||||
Require,
|
||||
/// Require, and check the server certificate against the CA file.
|
||||
VerifyCa,
|
||||
/// [`DbSslMode::VerifyCa`], and check that the certificate names the host.
|
||||
VerifyFull,
|
||||
}
|
||||
|
||||
/// IDEA's data source colours (tree node and console tab tint), e.g. red for production.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DbColor {
|
||||
Red,
|
||||
Orange,
|
||||
Yellow,
|
||||
Green,
|
||||
Blue,
|
||||
Violet,
|
||||
}
|
||||
|
||||
/// Transaction control of the data source's consoles.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DbTxMode {
|
||||
#[default]
|
||||
Auto,
|
||||
Manual,
|
||||
}
|
||||
|
||||
/// Options tab: session settings applied to every connection.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct DbOptions {
|
||||
pub transaction: DbTxMode,
|
||||
/// PostgreSQL `search_path` (unqualified names resolve there).
|
||||
pub default_schema: String,
|
||||
/// Session time zone (`TimeZone` / `time_zone`); empty keeps the default.
|
||||
pub time_zone: String,
|
||||
/// Statements run on every new connection.
|
||||
pub startup_script: String,
|
||||
/// Run `SELECT 1` this often while connected.
|
||||
pub keep_alive_secs: Option<u32>,
|
||||
/// Disconnect after this long without statements (enforced by the UI, which sees the activity).
|
||||
pub auto_disconnect_secs: Option<u32>,
|
||||
}
|
||||
|
||||
/// Schemas tab: the databases / schemas the tree shows. Names may use `*` and `?`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct DbIntrospection {
|
||||
pub all_databases: bool,
|
||||
pub databases: Vec<String>,
|
||||
pub all_schemas: bool,
|
||||
pub schemas: Vec<String>,
|
||||
/// `pg_catalog`, `information_schema`, `mysql`…, and PostgreSQL template databases.
|
||||
pub show_system: bool,
|
||||
}
|
||||
|
||||
impl Default for DbIntrospection {
|
||||
fn default() -> Self {
|
||||
Self { all_databases: true, databases: Vec::new(), all_schemas: true, schemas: Vec::new(), show_system: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Advanced tab: a driver property. PostgreSQL: run-time parameters (and
|
||||
/// `application_name`); MySQL: session variables (and `charset`, `collation`);
|
||||
/// SQLite: pragmas. See [`crate::conn`].
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct DbProperty {
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// How the SSH tunnel authenticates (IDEA's SSH configuration "Authentication type").
|
||||
@@ -84,6 +154,20 @@ pub struct DataSource {
|
||||
pub read_only: bool,
|
||||
/// SSH tunnel settings (`None`: never configured; kept but unused when not `enabled`).
|
||||
pub ssh: Option<DbSsh>,
|
||||
/// Wire-compatible product preset (`cockroachdb`, `tidb`…; empty: the driver itself).
|
||||
pub vendor: String,
|
||||
pub color: Option<DbColor>,
|
||||
pub comment: String,
|
||||
/// Connect with [`DataSource::url`] instead of the host / port / database fields.
|
||||
pub url_only: bool,
|
||||
pub url: String,
|
||||
/// PEM files; `~/` is the home directory.
|
||||
pub ssl_ca_file: String,
|
||||
pub ssl_cert_file: String,
|
||||
pub ssl_key_file: String,
|
||||
pub options: DbOptions,
|
||||
pub introspection: DbIntrospection,
|
||||
pub properties: Vec<DbProperty>,
|
||||
}
|
||||
|
||||
impl Default for DataSource {
|
||||
@@ -101,10 +185,188 @@ impl Default for DataSource {
|
||||
save_password: false,
|
||||
read_only: false,
|
||||
ssh: None,
|
||||
vendor: String::new(),
|
||||
color: None,
|
||||
comment: String::new(),
|
||||
url_only: false,
|
||||
url: String::new(),
|
||||
ssl_ca_file: String::new(),
|
||||
ssl_cert_file: String::new(),
|
||||
ssl_key_file: String::new(),
|
||||
options: DbOptions::default(),
|
||||
introspection: DbIntrospection::default(),
|
||||
properties: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection settings of a URL (`jdbc:` prefix allowed).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ParsedUrl {
|
||||
pub driver: Option<DbDriver>,
|
||||
pub host: String,
|
||||
pub port: Option<u16>,
|
||||
pub database: String,
|
||||
pub user: String,
|
||||
pub password: Option<String>,
|
||||
/// Query parameters, in order.
|
||||
pub params: Vec<(String, String)>,
|
||||
/// SQLite file.
|
||||
pub file: Option<String>,
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
let hex = |i: usize| b.get(i).and_then(|&c| (c as char).to_digit(16));
|
||||
while i < b.len() {
|
||||
if b[i] == b'%'
|
||||
&& let (Some(h), Some(l)) = (hex(i + 1), hex(i + 2))
|
||||
{
|
||||
out.push((h * 16 + l) as u8);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
out.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// The driver speaking the protocol of URL scheme `scheme` (wire-compatible products included).
|
||||
pub fn scheme_driver(scheme: &str) -> Option<DbDriver> {
|
||||
match scheme.to_ascii_lowercase().as_str() {
|
||||
"postgres" | "postgresql" | "pgsql" | "redshift" | "cockroachdb" | "cockroach" | "yugabytedb"
|
||||
| "timescaledb" | "greenplum" => Some(DbDriver::Postgres),
|
||||
"mysql" | "mariadb" | "tidb" | "singlestore" | "memsql" | "oceanbase" => Some(DbDriver::Mysql),
|
||||
"sqlite" | "sqlite3" => Some(DbDriver::Sqlite),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `scheme://[user[:password]@]host[:port][/database][?k=v&…]`, `jdbc:` forms
|
||||
/// included, and `sqlite:path`.
|
||||
pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
|
||||
let bad = || IdeError::invalid(format!("not a database URL: {raw}"));
|
||||
let url = raw.trim();
|
||||
let url = url.strip_prefix("jdbc:").or_else(|| url.strip_prefix("JDBC:")).unwrap_or(url);
|
||||
let (scheme, rest) = url.split_once(':').ok_or_else(bad)?;
|
||||
let driver = scheme_driver(scheme).ok_or_else(bad)?;
|
||||
if driver == DbDriver::Sqlite {
|
||||
let file = rest.strip_prefix("//").unwrap_or(rest);
|
||||
let file = file.split('?').next().unwrap_or_default();
|
||||
if file.is_empty() {
|
||||
return Err(bad());
|
||||
}
|
||||
return Ok(ParsedUrl { driver: Some(driver), file: Some(percent_decode(file)), ..Default::default() });
|
||||
}
|
||||
let rest = rest.strip_prefix("//").ok_or_else(bad)?;
|
||||
let (main, query) = rest.split_once('?').unwrap_or((rest, ""));
|
||||
let (authority, database) = main.split_once('/').unwrap_or((main, ""));
|
||||
let (userinfo, hostport) = match authority.rsplit_once('@') {
|
||||
Some((u, h)) => (Some(u), h),
|
||||
None => (None, authority),
|
||||
};
|
||||
// Several hosts (failover lists): the first.
|
||||
let hostport = hostport.split(',').next().unwrap_or_default();
|
||||
let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
|
||||
let (h, after) = v6.split_once(']').ok_or_else(bad)?;
|
||||
(h.to_owned(), after.strip_prefix(':'))
|
||||
} else {
|
||||
match hostport.rsplit_once(':') {
|
||||
Some((h, p)) => (h.to_owned(), Some(p)),
|
||||
None => (hostport.to_owned(), None),
|
||||
}
|
||||
};
|
||||
let port = match port.filter(|p| !p.is_empty()) {
|
||||
Some(p) => Some(p.parse::<u16>().map_err(|_| bad())?),
|
||||
None => None,
|
||||
};
|
||||
let mut parsed = ParsedUrl {
|
||||
driver: Some(driver),
|
||||
host,
|
||||
port,
|
||||
database: percent_decode(database.trim_end_matches('/')),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(u) = userinfo {
|
||||
let (user, password) = match u.split_once(':') {
|
||||
Some((u, p)) => (u, Some(percent_decode(p))),
|
||||
None => (u, None),
|
||||
};
|
||||
parsed.user = percent_decode(user);
|
||||
parsed.password = password;
|
||||
}
|
||||
for pair in query.split('&').filter(|p| !p.is_empty()) {
|
||||
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let (k, v) = (percent_decode(k), percent_decode(v));
|
||||
match k.as_str() {
|
||||
"user" if parsed.user.is_empty() => parsed.user = v,
|
||||
"password" if parsed.password.is_none() => parsed.password = Some(v),
|
||||
_ => parsed.params.push((k, v)),
|
||||
}
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
impl DataSource {
|
||||
/// The settings to connect with: with [`DataSource::url_only`], host, port,
|
||||
/// database, user, SSL and driver properties come from the URL (properties
|
||||
/// of the Advanced tab still apply after the URL's).
|
||||
pub fn resolved(&self) -> IdeResult<DataSource> {
|
||||
if !self.url_only {
|
||||
return Ok(self.clone());
|
||||
}
|
||||
let u = parse_url(&self.url)?;
|
||||
let mut s = self.clone();
|
||||
if let Some(d) = u.driver
|
||||
&& d != s.driver
|
||||
{
|
||||
return Err(IdeError::invalid(format!("the URL is not for the {:?} driver", s.driver)));
|
||||
}
|
||||
if s.driver == DbDriver::Sqlite {
|
||||
s.file = u.file.map(IpcPath::from);
|
||||
return Ok(s);
|
||||
}
|
||||
s.host = u.host;
|
||||
s.port = u.port;
|
||||
s.database = u.database;
|
||||
if !u.user.is_empty() {
|
||||
s.user = u.user;
|
||||
}
|
||||
let mut properties = Vec::new();
|
||||
for (k, v) in u.params {
|
||||
match k.to_ascii_lowercase().as_str() {
|
||||
"sslmode" | "ssl-mode" => {
|
||||
s.ssl = match v.to_ascii_lowercase().replace('-', "_").as_str() {
|
||||
"disable" | "disabled" => DbSslMode::Disable,
|
||||
"require" | "required" => DbSslMode::Require,
|
||||
"verify_ca" => DbSslMode::VerifyCa,
|
||||
"verify_full" | "verify_identity" => DbSslMode::VerifyFull,
|
||||
_ => DbSslMode::Prefer,
|
||||
}
|
||||
}
|
||||
"sslrootcert" | "ssl-ca" | "sslca" => s.ssl_ca_file = v,
|
||||
"sslcert" | "ssl-cert" => s.ssl_cert_file = v,
|
||||
"sslkey" | "ssl-key" => s.ssl_key_file = v,
|
||||
_ => properties.push(DbProperty { name: k, value: v }),
|
||||
}
|
||||
}
|
||||
properties.append(&mut s.properties);
|
||||
s.properties = properties;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The password written in the URL of a [`DataSource::url_only`] data source.
|
||||
pub fn url_password(&self) -> Option<String> {
|
||||
if !self.url_only {
|
||||
return None;
|
||||
}
|
||||
parse_url(&self.url).ok()?.password
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
struct SourcesFile {
|
||||
#[serde(default, rename = "data-source")]
|
||||
@@ -164,4 +426,77 @@ mod tests {
|
||||
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
|
||||
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_configs_written_before_the_new_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join(".openidea");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join(FILE),
|
||||
"[[data-source]]\nid = \"a\"\nname = \"old\"\ndriver = \"postgres\"\nhost = \"db\"\nssl = \"require\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let s = load(tmp.path()).unwrap().remove(0);
|
||||
assert_eq!(s.ssl, DbSslMode::Require);
|
||||
assert!(s.introspection.all_databases && s.introspection.all_schemas);
|
||||
assert_eq!((s.color, s.url_only, s.options.transaction), (None, false, DbTxMode::Auto));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_the_new_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let s = DataSource {
|
||||
id: "b".into(),
|
||||
name: "prod".into(),
|
||||
driver: DbDriver::Mysql,
|
||||
vendor: "tidb".into(),
|
||||
color: Some(DbColor::Red),
|
||||
comment: "careful".into(),
|
||||
ssl: DbSslMode::VerifyFull,
|
||||
ssl_ca_file: "~/ca.pem".into(),
|
||||
options: DbOptions { time_zone: "UTC".into(), keep_alive_secs: Some(60), ..Default::default() },
|
||||
introspection: DbIntrospection { all_schemas: false, schemas: vec!["app*".into()], ..Default::default() },
|
||||
properties: vec![DbProperty { name: "sql_mode".into(), value: "ANSI".into() }],
|
||||
..Default::default()
|
||||
};
|
||||
save(tmp.path(), std::slice::from_ref(&s)).unwrap();
|
||||
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_urls() {
|
||||
let u = parse_url("jdbc:postgresql://ann:s%[email protected]:5433/shop?sslmode=require&search_path=app").unwrap();
|
||||
assert_eq!(u.driver, Some(DbDriver::Postgres));
|
||||
assert_eq!((u.host.as_str(), u.port, u.database.as_str()), ("db.local", Some(5433), "shop"));
|
||||
assert_eq!((u.user.as_str(), u.password.as_deref()), ("ann", Some("s@cret")));
|
||||
assert_eq!(u.params, vec![("sslmode".into(), "require".into()), ("search_path".into(), "app".into())]);
|
||||
let u = parse_url("mysql://[::1]/app?user=root").unwrap();
|
||||
assert_eq!((u.host.as_str(), u.port, u.user.as_str()), ("::1", None, "root"));
|
||||
assert_eq!(parse_url("jdbc:redshift://r:5439/dev").unwrap().driver, Some(DbDriver::Postgres));
|
||||
assert_eq!(parse_url("tidb://h:4000").unwrap().driver, Some(DbDriver::Mysql));
|
||||
assert_eq!(parse_url("sqlite:/tmp/a.db").unwrap().file.as_deref(), Some("/tmp/a.db"));
|
||||
assert!(parse_url("oracle://x").is_err());
|
||||
assert!(parse_url("postgres://h:99999/db").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn url_only_sources_connect_with_the_url() {
|
||||
let s = DataSource {
|
||||
driver: DbDriver::Postgres,
|
||||
user: "fallback".into(),
|
||||
url_only: true,
|
||||
url: "postgres://ann:pw@h:6543/app?sslmode=verify-full&sslrootcert=/ca.pem&statement_timeout=5000".into(),
|
||||
properties: vec![DbProperty { name: "work_mem".into(), value: "64MB".into() }],
|
||||
..Default::default()
|
||||
};
|
||||
let r = s.resolved().unwrap();
|
||||
assert_eq!((r.host.as_str(), r.port, r.database.as_str(), r.user.as_str()), ("h", Some(6543), "app", "ann"));
|
||||
assert_eq!((r.ssl, r.ssl_ca_file.as_str()), (DbSslMode::VerifyFull, "/ca.pem"));
|
||||
let names: Vec<_> = r.properties.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["statement_timeout", "work_mem"]);
|
||||
assert_eq!(s.url_password().as_deref(), Some("pw"));
|
||||
assert!(DataSource { url: "mysql://h/db".into(), ..s.clone() }.resolved().is_err());
|
||||
assert_eq!(DataSource { url_only: false, ..s }.resolved().unwrap().host, "localhost");
|
||||
}
|
||||
}
|
||||
@@ -33,14 +33,26 @@ pub fn qualified(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
|
||||
/// Databases one can connect to (PostgreSQL).
|
||||
pub const DATABASES: &str = "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname";
|
||||
/// PostgreSQL databases one can connect to; templates only with `system`.
|
||||
pub fn databases(system: bool) -> &'static str {
|
||||
if system {
|
||||
"SELECT datname FROM pg_database WHERE datallowconn ORDER BY datname"
|
||||
} else {
|
||||
"SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname"
|
||||
}
|
||||
}
|
||||
|
||||
/// Databases of managed services that their users cannot use (hidden unless connected to).
|
||||
pub const INTERNAL_DATABASES: &[&str] = &["rdsadmin", "azure_maintenance", "azure_sys", "cloudsqladmin"];
|
||||
|
||||
pub fn schemas(driver: DbDriver) -> &'static str {
|
||||
pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
match driver {
|
||||
DbDriver::Sqlite => "SELECT name FROM pragma_database_list WHERE name <> 'temp' ORDER BY seq",
|
||||
DbDriver::Postgres if system => {
|
||||
"SELECT schema_name FROM information_schema.schemata \
|
||||
WHERE schema_name NOT LIKE 'pg\\_toast%' AND schema_name NOT LIKE 'pg\\_temp%' ORDER BY 1"
|
||||
}
|
||||
DbDriver::Mysql if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::Postgres => {
|
||||
"SELECT schema_name FROM information_schema.schemata \
|
||||
WHERE schema_name NOT IN ('pg_catalog', 'information_schema') \
|
||||
|
||||
@@ -200,7 +200,7 @@ fn home() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// `~/x` → `$HOME/x`.
|
||||
fn expand(path: &str) -> PathBuf {
|
||||
pub(crate) fn expand(path: &str) -> PathBuf {
|
||||
match (path.strip_prefix("~/"), home()) {
|
||||
(Some(rest), Some(h)) => h.join(rest),
|
||||
_ => PathBuf::from(path),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Introspection, queries and table edits against a real SQLite file.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbRowEdit, DbTableKind, SortKey};
|
||||
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbTableKind, SortKey};
|
||||
|
||||
async fn setup() -> (tempfile::TempDir, DbManager) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -246,3 +246,23 @@ async fn ddl_of_tables_and_views() -> IdeResult<()> {
|
||||
assert!(db.ddl("s1", "main", "nope").await.is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn applies_driver_properties_and_the_startup_script_on_connect() -> IdeResult<()> {
|
||||
let (tmp, db) = setup().await;
|
||||
let mut s = db.sources()?.remove(0);
|
||||
s.properties = vec![DbProperty { name: "cache_size".into(), value: "-1234".into() }];
|
||||
s.options = DbOptions {
|
||||
startup_script: "CREATE TEMP TABLE boot (x); INSERT INTO boot VALUES (7);".into(),
|
||||
..Default::default()
|
||||
};
|
||||
db.save_sources(vec![s.clone()]).await?;
|
||||
let c = CancellationToken::new();
|
||||
let r = db.execute("s1", "SELECT (SELECT x FROM boot), (SELECT cache_size FROM pragma_cache_size)", 10, &c).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some("7".into()), Some("-1234".into())]]);
|
||||
// URL only: the file comes from the URL.
|
||||
let url = format!("jdbc:sqlite:{}", tmp.path().join("app.db").display());
|
||||
db.save_sources(vec![DataSource { url_only: true, url, file: None, ..s }]).await?;
|
||||
assert_eq!(db.schemas("s1").await?, vec!["main"]);
|
||||
Ok(())
|
||||
}
|
||||
@@ -15,3 +15,6 @@ which = "8"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,402 @@
|
||||
//! Docker connections (which daemon the CLI talks to) and registries, as the
|
||||
//! Services tool window's "Add Service" menu creates them. Both are app-wide
|
||||
//! like in IDEA: `docker.json` in the app data directory; registry passwords
|
||||
//! live beside it in an owner-only `docker-passwords.json`.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// Which daemon a docker command talks to.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum DockerEndpoint {
|
||||
/// Whatever the CLI is configured for (`DOCKER_HOST`, the current context).
|
||||
#[default]
|
||||
Default,
|
||||
/// A local daemon socket, e.g. `/var/run/docker.sock` (or a `npipe://` URL on Windows).
|
||||
Socket { path: String },
|
||||
/// A remote daemon, e.g. `tcp://build:2376` or `ssh://me@build`; with TLS when
|
||||
/// `tls_cert_dir` holds `ca.pem`, `cert.pem` and `key.pem`.
|
||||
Tcp { host: String, tls_cert_dir: Option<String> },
|
||||
/// A named `docker context`.
|
||||
Context { name: String },
|
||||
}
|
||||
|
||||
impl DockerEndpoint {
|
||||
/// Global CLI options selecting this endpoint (before the subcommand).
|
||||
pub fn global_args(&self) -> Vec<String> {
|
||||
match self {
|
||||
Self::Default => Vec::new(),
|
||||
Self::Socket { path } => {
|
||||
let path = path.trim();
|
||||
let url = if path.contains("://") { path.to_owned() } else { format!("unix://{path}") };
|
||||
vec!["--host".into(), url]
|
||||
}
|
||||
Self::Tcp { host, tls_cert_dir } => {
|
||||
let host = host.trim();
|
||||
let url = if host.contains("://") { host.to_owned() } else { format!("tcp://{host}") };
|
||||
let mut args = vec!["--host".into(), url];
|
||||
if let Some(dir) = tls_cert_dir.as_deref().map(str::trim).filter(|d| !d.is_empty()) {
|
||||
let file = |name: &str| Path::new(dir).join(name).to_string_lossy().into_owned();
|
||||
args.extend([
|
||||
"--tlsverify".into(),
|
||||
"--tlscacert".into(),
|
||||
file("ca.pem"),
|
||||
"--tlscert".into(),
|
||||
file("cert.pem"),
|
||||
"--tlskey".into(),
|
||||
file("key.pem"),
|
||||
]);
|
||||
}
|
||||
args
|
||||
}
|
||||
Self::Context { name } => vec!["--context".into(), name.trim().to_owned()],
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the global options to `cmd`; an explicit endpoint also drops the
|
||||
/// inherited `DOCKER_HOST` / `DOCKER_CONTEXT`, which would conflict.
|
||||
pub(crate) fn apply(&self, cmd: &mut Command) {
|
||||
if *self != Self::Default {
|
||||
cmd.env_remove("DOCKER_HOST").env_remove("DOCKER_CONTEXT").env_remove("DOCKER_TLS_VERIFY");
|
||||
}
|
||||
cmd.args(self.global_args());
|
||||
}
|
||||
|
||||
/// The same selection as environment variables, for docker command lines run by
|
||||
/// others (run configurations). An empty value clears an inherited variable: the
|
||||
/// CLI treats `DOCKER_HOST=""` as unset.
|
||||
pub fn env_vars(&self) -> BTreeMap<String, String> {
|
||||
let mut env = BTreeMap::new();
|
||||
let mut set = |k: &str, v: String| {
|
||||
env.insert(k.to_owned(), v);
|
||||
};
|
||||
match self {
|
||||
Self::Default => {}
|
||||
Self::Socket { path } => {
|
||||
let path = path.trim();
|
||||
set("DOCKER_HOST", if path.contains("://") { path.to_owned() } else { format!("unix://{path}") });
|
||||
set("DOCKER_CONTEXT", String::new());
|
||||
set("DOCKER_TLS_VERIFY", String::new());
|
||||
}
|
||||
Self::Tcp { host, tls_cert_dir } => {
|
||||
let host = host.trim();
|
||||
set("DOCKER_HOST", if host.contains("://") { host.to_owned() } else { format!("tcp://{host}") });
|
||||
set("DOCKER_CONTEXT", String::new());
|
||||
match tls_cert_dir.as_deref().map(str::trim).filter(|d| !d.is_empty()) {
|
||||
// `DOCKER_CERT_PATH` holds `ca.pem`, `cert.pem` and `key.pem`, as `global_args` expects.
|
||||
Some(dir) => {
|
||||
set("DOCKER_TLS_VERIFY", "1".into());
|
||||
set("DOCKER_CERT_PATH", dir.to_owned());
|
||||
}
|
||||
None => set("DOCKER_TLS_VERIFY", String::new()),
|
||||
}
|
||||
}
|
||||
Self::Context { name } => {
|
||||
set("DOCKER_CONTEXT", name.trim().to_owned());
|
||||
set("DOCKER_HOST", String::new());
|
||||
set("DOCKER_TLS_VERIFY", String::new());
|
||||
}
|
||||
}
|
||||
env
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> IdeResult<()> {
|
||||
let empty = match self {
|
||||
Self::Default => false,
|
||||
Self::Socket { path } => path.trim().is_empty(),
|
||||
Self::Tcp { host, .. } => host.trim().is_empty(),
|
||||
Self::Context { name } => name.trim().is_empty() || name.trim().starts_with('-'),
|
||||
};
|
||||
if empty { Err(IdeError::invalid("the Docker connection needs a socket, host or context")) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerConnection {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub endpoint: DockerEndpoint,
|
||||
}
|
||||
|
||||
/// A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerRegistry {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// `docker.io`, `ghcr.io`, `registry.example.com:5000`.
|
||||
pub address: String,
|
||||
#[serde(default)]
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerSettings {
|
||||
#[serde(default = "default_connections")]
|
||||
pub connections: Vec<DockerConnection>,
|
||||
#[serde(default)]
|
||||
pub registries: Vec<DockerRegistry>,
|
||||
}
|
||||
|
||||
impl Default for DockerSettings {
|
||||
fn default() -> Self {
|
||||
Self { connections: default_connections(), registries: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Before anything is configured the CLI's own daemon is shown, as before connections existed.
|
||||
fn default_connections() -> Vec<DockerConnection> {
|
||||
vec![DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default }]
|
||||
}
|
||||
|
||||
const SETTINGS_FILE: &str = "docker.json";
|
||||
const PASSWORDS_FILE: &str = "docker-passwords.json";
|
||||
|
||||
pub fn load_settings(data_dir: &Path) -> DockerSettings {
|
||||
match std::fs::read(data_dir.join(SETTINGS_FILE)) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
|
||||
tracing::warn!("{SETTINGS_FILE}: {e}");
|
||||
DockerSettings::default()
|
||||
}),
|
||||
Err(_) => DockerSettings::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save_settings(data_dir: &Path, settings: &DockerSettings) -> IdeResult<()> {
|
||||
for c in &settings.connections {
|
||||
if c.id.is_empty() || c.name.trim().is_empty() {
|
||||
return Err(IdeError::invalid("every Docker connection needs a name"));
|
||||
}
|
||||
c.endpoint.validate()?;
|
||||
}
|
||||
for r in &settings.registries {
|
||||
if r.id.is_empty() || r.address.trim().is_empty() {
|
||||
return Err(IdeError::invalid("every Docker registry needs an address"));
|
||||
}
|
||||
}
|
||||
let bytes = serde_json::to_vec_pretty(settings).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
write_file(&data_dir.join(SETTINGS_FILE), &bytes, false)?;
|
||||
// Forget passwords of registries that are gone.
|
||||
let mut passwords = read_passwords(data_dir);
|
||||
let before = passwords.len();
|
||||
passwords.retain(|id, _| settings.registries.iter().any(|r| &r.id == id));
|
||||
if passwords.len() != before { write_passwords(data_dir, &passwords) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn read_passwords(data_dir: &Path) -> BTreeMap<String, String> {
|
||||
std::fs::read(data_dir.join(PASSWORDS_FILE)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn write_passwords(data_dir: &Path, all: &BTreeMap<String, String>) -> IdeResult<()> {
|
||||
let bytes = serde_json::to_vec_pretty(all).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
write_file(&data_dir.join(PASSWORDS_FILE), &bytes, true)
|
||||
}
|
||||
|
||||
pub fn registry_password(data_dir: &Path, id: &str) -> Option<String> {
|
||||
read_passwords(data_dir).remove(id)
|
||||
}
|
||||
|
||||
/// Saves (or with `None` forgets) the password of registry `id`.
|
||||
pub fn set_registry_password(data_dir: &Path, id: &str, password: Option<&str>) -> IdeResult<()> {
|
||||
let mut all = read_passwords(data_dir);
|
||||
match password {
|
||||
Some(p) => all.insert(id.to_owned(), p.to_owned()),
|
||||
None => all.remove(id),
|
||||
};
|
||||
write_passwords(data_dir, &all)
|
||||
}
|
||||
|
||||
fn write_file(path: &Path, bytes: &[u8], private: bool) -> IdeResult<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
if private {
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = private;
|
||||
std::io::Write::write_all(&mut options.open(&tmp)?, bytes)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Canonical registry host: no scheme or path; Docker Hub's aliases become `docker.io`.
|
||||
pub fn registry_host(address: &str) -> String {
|
||||
let a = address.trim();
|
||||
let a = a.split_once("://").map_or(a, |(_, rest)| rest);
|
||||
let host = a.split('/').next().unwrap_or_default().to_ascii_lowercase();
|
||||
match host.as_str() {
|
||||
"index.docker.io" | "registry-1.docker.io" | "registry.hub.docker.com" | "hub.docker.com" => "docker.io".into(),
|
||||
_ => host,
|
||||
}
|
||||
}
|
||||
|
||||
/// Registry host an image reference pulls from (`postgres:16` → `docker.io`).
|
||||
pub fn reference_registry(reference: &str) -> String {
|
||||
match reference.split_once('/') {
|
||||
Some((first, _)) if first.contains('.') || first.contains(':') || first == "localhost" => registry_host(first),
|
||||
_ => "docker.io".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Credentials for a `docker login`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RegistryAuth {
|
||||
pub address: String,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
/// The saved registry (with a password) matching `reference`, if any.
|
||||
pub fn auth_for(data_dir: &Path, reference: &str) -> Option<RegistryAuth> {
|
||||
let host = reference_registry(reference);
|
||||
let settings = load_settings(data_dir);
|
||||
let registry =
|
||||
settings.registries.into_iter().find(|r| registry_host(&r.address) == host && !r.username.is_empty())?;
|
||||
let password = registry_password(data_dir, ®istry.id)?;
|
||||
Some(RegistryAuth { address: registry.address, username: registry.username, password })
|
||||
}
|
||||
|
||||
/// A throwaway docker config directory: logins happen there, never in the user's
|
||||
/// `~/.docker/config.json`. Contexts are copied so a context endpoint still resolves.
|
||||
pub(crate) struct TempConfig {
|
||||
pub dir: PathBuf,
|
||||
}
|
||||
|
||||
impl TempConfig {
|
||||
pub fn new() -> IdeResult<Self> {
|
||||
let nanos =
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||
let dir = std::env::temp_dir().join(format!("openidea-docker-{}-{nanos}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
|
||||
}
|
||||
if let Some(contexts) = user_config_dir().map(|d| d.join("contexts")).filter(|d| d.is_dir()) {
|
||||
let _ = copy_dir(&contexts, &dir.join("contexts"));
|
||||
}
|
||||
Ok(Self { dir })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempConfig {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
fn user_config_dir() -> Option<PathBuf> {
|
||||
if let Some(dir) = std::env::var_os("DOCKER_CONFIG") {
|
||||
return Some(PathBuf::from(dir));
|
||||
}
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })?;
|
||||
Some(PathBuf::from(home).join(".docker"))
|
||||
}
|
||||
|
||||
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(to)?;
|
||||
for e in std::fs::read_dir(from)?.flatten() {
|
||||
let target = to.join(e.file_name());
|
||||
if e.file_type()?.is_dir() {
|
||||
copy_dir(&e.path(), &target)?;
|
||||
} else {
|
||||
std::fs::copy(e.path(), target)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn endpoint_args() {
|
||||
assert!(DockerEndpoint::Default.global_args().is_empty());
|
||||
assert_eq!(
|
||||
DockerEndpoint::Socket { path: "/var/run/docker.sock".into() }.global_args(),
|
||||
["--host", "unix:///var/run/docker.sock"]
|
||||
);
|
||||
let tls = DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: Some("/certs".into()) }.global_args();
|
||||
assert_eq!(tls[..3], ["--host", "tcp://build:2376", "--tlsverify"]);
|
||||
assert!(tls.contains(&Path::new("/certs").join("key.pem").to_string_lossy().into_owned()));
|
||||
assert_eq!(
|
||||
DockerEndpoint::Tcp { host: "ssh://me@box".into(), tls_cert_dir: Some(" ".into()) }.global_args(),
|
||||
["--host", "ssh://me@box"]
|
||||
);
|
||||
assert_eq!(DockerEndpoint::Context { name: "orbstack".into() }.global_args(), ["--context", "orbstack"]);
|
||||
assert!(DockerEndpoint::Context { name: "--x".into() }.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_env() {
|
||||
assert!(DockerEndpoint::Default.env_vars().is_empty());
|
||||
let socket = DockerEndpoint::Socket { path: "/var/run/docker.sock".into() }.env_vars();
|
||||
assert_eq!(socket["DOCKER_HOST"], "unix:///var/run/docker.sock");
|
||||
assert_eq!(socket["DOCKER_CONTEXT"], "");
|
||||
let tls = DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: Some("/certs".into()) }.env_vars();
|
||||
assert_eq!(
|
||||
(tls["DOCKER_HOST"].as_str(), tls["DOCKER_TLS_VERIFY"].as_str(), tls["DOCKER_CERT_PATH"].as_str()),
|
||||
("tcp://build:2376", "1", "/certs")
|
||||
);
|
||||
let ssh = DockerEndpoint::Tcp { host: "ssh://me@box".into(), tls_cert_dir: None }.env_vars();
|
||||
assert_eq!((ssh["DOCKER_HOST"].as_str(), ssh["DOCKER_TLS_VERIFY"].as_str()), ("ssh://me@box", ""));
|
||||
assert!(!ssh.contains_key("DOCKER_CERT_PATH"));
|
||||
let ctx = DockerEndpoint::Context { name: " orbstack ".into() }.env_vars();
|
||||
assert_eq!((ctx["DOCKER_CONTEXT"].as_str(), ctx["DOCKER_HOST"].as_str()), ("orbstack", ""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registries_match_references() {
|
||||
assert_eq!(reference_registry("postgres:16"), "docker.io");
|
||||
assert_eq!(reference_registry("library/postgres"), "docker.io");
|
||||
assert_eq!(reference_registry("ghcr.io/org/app:1"), "ghcr.io");
|
||||
assert_eq!(reference_registry("localhost:5000/app"), "localhost:5000");
|
||||
assert_eq!(registry_host("https://index.docker.io/v1/"), "docker.io");
|
||||
assert_eq!(registry_host("GHCR.io"), "ghcr.io");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_round_trip_and_passwords() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
assert_eq!(load_settings(dir).connections[0].endpoint, DockerEndpoint::Default);
|
||||
let settings = DockerSettings {
|
||||
connections: vec![DockerConnection {
|
||||
id: "c1".into(),
|
||||
name: "Build box".into(),
|
||||
endpoint: DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: None },
|
||||
}],
|
||||
registries: vec![DockerRegistry {
|
||||
id: "r1".into(),
|
||||
name: "GHCR".into(),
|
||||
address: "ghcr.io".into(),
|
||||
username: "me".into(),
|
||||
}],
|
||||
};
|
||||
save_settings(dir, &settings).unwrap();
|
||||
assert_eq!(load_settings(dir), settings);
|
||||
set_registry_password(dir, "r1", Some("s3cret")).unwrap();
|
||||
let auth = auth_for(dir, "ghcr.io/org/app").unwrap();
|
||||
assert_eq!((auth.username.as_str(), auth.password.as_str()), ("me", "s3cret"));
|
||||
assert!(auth_for(dir, "postgres").is_none());
|
||||
save_settings(dir, &DockerSettings { registries: Vec::new(), ..settings }).unwrap();
|
||||
assert_eq!(registry_password(dir, "r1"), None);
|
||||
// An empty list stays empty (the default connection is only for a missing file).
|
||||
save_settings(dir, &DockerSettings { connections: Vec::new(), registries: Vec::new() }).unwrap();
|
||||
assert!(load_settings(dir).connections.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@
|
||||
//!
|
||||
//! Every function blocks; callers run them off the UI / command threads.
|
||||
|
||||
mod connection;
|
||||
mod model;
|
||||
mod process;
|
||||
|
||||
pub use connection::*;
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
@@ -61,21 +63,38 @@ pub fn docker_executable() -> Option<PathBuf> {
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Environment for docker command lines a run configuration launches: the endpoint's
|
||||
/// variables plus a `PATH` that starts with docker's directory (GUI apps on macOS
|
||||
/// lack the usual install locations), so `docker` / `docker compose` resolve.
|
||||
pub fn run_env(ep: &DockerEndpoint) -> std::collections::BTreeMap<String, String> {
|
||||
let mut env = ep.env_vars();
|
||||
if let Some(dir) = docker_executable().as_deref().and_then(Path::parent) {
|
||||
let current = std::env::var_os("PATH").unwrap_or_default();
|
||||
let mut dirs: Vec<PathBuf> = vec![dir.to_path_buf()];
|
||||
dirs.extend(std::env::split_paths(¤t).filter(|d| d != dir));
|
||||
if let Ok(path) = std::env::join_paths(dirs) {
|
||||
env.insert("PATH".into(), path.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
env
|
||||
}
|
||||
|
||||
fn binary() -> IdeResult<PathBuf> {
|
||||
docker_executable()
|
||||
.ok_or_else(|| IdeError::unavailable("docker executable not found; install Docker and make sure it is on PATH"))
|
||||
}
|
||||
|
||||
fn command(args: &[&str]) -> IdeResult<Command> {
|
||||
fn command(ep: &DockerEndpoint, args: &[&str]) -> IdeResult<Command> {
|
||||
let mut cmd = Command::new(binary()?);
|
||||
ep.apply(&mut cmd);
|
||||
cmd.args(args).env("DOCKER_CLI_HINTS", "false").env("NO_COLOR", "1");
|
||||
tracing::debug!(?args, "docker");
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
/// Runs a docker command, mapping a non-zero exit to an error with docker's message.
|
||||
fn run(args: &[&str], timeout: Duration) -> IdeResult<String> {
|
||||
let out = process::run(command(args)?, timeout, None)?;
|
||||
fn run(ep: &DockerEndpoint, args: &[&str], timeout: Duration) -> IdeResult<String> {
|
||||
let out = process::run(command(ep, args)?, timeout, None)?;
|
||||
if out.success { Ok(out.stdout) } else { Err(failure(args, &out.stderr, &out.stdout)) }
|
||||
}
|
||||
|
||||
@@ -94,8 +113,8 @@ fn failure(args: &[&str], stderr: &str, stdout: &str) -> IdeError {
|
||||
}
|
||||
|
||||
/// Whether docker can be used right now.
|
||||
pub fn availability() -> DockerAvailability {
|
||||
let Ok(cmd) = command(&["version", "--format", "{{json .}}"]) else {
|
||||
pub fn availability(ep: &DockerEndpoint) -> DockerAvailability {
|
||||
let Ok(cmd) = command(ep, &["version", "--format", "{{json .}}"]) else {
|
||||
return DockerAvailability::NotInstalled;
|
||||
};
|
||||
match process::run(cmd, Duration::from_secs(15), None) {
|
||||
@@ -105,8 +124,8 @@ pub fn availability() -> DockerAvailability {
|
||||
}
|
||||
|
||||
/// Availability plus containers, images, volumes and networks (listed in parallel).
|
||||
pub fn snapshot() -> DockerSnapshot {
|
||||
let availability = availability();
|
||||
pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
|
||||
let availability = availability(ep);
|
||||
let executable = docker_executable().map(|p| ide_core::ipc_path::to_ipc(&p));
|
||||
let mut snap = DockerSnapshot {
|
||||
availability,
|
||||
@@ -116,16 +135,17 @@ pub fn snapshot() -> DockerSnapshot {
|
||||
volumes: Vec::new(),
|
||||
networks: Vec::new(),
|
||||
errors: Vec::new(),
|
||||
global_args: ep.global_args(),
|
||||
};
|
||||
if !matches!(snap.availability, DockerAvailability::Ready { .. }) {
|
||||
return snap;
|
||||
}
|
||||
const FMT: &str = "{{json .}}";
|
||||
let (containers, images, volumes, networks) = std::thread::scope(|s| {
|
||||
let c = s.spawn(|| run(&["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
|
||||
let i = s.spawn(|| run(&["image", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
let v = s.spawn(|| run(&["volume", "ls", "--format", FMT], QUICK));
|
||||
let n = s.spawn(|| run(&["network", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
|
||||
let i = s.spawn(|| run(ep, &["image", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
let v = s.spawn(|| run(ep, &["volume", "ls", "--format", FMT], QUICK));
|
||||
let n = s.spawn(|| run(ep, &["network", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
let join = |h: std::thread::ScopedJoinHandle<'_, IdeResult<String>>| {
|
||||
h.join().unwrap_or_else(|_| Err(IdeError::internal("docker listing panicked")))
|
||||
};
|
||||
@@ -178,13 +198,13 @@ impl ContainerOp {
|
||||
}
|
||||
|
||||
/// Starts / stops / … the containers `ids`.
|
||||
pub fn container_op(ids: &[String], op: ContainerOp) -> IdeResult<()> {
|
||||
pub fn container_op(ep: &DockerEndpoint, ids: &[String], op: ContainerOp) -> IdeResult<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut args = vec!["container", op.verb()];
|
||||
args.extend(ids.iter().map(String::as_str));
|
||||
run(&args, LIFECYCLE).map(drop)
|
||||
run(ep, &args, LIFECYCLE).map(drop)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -208,7 +228,7 @@ impl DockerObject {
|
||||
}
|
||||
|
||||
/// `docker <object> rm` (`force`: stop running containers / untag used images first).
|
||||
pub fn remove(object: DockerObject, ids: &[String], force: bool) -> IdeResult<()> {
|
||||
pub fn remove(ep: &DockerEndpoint, object: DockerObject, ids: &[String], force: bool) -> IdeResult<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -217,12 +237,12 @@ pub fn remove(object: DockerObject, ids: &[String], force: bool) -> IdeResult<()
|
||||
args.push("--force");
|
||||
}
|
||||
args.extend(ids.iter().map(String::as_str));
|
||||
run(&args, LIFECYCLE).map(drop)
|
||||
run(ep, &args, LIFECYCLE).map(drop)
|
||||
}
|
||||
|
||||
/// `docker inspect` of one object, pretty-printed.
|
||||
pub fn inspect(object: DockerObject, id: &str) -> IdeResult<String> {
|
||||
let out = run(&["inspect", "--type", object.noun(), id], QUICK)?;
|
||||
pub fn inspect(ep: &DockerEndpoint, object: DockerObject, id: &str) -> IdeResult<String> {
|
||||
let out = run(ep, &["inspect", "--type", object.noun(), id], QUICK)?;
|
||||
match serde_json::from_str::<serde_json::Value>(&out) {
|
||||
// A one-element array for a single id: show the object itself.
|
||||
Ok(serde_json::Value::Array(mut items)) if items.len() == 1 => {
|
||||
@@ -236,6 +256,7 @@ pub fn inspect(object: DockerObject, id: &str) -> IdeResult<String> {
|
||||
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
|
||||
/// until it ends or `cancel` fires.
|
||||
pub fn logs(
|
||||
ep: &DockerEndpoint,
|
||||
id: &str,
|
||||
tail: u32,
|
||||
follow: bool,
|
||||
@@ -252,16 +273,16 @@ pub fn logs(
|
||||
args.push("--timestamps");
|
||||
}
|
||||
args.push(id);
|
||||
let (ok, stderr) = process::stream(command(&args)?, cancel, &mut |stream, text| {
|
||||
let (ok, stderr) = process::stream(command(ep, &args)?, cancel, &mut |stream, text| {
|
||||
on_line(DockerLogLine { stderr: stream == Stream::Stderr, text })
|
||||
})?;
|
||||
if ok { Ok(()) } else { Err(failure(&args, &stderr.join("\n"), "")) }
|
||||
}
|
||||
|
||||
/// Follows `docker events` until it ends (daemon gone) or `cancel` fires.
|
||||
pub fn watch_events(cancel: &CancellationToken, on_event: &dyn Fn(DockerEvent)) -> IdeResult<()> {
|
||||
pub fn watch_events(ep: &DockerEndpoint, cancel: &CancellationToken, on_event: &dyn Fn(DockerEvent)) -> IdeResult<()> {
|
||||
let args = ["events", "--format", "{{json .}}"];
|
||||
let (ok, stderr) = process::stream(command(&args)?, cancel, &mut |stream, line| {
|
||||
let (ok, stderr) = process::stream(command(ep, &args)?, cancel, &mut |stream, line| {
|
||||
if stream == Stream::Stdout
|
||||
&& let Some(e) = parse_event(&line)
|
||||
{
|
||||
@@ -272,9 +293,19 @@ pub fn watch_events(cancel: &CancellationToken, on_event: &dyn Fn(DockerEvent))
|
||||
}
|
||||
|
||||
/// Runs a long docker command (pull, prune, compose…), streaming its output lines.
|
||||
fn run_streaming(args: &[&str], cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
fn run_streaming(
|
||||
ep: &DockerEndpoint,
|
||||
config: Option<&Path>,
|
||||
args: &[&str],
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
on_output(format!("docker {}", args.join(" ")));
|
||||
let (ok, stderr) = process::stream(command(args)?, cancel, &mut |_, line| {
|
||||
let mut cmd = command(ep, args)?;
|
||||
if let Some(dir) = config {
|
||||
cmd.env("DOCKER_CONFIG", dir);
|
||||
}
|
||||
let (ok, stderr) = process::stream(cmd, cancel, &mut |_, line| {
|
||||
if !line.trim().is_empty() {
|
||||
on_output(line);
|
||||
}
|
||||
@@ -282,13 +313,57 @@ fn run_streaming(args: &[&str], cancel: &CancellationToken, on_output: &dyn Fn(S
|
||||
if ok { Ok(()) } else { Err(failure(args, &stderr.join("\n"), "")) }
|
||||
}
|
||||
|
||||
/// `docker pull <reference>`.
|
||||
pub fn pull(reference: &str, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
/// `docker pull <reference>`; with `auth` it logs in to the registry first, in a
|
||||
/// throwaway config directory (the user's docker config stays untouched).
|
||||
pub fn pull(
|
||||
ep: &DockerEndpoint,
|
||||
reference: &str,
|
||||
auth: Option<&RegistryAuth>,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let reference = reference.trim();
|
||||
if reference.is_empty() || reference.starts_with('-') {
|
||||
return Err(IdeError::invalid("enter an image name, e.g. postgres:16"));
|
||||
}
|
||||
run_streaming(&["pull", reference], cancel, on_output)
|
||||
let Some(auth) = auth else { return run_streaming(ep, None, &["pull", reference], cancel, on_output) };
|
||||
let config = TempConfig::new()?;
|
||||
on_output(format!("Logging in to {} as {}", auth.address, auth.username));
|
||||
login_in(ep, &config.dir, auth, Some(cancel))?;
|
||||
run_streaming(ep, Some(&config.dir), &["pull", reference], cancel, on_output)
|
||||
}
|
||||
|
||||
/// `docker login` with `auth`; returns docker's answer (`Login Succeeded`). Nothing is
|
||||
/// stored in the user's docker config.
|
||||
pub fn login(ep: &DockerEndpoint, auth: &RegistryAuth) -> IdeResult<String> {
|
||||
let config = TempConfig::new()?;
|
||||
login_in(ep, &config.dir, auth, None)
|
||||
}
|
||||
|
||||
fn login_in(
|
||||
ep: &DockerEndpoint,
|
||||
config: &Path,
|
||||
auth: &RegistryAuth,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<String> {
|
||||
let host = registry_host(&auth.address);
|
||||
let user = auth.username.trim();
|
||||
if host.is_empty() || host.starts_with('-') || user.is_empty() || user.starts_with('-') {
|
||||
return Err(IdeError::invalid("the registry needs an address and a username"));
|
||||
}
|
||||
let mut args = vec!["login", "--username", user, "--password-stdin"];
|
||||
// Docker Hub is the CLI's default server.
|
||||
if host != "docker.io" {
|
||||
args.push(&host);
|
||||
}
|
||||
let mut cmd = command(ep, &args)?;
|
||||
cmd.env("DOCKER_CONFIG", config);
|
||||
let out = process::run_with_input(cmd, QUICK, cancel, Some(&auth.password))?;
|
||||
if out.success {
|
||||
Ok(out.stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or("Login Succeeded").to_owned())
|
||||
} else {
|
||||
Err(failure(&args, &out.stderr, &out.stdout))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -306,7 +381,12 @@ pub enum PruneTarget {
|
||||
}
|
||||
|
||||
/// `docker <object> prune --force`.
|
||||
pub fn prune(target: PruneTarget, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
pub fn prune(
|
||||
ep: &DockerEndpoint,
|
||||
target: PruneTarget,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let args: &[&str] = match target {
|
||||
PruneTarget::Containers => &["container", "prune", "--force"],
|
||||
PruneTarget::Images => &["image", "prune", "--force"],
|
||||
@@ -315,7 +395,7 @@ pub fn prune(target: PruneTarget, cancel: &CancellationToken, on_output: &dyn Fn
|
||||
PruneTarget::Networks => &["network", "prune", "--force"],
|
||||
PruneTarget::System => &["system", "prune", "--force"],
|
||||
};
|
||||
run_streaming(args, cancel, on_output)
|
||||
run_streaming(ep, None, args, cancel, on_output)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -332,6 +412,7 @@ pub enum ComposeOp {
|
||||
/// labels. `files` / `working_dir` (from the labels too) are passed when they still
|
||||
/// exist, so commands that need the model keep working.
|
||||
pub fn compose_op(
|
||||
ep: &DockerEndpoint,
|
||||
project: &str,
|
||||
files: &[String],
|
||||
working_dir: Option<&str>,
|
||||
@@ -357,5 +438,5 @@ pub fn compose_op(
|
||||
ComposeOp::Restart => "restart",
|
||||
ComposeOp::Down => "down",
|
||||
});
|
||||
run_streaming(&args, cancel, on_output)
|
||||
run_streaming(ep, None, &args, cancel, on_output)
|
||||
}
|
||||
@@ -105,6 +105,9 @@ pub struct DockerSnapshot {
|
||||
pub networks: Vec<DockerNetwork>,
|
||||
/// Lists that failed although the daemon answered (shown, not fatal).
|
||||
pub errors: Vec<String>,
|
||||
/// Global CLI options selecting the connection's daemon (for `docker exec` in a terminal).
|
||||
#[serde(default)]
|
||||
pub global_args: Vec<String>,
|
||||
}
|
||||
|
||||
/// One relevant `docker events` entry.
|
||||
|
||||
@@ -25,11 +25,7 @@ fn prepare(cmd: &mut Command) {
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x0800_0000);
|
||||
}
|
||||
ide_core::process::no_window(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
@@ -64,9 +60,26 @@ fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<Str
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
run_with_input(cmd, timeout, cancel, None)
|
||||
}
|
||||
|
||||
/// [`run`] with `input` written to the child's stdin (e.g. `--password-stdin`).
|
||||
pub(crate) fn run_with_input(
|
||||
mut cmd: Command,
|
||||
timeout: Duration,
|
||||
cancel: Option<&CancellationToken>,
|
||||
input: Option<&str>,
|
||||
) -> IdeResult<Output> {
|
||||
prepare(&mut cmd);
|
||||
if input.is_some() {
|
||||
cmd.stdin(Stdio::piped());
|
||||
}
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
if let (Some(text), Some(mut stdin)) = (input, child.stdin.take()) {
|
||||
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
|
||||
let _ = std::io::Write::write_all(&mut stdin, text.as_bytes());
|
||||
}
|
||||
let out = child.stdout.take().map(read_all);
|
||||
let err = child.stderr.take().map(read_all);
|
||||
let deadline = Instant::now() + timeout;
|
||||
|
||||
@@ -25,11 +25,7 @@ fn prepare(cmd: &mut Command) {
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x0800_0000);
|
||||
}
|
||||
ide_core::process::no_window(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
|
||||
@@ -181,10 +181,10 @@ impl IndexData {
|
||||
Some(old)
|
||||
}
|
||||
|
||||
/// Removes every file at or below `dir`; returns their relative paths.
|
||||
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<String> {
|
||||
/// Removes every file at or below `dir`; returns their paths.
|
||||
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<PathBuf> {
|
||||
let doomed: Vec<PathBuf> = self.by_path.keys().filter(|p| p.starts_with(dir)).cloned().collect();
|
||||
doomed.iter().filter_map(|p| self.remove(p)).map(|e| e.rel.into_string()).collect()
|
||||
doomed.into_iter().filter(|p| self.remove(p).is_some()).collect()
|
||||
}
|
||||
|
||||
/// Releases spare capacity (after large deletions).
|
||||
@@ -235,7 +235,7 @@ mod tests {
|
||||
assert_eq!((d.file_count, d.symbol_count), (1, 5));
|
||||
d.insert(entry("d.rs", 0));
|
||||
assert_eq!(d.files.len(), 2, "slot reused");
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")), vec!["a/b.rs".to_owned()]);
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")), vec![PathBuf::from("/r/a/b.rs")]);
|
||||
assert_eq!((d.file_count, d.symbol_count), (1, 0));
|
||||
let e = d.get(Path::new("/r/d.rs")).unwrap();
|
||||
assert_eq!((e.name(), e.dir()), ("d.rs", ""));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Which paths belong in the index: `.gitignore`/`.ignore` rules (via the
|
||||
//! `ignore` crate) plus the user's `files.exclude` globs.
|
||||
//! `ignore` crate) plus the user's `files.exclude` globs, below the project root
|
||||
//! and the extra content roots (Project Structure).
|
||||
|
||||
use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
|
||||
use ignore::gitignore::{Gitignore, GitignoreBuilder};
|
||||
@@ -9,15 +10,50 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
/// VCS metadata directories are never indexed.
|
||||
const ALWAYS_SKIP: &[&str] = &[".git", ".hg", ".svn", ".jj", ".DS_Store"];
|
||||
/// VCS metadata directories are never indexed, whatever the ignored names say.
|
||||
const ALWAYS_SKIP: &[&str] = &[".git", ".hg", ".svn", ".jj"];
|
||||
|
||||
pub(crate) struct PathFilter {
|
||||
root: PathBuf,
|
||||
/// Content roots outside `root`, indexed as `<folder name>/<path>`.
|
||||
extra: Vec<ExtraRoot>,
|
||||
excludes: GlobSet,
|
||||
/// Root-level ignore files, for paths reported by the watcher (the walker
|
||||
/// applies nested ignore files itself).
|
||||
gitignore: Gitignore,
|
||||
/// What the filter was built from: `(extra roots, exclude globs)`.
|
||||
config: (Vec<PathBuf>, Vec<String>),
|
||||
}
|
||||
|
||||
struct ExtraRoot {
|
||||
path: PathBuf,
|
||||
/// Shown before the paths inside it (`shared-lib/src/x.rs`).
|
||||
name: String,
|
||||
gitignore: Gitignore,
|
||||
}
|
||||
|
||||
fn root_ignores(root: &Path) -> Gitignore {
|
||||
let mut gi = GitignoreBuilder::new(root);
|
||||
for f in [".gitignore", ".ignore", ".git/info/exclude"] {
|
||||
let path = root.join(f);
|
||||
if path.is_file()
|
||||
&& let Some(e) = gi.add(&path)
|
||||
{
|
||||
tracing::debug!("{}: {e}", path.display());
|
||||
}
|
||||
}
|
||||
gi.build().unwrap_or_else(|_| Gitignore::empty())
|
||||
}
|
||||
|
||||
fn rel_string(rel: &Path) -> String {
|
||||
let mut out = String::new();
|
||||
for c in rel.components() {
|
||||
if !out.is_empty() {
|
||||
out.push('/');
|
||||
}
|
||||
out.push_str(&c.as_os_str().to_string_lossy());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -32,9 +68,9 @@ pub(crate) fn mtime_of(meta: &std::fs::Metadata) -> u64 {
|
||||
}
|
||||
|
||||
impl PathFilter {
|
||||
pub(crate) fn new(root: &Path, excludes: &[String]) -> Self {
|
||||
pub(crate) fn new(root: &Path, extra_roots: &[PathBuf], exclude_globs: &[String]) -> Self {
|
||||
let mut set = GlobSetBuilder::new();
|
||||
for raw in excludes {
|
||||
for raw in exclude_globs {
|
||||
let p = raw.trim().trim_end_matches('/');
|
||||
let anchored = p.starts_with('/');
|
||||
let p = p.trim_start_matches("./").trim_start_matches('/');
|
||||
@@ -55,34 +91,76 @@ impl PathFilter {
|
||||
}
|
||||
}
|
||||
let excludes = set.build().unwrap_or_else(|_| GlobSet::empty());
|
||||
let mut gi = GitignoreBuilder::new(root);
|
||||
for f in [".gitignore", ".ignore", ".git/info/exclude"] {
|
||||
let path = root.join(f);
|
||||
if path.is_file()
|
||||
&& let Some(e) = gi.add(&path)
|
||||
{
|
||||
tracing::debug!("{}: {e}", path.display());
|
||||
let mut extra: Vec<ExtraRoot> = Vec::new();
|
||||
for r in extra_roots {
|
||||
let path = dunce::canonicalize(r).unwrap_or_else(|_| r.clone());
|
||||
let nested = path.starts_with(root)
|
||||
|| root.starts_with(&path)
|
||||
|| extra.iter().any(|e| path.starts_with(&e.path) || e.path.starts_with(&path));
|
||||
if nested || !path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
extra.push(ExtraRoot { gitignore: root_ignores(&path), name, path });
|
||||
}
|
||||
let gitignore = gi.build().unwrap_or_else(|_| Gitignore::empty());
|
||||
Self { root: root.to_owned(), excludes, gitignore }
|
||||
Self {
|
||||
root: root.to_owned(),
|
||||
extra,
|
||||
excludes,
|
||||
gitignore: root_ignores(root),
|
||||
config: (extra_roots.to_vec(), exclude_globs.to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the filter was built from these roots and globs.
|
||||
pub(crate) fn same_config(&self, extra_roots: &[PathBuf], excludes: &[String]) -> bool {
|
||||
self.config.0 == extra_roots && self.config.1 == excludes
|
||||
}
|
||||
|
||||
pub(crate) fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// `/`-separated path relative to the root.
|
||||
pub(crate) fn rel(&self, path: &Path) -> Option<String> {
|
||||
let rel = path.strip_prefix(&self.root).ok()?;
|
||||
let mut out = String::new();
|
||||
for c in rel.components() {
|
||||
if !out.is_empty() {
|
||||
out.push('/');
|
||||
}
|
||||
out.push_str(&c.as_os_str().to_string_lossy());
|
||||
/// The project root, then the extra content roots.
|
||||
pub(crate) fn roots(&self) -> impl Iterator<Item = &Path> {
|
||||
std::iter::once(self.root.as_path()).chain(self.extra.iter().map(|e| e.path.as_path()))
|
||||
}
|
||||
|
||||
/// The root containing `path`, its display prefix (`None` for the project root) and ignore rules.
|
||||
fn base_of(&self, path: &Path) -> Option<(&Path, Option<&str>, &Gitignore)> {
|
||||
if path.starts_with(&self.root) {
|
||||
return Some((&self.root, None, &self.gitignore));
|
||||
}
|
||||
(!out.is_empty()).then_some(out)
|
||||
self.extra
|
||||
.iter()
|
||||
.find(|e| path.starts_with(&e.path))
|
||||
.map(|e| (e.path.as_path(), Some(e.name.as_str()), &e.gitignore))
|
||||
}
|
||||
|
||||
/// Whether `path` is (at or) below one of the roots.
|
||||
pub(crate) fn contains(&self, path: &Path) -> bool {
|
||||
self.base_of(path).is_some()
|
||||
}
|
||||
|
||||
/// `/`-separated path relative to its root, as displayed; paths in extra
|
||||
/// content roots start with the root's folder name.
|
||||
pub(crate) fn rel(&self, path: &Path) -> Option<String> {
|
||||
let (base, prefix, _) = self.base_of(path)?;
|
||||
let rel = rel_string(path.strip_prefix(base).ok()?);
|
||||
if rel.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(match prefix {
|
||||
Some(p) => format!("{p}/{rel}"),
|
||||
None => rel,
|
||||
})
|
||||
}
|
||||
|
||||
/// Key of `path` in the persistent store: only files below the project root
|
||||
/// are persisted (extra content roots are rescanned when the project opens).
|
||||
pub(crate) fn store_key(&self, path: &Path) -> Option<String> {
|
||||
let rel = rel_string(path.strip_prefix(&self.root).ok()?);
|
||||
(!rel.is_empty()).then_some(rel)
|
||||
}
|
||||
|
||||
fn excluded_rel(&self, rel: &str) -> bool {
|
||||
@@ -96,7 +174,11 @@ impl PathFilter {
|
||||
/// Whether a path reported by the watcher should be ignored (outside the
|
||||
/// root, inside an excluded/ignored directory, or ignored itself).
|
||||
pub(crate) fn is_excluded(&self, path: &Path, is_dir: bool) -> bool {
|
||||
let Some(rel) = self.rel(path) else { return true };
|
||||
let Some((base, _, gitignore)) = self.base_of(path) else { return true };
|
||||
let rel = path.strip_prefix(base).map(rel_string).unwrap_or_default();
|
||||
if rel.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let mut prefix = String::new();
|
||||
for seg in rel.split('/') {
|
||||
if Self::skip_name(seg) {
|
||||
@@ -110,14 +192,15 @@ impl PathFilter {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
self.gitignore.matched_path_or_any_parents(path, is_dir).is_ignore()
|
||||
gitignore.matched_path_or_any_parents(path, is_dir).is_ignore()
|
||||
}
|
||||
|
||||
/// All indexable files at or below `dir`, walked in parallel.
|
||||
/// Stops early (returning what was found so far) once `cancel` is set.
|
||||
pub(crate) fn walk(&self, dir: &Path, cancel: &AtomicBool) -> Vec<Found> {
|
||||
let (tx, rx) = mpsc::channel::<Vec<Found>>();
|
||||
let root = self.root.clone();
|
||||
let Some((root, _, _)) = self.base_of(dir) else { return Vec::new() };
|
||||
let root = root.to_path_buf();
|
||||
let excludes = self.excludes.clone();
|
||||
let walker = WalkBuilder::new(dir)
|
||||
.hidden(false)
|
||||
@@ -207,7 +290,7 @@ mod tests {
|
||||
touch(&root, f);
|
||||
}
|
||||
std::fs::write(root.join(".gitignore"), "build/\n").unwrap();
|
||||
let filter = PathFilter::new(&root, &["**/node_modules".into(), "target".into(), "docs/**".into()]);
|
||||
let filter = PathFilter::new(&root, &[], &["**/node_modules".into(), "target".into(), "docs/**".into()]);
|
||||
let mut found: Vec<String> =
|
||||
filter.walk(&root, &AtomicBool::new(false)).iter().filter_map(|f| filter.rel(&f.path)).collect();
|
||||
found.sort();
|
||||
@@ -220,4 +303,31 @@ mod tests {
|
||||
assert!(filter.is_excluded(Path::new("/elsewhere/x.rs"), false));
|
||||
assert!(!filter.is_excluded(&root.join("src/new.rs"), false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_content_roots_are_walked_and_prefixed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(dir.path()).unwrap();
|
||||
let (root, shared) = (base.join("app"), base.join("shared-lib"));
|
||||
for f in ["app/src/a.rs", "shared-lib/src/b.rs", "shared-lib/target/gen.rs", "shared-lib/out/x.rs"] {
|
||||
touch(&base, f);
|
||||
}
|
||||
std::fs::write(shared.join(".gitignore"), "out/\n").unwrap();
|
||||
let filter = PathFilter::new(&root, &[shared.clone(), root.join("src")], &["target".into()]);
|
||||
assert_eq!(filter.roots().count(), 2, "roots inside the project are not extra roots");
|
||||
let mut found: Vec<String> = filter
|
||||
.roots()
|
||||
.flat_map(|r| filter.walk(r, &AtomicBool::new(false)))
|
||||
.filter_map(|f| filter.rel(&f.path))
|
||||
.collect();
|
||||
found.sort();
|
||||
assert_eq!(found, ["shared-lib/.gitignore", "shared-lib/src/b.rs", "src/a.rs"]);
|
||||
assert_eq!(filter.store_key(&shared.join("src/b.rs")), None, "extra roots are not persisted");
|
||||
assert_eq!(filter.store_key(&root.join("src/a.rs")).as_deref(), Some("src/a.rs"));
|
||||
assert!(!filter.is_excluded(&shared.join("src/new.rs"), false));
|
||||
assert!(filter.is_excluded(&shared.join("target/y.rs"), false));
|
||||
assert!(filter.is_excluded(&shared.join("out/y.rs"), false));
|
||||
assert!(filter.same_config(&[shared.clone(), root.join("src")], &["target".into()]));
|
||||
assert!(!filter.same_config(&[shared], &["target".into()]));
|
||||
}
|
||||
}
|
||||
@@ -67,14 +67,17 @@ pub struct IndexStatus {
|
||||
pub struct ProjectIndex {
|
||||
shared: Arc<Shared>,
|
||||
worker: Mutex<Option<JoinHandle<()>>>,
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl ProjectIndex {
|
||||
/// Opens (or creates) the persistent index at `cache_dir` and starts a
|
||||
/// background full scan that skips files whose content hash is unchanged.
|
||||
/// `content_roots` are folders outside `root` indexed with it (not persisted).
|
||||
pub fn open(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
content_roots: Vec<PathBuf>,
|
||||
excludes: Vec<String>,
|
||||
languages: Arc<LanguageRegistry>,
|
||||
syntax: Arc<Syntax>,
|
||||
@@ -85,7 +88,7 @@ impl ProjectIndex {
|
||||
return Err(ide_core::IdeError::not_found(format!("{} is not a directory", root.display())));
|
||||
}
|
||||
let store = store::Store::open(cache_dir, &root, &syntax.fingerprint());
|
||||
let filter = filter::PathFilter::new(&root, &excludes);
|
||||
let filter = filter::PathFilter::new(&root, &content_roots, &excludes);
|
||||
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, store));
|
||||
let worker = {
|
||||
let shared = shared.clone();
|
||||
@@ -94,7 +97,25 @@ impl ProjectIndex {
|
||||
.spawn(move || shared.run())
|
||||
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
|
||||
};
|
||||
Ok(Arc::new(Self { shared, worker: Mutex::new(Some(worker)) }))
|
||||
Ok(Arc::new(Self { shared, worker: Mutex::new(Some(worker)), root }))
|
||||
}
|
||||
|
||||
/// Changes what is indexed besides the root (content roots) and the exclude
|
||||
/// globs, rescanning in the background (unchanged files are not re-read).
|
||||
/// Returns whether anything changed.
|
||||
pub fn set_scope(&self, content_roots: Vec<PathBuf>, excludes: Vec<String>) -> bool {
|
||||
if self.shared.filter().same_config(&content_roots, &excludes) {
|
||||
return false;
|
||||
}
|
||||
self.shared.set_filter(filter::PathFilter::new(&self.root, &content_roots, &excludes));
|
||||
self.shared.enqueue(Job::Rescan);
|
||||
true
|
||||
}
|
||||
|
||||
/// File types changed (the registry the index shares was updated): re-parses
|
||||
/// the files whose language under `before` differs from the current one.
|
||||
pub fn languages_changed(&self, before: Arc<LanguageRegistry>) {
|
||||
self.shared.enqueue(Job::Reparse(before));
|
||||
}
|
||||
|
||||
pub fn status(&self) -> IndexStatus {
|
||||
@@ -121,6 +142,11 @@ impl ProjectIndex {
|
||||
matching::find_symbols(&d, &matching::Recents { paths: &recent }, query, filter, limit)
|
||||
}
|
||||
|
||||
/// Symbols named exactly `name` (of `kind`, if given): `.card` selectors for `class="card"`.
|
||||
pub fn symbols_named(&self, name: &str, kind: Option<SymbolKind>, limit: usize) -> Vec<SymbolMatch> {
|
||||
matching::symbols_named(&self.shared.data.read(), name, kind, limit)
|
||||
}
|
||||
|
||||
/// Incrementally re-indexes changed paths (called from the vfs watcher).
|
||||
/// Cheap: the work is queued for the indexing thread.
|
||||
pub fn update(&self, changed: &[PathBuf], removed: &[PathBuf]) {
|
||||
@@ -154,6 +180,26 @@ impl ProjectIndex {
|
||||
self.shared.enqueue(Job::SaveRecent);
|
||||
}
|
||||
|
||||
/// Drops a file from Recent Files (Delete in the ⌘E popup).
|
||||
pub fn remove_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
let before = r.len();
|
||||
r.retain(|p| p != &path);
|
||||
if r.len() == before {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.shared.enqueue(Job::SaveRecent);
|
||||
}
|
||||
|
||||
/// Recently opened files, most recent first.
|
||||
pub fn recent_files(&self) -> Vec<PathBuf> {
|
||||
self.shared.recent.lock().clone()
|
||||
@@ -177,14 +223,15 @@ impl ProjectIndex {
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
self.shared.filter.root()
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// Absolute path inside the root, or `None` for paths outside the project / excluded.
|
||||
/// Absolute path inside the root (or a content root), or `None` for paths outside the project.
|
||||
fn normalize(&self, path: &Path) -> Option<PathBuf> {
|
||||
let root = self.shared.filter.root();
|
||||
let filter = self.shared.filter();
|
||||
let root = &self.root;
|
||||
let path = if path.is_absolute() { path.to_owned() } else { root.join(path) };
|
||||
let path = if path.starts_with(root) {
|
||||
let path = if filter.contains(&path) {
|
||||
path
|
||||
} else {
|
||||
// Watchers / the UI may report non-canonical spellings (`/tmp` vs `/private/tmp`).
|
||||
@@ -196,7 +243,7 @@ impl ProjectIndex {
|
||||
}
|
||||
}
|
||||
};
|
||||
(path.starts_with(root) && path != root).then_some(path)
|
||||
(filter.contains(&path) && filter.rel(&path).is_some()).then_some(path)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
use crate::data::{FileEntry, IndexData, char_mask};
|
||||
use crate::{FileMatch, SymbolFilter, SymbolMatch};
|
||||
use ide_core::SymbolKind;
|
||||
use nucleo_matcher::{Config, Matcher, Utf32Str, Utf32String};
|
||||
use rayon::prelude::*;
|
||||
use std::cell::RefCell;
|
||||
@@ -419,6 +420,33 @@ pub(crate) fn find_symbols(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Symbols named exactly `name` (and of `kind`, when given), by path then position.
|
||||
pub(crate) fn symbols_named(data: &IndexData, name: &str, kind: Option<SymbolKind>, limit: usize) -> Vec<SymbolMatch> {
|
||||
let mask = char_mask(name);
|
||||
let mut out: Vec<SymbolMatch> = data
|
||||
.files
|
||||
.iter()
|
||||
.flatten()
|
||||
.flat_map(|e| {
|
||||
e.symbols.iter().filter(|s| s.mask == mask && &*s.name == name && kind.is_none_or(|k| s.kind == k)).map(
|
||||
move |s| SymbolMatch {
|
||||
name: s.name.to_string(),
|
||||
kind: s.kind,
|
||||
container: s.container.as_deref().map(str::to_owned),
|
||||
path: e.path.clone().into(),
|
||||
rel_path: e.rel.to_string(),
|
||||
range: s.range,
|
||||
score: 0,
|
||||
indices: Vec::new(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path).then_with(|| a.range.cmp(&b.range)));
|
||||
out.truncate(limit);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -37,6 +37,7 @@ impl Fixture {
|
||||
let idx = ProjectIndex::open(
|
||||
&self.root,
|
||||
&self.cache,
|
||||
Vec::new(),
|
||||
vec!["**/node_modules".into(), "**/target".into()],
|
||||
languages,
|
||||
syntax,
|
||||
@@ -192,7 +193,11 @@ fn persistence_skips_unchanged_files_on_reopen() {
|
||||
assert_eq!(idx.status().files, 8);
|
||||
assert_eq!(symbols(&idx, "OrderController", SymbolFilter::Types)[0], "OrderController");
|
||||
assert_eq!(idx.recent_files(), vec![fx.root.join("web/app.py")]);
|
||||
idx.remove_recent(&fx.root.join("web/app.py"));
|
||||
assert!(idx.recent_files().is_empty());
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
}
|
||||
assert!(fx.open().recent_files().is_empty(), "removal is persisted");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
fx.write("src/main.rs", "fn main() {}\nfn renamed_fn() {}\n");
|
||||
std::fs::remove_file(fx.root.join("docs/maintenance.md")).unwrap();
|
||||
@@ -381,3 +386,90 @@ fn synthetic_index_answers_queries() {
|
||||
assert!(!s.find_symbols("PaySe", SymbolFilter::All, 20).is_empty());
|
||||
assert!(s.find_symbols("PaySe", SymbolFilter::Types, 20).iter().all(|m| m.kind == SymbolKind::Class));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_selectors_are_found_by_exact_name() {
|
||||
let f = Fixture::new(&[
|
||||
("web/a.css", ".card { --gap: 1px }\n.cardigan {}\n"),
|
||||
("web/b.scss", ".list { .card { } }\n"),
|
||||
("web/index.html", "<style>.card{}</style>\n<div class=\"card\"></div>\n"),
|
||||
]);
|
||||
let idx = f.open();
|
||||
let found: Vec<(String, u32)> = idx
|
||||
.symbols_named(".card", Some(SymbolKind::Class), 10)
|
||||
.into_iter()
|
||||
.map(|m| (m.rel_path, m.range.start.line))
|
||||
.collect();
|
||||
assert_eq!(found, vec![("web/a.css".into(), 0), ("web/b.scss".into(), 0), ("web/index.html".into(), 0)]);
|
||||
assert_eq!(idx.symbols_named("--gap", None, 10).len(), 1);
|
||||
assert!(idx.symbols_named(".card", Some(SymbolKind::Field), 10).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_roots_and_excludes_change_without_reopening() {
|
||||
let fx = Fixture::new(&[("src/main.rs", "fn alpha() {}\n"), ("src/gen/out.rs", "fn generated() {}\n")]);
|
||||
let shared = fx._dir.path().join("shared-lib");
|
||||
std::fs::create_dir_all(shared.join("src")).unwrap();
|
||||
std::fs::write(shared.join("src/lib.rs"), "fn gamma() {}\n").unwrap();
|
||||
let idx = fx.open();
|
||||
assert!(files(&idx, "lib.rs").is_empty());
|
||||
|
||||
let excludes = vec!["**/node_modules".to_owned(), "**/target".to_owned()];
|
||||
assert!(idx.set_scope(vec![shared.clone()], excludes.clone()));
|
||||
assert!(!idx.set_scope(vec![shared.clone()], excludes.clone()), "unchanged scope");
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(files(&idx, "lib.rs"), ["shared-lib/src/lib.rs"]);
|
||||
let gamma = &idx.find_symbols("gamma", SymbolFilter::All, 5)[0];
|
||||
assert_eq!(gamma.path, dunce::canonicalize(shared.join("src/lib.rs")).unwrap());
|
||||
|
||||
// Files created in a content root are picked up incrementally.
|
||||
std::fs::write(shared.join("src/more.rs"), "fn delta() {}\n").unwrap();
|
||||
idx.update(&[shared.join("src/more.rs")], &[]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(symbols(&idx, "delta", SymbolFilter::All), ["delta"]);
|
||||
|
||||
// A new exclude drops what it matches; removing the root drops its files.
|
||||
let mut more = excludes.clone();
|
||||
more.push("gen".into());
|
||||
idx.set_scope(Vec::new(), more);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(files(&idx, "out.rs").is_empty());
|
||||
assert!(files(&idx, "lib.rs").is_empty());
|
||||
assert_eq!(idx.status().files, 1);
|
||||
drop(idx);
|
||||
|
||||
// Extra roots are not persisted: reopening without them lists only the project.
|
||||
let idx = fx.open();
|
||||
assert!(symbols(&idx, "gamma", SymbolFilter::All).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_type_changes_reparse_affected_files() {
|
||||
let fx = Fixture::new(&[("src/main.rs", "fn alpha() {}\n"), ("src/legacy.inc", "fn beta() {}\n")]);
|
||||
let languages = Arc::new(LanguageRegistry::load(None).unwrap());
|
||||
let idx = ProjectIndex::open(
|
||||
&fx.root,
|
||||
&fx.cache,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
languages.clone(),
|
||||
Arc::new(Syntax::new()),
|
||||
Arc::new(NullSink),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(symbols(&idx, "beta", SymbolFilter::All).is_empty(), "plain text has no symbols");
|
||||
let parsed = idx.shared.parsed.load(Ordering::SeqCst);
|
||||
|
||||
let before = Arc::new(languages.snapshot());
|
||||
let mut ft = ide_language::FileTypes::default();
|
||||
ft.associations.insert(
|
||||
"rust".into(),
|
||||
ide_core::settings::FileTypeAssociation { patterns: vec!["*.inc".into()], ..Default::default() },
|
||||
);
|
||||
assert!(languages.set_file_types(ft));
|
||||
idx.languages_changed(before);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(symbols(&idx, "beta", SymbolFilter::All), ["beta"]);
|
||||
assert_eq!(idx.shared.parsed.load(Ordering::SeqCst), parsed + 1, "only the affected file is re-parsed");
|
||||
}
|
||||
@@ -24,6 +24,11 @@ pub(crate) enum Job {
|
||||
Changed(Vec<PathBuf>),
|
||||
Removed(Vec<PathBuf>),
|
||||
SaveRecent,
|
||||
/// The roots or excludes changed: scan again (unchanged files are kept).
|
||||
Rescan,
|
||||
/// File types changed: re-parse the indexed files whose language under the
|
||||
/// previous registry differs from the current one.
|
||||
Reparse(std::sync::Arc<LanguageRegistry>),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -34,7 +39,7 @@ struct Queue {
|
||||
}
|
||||
|
||||
pub(crate) struct Shared {
|
||||
pub filter: PathFilter,
|
||||
filter: RwLock<std::sync::Arc<PathFilter>>,
|
||||
pub languages: std::sync::Arc<LanguageRegistry>,
|
||||
pub syntax: std::sync::Arc<Syntax>,
|
||||
pub sink: SharedSink,
|
||||
@@ -60,7 +65,7 @@ impl Shared {
|
||||
store: Option<Store>,
|
||||
) -> Self {
|
||||
Self {
|
||||
filter,
|
||||
filter: RwLock::new(std::sync::Arc::new(filter)),
|
||||
languages,
|
||||
syntax,
|
||||
sink,
|
||||
@@ -76,6 +81,14 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn filter(&self) -> std::sync::Arc<PathFilter> {
|
||||
self.filter.read().clone()
|
||||
}
|
||||
|
||||
pub(crate) fn set_filter(&self, filter: PathFilter) {
|
||||
*self.filter.write() = std::sync::Arc::new(filter);
|
||||
}
|
||||
|
||||
pub(crate) fn enqueue(&self, job: Job) {
|
||||
self.queue.lock().jobs.push_back(job);
|
||||
self.wake.notify_one();
|
||||
@@ -150,7 +163,7 @@ impl Shared {
|
||||
|
||||
fn load_persisted(&self) {
|
||||
let Some(store) = &self.store else { return };
|
||||
let root = self.filter.root().to_owned();
|
||||
let root = self.filter().root().to_owned();
|
||||
match store.load() {
|
||||
Ok(records) => {
|
||||
let entries: Vec<FileEntry> =
|
||||
@@ -198,26 +211,31 @@ impl Shared {
|
||||
done: false,
|
||||
});
|
||||
|
||||
let found = self.filter.walk(self.filter.root(), &self.cancelled);
|
||||
let filter = self.filter();
|
||||
let mut found = Vec::new();
|
||||
for root in filter.roots() {
|
||||
found.extend(filter.walk(root, &self.cancelled));
|
||||
}
|
||||
if self.is_cancelled() {
|
||||
return self.end_scan(task);
|
||||
}
|
||||
let seen: HashSet<&Path> = found.iter().map(|f| f.path.as_path()).collect();
|
||||
let (todo, stale): (Vec<&Found>, Vec<String>) = {
|
||||
let (todo, stale): (Vec<&Found>, Vec<PathBuf>) = {
|
||||
let d = self.data.read();
|
||||
let todo = found
|
||||
.iter()
|
||||
.filter(|f| d.get(&f.path).is_none_or(|e| e.mtime != f.mtime || e.size != f.size))
|
||||
.collect();
|
||||
let stale = d.paths().filter(|p| !seen.contains(p.as_path())).filter_map(|p| self.filter.rel(p)).collect();
|
||||
let stale = d.paths().filter(|p| !seen.contains(p.as_path())).cloned().collect();
|
||||
(todo, stale)
|
||||
};
|
||||
if !stale.is_empty() {
|
||||
let mut d = self.data.write();
|
||||
for rel in &stale {
|
||||
d.remove(&self.filter.root().join(rel));
|
||||
for path in &stale {
|
||||
d.remove(path);
|
||||
}
|
||||
}
|
||||
let stale: Vec<String> = stale.iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
self.persist(&[], &stale, false);
|
||||
|
||||
let total = todo.len();
|
||||
@@ -227,7 +245,7 @@ impl Shared {
|
||||
if self.is_cancelled() {
|
||||
return self.end_scan(task);
|
||||
}
|
||||
self.index_files(chunk.iter().copied());
|
||||
self.index_files(chunk.iter().copied(), false);
|
||||
done += chunk.len();
|
||||
if last_progress.elapsed() >= PROGRESS_EVERY {
|
||||
last_progress = Instant::now();
|
||||
@@ -261,16 +279,18 @@ impl Shared {
|
||||
}
|
||||
|
||||
/// Extracts records in parallel, then publishes them to memory and disk.
|
||||
fn index_files<'a>(&self, files: impl Iterator<Item = &'a Found>) {
|
||||
/// `force` re-parses files whose content is unchanged (their language changed).
|
||||
fn index_files<'a>(&self, files: impl Iterator<Item = &'a Found>, force: bool) {
|
||||
let files: Vec<&Found> = files.collect();
|
||||
let filter = self.filter();
|
||||
let extracted: Vec<(String, FileRecord, PathBuf)> = files
|
||||
.par_iter()
|
||||
.filter_map(|f| {
|
||||
if self.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
let rel = self.filter.rel(&f.path)?;
|
||||
let prev_hash = self.data.read().get(&f.path).map(|e| e.hash);
|
||||
let rel = filter.rel(&f.path)?;
|
||||
let prev_hash = if force { None } else { self.data.read().get(&f.path).map(|e| e.hash) };
|
||||
match self.extract(f, prev_hash) {
|
||||
Extracted::Unchanged => {
|
||||
// Same content, new mtime: keep the symbols, refresh metadata.
|
||||
@@ -288,7 +308,7 @@ impl Shared {
|
||||
return;
|
||||
}
|
||||
let puts: Vec<(String, FileRecord)> =
|
||||
extracted.iter().map(|(rel, rec, _)| (rel.clone(), rec.clone())).collect();
|
||||
extracted.iter().filter_map(|(_, rec, path)| Some((filter.store_key(path)?, rec.clone()))).collect();
|
||||
{
|
||||
let entries: Vec<FileEntry> =
|
||||
extracted.into_iter().map(|(rel, rec, path)| FileEntry::new(path, rel, rec)).collect();
|
||||
@@ -346,13 +366,24 @@ impl Shared {
|
||||
let mut changed: Vec<PathBuf> = Vec::new();
|
||||
let mut removed: Vec<PathBuf> = Vec::new();
|
||||
let mut save_recent = false;
|
||||
let mut rescan = false;
|
||||
let mut reparse: Vec<std::sync::Arc<LanguageRegistry>> = Vec::new();
|
||||
for job in jobs {
|
||||
match job {
|
||||
Job::Changed(p) => changed.extend(p),
|
||||
Job::Removed(p) => removed.extend(p),
|
||||
Job::SaveRecent => save_recent = true,
|
||||
Job::Rescan => rescan = true,
|
||||
Job::Reparse(before) => reparse.push(before),
|
||||
}
|
||||
}
|
||||
if rescan {
|
||||
// The scan also picks up whatever `changed` / `removed` reported.
|
||||
self.full_scan();
|
||||
changed.clear();
|
||||
removed.clear();
|
||||
}
|
||||
let filter = self.filter();
|
||||
let mut touched = false;
|
||||
|
||||
// Removals first; a path removed then re-created shows up in `changed` too.
|
||||
@@ -363,11 +394,11 @@ impl Shared {
|
||||
continue;
|
||||
}
|
||||
let mut d = self.data.write();
|
||||
if let Some(e) = d.remove(&path) {
|
||||
deletes.push(e.rel.into_string());
|
||||
} else {
|
||||
deletes.extend(d.remove_tree(&path));
|
||||
}
|
||||
let gone = match d.remove(&path) {
|
||||
Some(_) => vec![path],
|
||||
None => d.remove_tree(&path),
|
||||
};
|
||||
deletes.extend(gone.iter().filter_map(|p| filter.store_key(p)));
|
||||
}
|
||||
if !deletes.is_empty() {
|
||||
touched = true;
|
||||
@@ -381,11 +412,11 @@ impl Shared {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { continue };
|
||||
if self.filter.is_excluded(&path, meta.is_dir()) {
|
||||
if filter.is_excluded(&path, meta.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
if meta.is_dir() {
|
||||
files.extend(self.filter.walk(&path, &self.cancelled));
|
||||
files.extend(filter.walk(&path, &self.cancelled));
|
||||
} else if meta.is_file() {
|
||||
files.push(Found { mtime: mtime_of(&meta), size: meta.len(), path });
|
||||
}
|
||||
@@ -403,11 +434,32 @@ impl Shared {
|
||||
if self.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
self.index_files(chunk.iter());
|
||||
self.index_files(chunk.iter(), false);
|
||||
}
|
||||
}
|
||||
for before in reparse {
|
||||
let affected: Vec<Found> = {
|
||||
let d = self.data.read();
|
||||
d.paths()
|
||||
.filter(|p| before.detect(p, None) != self.languages.detect(p, None))
|
||||
.filter_map(|p| {
|
||||
let e = d.get(p)?;
|
||||
Some(Found { path: p.clone(), mtime: e.mtime, size: e.size })
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
if !affected.is_empty() {
|
||||
touched = true;
|
||||
for chunk in affected.chunks(CHUNK) {
|
||||
if self.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
self.index_files(chunk.iter(), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
if save_recent && let Some(store) = &self.store {
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| self.filter.rel(p)).collect();
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
if let Err(e) = store.save_recent(&rels) {
|
||||
tracing::warn!("index cache: saving recent files failed: {e}");
|
||||
}
|
||||
|
||||
@@ -241,6 +241,7 @@ impl Peer {
|
||||
) -> std::io::Result<Self> {
|
||||
use std::process::Stdio;
|
||||
let mut cmd = tokio::process::Command::new(command);
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.current_dir(cwd)
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
; GraphQL highlighting (the grammar crate ships no query). Later patterns win.
|
||||
|
||||
(comment) @comment
|
||||
(description (string_value) @comment.doc)
|
||||
(string_value) @string
|
||||
(int_value) @number
|
||||
(float_value) @number
|
||||
[(boolean_value) (null_value)] @keyword
|
||||
(enum_value (name) @constant)
|
||||
|
||||
(variable) @variable
|
||||
(argument (name) @variable.parameter)
|
||||
(input_value_definition (name) @variable.parameter)
|
||||
(object_field (name) @property)
|
||||
|
||||
(field (name) @property)
|
||||
(alias (name) @property)
|
||||
(field_definition (name) @property)
|
||||
(enum_value_definition (enum_value (name) @constant))
|
||||
|
||||
(named_type (name) @type)
|
||||
(object_type_definition (name) @type)
|
||||
(interface_type_definition (name) @type)
|
||||
(union_type_definition (name) @type)
|
||||
(enum_type_definition (name) @type)
|
||||
(input_object_type_definition (name) @type)
|
||||
(scalar_type_definition (name) @type)
|
||||
(object_type_extension (name) @type)
|
||||
(interface_type_extension (name) @type)
|
||||
(union_type_extension (name) @type)
|
||||
(enum_type_extension (name) @type)
|
||||
(input_object_type_extension (name) @type)
|
||||
(scalar_type_extension (name) @type)
|
||||
|
||||
(operation_definition (name) @function)
|
||||
(fragment_name (name) @function)
|
||||
(directive_definition (name) @attribute)
|
||||
(directive (name) @attribute)
|
||||
"@" @attribute
|
||||
(directive_location) @constant
|
||||
|
||||
(operation_type) @keyword
|
||||
[
|
||||
"query" "mutation" "subscription" "fragment" "on" "type" "interface" "union"
|
||||
"enum" "input" "scalar" "schema" "extend" "implements" "directive" "repeatable"
|
||||
] @keyword
|
||||
|
||||
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
|
||||
[":" "=" "|" "&" "!" "..."] @punctuation.delimiter
|
||||
@@ -0,0 +1,29 @@
|
||||
; HCL / Terraform highlighting (the grammar crate ships no query). Later patterns win.
|
||||
|
||||
(comment) @comment
|
||||
(string_lit) @string
|
||||
(quoted_template) @string
|
||||
(heredoc_template) @string
|
||||
[(heredoc_start) (heredoc_identifier)] @string.special
|
||||
(template_literal) @string
|
||||
(numeric_lit) @number
|
||||
[(bool_lit) (null_lit)] @keyword
|
||||
|
||||
(identifier) @variable
|
||||
(attribute (identifier) @property)
|
||||
(object_elem key: (expression (variable_expr (identifier) @property)))
|
||||
(get_attr (identifier) @property)
|
||||
(function_call (identifier) @function)
|
||||
; `resource "aws_instance" "web" {`
|
||||
(block (identifier) @keyword)
|
||||
(block (string_lit (template_literal) @type))
|
||||
|
||||
(template_interpolation) @embedded
|
||||
[(template_interpolation_start) (template_interpolation_end)] @punctuation.special
|
||||
[(template_directive_start) (template_directive_end) (strip_marker)] @punctuation.special
|
||||
["for" "in" "if" "else" "endfor" "endif"] @keyword
|
||||
|
||||
(operation) @operator
|
||||
["!" "!=" "%" "&&" "*" "+" "-" "/" "<" "<=" "==" ">" ">=" "||" "?" "=>"] @operator
|
||||
["=" ":" "," "."] @punctuation.delimiter
|
||||
["(" ")" "[" "]" "{" "}" "[*]" ".*"] @punctuation.bracket
|
||||
@@ -11,8 +11,12 @@ use std::collections::BTreeMap;
|
||||
|
||||
mod registry;
|
||||
mod syntax;
|
||||
pub use registry::LanguageRegistry;
|
||||
pub use syntax::{MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, TreeError};
|
||||
pub use registry::{FileTypes, LanguageRegistry};
|
||||
pub use syntax::{
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES,
|
||||
ParsedTree, SpellingKind, SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind,
|
||||
SyntaxHighlights, TreeError, WebReference, WebReferenceKind, merge_visibility,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -75,6 +79,10 @@ pub struct LanguageServerConfig {
|
||||
/// basedpyright): only used while none of those is installed.
|
||||
#[serde(default)]
|
||||
pub fallback: bool,
|
||||
/// Set by the settings hook when the server can't run here (jdtls without
|
||||
/// a JDK 21+); reported as the failure instead of launching it.
|
||||
#[serde(skip)]
|
||||
pub launch_error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -111,6 +119,18 @@ pub struct LanguageInfo {
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub debuggable: bool,
|
||||
/// Names of the configured language servers (Settings › Inspections).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub language_servers: Vec<String>,
|
||||
/// Exact file names and file-name patterns of the definition (Settings › File Types).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub filenames: Vec<String>,
|
||||
/// First-line regex of the definition (shebangs, `<?php`).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub first_line: Option<String>,
|
||||
}
|
||||
|
||||
impl From<&LanguageConfig> for LanguageInfo {
|
||||
@@ -124,6 +144,9 @@ impl From<&LanguageConfig> for LanguageInfo {
|
||||
block_comment: c.block_comment.clone(),
|
||||
indent: c.indent,
|
||||
debuggable: c.debugger.is_some(),
|
||||
language_servers: c.language_servers.iter().map(|s| s.name.clone()).collect(),
|
||||
filenames: c.filenames.clone(),
|
||||
first_line: c.first_line.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::LanguageConfig;
|
||||
use ide_core::settings::{FileSettings, FileTypeAssociation};
|
||||
use ide_core::{IdeError, IdeResult, LanguageId};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use parking_lot::RwLock;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Built-in definitions, embedded at compile time. Add new languages here.
|
||||
const BUILTIN: &[(&str, &str)] = &[
|
||||
@@ -78,11 +81,130 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
|
||||
pub struct LanguageRegistry {
|
||||
languages: Vec<LanguageConfig>,
|
||||
/// Lookup tables of the definitions with the user's file types applied.
|
||||
tables: RwLock<Arc<Tables>>,
|
||||
file_types: RwLock<FileTypes>,
|
||||
}
|
||||
|
||||
/// The user's file type associations (Settings › Editor › File Types) and
|
||||
/// per-file overrides (Override File Type), resolved for one project.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct FileTypes {
|
||||
/// Language id → patterns added to / removed from its definition.
|
||||
pub associations: BTreeMap<String, FileTypeAssociation>,
|
||||
/// Absolute path → language id.
|
||||
pub overrides: HashMap<PathBuf, LanguageId>,
|
||||
}
|
||||
|
||||
impl FileTypes {
|
||||
/// From `files.fileTypes` / `files.fileTypeOverrides`; relative override paths resolve against `root`.
|
||||
pub fn from_settings(files: &FileSettings, root: Option<&Path>) -> Self {
|
||||
let overrides = files
|
||||
.file_type_overrides
|
||||
.iter()
|
||||
.filter(|(_, lang)| !lang.trim().is_empty())
|
||||
.filter_map(|(path, lang)| {
|
||||
let p = Path::new(path.as_str());
|
||||
let abs = if p.is_absolute() { p.to_path_buf() } else { root?.join(p) };
|
||||
Some((abs, LanguageId::new(lang.trim())))
|
||||
})
|
||||
.collect();
|
||||
Self { associations: files.file_types.clone(), overrides }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Tables {
|
||||
by_ext: HashMap<String, usize>,
|
||||
by_name: HashMap<String, usize>,
|
||||
/// File-name patterns containing `*`, e.g. `Dockerfile.*`, `tsconfig.*.json`.
|
||||
/// File-name patterns with wildcards, e.g. `Dockerfile.*`, `tsconfig.*.json`; the user's first.
|
||||
name_globs: Vec<(String, usize)>,
|
||||
/// Interpreter names of user hashbang patterns.
|
||||
hashbangs: Vec<(String, usize)>,
|
||||
first_line: Vec<(regex_lite::Regex, usize)>,
|
||||
overrides: HashMap<PathBuf, usize>,
|
||||
}
|
||||
|
||||
/// How a file name pattern is looked up.
|
||||
enum Pattern<'a> {
|
||||
/// `*.ext` (lower-cased).
|
||||
Ext(String),
|
||||
Name(&'a str),
|
||||
Glob(&'a str),
|
||||
}
|
||||
|
||||
fn classify(pattern: &str) -> Pattern<'_> {
|
||||
let wild = |s: &str| s.contains(['*', '?']);
|
||||
match pattern.strip_prefix("*.") {
|
||||
Some(ext) if !ext.is_empty() && !wild(ext) => Pattern::Ext(ext.to_ascii_lowercase()),
|
||||
_ if wild(pattern) => Pattern::Glob(pattern),
|
||||
_ => Pattern::Name(pattern),
|
||||
}
|
||||
}
|
||||
|
||||
impl Tables {
|
||||
fn build(languages: &[LanguageConfig], file_types: &FileTypes) -> Self {
|
||||
let mut t = Tables::default();
|
||||
let index_of = |id: &str| languages.iter().position(|l| l.id.as_str() == id);
|
||||
let removed = |l: &LanguageConfig, pattern: &str| {
|
||||
file_types.associations.get(l.id.as_str()).is_some_and(|a| {
|
||||
a.removed_patterns.iter().any(|r| r.trim() == pattern || r.trim().eq_ignore_ascii_case(pattern))
|
||||
})
|
||||
};
|
||||
let mut builtin_globs = Vec::new();
|
||||
for (i, l) in languages.iter().enumerate() {
|
||||
for ext in &l.extensions {
|
||||
if !removed(l, &format!("*.{ext}")) {
|
||||
t.by_ext.insert(ext.to_ascii_lowercase(), i);
|
||||
}
|
||||
}
|
||||
for name in l.filenames.iter().filter(|n| !removed(l, n)) {
|
||||
if name.contains(['*', '?']) {
|
||||
builtin_globs.push((name.clone(), i));
|
||||
} else {
|
||||
t.by_name.insert(name.clone(), i);
|
||||
}
|
||||
}
|
||||
if let Some(pattern) = l.first_line.as_deref() {
|
||||
match regex_lite::Regex::new(pattern) {
|
||||
Ok(re) => t.first_line.push((re, i)),
|
||||
Err(e) => tracing::warn!("language {}: invalid first-line pattern: {e}", l.id),
|
||||
}
|
||||
}
|
||||
}
|
||||
// The user's patterns win over the definitions'.
|
||||
let mut user_globs = Vec::new();
|
||||
for (id, assoc) in &file_types.associations {
|
||||
let Some(i) = index_of(id) else { continue };
|
||||
for pattern in assoc.patterns.iter().map(|p| p.trim()).filter(|p| !p.is_empty()) {
|
||||
match classify(pattern) {
|
||||
Pattern::Ext(ext) => {
|
||||
t.by_ext.insert(ext, i);
|
||||
}
|
||||
Pattern::Name(name) => {
|
||||
t.by_name.insert(name.to_owned(), i);
|
||||
}
|
||||
Pattern::Glob(glob) => user_globs.push((glob.to_owned(), i)),
|
||||
}
|
||||
}
|
||||
for h in assoc.hashbangs.iter().map(|h| h.trim()).filter(|h| !h.is_empty()) {
|
||||
t.hashbangs.push((h.to_owned(), i));
|
||||
}
|
||||
}
|
||||
// More specific (longer) patterns first: `tsconfig.*.json` before `*.json`-like ones.
|
||||
user_globs.sort_by_key(|(p, _): &(String, usize)| std::cmp::Reverse(p.len()));
|
||||
builtin_globs.sort_by_key(|(p, _): &(String, usize)| std::cmp::Reverse(p.len()));
|
||||
t.name_globs = user_globs.into_iter().chain(builtin_globs).collect();
|
||||
t.overrides =
|
||||
file_types.overrides.iter().filter_map(|(p, id)| Some((p.clone(), index_of(id.as_str())?))).collect();
|
||||
t
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the `#!` line runs `interpreter` (`#!/usr/bin/env node`, `#!/bin/node -x` for `node`).
|
||||
fn hashbang_runs(line: &str, interpreter: &str) -> bool {
|
||||
let Some(rest) = line.strip_prefix("#!") else { return false };
|
||||
rest.split(|c: char| c.is_whitespace() || c == '/').any(|token| token == interpreter)
|
||||
}
|
||||
|
||||
impl LanguageRegistry {
|
||||
@@ -116,31 +238,31 @@ impl LanguageRegistry {
|
||||
None => languages.push(cfg),
|
||||
}
|
||||
}
|
||||
let mut by_ext = HashMap::new();
|
||||
let mut by_name = HashMap::new();
|
||||
let mut name_globs = Vec::new();
|
||||
let mut first_line = Vec::new();
|
||||
for (i, l) in languages.iter().enumerate() {
|
||||
for ext in &l.extensions {
|
||||
by_ext.insert(ext.to_ascii_lowercase(), i);
|
||||
}
|
||||
for name in &l.filenames {
|
||||
if name.contains('*') {
|
||||
name_globs.push((name.clone(), i));
|
||||
} else {
|
||||
by_name.insert(name.clone(), i);
|
||||
}
|
||||
}
|
||||
if let Some(pattern) = l.first_line.as_deref() {
|
||||
match regex_lite::Regex::new(pattern) {
|
||||
Ok(re) => first_line.push((re, i)),
|
||||
Err(e) => tracing::warn!("language {}: invalid first-line pattern: {e}", l.id),
|
||||
}
|
||||
}
|
||||
let tables = Tables::build(&languages, &FileTypes::default());
|
||||
Self { languages, tables: RwLock::new(Arc::new(tables)), file_types: RwLock::default() }
|
||||
}
|
||||
|
||||
/// A registry with the same definitions and no user file types (one per project).
|
||||
pub fn fork(&self) -> Self {
|
||||
Self::from_configs(self.languages.clone())
|
||||
}
|
||||
|
||||
/// A copy with the same definitions and file types (to compare detection before / after a change).
|
||||
pub fn snapshot(&self) -> Self {
|
||||
let copy = self.fork();
|
||||
copy.set_file_types(self.file_types.read().clone());
|
||||
copy
|
||||
}
|
||||
|
||||
/// Applies the user's file types; returns whether they changed.
|
||||
pub fn set_file_types(&self, file_types: FileTypes) -> bool {
|
||||
let mut current = self.file_types.write();
|
||||
if *current == file_types {
|
||||
return false;
|
||||
}
|
||||
// More specific (longer) patterns first: `tsconfig.*.json` before `*.json`-like ones.
|
||||
name_globs.sort_by_key(|(p, _): &(String, usize)| std::cmp::Reverse(p.len()));
|
||||
Self { languages, by_ext, by_name, name_globs, first_line }
|
||||
*self.tables.write() = Arc::new(Tables::build(&self.languages, &file_types));
|
||||
*current = file_types;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn all(&self) -> Vec<LanguageConfig> {
|
||||
@@ -151,48 +273,67 @@ impl LanguageRegistry {
|
||||
self.languages.iter().find(|l| &l.id == id).cloned()
|
||||
}
|
||||
|
||||
/// Detects by exact file name, then file-name pattern (`Dockerfile.*`), then
|
||||
/// extension (longest compound first, e.g. `d.ts`), then first line; falls
|
||||
/// back to plaintext.
|
||||
/// Detects by Override File Type, exact file name, then file-name pattern
|
||||
/// (`Dockerfile.*`), then extension (longest compound first, e.g. `d.ts`),
|
||||
/// then hashbang / first line; falls back to plaintext. The user's patterns
|
||||
/// win over the definitions'.
|
||||
pub fn detect(&self, path: &Path, first_line: Option<&str>) -> LanguageId {
|
||||
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
|
||||
if let Some(&i) = self.by_name.get(file_name) {
|
||||
let t = self.tables.read().clone();
|
||||
if !t.overrides.is_empty()
|
||||
&& let Some(&i) = t.overrides.get(path)
|
||||
{
|
||||
return self.languages[i].id.clone();
|
||||
}
|
||||
if let Some((_, i)) = self.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) {
|
||||
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
|
||||
if let Some(&i) = t.by_name.get(file_name) {
|
||||
return self.languages[i].id.clone();
|
||||
}
|
||||
if let Some((_, i)) = t.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) {
|
||||
return self.languages[*i].id.clone();
|
||||
}
|
||||
let lower = file_name.to_ascii_lowercase();
|
||||
let mut rest = lower.as_str();
|
||||
while let Some(dot) = rest.find('.') {
|
||||
rest = &rest[dot + 1..];
|
||||
if let Some(&i) = self.by_ext.get(rest) {
|
||||
if let Some(&i) = t.by_ext.get(rest) {
|
||||
return self.languages[i].id.clone();
|
||||
}
|
||||
}
|
||||
if let Some(line) = first_line
|
||||
&& let Some((_, i)) = self.first_line.iter().find(|(re, _)| re.is_match(line))
|
||||
{
|
||||
return self.languages[*i].id.clone();
|
||||
if let Some(line) = first_line {
|
||||
if let Some((_, i)) = t.hashbangs.iter().find(|(h, _)| hashbang_runs(line, h)) {
|
||||
return self.languages[*i].id.clone();
|
||||
}
|
||||
if let Some((_, i)) = t.first_line.iter().find(|(re, _)| re.is_match(line)) {
|
||||
return self.languages[*i].id.clone();
|
||||
}
|
||||
}
|
||||
LanguageId::plain_text()
|
||||
}
|
||||
}
|
||||
|
||||
/// `*` matches any (possibly empty) run of characters; everything else is literal.
|
||||
/// `*` matches any (possibly empty) run of characters, `?` exactly one; everything else is literal.
|
||||
fn wildcard_match(pattern: &str, name: &str) -> bool {
|
||||
let mut parts = pattern.split('*');
|
||||
let first = parts.next().unwrap_or_default();
|
||||
let Some(mut rest) = name.strip_prefix(first) else { return false };
|
||||
let parts: Vec<&str> = parts.collect();
|
||||
let Some((last, middle)) = parts.split_last() else { return rest.is_empty() };
|
||||
for part in middle {
|
||||
match rest.find(part) {
|
||||
Some(i) => rest = &rest[i + part.len()..],
|
||||
None => return false,
|
||||
let p: Vec<char> = pattern.chars().collect();
|
||||
let n: Vec<char> = name.chars().collect();
|
||||
let (mut pi, mut ni) = (0, 0);
|
||||
// Position after the last `*` and the name position it is matched up to.
|
||||
let mut star: Option<(usize, usize)> = None;
|
||||
while ni < n.len() {
|
||||
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
|
||||
pi += 1;
|
||||
ni += 1;
|
||||
} else if pi < p.len() && p[pi] == '*' {
|
||||
star = Some((pi + 1, ni));
|
||||
pi += 1;
|
||||
} else if let Some((sp, sn)) = star {
|
||||
pi = sp;
|
||||
ni = sn + 1;
|
||||
star = Some((sp, sn + 1));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
rest.len() >= last.len() && rest.ends_with(last)
|
||||
p[pi..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
fn parse(src: &str) -> Result<LanguageConfig, String> {
|
||||
@@ -573,6 +714,60 @@ mod tests {
|
||||
assert!(wildcard_match("*.Dockerfile", "web.Dockerfile"));
|
||||
assert!(wildcard_match("a*b*c", "aXbYc"));
|
||||
assert!(!wildcard_match("a*b*c", "aXcYb"));
|
||||
assert!(wildcard_match("file?.txt", "file1.txt"));
|
||||
assert!(!wildcard_match("file?.txt", "file.txt"));
|
||||
assert!(wildcard_match("*", ""));
|
||||
assert!(wildcard_match("a**", "abc"));
|
||||
}
|
||||
|
||||
fn assoc(patterns: &[&str], removed: &[&str], hashbangs: &[&str]) -> FileTypeAssociation {
|
||||
let v = |xs: &[&str]| xs.iter().map(|s| (*s).to_owned()).collect();
|
||||
FileTypeAssociation { patterns: v(patterns), removed_patterns: v(removed), hashbangs: v(hashbangs) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_file_types_add_remove_and_win() {
|
||||
let reg = reg();
|
||||
let mut ft = FileTypes::default();
|
||||
ft.associations
|
||||
.insert("python".into(), assoc(&["*.foo", "Pipfile.lock", "build_*.cfg", "*.LOG"], &[], &["mypy"]));
|
||||
ft.associations.insert("groovy".into(), assoc(&[], &["Jenkinsfile"], &[]));
|
||||
ft.associations.insert("shellscript".into(), assoc(&["Jenkinsfile"], &[], &[]));
|
||||
ft.associations.insert("rust".into(), assoc(&[], &["*.rs"], &[]));
|
||||
assert!(reg.set_file_types(ft.clone()));
|
||||
assert!(!reg.set_file_types(ft), "unchanged file types report no change");
|
||||
assert_eq!(detect(®, "a/x.foo"), "python");
|
||||
assert_eq!(detect(®, "x.FOO"), "python");
|
||||
assert_eq!(detect(®, "Pipfile.lock"), "python");
|
||||
assert_eq!(detect(®, "build_dev.cfg"), "python");
|
||||
assert_eq!(detect(®, "setup.cfg"), "ini");
|
||||
assert_eq!(detect(®, "server.log"), "python", "a user extension overrides a built-in one");
|
||||
assert_eq!(detect(®, "Jenkinsfile"), "shellscript");
|
||||
assert_eq!(detect(®, "main.rs"), "plaintext");
|
||||
assert_eq!(reg.detect(Path::new("tool"), Some("#!/usr/bin/env mypy --strict")).as_str(), "python");
|
||||
assert_eq!(reg.detect(Path::new("tool"), Some("#!/usr/bin/env mypyc")).as_str(), "plaintext");
|
||||
reg.set_file_types(FileTypes::default());
|
||||
assert_eq!(detect(®, "main.rs"), "rust");
|
||||
assert_eq!(detect(®, "x.foo"), "plaintext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn override_file_type_per_file() {
|
||||
let reg = reg().fork();
|
||||
let files = FileSettings {
|
||||
file_type_overrides: [
|
||||
("notes.txt".to_owned(), "markdown".to_owned()),
|
||||
("/abs/run".to_owned(), "python".to_owned()),
|
||||
("bad.txt".to_owned(), "no-such-language".to_owned()),
|
||||
]
|
||||
.into(),
|
||||
..Default::default()
|
||||
};
|
||||
reg.set_file_types(FileTypes::from_settings(&files, Some(Path::new("/proj"))));
|
||||
assert_eq!(detect(®, "/proj/notes.txt"), "markdown");
|
||||
assert_eq!(detect(®, "/other/notes.txt"), "plaintext");
|
||||
assert_eq!(detect(®, "/abs/run"), "python");
|
||||
assert_eq!(detect(®, "/proj/bad.txt"), "plaintext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
//! Structure / folding / Extend Selection on a large file cost an incremental
|
||||
//! parse instead of a full one.
|
||||
|
||||
use super::{Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, TreeError, folding, outline, parse_cancellable, selection};
|
||||
use super::{
|
||||
Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxHighlights, TreeError, folding, highlight, outline,
|
||||
parse_cancellable, selection,
|
||||
};
|
||||
use crate::FoldRange;
|
||||
use ide_core::{DocId, LanguageId, OutlineItem, Range};
|
||||
use ide_text::ByteEdit;
|
||||
@@ -59,6 +62,7 @@ struct Memo {
|
||||
key: Option<(u32, LanguageId)>,
|
||||
outline: Option<Arc<Vec<OutlineItem>>>,
|
||||
folding: Option<Arc<Vec<FoldRange>>>,
|
||||
highlights: Option<Arc<Vec<u32>>>,
|
||||
}
|
||||
|
||||
impl Memo {
|
||||
@@ -211,6 +215,21 @@ impl SyntaxCache {
|
||||
)
|
||||
}
|
||||
|
||||
/// Highlighting from the grammar's own query; empty without one.
|
||||
pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights {
|
||||
SyntaxHighlights::new(self.memoized(
|
||||
doc,
|
||||
lang,
|
||||
version,
|
||||
|m| &mut m.highlights,
|
||||
|| {
|
||||
self.with_tree(doc, lang, version, text, |g, tree, text| {
|
||||
Some(highlight::highlights(g.highlight_query()?, tree, text))
|
||||
})
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// `compute()` once per document version; `None` (no grammar / query) is not memoized.
|
||||
fn memoized<T: Clone>(
|
||||
&self,
|
||||
|
||||
@@ -9,6 +9,8 @@ pub(crate) struct Spec {
|
||||
pub language: LanguageFn,
|
||||
/// `queries/<name>/outline.scm`; see `queries/README.md` for the capture vocabulary.
|
||||
pub outline: &'static str,
|
||||
/// The grammar's `highlights.scm`, for languages without a CodeMirror mode.
|
||||
pub highlights: Option<Highlights>,
|
||||
/// Node kinds folded when they span several lines (in addition to every
|
||||
/// bracket-delimited node, which is folded generically).
|
||||
pub fold_nodes: &'static [&'static str],
|
||||
@@ -20,6 +22,21 @@ pub(crate) struct Spec {
|
||||
pub constructors: &'static [&'static str],
|
||||
}
|
||||
|
||||
/// A highlights query and how its patterns rank against each other.
|
||||
pub(crate) struct Highlights {
|
||||
pub query: &'static str,
|
||||
/// For the same node, the first matching pattern wins (tree-sitter CLI /
|
||||
/// GitHub queries) instead of the last one (nvim / Zed queries).
|
||||
pub first_wins: bool,
|
||||
}
|
||||
|
||||
/// Our own `queries/<name>/highlights.scm`, for grammars that ship none.
|
||||
macro_rules! highlights {
|
||||
($name:literal) => {
|
||||
include_str!(concat!("../../queries/", $name, "/highlights.scm"))
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! outline {
|
||||
($name:literal) => {
|
||||
include_str!(concat!("../../queries/", $name, "/outline.scm"))
|
||||
@@ -33,6 +50,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "rust",
|
||||
language: tree_sitter_rust::LANGUAGE,
|
||||
outline: outline!("rust"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: &["use_declaration", "extern_crate_declaration"],
|
||||
@@ -42,6 +60,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "typescript",
|
||||
language: tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
|
||||
outline: outline!("typescript"),
|
||||
highlights: None,
|
||||
fold_nodes: &["template_string"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_statement"],
|
||||
@@ -51,6 +70,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "tsx",
|
||||
language: tree_sitter_typescript::LANGUAGE_TSX,
|
||||
outline: outline!("typescript"),
|
||||
highlights: None,
|
||||
fold_nodes: &["template_string", "jsx_element"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_statement"],
|
||||
@@ -60,6 +80,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "javascript",
|
||||
language: tree_sitter_javascript::LANGUAGE,
|
||||
outline: outline!("javascript"),
|
||||
highlights: None,
|
||||
fold_nodes: &["template_string", "jsx_element"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_statement"],
|
||||
@@ -69,6 +90,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "python",
|
||||
language: tree_sitter_python::LANGUAGE,
|
||||
outline: outline!("python"),
|
||||
highlights: None,
|
||||
fold_nodes: &["string"],
|
||||
fold_bodies: &["block"],
|
||||
imports: &["import_statement", "import_from_statement", "future_import_statement"],
|
||||
@@ -78,6 +100,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "go",
|
||||
language: tree_sitter_go::LANGUAGE,
|
||||
outline: outline!("go"),
|
||||
highlights: None,
|
||||
fold_nodes: &["raw_string_literal"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_declaration"],
|
||||
@@ -87,6 +110,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "java",
|
||||
language: tree_sitter_java::LANGUAGE,
|
||||
outline: outline!("java"),
|
||||
highlights: None,
|
||||
fold_nodes: &["text_block"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_declaration"],
|
||||
@@ -96,6 +120,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "kotlin",
|
||||
language: tree_sitter_kotlin_ng::LANGUAGE,
|
||||
outline: outline!("kotlin"),
|
||||
highlights: None,
|
||||
fold_nodes: &["string_literal"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import"],
|
||||
@@ -105,6 +130,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "scala",
|
||||
language: tree_sitter_scala::LANGUAGE,
|
||||
outline: outline!("scala"),
|
||||
highlights: None,
|
||||
fold_nodes: &["string"],
|
||||
fold_bodies: &["indented_block", "template_body"],
|
||||
imports: &["import_declaration"],
|
||||
@@ -114,6 +140,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "c",
|
||||
language: tree_sitter_c::LANGUAGE,
|
||||
outline: outline!("c"),
|
||||
highlights: None,
|
||||
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["preproc_include"],
|
||||
@@ -123,6 +150,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "cpp",
|
||||
language: tree_sitter_cpp::LANGUAGE,
|
||||
outline: outline!("cpp"),
|
||||
highlights: None,
|
||||
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def", "raw_string_literal"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["preproc_include", "using_declaration"],
|
||||
@@ -132,6 +160,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "csharp",
|
||||
language: tree_sitter_c_sharp::LANGUAGE,
|
||||
outline: outline!("csharp"),
|
||||
highlights: None,
|
||||
fold_nodes: &["preproc_region", "raw_string_literal", "verbatim_string_literal"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["using_directive"],
|
||||
@@ -141,6 +170,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "swift",
|
||||
language: tree_sitter_swift::LANGUAGE,
|
||||
outline: outline!("swift"),
|
||||
highlights: None,
|
||||
// Control-flow statements hold `{ statements }` without a block node of their own.
|
||||
fold_nodes: &[
|
||||
"multi_line_string_literal",
|
||||
@@ -160,6 +190,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "ruby",
|
||||
language: tree_sitter_ruby::LANGUAGE,
|
||||
outline: outline!("ruby"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"method",
|
||||
"singleton_method",
|
||||
@@ -185,6 +216,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "php",
|
||||
language: tree_sitter_php::LANGUAGE_PHP,
|
||||
outline: outline!("php"),
|
||||
highlights: None,
|
||||
fold_nodes: &["heredoc", "nowdoc"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["namespace_use_declaration"],
|
||||
@@ -194,6 +226,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "lua",
|
||||
language: tree_sitter_lua::LANGUAGE,
|
||||
outline: outline!("lua"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"function_declaration",
|
||||
"function_definition",
|
||||
@@ -212,6 +245,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "dart",
|
||||
language: tree_sitter_dart::LANGUAGE,
|
||||
outline: outline!("dart"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_or_export", "library_name", "part_directive", "part_of_directive"],
|
||||
@@ -221,6 +255,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "zig",
|
||||
language: tree_sitter_zig::LANGUAGE,
|
||||
outline: outline!("zig"),
|
||||
highlights: Some(Highlights { query: tree_sitter_zig::HIGHLIGHTS_QUERY, first_wins: false }),
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -230,6 +265,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "elixir",
|
||||
language: tree_sitter_elixir::LANGUAGE,
|
||||
outline: outline!("elixir"),
|
||||
highlights: Some(Highlights { query: tree_sitter_elixir::HIGHLIGHTS_QUERY, first_wins: false }),
|
||||
fold_nodes: &["do_block", "anonymous_function", "string", "sigil"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -239,6 +275,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "haskell",
|
||||
language: tree_sitter_haskell::LANGUAGE,
|
||||
outline: outline!("haskell"),
|
||||
highlights: None,
|
||||
// `bind`: equations without arguments (`main = do …`).
|
||||
fold_nodes: &["function", "bind", "data_type", "newtype", "class", "instance", "signature"],
|
||||
fold_bodies: NONE,
|
||||
@@ -249,6 +286,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "ocaml",
|
||||
language: tree_sitter_ocaml::LANGUAGE_OCAML,
|
||||
outline: outline!("ocaml"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"value_definition",
|
||||
"type_definition",
|
||||
@@ -266,6 +304,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "ocaml_interface",
|
||||
language: tree_sitter_ocaml::LANGUAGE_OCAML_INTERFACE,
|
||||
outline: outline!("ocaml_interface"),
|
||||
highlights: None,
|
||||
fold_nodes: &["module_definition", "module_type_definition", "signature", "type_definition"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["open_module"],
|
||||
@@ -275,6 +314,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "bash",
|
||||
language: tree_sitter_bash::LANGUAGE,
|
||||
outline: outline!("bash"),
|
||||
highlights: None,
|
||||
fold_nodes: &["do_group", "if_statement", "case_statement", "heredoc_body"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -284,6 +324,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "html",
|
||||
language: tree_sitter_html::LANGUAGE,
|
||||
outline: outline!("html"),
|
||||
highlights: None,
|
||||
fold_nodes: &["element", "script_element", "style_element"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -293,6 +334,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "xml",
|
||||
language: tree_sitter_xml::LANGUAGE_XML,
|
||||
outline: outline!("xml"),
|
||||
highlights: None,
|
||||
fold_nodes: &["element", "CDSect"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -302,6 +344,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "css",
|
||||
language: tree_sitter_css::LANGUAGE,
|
||||
outline: outline!("css"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_statement"],
|
||||
@@ -311,6 +354,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "json",
|
||||
language: tree_sitter_json::LANGUAGE,
|
||||
outline: outline!("json"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -320,6 +364,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "yaml",
|
||||
language: tree_sitter_yaml::LANGUAGE,
|
||||
outline: outline!("yaml"),
|
||||
highlights: None,
|
||||
fold_nodes: &["block_mapping_pair", "block_sequence_item", "block_scalar"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -329,6 +374,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "toml",
|
||||
language: tree_sitter_toml_ng::LANGUAGE,
|
||||
outline: outline!("toml"),
|
||||
highlights: None,
|
||||
fold_nodes: &["table", "table_array_element", "string"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -338,6 +384,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "markdown",
|
||||
language: tree_sitter_md::LANGUAGE,
|
||||
outline: outline!("markdown"),
|
||||
highlights: None,
|
||||
fold_nodes: &["section", "fenced_code_block", "list", "block_quote", "html_block"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -347,6 +394,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "hcl",
|
||||
language: tree_sitter_hcl::LANGUAGE,
|
||||
outline: outline!("hcl"),
|
||||
highlights: Some(Highlights { query: highlights!("hcl"), first_wins: false }),
|
||||
fold_nodes: &["block", "heredoc_template"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -356,6 +404,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "nix",
|
||||
language: tree_sitter_nix::LANGUAGE,
|
||||
outline: outline!("nix"),
|
||||
highlights: Some(Highlights { query: tree_sitter_nix::HIGHLIGHTS_QUERY, first_wins: true }),
|
||||
fold_nodes: &["let_expression", "indented_string_expression"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -365,6 +414,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "proto",
|
||||
language: tree_sitter_proto::LANGUAGE,
|
||||
outline: outline!("proto"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: &["import"],
|
||||
@@ -374,6 +424,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "graphql",
|
||||
language: tree_sitter_graphql::LANGUAGE,
|
||||
outline: outline!("graphql"),
|
||||
highlights: Some(Highlights { query: highlights!("graphql"), first_wins: false }),
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -383,6 +434,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "make",
|
||||
language: tree_sitter_make::LANGUAGE,
|
||||
outline: outline!("make"),
|
||||
highlights: Some(Highlights { query: tree_sitter_make::HIGHLIGHTS_QUERY, first_wins: false }),
|
||||
fold_nodes: &["rule", "conditional", "define_directive"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["include_directive"],
|
||||
@@ -392,6 +444,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "cmake",
|
||||
language: tree_sitter_cmake::LANGUAGE,
|
||||
outline: outline!("cmake"),
|
||||
highlights: None,
|
||||
fold_nodes: &["function_def", "macro_def", "if_condition", "foreach_loop", "while_loop", "block_def"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
//! Syntax highlighting from a grammar's own `highlights.scm`, for languages the
|
||||
//! UI has no CodeMirror mode for.
|
||||
//!
|
||||
//! Capture names follow the nvim-treesitter / Zed conventions (`@keyword`,
|
||||
//! `@string.special.symbol`, ...) and are folded into [`SyntaxHighlightKind`] by
|
||||
//! their longest known dotted prefix. Overlaps resolve the way those editors
|
||||
//! do: a smaller node wins over the node containing it, and for the same node
|
||||
//! the later pattern wins (the first one for tree-sitter CLI style queries). `@embedded` (string interpolation) clears the
|
||||
//! surrounding colour. Besides tree-sitter's own text predicates, nvim's
|
||||
//! `#lua-match?` is understood; patterns with other predicates never match.
|
||||
|
||||
use super::lines::LineIndex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use tree_sitter::{Language, Query, QueryCursor, QueryMatch, QueryPredicateArg, StreamingIterator, Tree};
|
||||
|
||||
/// Highlight classes sent to the UI, which maps each onto a Lezer tag.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SyntaxHighlightKind {
|
||||
Keyword,
|
||||
String,
|
||||
StringSpecial,
|
||||
Escape,
|
||||
Regexp,
|
||||
Atom,
|
||||
Number,
|
||||
Constant,
|
||||
Comment,
|
||||
DocComment,
|
||||
Function,
|
||||
FunctionCall,
|
||||
Builtin,
|
||||
Type,
|
||||
Namespace,
|
||||
Variable,
|
||||
SelfVariable,
|
||||
Property,
|
||||
Attribute,
|
||||
Macro,
|
||||
Label,
|
||||
Tag,
|
||||
Operator,
|
||||
Punctuation,
|
||||
}
|
||||
|
||||
impl SyntaxHighlightKind {
|
||||
/// Every kind, in `as u32` order: the legend for [`SyntaxHighlights::data`].
|
||||
pub const ALL: [Self; 24] = [
|
||||
Self::Keyword,
|
||||
Self::String,
|
||||
Self::StringSpecial,
|
||||
Self::Escape,
|
||||
Self::Regexp,
|
||||
Self::Atom,
|
||||
Self::Number,
|
||||
Self::Constant,
|
||||
Self::Comment,
|
||||
Self::DocComment,
|
||||
Self::Function,
|
||||
Self::FunctionCall,
|
||||
Self::Builtin,
|
||||
Self::Type,
|
||||
Self::Namespace,
|
||||
Self::Variable,
|
||||
Self::SelfVariable,
|
||||
Self::Property,
|
||||
Self::Attribute,
|
||||
Self::Macro,
|
||||
Self::Label,
|
||||
Self::Tag,
|
||||
Self::Operator,
|
||||
Self::Punctuation,
|
||||
];
|
||||
}
|
||||
|
||||
/// Highlighted ranges of a whole document, packed like LSP semantic tokens.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyntaxHighlights {
|
||||
/// Legend: `data` kind `i` is `kinds[i]`.
|
||||
pub kinds: Vec<SyntaxHighlightKind>,
|
||||
/// `[from, to, kind]` triples: sorted, non-overlapping UTF-16 offsets.
|
||||
pub data: Vec<u32>,
|
||||
}
|
||||
|
||||
impl SyntaxHighlights {
|
||||
pub(crate) fn new(data: Vec<u32>) -> Self {
|
||||
Self { kinds: SyntaxHighlightKind::ALL.to_vec(), data }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a capture paints over its node.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Paint {
|
||||
Kind(SyntaxHighlightKind),
|
||||
/// `@embedded`: code inside a string, uncoloured unless captured itself.
|
||||
Clear,
|
||||
}
|
||||
|
||||
/// Capture name prefixes, most specific first within each family.
|
||||
const CAPTURES: &[(&str, Paint)] = {
|
||||
use Paint::{Clear, Kind};
|
||||
use SyntaxHighlightKind as K;
|
||||
&[
|
||||
("embedded", Clear),
|
||||
("keyword", Kind(K::Keyword)),
|
||||
("include", Kind(K::Keyword)),
|
||||
("import", Kind(K::Keyword)),
|
||||
("conditional", Kind(K::Keyword)),
|
||||
("repeat", Kind(K::Keyword)),
|
||||
("exception", Kind(K::Keyword)),
|
||||
("boolean", Kind(K::Keyword)),
|
||||
("string.escape", Kind(K::Escape)),
|
||||
("escape", Kind(K::Escape)),
|
||||
("string.regex", Kind(K::Regexp)),
|
||||
("string.regexp", Kind(K::Regexp)),
|
||||
("string.special.symbol", Kind(K::Atom)),
|
||||
("symbol", Kind(K::Atom)),
|
||||
("string.special", Kind(K::StringSpecial)),
|
||||
("string", Kind(K::String)),
|
||||
("character", Kind(K::String)),
|
||||
("number", Kind(K::Number)),
|
||||
("float", Kind(K::Number)),
|
||||
("constant.builtin", Kind(K::Constant)),
|
||||
("constant.macro", Kind(K::Macro)),
|
||||
("constant", Kind(K::Constant)),
|
||||
// nvim greys out unused bindings (`_acc`); IDEA shows them as variables.
|
||||
("comment.unused", Kind(K::Variable)),
|
||||
("comment.doc", Kind(K::DocComment)),
|
||||
("comment.documentation", Kind(K::DocComment)),
|
||||
("comment", Kind(K::Comment)),
|
||||
("function.builtin", Kind(K::Builtin)),
|
||||
("function.macro", Kind(K::Macro)),
|
||||
("function.definition", Kind(K::Function)),
|
||||
("function", Kind(K::FunctionCall)),
|
||||
("method", Kind(K::FunctionCall)),
|
||||
("constructor", Kind(K::Type)),
|
||||
("type.builtin", Kind(K::Builtin)),
|
||||
("type", Kind(K::Type)),
|
||||
("module", Kind(K::Namespace)),
|
||||
("namespace", Kind(K::Namespace)),
|
||||
("variable.builtin", Kind(K::SelfVariable)),
|
||||
("variable.member", Kind(K::Property)),
|
||||
("variable.field", Kind(K::Property)),
|
||||
("variable", Kind(K::Variable)),
|
||||
("parameter", Kind(K::Variable)),
|
||||
("property", Kind(K::Property)),
|
||||
("field", Kind(K::Property)),
|
||||
("attribute", Kind(K::Attribute)),
|
||||
("label", Kind(K::Label)),
|
||||
("tag", Kind(K::Tag)),
|
||||
("operator", Kind(K::Operator)),
|
||||
("punctuation", Kind(K::Punctuation)),
|
||||
]
|
||||
};
|
||||
|
||||
/// The paint for a capture name: its longest prefix (on `.` boundaries) in
|
||||
/// [`CAPTURES`]. Private captures (`@__name__`) and unknown names paint nothing.
|
||||
fn paint_for(name: &str) -> Option<Paint> {
|
||||
if name.starts_with('_') {
|
||||
return None;
|
||||
}
|
||||
let mut prefix = name;
|
||||
loop {
|
||||
if let Some((_, p)) = CAPTURES.iter().find(|(n, _)| *n == prefix) {
|
||||
return Some(*p);
|
||||
}
|
||||
prefix = &prefix[..prefix.rfind('.')?];
|
||||
}
|
||||
}
|
||||
|
||||
/// A predicate tree-sitter leaves to the caller.
|
||||
enum Check {
|
||||
/// `#lua-match?` / `#not-lua-match?` on a capture's text.
|
||||
Matches {
|
||||
capture: u32,
|
||||
regex: regex_lite::Regex,
|
||||
negate: bool,
|
||||
},
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
pub(crate) struct HighlightQuery {
|
||||
query: Query,
|
||||
/// By capture index.
|
||||
paints: Vec<Option<Paint>>,
|
||||
/// By pattern index.
|
||||
checks: Vec<Vec<Check>>,
|
||||
first_wins: bool,
|
||||
}
|
||||
|
||||
impl HighlightQuery {
|
||||
pub(crate) fn new(language: &Language, source: &str, first_wins: bool) -> Result<Self, tree_sitter::QueryError> {
|
||||
let query = Query::new(language, source)?;
|
||||
let paints = query.capture_names().iter().map(|n| paint_for(n)).collect();
|
||||
let checks = (0..query.pattern_count())
|
||||
.map(|i| {
|
||||
query
|
||||
.general_predicates(i)
|
||||
.iter()
|
||||
.filter_map(|p| match (&*p.operator, &*p.args) {
|
||||
// Locals are not tracked: builtins are assumed not to be shadowed.
|
||||
("is-not?", [QueryPredicateArg::String(s)]) if &**s == "local" => None,
|
||||
(
|
||||
op @ ("lua-match?" | "not-lua-match?"),
|
||||
[QueryPredicateArg::Capture(c), QueryPredicateArg::String(pat)],
|
||||
) => Some(match regex_lite::Regex::new(&lua_pattern_to_regex(pat)) {
|
||||
Ok(regex) => Check::Matches { capture: *c, regex, negate: op.starts_with("not-") },
|
||||
Err(_) => Check::Unsupported,
|
||||
}),
|
||||
_ => Some(Check::Unsupported),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
Ok(Self { query, paints, checks, first_wins })
|
||||
}
|
||||
|
||||
fn accepts(&self, m: &QueryMatch<'_, '_>, text: &str) -> bool {
|
||||
self.checks[m.pattern_index].iter().all(|check| match check {
|
||||
Check::Matches { capture, regex, negate } => m
|
||||
.captures
|
||||
.iter()
|
||||
.filter(|c| c.index == *capture)
|
||||
.all(|c| regex.is_match(&text[c.node.byte_range()]) != *negate),
|
||||
Check::Unsupported => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates the Lua patterns used by nvim queries (`^[A-Z][A-Z_0-9]+$`, `^//!`) to regex syntax.
|
||||
fn lua_pattern_to_regex(pat: &str) -> String {
|
||||
let class = |c: char| match c {
|
||||
'a' => Some("A-Za-z"),
|
||||
'd' => Some("0-9"),
|
||||
'l' => Some("a-z"),
|
||||
'u' => Some("A-Z"),
|
||||
'w' => Some("A-Za-z0-9"),
|
||||
's' => Some("\\s"),
|
||||
'x' => Some("0-9A-Fa-f"),
|
||||
'p' => Some("[:punct:]"),
|
||||
_ => None,
|
||||
};
|
||||
let mut out = String::with_capacity(pat.len() + 8);
|
||||
let mut in_set = false;
|
||||
let mut chars = pat.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'%' => {
|
||||
let Some(next) = chars.next() else { break };
|
||||
match class(next) {
|
||||
Some(set) if in_set => out.push_str(set),
|
||||
Some(set) => {
|
||||
out.push('[');
|
||||
out.push_str(set);
|
||||
out.push(']');
|
||||
}
|
||||
None => out.push_str(®ex_lite::escape(&next.to_string())),
|
||||
}
|
||||
}
|
||||
'[' if !in_set => {
|
||||
in_set = true;
|
||||
out.push(c);
|
||||
}
|
||||
']' if in_set => {
|
||||
in_set = false;
|
||||
out.push(c);
|
||||
}
|
||||
// Lua's lazy `*` (inside a set, `-` is a range).
|
||||
'-' if !in_set => out.push_str("*?"),
|
||||
'\\' | '{' | '}' | '|' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Byte value for "no colour" in the paint buffer; kinds are `1 + index`.
|
||||
const NONE: u8 = 0;
|
||||
|
||||
/// `[from, to, kind]` UTF-16 triples for `text`; see [`SyntaxHighlights::data`].
|
||||
pub(crate) fn highlights(q: &HighlightQuery, tree: &Tree, text: &str) -> Vec<u32> {
|
||||
// (byte len, rank, start, end, paint): painted largest first, then by rank,
|
||||
// so inner nodes and winning patterns overwrite.
|
||||
let mut captures: Vec<(usize, usize, usize, usize, Paint)> = Vec::new();
|
||||
let mut cursor = QueryCursor::new();
|
||||
let mut matches = cursor.matches(&q.query, tree.root_node(), text.as_bytes());
|
||||
while let Some(m) = matches.next() {
|
||||
if !q.accepts(m, text) {
|
||||
continue;
|
||||
}
|
||||
for c in m.captures {
|
||||
if let Some(paint) = q.paints[c.index as usize] {
|
||||
let r = c.node.byte_range();
|
||||
if r.start < r.end {
|
||||
let rank = if q.first_wins { usize::MAX - m.pattern_index } else { m.pattern_index };
|
||||
captures.push((r.end - r.start, rank, r.start, r.end, paint));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
captures.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
|
||||
|
||||
let mut painted = vec![NONE; text.len()];
|
||||
for &(_, _, start, end, paint) in &captures {
|
||||
let v = match paint {
|
||||
Paint::Kind(k) => 1 + k as u8,
|
||||
Paint::Clear => NONE,
|
||||
};
|
||||
painted[start..end].fill(v);
|
||||
}
|
||||
|
||||
let lines = LineIndex::new(text);
|
||||
let mut data = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < painted.len() {
|
||||
let v = painted[i];
|
||||
let start = i;
|
||||
while i < painted.len() && painted[i] == v {
|
||||
i += 1;
|
||||
}
|
||||
// Node boundaries are char boundaries; whitespace-only runs stay uncoloured.
|
||||
if v != NONE && text.is_char_boundary(start) && text.is_char_boundary(i) && !text[start..i].trim().is_empty() {
|
||||
data.extend([lines.utf16_at(start) as u32, lines.utf16_at(i) as u32, (v - 1) as u32]);
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capture_names_fold_to_the_longest_known_prefix() {
|
||||
use SyntaxHighlightKind as K;
|
||||
assert_eq!(paint_for("keyword.function"), Some(Paint::Kind(K::Keyword)));
|
||||
assert_eq!(paint_for("string.special.symbol"), Some(Paint::Kind(K::Atom)));
|
||||
assert_eq!(paint_for("string.special.path"), Some(Paint::Kind(K::StringSpecial)));
|
||||
assert_eq!(paint_for("comment.doc.__attribute__"), Some(Paint::Kind(K::DocComment)));
|
||||
assert_eq!(paint_for("punctuation.bracket"), Some(Paint::Kind(K::Punctuation)));
|
||||
assert_eq!(paint_for("embedded"), Some(Paint::Clear));
|
||||
assert_eq!(paint_for("__name__"), None);
|
||||
assert_eq!(paint_for("spell"), None);
|
||||
}
|
||||
|
||||
/// `(text, kind)` of every highlighted range.
|
||||
fn spans(lang: &str, text: &str) -> Vec<(String, SyntaxHighlightKind)> {
|
||||
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new(lang), text).unwrap();
|
||||
let units: Vec<u16> = text.encode_utf16().collect();
|
||||
h.data
|
||||
.chunks(3)
|
||||
.map(|t| (String::from_utf16(&units[t[0] as usize..t[1] as usize]).unwrap(), h.kinds[t[2] as usize]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlights_elixir() {
|
||||
use SyntaxHighlightKind as K;
|
||||
let src = "defmodule Greeter do\n @moduledoc \"Hi\"\n # 😀 note\n def hello(name, _opts) do\n IO.puts(\"Hello #{name}\")\n :ok\n end\nend\n";
|
||||
let got = spans("elixir", src);
|
||||
let kind = |t: &str| got.iter().find(|(s, _)| s == t).map(|(_, k)| *k);
|
||||
assert_eq!(kind("defmodule"), Some(K::Keyword));
|
||||
assert_eq!(kind("Greeter"), Some(K::Namespace));
|
||||
assert_eq!(kind("\"Hi\""), Some(K::DocComment));
|
||||
assert_eq!(kind("# 😀 note"), Some(K::Comment));
|
||||
assert_eq!(kind("def"), Some(K::Keyword));
|
||||
assert_eq!(kind("hello"), Some(K::FunctionCall));
|
||||
assert_eq!(kind("_opts"), Some(K::Variable));
|
||||
assert_eq!(kind("puts"), Some(K::FunctionCall));
|
||||
// Interpolation clears the string colour; its contents are coloured on their own.
|
||||
assert_eq!(kind("\"Hello "), Some(K::String));
|
||||
assert_eq!(kind("#{"), Some(K::Punctuation));
|
||||
assert_eq!(kind(":ok"), Some(K::Atom));
|
||||
assert_eq!(kind("end"), Some(K::Keyword));
|
||||
// Sorted and non-overlapping.
|
||||
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new("elixir"), src).unwrap();
|
||||
assert!(h.data.chunks(3).zip(h.data.chunks(3).skip(1)).all(|(a, b)| a[0] < a[1] && a[1] <= b[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlights_other_grammar_only_languages() {
|
||||
use SyntaxHighlightKind as K;
|
||||
type Expect<'a> = &'a [(&'a str, SyntaxHighlightKind)];
|
||||
let cases: &[(&str, &str, Expect)] = &[
|
||||
(
|
||||
"zig",
|
||||
"const std = @import(\"std\");\n// hi\npub fn main() void {\n var x: u32 = 42;\n _ = x;\n}\n",
|
||||
&[
|
||||
("const", K::Keyword),
|
||||
("\"std\"", K::String),
|
||||
("// hi", K::Comment),
|
||||
("42", K::Number),
|
||||
("u32", K::Builtin),
|
||||
],
|
||||
),
|
||||
(
|
||||
"nix",
|
||||
"{ pkgs ? import <nixpkgs> {} }:\n# hi\nlet x = 1; in pkgs.mkShell { name = \"dev\"; }\n",
|
||||
&[
|
||||
("let", K::Keyword),
|
||||
("# hi", K::Comment),
|
||||
("1", K::Number),
|
||||
("\"dev\"", K::String),
|
||||
("import", K::Builtin),
|
||||
],
|
||||
),
|
||||
(
|
||||
"graphql",
|
||||
"# hi\nquery Hero($id: ID!) @cached {\n hero(id: $id) { name ...Friends }\n}\nenum Episode { NEWHOPE }\n",
|
||||
&[
|
||||
("# hi", K::Comment),
|
||||
("query", K::Keyword),
|
||||
("Hero", K::FunctionCall),
|
||||
("$id", K::Variable),
|
||||
("ID", K::Type),
|
||||
("@cached", K::Attribute),
|
||||
("name", K::Property),
|
||||
("Friends", K::FunctionCall),
|
||||
("NEWHOPE", K::Constant),
|
||||
],
|
||||
),
|
||||
(
|
||||
"hcl",
|
||||
"# hi\nresource \"aws_instance\" \"web\" {\n ami = var.ami\n count = 2\n tags = { Name = \"web-${var.env}\" }\n name = upper(\"x\")\n}\n",
|
||||
&[
|
||||
("# hi", K::Comment),
|
||||
("resource", K::Keyword),
|
||||
("aws_instance", K::Type),
|
||||
("ami", K::Property),
|
||||
("2", K::Number),
|
||||
("upper", K::FunctionCall),
|
||||
("\"web-", K::String),
|
||||
("env", K::Property),
|
||||
("var", K::Variable),
|
||||
],
|
||||
),
|
||||
("make", "# hi\nCC := gcc\nall: main.o\n\t$(CC) -o app main.o\n", &[("# hi", K::Comment)]),
|
||||
];
|
||||
for (lang, src, expect) in cases {
|
||||
let got = spans(lang, src);
|
||||
for (text, kind) in *expect {
|
||||
assert!(got.iter().any(|(s, k)| s == text && k == kind), "{lang}: {text:?} as {kind:?} in {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn languages_without_a_query_have_none() {
|
||||
assert_eq!(crate::Syntax::new().highlights(&ide_core::LanguageId::new("rust"), "fn a() {}"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_highlights_query_compiles() {
|
||||
for spec in super::super::grammars::SPECS {
|
||||
if let Some(h) = &spec.highlights {
|
||||
let lang = Language::new(spec.language);
|
||||
if let Err(e) = HighlightQuery::new(&lang, h.query, h.first_wins) {
|
||||
panic!("{}: {e}", spec.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lua_patterns_translate() {
|
||||
assert_eq!(lua_pattern_to_regex("^[A-Z][A-Z_0-9]+$"), "^[A-Z][A-Z_0-9]+$");
|
||||
assert_eq!(lua_pattern_to_regex("^//!"), "^//!");
|
||||
assert_eq!(lua_pattern_to_regex("^%u[%w_]*$"), "^[A-Z][A-Za-z0-9_]*$");
|
||||
assert_eq!(lua_pattern_to_regex("a.-b%."), "a.*?b\\.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legend_matches_discriminants() {
|
||||
for (i, k) in SyntaxHighlightKind::ALL.iter().enumerate() {
|
||||
assert_eq!(*k as usize, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ impl<'a> LineIndex<'a> {
|
||||
}
|
||||
|
||||
/// UTF-16 offset of a char-boundary byte offset.
|
||||
fn utf16_at(&self, byte: usize) -> usize {
|
||||
pub(crate) fn utf16_at(&self, byte: usize) -> usize {
|
||||
if self.checkpoints.is_empty() {
|
||||
return byte;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Comments and string literals of a text, for Find in Files' search context
|
||||
//! filter ("In comments", "Except string literals", …).
|
||||
|
||||
use super::folding::is_comment;
|
||||
use tree_sitter::{Node, Tree, TreeCursor};
|
||||
|
||||
/// What a [`Literal`] range is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LiteralKind {
|
||||
Comment,
|
||||
String,
|
||||
}
|
||||
|
||||
/// A comment or string literal: byte range of the outermost node.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Literal {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: LiteralKind,
|
||||
}
|
||||
|
||||
fn kind_of(node: &Node<'_>) -> Option<LiteralKind> {
|
||||
if !node.is_named() {
|
||||
return None;
|
||||
}
|
||||
let kind = node.kind();
|
||||
if is_comment(kind) {
|
||||
Some(LiteralKind::Comment)
|
||||
} else if kind.contains("string") || matches!(kind, "char_literal" | "character_literal" | "rune_literal") {
|
||||
Some(LiteralKind::String)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Comments and string literals in document order; nested ones (a string in a
|
||||
/// comment, interpolations) are covered by the outermost.
|
||||
pub(crate) fn literals(tree: &Tree) -> Vec<Literal> {
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = tree.walk();
|
||||
loop {
|
||||
let node = cursor.node();
|
||||
let kind = kind_of(&node);
|
||||
if let Some(kind) = kind {
|
||||
out.push(Literal { start: node.start_byte(), end: node.end_byte(), kind });
|
||||
}
|
||||
if kind.is_none() && cursor.goto_first_child() {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
if cursor.goto_next_sibling() {
|
||||
break;
|
||||
}
|
||||
if !cursor.goto_parent() {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`SpellingRegion`] covers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SpellingKind {
|
||||
Comment,
|
||||
String,
|
||||
/// The name a declaration introduces (not its uses).
|
||||
Name,
|
||||
}
|
||||
|
||||
/// Text the Typo inspection checks: byte range in document order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct SpellingRegion {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: SpellingKind,
|
||||
}
|
||||
|
||||
fn is_name_leaf(kind: &str) -> bool {
|
||||
kind.contains("identifier") || kind == "name"
|
||||
}
|
||||
|
||||
/// Whether the identifier leaf under `cursor` is the name a declaration
|
||||
/// introduces (`fn name`, `let pattern`, `int *declarator`, parameters,
|
||||
/// `name = …` assignments) rather than a use of one.
|
||||
fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
|
||||
let parent = node.parent().map(|p| p.kind()).unwrap_or_default();
|
||||
match cursor.field_name() {
|
||||
Some("name" | "pattern" | "declarator") => true,
|
||||
Some("left") => parent.contains("assignment") || parent.contains("declarator"),
|
||||
_ => parent.contains("parameter"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Comments, string literals and declared names, for spell checking.
|
||||
pub(crate) fn spelling_regions(tree: &Tree) -> Vec<SpellingRegion> {
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = tree.walk();
|
||||
loop {
|
||||
let node = cursor.node();
|
||||
let literal = kind_of(&node);
|
||||
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind };
|
||||
match literal {
|
||||
Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)),
|
||||
Some(LiteralKind::String) => out.push(region(SpellingKind::String)),
|
||||
None if node.is_named()
|
||||
&& node.child_count() == 0
|
||||
&& is_name_leaf(node.kind())
|
||||
&& declares(&cursor, &node) =>
|
||||
{
|
||||
out.push(region(SpellingKind::Name))
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if literal.is_none() && cursor.goto_first_child() {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
if cursor.goto_next_sibling() {
|
||||
break;
|
||||
}
|
||||
if !cursor.goto_parent() {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,27 @@
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges.
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
|
||||
|
||||
mod cache;
|
||||
mod folding;
|
||||
mod grammars;
|
||||
mod highlight;
|
||||
pub(crate) mod lines;
|
||||
mod literals;
|
||||
mod outline;
|
||||
mod selection;
|
||||
mod web;
|
||||
|
||||
use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag};
|
||||
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
|
||||
use grammars::{SPECS, Spec};
|
||||
use ide_core::{LanguageId, OutlineItem, Range};
|
||||
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
|
||||
use ide_core::{LanguageId, OutlineItem, Pos, Range};
|
||||
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
|
||||
pub use outline::merge_visibility;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
use tree_sitter::{Language, Parser, Tree};
|
||||
pub use web::{CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, WebReference, WebReferenceKind};
|
||||
|
||||
/// Texts larger than this are not parsed (minified bundles, generated dumps).
|
||||
pub const MAX_PARSE_BYTES: usize = 16 * 1024 * 1024;
|
||||
@@ -31,6 +38,7 @@ pub(crate) struct Grammar {
|
||||
pub(crate) spec: &'static Spec,
|
||||
pub(crate) language: Language,
|
||||
outline: OnceLock<Option<outline::OutlineQuery>>,
|
||||
highlights: OnceLock<Option<highlight::HighlightQuery>>,
|
||||
kinds: OnceLock<folding::KindTable>,
|
||||
}
|
||||
|
||||
@@ -50,6 +58,17 @@ impl Grammar {
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
fn highlight_query(&self) -> Option<&highlight::HighlightQuery> {
|
||||
self.highlights
|
||||
.get_or_init(|| {
|
||||
let h = self.spec.highlights.as_ref()?;
|
||||
highlight::HighlightQuery::new(&self.language, h.query, h.first_wins)
|
||||
.inspect_err(|e| tracing::error!("highlights query for {} is invalid: {e}", self.spec.name))
|
||||
.ok()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -72,6 +91,7 @@ impl Syntax {
|
||||
spec,
|
||||
language: Language::new(spec.language),
|
||||
outline: OnceLock::new(),
|
||||
highlights: OnceLock::new(),
|
||||
kinds: OnceLock::new(),
|
||||
})
|
||||
.collect();
|
||||
@@ -102,6 +122,8 @@ impl Syntax {
|
||||
FP.get_or_init(|| {
|
||||
let mut h = blake3::Hasher::new();
|
||||
h.update(env!("CARGO_PKG_VERSION").as_bytes());
|
||||
// Bump when web definitions (`.class`, `#id`, `--var` tags) change.
|
||||
h.update(b"web-definitions-1");
|
||||
for s in SPECS {
|
||||
h.update(s.name.as_bytes());
|
||||
h.update(&Language::new(s.language).abi_version().to_le_bytes());
|
||||
@@ -126,7 +148,8 @@ impl Syntax {
|
||||
/// Whether [`Syntax::tags`] can return anything for this language (data
|
||||
/// formats such as JSON only have an outline). Lets indexers skip parsing.
|
||||
pub fn has_symbols(&self, lang: &LanguageId) -> bool {
|
||||
self.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
|
||||
self.web_grammar(lang).is_some()
|
||||
|| self.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
|
||||
}
|
||||
|
||||
pub fn outline(&self, lang: &LanguageId, text: &str) -> Vec<OutlineItem> {
|
||||
@@ -143,11 +166,80 @@ impl Syntax {
|
||||
}
|
||||
|
||||
pub fn tags(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
|
||||
let mut tags = self
|
||||
.analyze(lang, text, |g, tree, text| {
|
||||
let query = g.outline_query()?;
|
||||
Some(outline::tags(g, query, tree, text))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
tags.extend(self.web_definitions(lang, text));
|
||||
tags
|
||||
}
|
||||
|
||||
/// The grammar web features parse `lang` with: its own for HTML and CSS, the
|
||||
/// CSS grammar for SCSS / Less (selectors and custom properties parse alike),
|
||||
/// HTML for Vue / Svelte single-file components.
|
||||
fn web_grammar(&self, lang: &LanguageId) -> Option<&Grammar> {
|
||||
let name = match lang.as_str() {
|
||||
"scss" | "less" => "css",
|
||||
"vue" | "svelte" => "html",
|
||||
_ => self.grammar(lang).map(|g| g.spec.name)?,
|
||||
};
|
||||
web::is_web_grammar(name).then(|| self.grammar(&LanguageId::new(name))).flatten()
|
||||
}
|
||||
|
||||
fn with_web_tree<R>(
|
||||
&self,
|
||||
lang: &LanguageId,
|
||||
text: &str,
|
||||
f: impl FnOnce(&Grammar, Option<&Grammar>, &Tree) -> R,
|
||||
) -> Option<R> {
|
||||
let g = self.web_grammar(lang)?;
|
||||
if text.len() > MAX_PARSE_BYTES {
|
||||
return None;
|
||||
}
|
||||
let tree = parse(&g.language, text, None)?;
|
||||
Some(f(g, self.grammar(&LanguageId::new("css")), &tree))
|
||||
}
|
||||
|
||||
/// CSS class (`.card`), id (`#main`) and custom property (`--accent`)
|
||||
/// definitions of a stylesheet or of the `<style>` elements of a document.
|
||||
pub fn web_definitions(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
|
||||
self.with_web_tree(lang, text, |g, css, tree| web::definitions(g, css, tree, text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The `class` / `id` / `href="#…"` / `var(--…)` reference at `pos`.
|
||||
pub fn web_reference_at(&self, lang: &LanguageId, text: &str, pos: Pos) -> Option<WebReference> {
|
||||
self.with_web_tree(lang, text, |g, css, tree| web::reference_at(g, css, tree, text, pos)).flatten()
|
||||
}
|
||||
|
||||
/// File paths written in an HTML document or stylesheet (`href`, `src`, `srcset`, `url()`, `@import`).
|
||||
pub fn web_file_references(&self, lang: &LanguageId, text: &str) -> Vec<FileReference> {
|
||||
self.with_web_tree(lang, text, |g, css, tree| web::file_references(g, css, tree, text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Value ranges of the `id="name"` / `name="name"` attributes in an HTML document.
|
||||
pub fn web_anchors(&self, lang: &LanguageId, text: &str, name: &str) -> Vec<Range> {
|
||||
self.with_web_tree(lang, text, |_, _, tree| web::anchors(tree, text, name)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Highlighting from the grammar's own query; `None` without one.
|
||||
pub fn highlights(&self, lang: &LanguageId, text: &str) -> Option<SyntaxHighlights> {
|
||||
self.analyze(lang, text, |g, tree, text| {
|
||||
let query = g.outline_query()?;
|
||||
Some(outline::tags(g, query, tree, text))
|
||||
Some(SyntaxHighlights::new(highlight::highlights(g.highlight_query()?, tree, text)))
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Comments and string literals of `text` (byte ranges, document order);
|
||||
/// `None` without a grammar for `lang` or for texts too large to parse.
|
||||
pub fn literals(&self, lang: &LanguageId, text: &str) -> Option<Vec<Literal>> {
|
||||
self.analyze(lang, text, |_, tree, _| Some(literals::literals(tree)))
|
||||
}
|
||||
|
||||
/// Comments, string literals and declared names (byte ranges, document
|
||||
/// order) for the Typo inspection; `None` like [`Self::literals`].
|
||||
pub fn spelling_regions(&self, lang: &LanguageId, text: &str) -> Option<Vec<SpellingRegion>> {
|
||||
self.analyze(lang, text, |_, tree, _| Some(literals::spelling_regions(tree)))
|
||||
}
|
||||
|
||||
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
use super::Grammar;
|
||||
use super::lines::LineIndex;
|
||||
use crate::SymbolTag;
|
||||
use ide_core::{OutlineItem, SymbolKind};
|
||||
use ide_core::{OutlineItem, SymbolKind, Visibility};
|
||||
use std::collections::HashMap;
|
||||
use tree_sitter::{Node, Query, QueryCursor, StreamingIterator, Tree};
|
||||
|
||||
@@ -139,11 +139,16 @@ struct Raw {
|
||||
container_name: String,
|
||||
explicit_container: Option<String>,
|
||||
detail: Option<String>,
|
||||
/// From a modifier keyword in the declaration (`pub`, `private`, ...).
|
||||
visibility: Option<Visibility>,
|
||||
/// Rust `impl Trait for Type`: members take the trait's visibility.
|
||||
trait_impl: bool,
|
||||
}
|
||||
|
||||
struct Built {
|
||||
raw: Raw,
|
||||
kind: SymbolKind,
|
||||
visibility: Option<Visibility>,
|
||||
children: Vec<Built>,
|
||||
}
|
||||
|
||||
@@ -188,6 +193,7 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
|
||||
base = last.to_owned();
|
||||
kind = ItemKind::Symbol(SymbolKind::Method);
|
||||
}
|
||||
let trait_impl = kind == ItemKind::Impl && trait_.is_some();
|
||||
let name = match (kind, trait_) {
|
||||
(ItemKind::Impl, Some(t)) => format!("impl {} for {base}", clean(node_text(&t, text), 120)),
|
||||
(ItemKind::Impl, None) => format!("impl {base}"),
|
||||
@@ -213,6 +219,8 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
|
||||
container_name,
|
||||
explicit_container: container,
|
||||
detail: detail.map(|d| clean(node_text(&d, text), 80)).filter(|d| !d.is_empty()),
|
||||
visibility: explicit_visibility(&node, text),
|
||||
trait_impl,
|
||||
};
|
||||
match by_node.get(&raw.node_id) {
|
||||
Some(existing) if existing.pattern <= raw.pattern => {}
|
||||
@@ -239,6 +247,7 @@ fn build_tree(g: &Grammar, raws: Vec<Raw>) -> Vec<Built> {
|
||||
push_child(&mut stack, &mut roots, done);
|
||||
}
|
||||
let parent_kind = stack.last().map(|p| p.raw.kind);
|
||||
let parent_trait_impl = stack.last().is_some_and(|p| p.raw.trait_impl);
|
||||
let mut kind = raw.kind.symbol_kind();
|
||||
if kind == SymbolKind::Function && parent_kind.is_some_and(ItemKind::holds_methods) {
|
||||
kind = SymbolKind::Method;
|
||||
@@ -250,7 +259,10 @@ fn build_tree(g: &Grammar, raws: Vec<Raw>) -> Vec<Built> {
|
||||
kind = SymbolKind::Constructor;
|
||||
}
|
||||
}
|
||||
stack.push(Built { raw, kind, children: Vec::new() });
|
||||
let visibility = raw
|
||||
.visibility
|
||||
.or_else(|| implicit_visibility(g.spec.name, raw.kind, kind, &raw.name, parent_kind, parent_trait_impl));
|
||||
stack.push(Built { raw, kind, visibility, children: Vec::new() });
|
||||
}
|
||||
while let Some(done) = stack.pop() {
|
||||
push_child(&mut stack, &mut roots, done);
|
||||
@@ -278,6 +290,7 @@ pub(crate) fn outline(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) ->
|
||||
range: b.raw.range,
|
||||
selection_range: b.raw.sel,
|
||||
children: b.children.into_iter().map(convert).collect(),
|
||||
visibility: b.visibility,
|
||||
}
|
||||
}
|
||||
collect(g, q, tree, text).into_iter().map(convert).collect()
|
||||
@@ -308,6 +321,107 @@ pub(crate) fn tags(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Ve
|
||||
out
|
||||
}
|
||||
|
||||
/// Visibility spelled out by a modifier child (`visibility_modifier`, `modifiers`,
|
||||
/// `accessibility_modifier`, ...) of the declaration.
|
||||
fn explicit_visibility(node: &Node, text: &str) -> Option<Visibility> {
|
||||
let mut cursor = node.walk();
|
||||
let mut found: Option<Visibility> = None;
|
||||
for child in node.children(&mut cursor) {
|
||||
if !child.kind().contains("modifier") {
|
||||
continue;
|
||||
}
|
||||
let t = node_text(&child, text);
|
||||
if child.kind() == "visibility_modifier" && t.starts_with("pub") {
|
||||
// Rust: `pub` / `pub(crate)` / `pub(super)` / `pub(in path)`.
|
||||
let v = if t.trim() == "pub" { Visibility::Public } else { Visibility::Package };
|
||||
found = Some(found.map_or(v, |f| narrower(f, v)));
|
||||
continue;
|
||||
}
|
||||
for word in t.split(|c: char| !c.is_ascii_alphanumeric() && c != '_') {
|
||||
let v = match word {
|
||||
"public" | "open" => Visibility::Public,
|
||||
"protected" => Visibility::Protected,
|
||||
"internal" | "fileprivate" => Visibility::Package,
|
||||
"private" => Visibility::Private,
|
||||
_ => continue,
|
||||
};
|
||||
found = Some(found.map_or(v, |f| narrower(f, v)));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Several keywords (C# `private protected`): the narrower one wins.
|
||||
fn narrower(a: Visibility, b: Visibility) -> Visibility {
|
||||
let rank = |v: Visibility| match v {
|
||||
Visibility::Public => 0,
|
||||
Visibility::Protected => 1,
|
||||
Visibility::Package => 2,
|
||||
Visibility::Private => 3,
|
||||
};
|
||||
if rank(a) >= rank(b) { a } else { b }
|
||||
}
|
||||
|
||||
/// The language's default when no modifier is written.
|
||||
fn implicit_visibility(
|
||||
lang: &str,
|
||||
item: ItemKind,
|
||||
kind: SymbolKind,
|
||||
name: &str,
|
||||
parent: Option<ItemKind>,
|
||||
parent_trait_impl: bool,
|
||||
) -> Option<Visibility> {
|
||||
use SymbolKind as K;
|
||||
if matches!(item, ItemKind::Impl | ItemKind::Extension | ItemKind::Heading)
|
||||
|| matches!(kind, K::EnumMember | K::Package | K::Namespace)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let in_interface = matches!(parent, Some(ItemKind::Symbol(K::Interface | K::Trait)));
|
||||
match lang {
|
||||
"rust" => (!in_interface && !parent_trait_impl && kind != K::Macro).then_some(Visibility::Private),
|
||||
"java" => (!in_interface).then_some(Visibility::Package),
|
||||
"csharp" => match parent {
|
||||
_ if in_interface => None,
|
||||
Some(ItemKind::Symbol(K::Class | K::Struct | K::Enum)) => Some(Visibility::Private),
|
||||
_ => Some(Visibility::Package),
|
||||
},
|
||||
"go" => name.starts_with(|c: char| c.is_lowercase() || c == '_').then_some(Visibility::Package),
|
||||
"python" => {
|
||||
(name.starts_with('_') && !(name.starts_with("__") && name.ends_with("__"))).then_some(Visibility::Private)
|
||||
}
|
||||
"dart" => name.starts_with('_').then_some(Visibility::Private),
|
||||
"typescript" | "tsx" | "javascript" => name.starts_with('#').then_some(Visibility::Private),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies tree-sitter visibility onto language-server symbols (which carry none),
|
||||
/// matching by name and identifier start.
|
||||
pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
|
||||
fn index(items: &[OutlineItem], out: &mut HashMap<(ide_core::Pos, String), Visibility>) {
|
||||
for i in items {
|
||||
if let Some(v) = i.visibility {
|
||||
out.insert((i.selection_range.start, i.name.clone()), v);
|
||||
}
|
||||
index(&i.children, out);
|
||||
}
|
||||
}
|
||||
fn apply(items: &mut [OutlineItem], map: &HashMap<(ide_core::Pos, String), Visibility>) {
|
||||
for i in items {
|
||||
if i.visibility.is_none() {
|
||||
i.visibility = map.get(&(i.selection_range.start, i.name.clone())).copied();
|
||||
}
|
||||
apply(&mut i.children, map);
|
||||
}
|
||||
}
|
||||
let mut map = HashMap::new();
|
||||
index(source, &mut map);
|
||||
if !map.is_empty() {
|
||||
apply(target, &map);
|
||||
}
|
||||
}
|
||||
|
||||
/// End of `node` without trailing whitespace (C macros and others include the newline).
|
||||
fn trimmed_end(node: &Node, text: &str) -> usize {
|
||||
let (s, e) = (node.start_byte(), node.end_byte());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
use crate::FoldKind;
|
||||
use ide_core::{OutlineItem, Pos, SymbolKind};
|
||||
use ide_core::{OutlineItem, Pos, SymbolKind, Visibility};
|
||||
|
||||
fn syntax() -> &'static Syntax {
|
||||
static S: OnceLock<Syntax> = OnceLock::new();
|
||||
@@ -1085,3 +1085,211 @@ fn large_input_is_not_parsed() {
|
||||
let big = "a".repeat(MAX_PARSE_BYTES + 1);
|
||||
assert!(syntax().outline(&lang("rust"), &big).is_empty());
|
||||
}
|
||||
|
||||
// --- web references -------------------------------------------------------------
|
||||
|
||||
fn web_defs(id: &str, src: &str) -> Vec<(String, SymbolKind, u32, u32)> {
|
||||
syntax()
|
||||
.web_definitions(&lang(id), src)
|
||||
.into_iter()
|
||||
.map(|t| (t.name, t.kind, t.range.start.line, t.range.start.col))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn web_ref(id: &str, src: &str) -> Option<(WebReferenceKind, String, u32, u32)> {
|
||||
let at = src.find('|').expect("caret marker");
|
||||
let text = src.replace('|', "");
|
||||
let line = text[..at].matches('\n').count() as u32;
|
||||
let col = (at - text[..at].rfind('\n').map_or(0, |i| i + 1)) as u32;
|
||||
syntax()
|
||||
.web_reference_at(&lang(id), &text, Pos::new(line, col))
|
||||
.map(|r| (r.kind, r.name, r.range.start.col, r.range.end.col))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_definitions_of_stylesheets_and_style_elements() {
|
||||
let css = ".a.b, div#main > .c:hover { color: var(--x); --y: 1px; }\n@media (x) { .d {} }\n";
|
||||
assert_eq!(
|
||||
web_defs("css", css),
|
||||
vec![
|
||||
(".a".into(), CSS_CLASS, 0, 1),
|
||||
(".b".into(), CSS_CLASS, 0, 3),
|
||||
("#main".into(), CSS_ID, 0, 10),
|
||||
(".c".into(), CSS_CLASS, 0, 18),
|
||||
("--y".into(), CSS_VARIABLE, 0, 45),
|
||||
(".d".into(), CSS_CLASS, 1, 14),
|
||||
]
|
||||
);
|
||||
// Pseudo-classes (`:hover`) are not classes; nested SCSS rules parse with the CSS grammar.
|
||||
assert!(!web_defs("css", css).iter().any(|d| d.0 == ".hover"));
|
||||
assert!(web_defs("scss", ".card { &:hover { } .title { } }").iter().any(|d| d.0 == ".title"));
|
||||
let html = "<p class=\"x\">\n<style>\n .card { --gap: 2px }\n</style>";
|
||||
assert_eq!(web_defs("html", html), vec![(".card".into(), CSS_CLASS, 2, 3), ("--gap".into(), CSS_VARIABLE, 2, 10)]);
|
||||
assert!(syntax().tags(&lang("css"), css).iter().any(|t| t.name == ".a"));
|
||||
assert!(syntax().has_symbols(&lang("css")) && syntax().has_symbols(&lang("vue")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_references_in_attributes_and_stylesheets() {
|
||||
use WebReferenceKind::*;
|
||||
assert_eq!(web_ref("html", r##"<div class="card bi|g">"##), Some((Class, "big".into(), 17, 20)));
|
||||
assert_eq!(web_ref("html", r##"<div class="|card big">"##), Some((Class, "card".into(), 12, 16)));
|
||||
assert_eq!(web_ref("html", r##"<div id="ma|in">"##), Some((Id, "main".into(), 9, 13)));
|
||||
assert_eq!(web_ref("html", r##"<a href="#to|p">"##), Some((Anchor, "top".into(), 9, 13)));
|
||||
assert_eq!(web_ref("html", r##"<a href="page.ht|ml">"##), None);
|
||||
assert_eq!(
|
||||
web_ref("html", r##"<p style="color: var(--ac|cent)">"##),
|
||||
Some((CssVariable, "--accent".into(), 21, 29))
|
||||
);
|
||||
assert_eq!(web_ref("html", "<style>\n.a { color: var(--x|) }\n</style>").map(|r| r.1), Some("--x".into()));
|
||||
assert_eq!(web_ref("css", ".a { color: var(--a|ccent, red) }"), Some((CssVariable, "--accent".into(), 16, 24)));
|
||||
assert_eq!(web_ref("css", ".a { color: re|d }"), None);
|
||||
assert_eq!(web_ref("vue", r##"<template><div class="ti|tle"/></template>"##).map(|r| r.0), Some(Class));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_anchors_find_ids_and_names() {
|
||||
let html = "<h2 id=\"top\">x</h2>\n<a name=\"top\"></a>\n<p class=\"top\">";
|
||||
let found: Vec<(u32, u32)> =
|
||||
syntax().web_anchors(&lang("html"), html, "top").into_iter().map(|r| (r.start.line, r.start.col)).collect();
|
||||
assert_eq!(found, vec![(0, 8), (1, 9)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_file_references_in_attributes_and_stylesheets() {
|
||||
let refs = |id: &str, src: &str| -> Vec<String> {
|
||||
syntax().web_file_references(&lang(id), src).into_iter().map(|r| r.value).collect()
|
||||
};
|
||||
let html = concat!(
|
||||
"<link href=\"css/a.css\"><img srcset=\"a.png 1x, b.png 2x\" src=img/c.png alt=\"x\">\n",
|
||||
"<a href=\"#top\" class=\"k\">t</a><div style=\"background: url(d.svg)\"></div>\n",
|
||||
"<style>@import \"e.css\"; .x { background: url('f.png') }</style>",
|
||||
);
|
||||
assert_eq!(refs("html", html), ["css/a.css", "a.png", "b.png", "img/c.png", "#top", "d.svg", "e.css", "f.png"]);
|
||||
assert_eq!(refs("css", "@import url(g.css);\n.y { mask: url(\"h.svg#i\") }"), ["g.css", "h.svg#i"]);
|
||||
let first = &syntax().web_file_references(&lang("html"), html)[0];
|
||||
assert_eq!((first.range.start.col, first.range.end.col), (12, 21));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literals_are_outermost_comments_and_strings() {
|
||||
let src = "// note \"q\"\nfn main() { let s = \"a // b\"; /* c */ let c = 'x'; }\n";
|
||||
let found: Vec<(&str, LiteralKind)> =
|
||||
syntax().literals(&lang("rust"), src).unwrap().iter().map(|l| (&src[l.start..l.end], l.kind)).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
vec![
|
||||
("// note \"q\"", LiteralKind::Comment),
|
||||
("\"a // b\"", LiteralKind::String),
|
||||
("/* c */", LiteralKind::Comment),
|
||||
("'x'", LiteralKind::String),
|
||||
]
|
||||
);
|
||||
assert!(syntax().literals(&lang("plaintext"), "// x").is_none());
|
||||
}
|
||||
|
||||
/// `name: visibility` for every outline item, depth-first.
|
||||
fn visibilities(id: &str, src: &str) -> Vec<(String, Option<Visibility>)> {
|
||||
fn go(items: &[OutlineItem], out: &mut Vec<(String, Option<Visibility>)>) {
|
||||
for i in items {
|
||||
out.push((i.name.clone(), i.visibility));
|
||||
go(&i.children, out);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
go(&syntax().outline(&lang(id), src), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn vis_of(list: &[(String, Option<Visibility>)], name: &str) -> Option<Visibility> {
|
||||
list.iter().find(|(n, _)| n == name).unwrap_or_else(|| panic!("no {name} in {list:?}")).1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_visibility_rust() {
|
||||
let src = "pub struct S { a: i32, pub b: i32, pub(crate) c: i32 }\n\
|
||||
trait T { fn req(&self); }\n\
|
||||
impl T for S { fn req(&self) {} }\n\
|
||||
impl S { pub fn new() {} fn helper() {} }\n\
|
||||
fn main() {}\n";
|
||||
let v = visibilities("rust", src);
|
||||
assert_eq!(vis_of(&v, "S"), Some(Visibility::Public));
|
||||
assert_eq!(vis_of(&v, "a"), Some(Visibility::Private));
|
||||
assert_eq!(vis_of(&v, "b"), Some(Visibility::Public));
|
||||
assert_eq!(vis_of(&v, "c"), Some(Visibility::Package));
|
||||
assert_eq!(vis_of(&v, "new"), Some(Visibility::Public));
|
||||
assert_eq!(vis_of(&v, "helper"), Some(Visibility::Private));
|
||||
assert_eq!(vis_of(&v, "main"), Some(Visibility::Private));
|
||||
assert_eq!(vis_of(&v, "impl T for S"), None);
|
||||
// Trait members and trait impl members follow the trait.
|
||||
assert!(v.iter().filter(|(n, _)| n == "req").all(|(_, vis)| vis.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_visibility_java_ts_python() {
|
||||
let java = "public class A {\n private int x;\n protected void p() {}\n void pkg() {}\n public A() {}\n}\ninterface I { void m(); }\n";
|
||||
let v = visibilities("java", java);
|
||||
assert_eq!(vis_of(&v, "x"), Some(Visibility::Private));
|
||||
assert_eq!(vis_of(&v, "p"), Some(Visibility::Protected));
|
||||
assert_eq!(vis_of(&v, "pkg"), Some(Visibility::Package));
|
||||
assert_eq!(vis_of(&v, "A"), Some(Visibility::Public));
|
||||
assert_eq!(vis_of(&v, "m"), None);
|
||||
|
||||
let ts = "class C {\n private a = 1;\n protected b(): void {}\n c(): void {}\n #d = 2;\n}\n";
|
||||
let v = visibilities("typescript", ts);
|
||||
assert_eq!(vis_of(&v, "a"), Some(Visibility::Private));
|
||||
assert_eq!(vis_of(&v, "b"), Some(Visibility::Protected));
|
||||
assert_eq!(vis_of(&v, "c"), None);
|
||||
assert_eq!(vis_of(&v, "#d"), Some(Visibility::Private));
|
||||
|
||||
let py = "class K:\n def _hidden(self): pass\n def __init__(self): pass\n def shown(self): pass\n";
|
||||
let v = visibilities("python", py);
|
||||
assert_eq!(vis_of(&v, "_hidden"), Some(Visibility::Private));
|
||||
assert_eq!(vis_of(&v, "__init__"), None);
|
||||
assert_eq!(vis_of(&v, "shown"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_visibility_matches_by_name_and_position() {
|
||||
fn clear(items: &mut [OutlineItem]) {
|
||||
for i in items {
|
||||
i.visibility = None;
|
||||
clear(&mut i.children);
|
||||
}
|
||||
}
|
||||
let src = "struct S { a: i32 }\nfn f() {}\n";
|
||||
let ts = syntax().outline(&lang("rust"), src);
|
||||
let mut lsp = ts.clone();
|
||||
clear(&mut lsp);
|
||||
lsp[1].name = "renamed".into();
|
||||
crate::merge_visibility(&mut lsp, &ts);
|
||||
assert_eq!(lsp[0].visibility, Some(Visibility::Private));
|
||||
assert_eq!(lsp[0].children[0].visibility, Some(Visibility::Private));
|
||||
assert_eq!(lsp[1].visibility, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spelling_regions_cover_declared_names_only() {
|
||||
let src = "// note\nfn parse_input(raw_text: &str) -> Value { let mut counter = helper(raw_text); \"hi\" }\n";
|
||||
let found: Vec<(&str, SpellingKind)> =
|
||||
syntax().spelling_regions(&lang("rust"), src).unwrap().iter().map(|r| (&src[r.start..r.end], r.kind)).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
vec![
|
||||
("// note", SpellingKind::Comment),
|
||||
("parse_input", SpellingKind::Name),
|
||||
("raw_text", SpellingKind::Name),
|
||||
("counter", SpellingKind::Name),
|
||||
("\"hi\"", SpellingKind::String),
|
||||
]
|
||||
);
|
||||
let py = "def load_config(path, retries=3):\n \"\"\"Doc.\"\"\"\n total = 0\n";
|
||||
let names: Vec<&str> = syntax()
|
||||
.spelling_regions(&lang("python"), py)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|r| r.kind == SpellingKind::Name)
|
||||
.map(|r| &py[r.start..r.end])
|
||||
.collect();
|
||||
assert_eq!(names, ["load_config", "path", "retries", "total"]);
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
//! Web references that no language server resolves: HTML `class` / `id`
|
||||
//! attributes to the CSS selectors that style them, `href="#id"` to the element
|
||||
//! with that id, and `var(--x)` to the custom property's declarations.
|
||||
//!
|
||||
//! Definitions (`.card`, `#main`, `--accent`) come from stylesheets and the
|
||||
//! `<style>` elements of HTML documents and feed the symbol index (see
|
||||
//! [`super::Syntax::tags`]), so a lookup is an exact index query.
|
||||
|
||||
use super::lines::{LineIndex, utf16_to_byte};
|
||||
use super::{Grammar, parse};
|
||||
use crate::SymbolTag;
|
||||
use ide_core::{Pos, Range, SymbolKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use tree_sitter::{Node, Tree};
|
||||
|
||||
/// Index symbol kinds of web definitions; names carry the CSS sigil.
|
||||
pub const CSS_CLASS: SymbolKind = SymbolKind::Class;
|
||||
pub const CSS_ID: SymbolKind = SymbolKind::Field;
|
||||
pub const CSS_VARIABLE: SymbolKind = SymbolKind::Variable;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum WebReferenceKind {
|
||||
/// A class in a `class` / `className` attribute: `.name` selectors.
|
||||
Class,
|
||||
/// An `id` attribute value: `#name` selectors.
|
||||
Id,
|
||||
/// `href="#name"`: the element with that id in the same document.
|
||||
Anchor,
|
||||
/// `var(--name)`: the custom property's declarations.
|
||||
CssVariable,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebReference {
|
||||
pub kind: WebReferenceKind,
|
||||
/// Without sigil: `card`, `main`, `--accent`.
|
||||
pub name: String,
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
impl WebReference {
|
||||
/// The index symbol a reference resolves to: `.card`, `#main`, `--accent`.
|
||||
pub fn symbol(&self) -> Option<(String, SymbolKind)> {
|
||||
match self.kind {
|
||||
WebReferenceKind::Class => Some((format!(".{}", self.name), CSS_CLASS)),
|
||||
WebReferenceKind::Id => Some((format!("#{}", self.name), CSS_ID)),
|
||||
WebReferenceKind::CssVariable => Some((self.name.clone(), CSS_VARIABLE)),
|
||||
WebReferenceKind::Anchor => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Grammars whose documents carry web definitions and references.
|
||||
pub(crate) fn is_web_grammar(name: &str) -> bool {
|
||||
matches!(name, "css" | "html")
|
||||
}
|
||||
|
||||
/// Stylesheet text embedded in a document: `(byte offset, text)`.
|
||||
fn css_regions<'t>(grammar: &str, tree: &Tree, text: &'t str) -> Vec<(usize, &'t str)> {
|
||||
match grammar {
|
||||
"css" => vec![(0, text)],
|
||||
"html" => {
|
||||
let mut out = Vec::new();
|
||||
walk(tree.root_node(), &mut |n| {
|
||||
if n.kind() == "style_element" {
|
||||
let mut c = n.walk();
|
||||
for raw in n.children(&mut c).filter(|c| c.kind() == "raw_text") {
|
||||
out.push((raw.start_byte(), &text[raw.start_byte()..raw.end_byte()]));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
out
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pre-order walk; `f` returns whether to descend.
|
||||
fn walk<'t>(n: Node<'t>, f: &mut dyn FnMut(Node<'t>) -> bool) {
|
||||
if !f(n) {
|
||||
return;
|
||||
}
|
||||
let mut c = n.walk();
|
||||
for child in n.children(&mut c) {
|
||||
walk(child, f);
|
||||
}
|
||||
}
|
||||
|
||||
fn text_of<'t>(n: Node, text: &'t str) -> &'t str {
|
||||
text.get(n.start_byte()..n.end_byte()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `.name`, `#name` and `--name` definitions in `text` (a stylesheet, or a document with `<style>`).
|
||||
pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<SymbolTag> {
|
||||
let idx = LineIndex::new(text);
|
||||
let mut out = Vec::new();
|
||||
for (base, css_text) in css_regions(g.spec.name, tree, text) {
|
||||
let parsed;
|
||||
let css_tree = if base == 0 && g.spec.name == "css" {
|
||||
tree
|
||||
} else {
|
||||
let Some(css) = css else { continue };
|
||||
let Some(t) = parse(&css.language, css_text, None) else { continue };
|
||||
parsed = t;
|
||||
&parsed
|
||||
};
|
||||
walk(css_tree.root_node(), &mut |n| {
|
||||
let def = match n.kind() {
|
||||
"class_name" if n.parent().is_some_and(|p| p.kind() == "class_selector") => {
|
||||
Some((format!(".{}", text_of(n, css_text)), CSS_CLASS))
|
||||
}
|
||||
"id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID)),
|
||||
"property_name" if text_of(n, css_text).starts_with("--") => {
|
||||
Some((text_of(n, css_text).to_owned(), CSS_VARIABLE))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some((name, kind)) = def {
|
||||
let range = idx.range(base + n.start_byte(), base + n.end_byte());
|
||||
out.push(SymbolTag { name, kind, container: None, range });
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn byte_at(text: &str, pos: Pos) -> Option<usize> {
|
||||
let mut start = 0;
|
||||
for _ in 0..pos.line {
|
||||
start += text[start..].find('\n')? + 1;
|
||||
}
|
||||
let line_end = text[start..].find('\n').map_or(text.len(), |i| start + i);
|
||||
Some(start + utf16_to_byte(&text[start..line_end], pos.col as usize))
|
||||
}
|
||||
|
||||
/// The whitespace-separated token of `value` (starting at byte `base`) around byte `at`.
|
||||
fn token_at(value: &str, base: usize, at: usize) -> Option<(usize, &str)> {
|
||||
let rel = at.checked_sub(base)?;
|
||||
let start = value[..rel.min(value.len())].rfind(char::is_whitespace).map_or(0, |i| i + 1);
|
||||
let end = value[rel.min(value.len())..].find(char::is_whitespace).map_or(value.len(), |i| rel + i);
|
||||
(start < end).then(|| (base + start, &value[start..end]))
|
||||
}
|
||||
|
||||
/// `var(--name)` around byte `at` of a stylesheet tree.
|
||||
fn css_variable_at(tree: &Tree, css_text: &str, at: usize) -> Option<(usize, usize, String)> {
|
||||
let mut n = tree.root_node().descendant_for_byte_range(at, at)?;
|
||||
if n.kind() != "plain_value" {
|
||||
// The caret right after `--x` in `var(--x)`.
|
||||
n = tree.root_node().descendant_for_byte_range(at.saturating_sub(1), at.saturating_sub(1))?;
|
||||
}
|
||||
let name = text_of(n, css_text);
|
||||
let call = n.parent()?.parent()?;
|
||||
let is_var = call.kind() == "call_expression"
|
||||
&& call
|
||||
.child_by_field_name("function_name")
|
||||
.or_else(|| call.child(0))
|
||||
.is_some_and(|f| text_of(f, css_text) == "var");
|
||||
(n.kind() == "plain_value" && name.starts_with("--") && is_var)
|
||||
.then(|| (n.start_byte(), n.end_byte(), name.to_owned()))
|
||||
}
|
||||
|
||||
/// The web reference at `pos` of a document parsed as `tree`.
|
||||
pub(crate) fn reference_at(
|
||||
g: &Grammar,
|
||||
css: Option<&Grammar>,
|
||||
tree: &Tree,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
) -> Option<WebReference> {
|
||||
let at = byte_at(text, pos)?;
|
||||
let idx = LineIndex::new(text);
|
||||
let make = |kind, from: usize, to: usize, name: String| WebReference { kind, name, range: idx.range(from, to) };
|
||||
|
||||
// Stylesheet regions: `var(--x)`.
|
||||
for (base, css_text) in css_regions(g.spec.name, tree, text) {
|
||||
if at < base || at > base + css_text.len() {
|
||||
continue;
|
||||
}
|
||||
let parsed;
|
||||
let css_tree = if g.spec.name == "css" {
|
||||
tree
|
||||
} else {
|
||||
parsed = parse(&css?.language, css_text, None)?;
|
||||
&parsed
|
||||
};
|
||||
let (from, to, name) = css_variable_at(css_tree, css_text, at - base)?;
|
||||
return Some(make(WebReferenceKind::CssVariable, base + from, base + to, name));
|
||||
}
|
||||
if g.spec.name != "html" {
|
||||
return None;
|
||||
}
|
||||
|
||||
// HTML attribute values.
|
||||
let node = tree.root_node().descendant_for_byte_range(at, at)?;
|
||||
let value = std::iter::successors(Some(node), |n| n.parent()).find(|n| n.kind() == "attribute_value")?;
|
||||
let attribute = std::iter::successors(value.parent(), |n| n.parent()).find(|n| n.kind() == "attribute")?;
|
||||
let attr_name = attribute.child(0).map(|n| text_of(n, text).to_ascii_lowercase())?;
|
||||
let (vs, vtext) = (value.start_byte(), text_of(value, text));
|
||||
match attr_name.as_str() {
|
||||
"class" | "classname" | "class:list" => {
|
||||
let (from, token) = token_at(vtext, vs, at)?;
|
||||
Some(make(WebReferenceKind::Class, from, from + token.len(), token.to_owned()))
|
||||
}
|
||||
"id" => {
|
||||
let (from, token) = token_at(vtext, vs, at)?;
|
||||
Some(make(WebReferenceKind::Id, from, from + token.len(), token.to_owned()))
|
||||
}
|
||||
"href" | "xlink:href" if vtext.len() > 1 && vtext.starts_with('#') => {
|
||||
Some(make(WebReferenceKind::Anchor, vs, vs + vtext.len(), vtext[1..].to_owned()))
|
||||
}
|
||||
"style" => {
|
||||
// An inline declaration list: parse it as the block of a rule.
|
||||
let wrapped = format!("x{{{vtext}}}");
|
||||
let t = parse(&css?.language, &wrapped, None)?;
|
||||
let (from, to, name) = css_variable_at(&t, &wrapped, at - vs + 2)?;
|
||||
Some(make(WebReferenceKind::CssVariable, vs + from - 2, vs + to - 2, name))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Elements whose `id` (or `<a name>`) is `name`: the targets of `href="#name"`.
|
||||
pub(crate) fn anchors(tree: &Tree, text: &str, name: &str) -> Vec<Range> {
|
||||
let idx = LineIndex::new(text);
|
||||
let mut out = Vec::new();
|
||||
walk(tree.root_node(), &mut |n| {
|
||||
if n.kind() == "attribute" {
|
||||
let attr = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase());
|
||||
if matches!(attr.as_deref(), Some("id" | "name")) {
|
||||
let mut found = None;
|
||||
walk(n, &mut |v| {
|
||||
if v.kind() == "attribute_value" && text_of(v, text) == name {
|
||||
found = Some(v);
|
||||
}
|
||||
found.is_none()
|
||||
});
|
||||
if let Some(v) = found {
|
||||
out.push(idx.range(v.start_byte(), v.end_byte()));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// A path written in a document: an HTML URL attribute, a CSS `url()` / `@import`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileReference {
|
||||
pub range: Range,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// HTML attributes whose value is a URL.
|
||||
const URL_ATTRIBUTES: &[&str] = &[
|
||||
"href",
|
||||
"src",
|
||||
"srcset",
|
||||
"action",
|
||||
"formaction",
|
||||
"poster",
|
||||
"data",
|
||||
"cite",
|
||||
"background",
|
||||
"manifest",
|
||||
"xlink:href",
|
||||
"longdesc",
|
||||
"icon",
|
||||
];
|
||||
|
||||
/// `url(…)` arguments and `@import` targets of a stylesheet: `(start, end)` byte ranges.
|
||||
fn css_paths(tree: &Tree, css_text: &str, out: &mut Vec<(usize, usize)>) {
|
||||
let target = |n: Node| -> Option<(usize, usize)> {
|
||||
let n =
|
||||
if n.kind() == "string_value" { n.named_child(0).filter(|c| c.kind() == "string_content")? } else { n };
|
||||
matches!(n.kind(), "plain_value" | "string_content").then(|| (n.start_byte(), n.end_byte()))
|
||||
};
|
||||
walk(tree.root_node(), &mut |n| {
|
||||
match n.kind() {
|
||||
"import_statement" => {
|
||||
if let Some(first) = n.named_child(0)
|
||||
&& first.kind() == "string_value"
|
||||
{
|
||||
out.extend(target(first));
|
||||
}
|
||||
}
|
||||
"call_expression" => {
|
||||
let is_url =
|
||||
n.named_child(0).is_some_and(|f| f.kind() == "function_name" && text_of(f, css_text) == "url");
|
||||
if is_url
|
||||
&& let Some(args) = n.child_by_field_name("arguments").or_else(|| n.named_child(1))
|
||||
&& let Some(arg) = args.named_child(0)
|
||||
{
|
||||
out.extend(target(arg));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// File paths written in an HTML document or a stylesheet.
|
||||
pub(crate) fn file_references(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<FileReference> {
|
||||
let idx = LineIndex::new(text);
|
||||
let mut spans: Vec<(usize, usize)> = Vec::new();
|
||||
for (base, css_text) in css_regions(g.spec.name, tree, text) {
|
||||
let parsed;
|
||||
let css_tree = if g.spec.name == "css" {
|
||||
tree
|
||||
} else {
|
||||
let Some(t) = css.and_then(|c| parse(&c.language, css_text, None)) else { continue };
|
||||
parsed = t;
|
||||
&parsed
|
||||
};
|
||||
let mut found = Vec::new();
|
||||
css_paths(css_tree, css_text, &mut found);
|
||||
spans.extend(found.into_iter().map(|(s, e)| (base + s, base + e)));
|
||||
}
|
||||
if g.spec.name == "html" {
|
||||
walk(tree.root_node(), &mut |n| {
|
||||
if n.kind() != "attribute" {
|
||||
return true;
|
||||
}
|
||||
let name = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase()).unwrap_or_default();
|
||||
let mut value = None;
|
||||
walk(n, &mut |v| {
|
||||
if v.kind() == "attribute_value" {
|
||||
value = Some(v);
|
||||
}
|
||||
value.is_none()
|
||||
});
|
||||
let Some(v) = value else { return false };
|
||||
let (vs, vtext) = (v.start_byte(), text_of(v, text));
|
||||
match name.as_str() {
|
||||
"srcset" => {
|
||||
// `a.png 1x, b.png 2x`: the URL of each candidate.
|
||||
let mut at = 0;
|
||||
for part in vtext.split(',') {
|
||||
let lead = part.len() - part.trim_start().len();
|
||||
let url = part.split_whitespace().next().unwrap_or_default();
|
||||
if !url.is_empty() {
|
||||
spans.push((vs + at + lead, vs + at + lead + url.len()));
|
||||
}
|
||||
at += part.len() + 1;
|
||||
}
|
||||
}
|
||||
"style" => {
|
||||
let wrapped = format!("x{{{vtext}}}");
|
||||
if let Some(t) = css.and_then(|c| parse(&c.language, &wrapped, None)) {
|
||||
let mut found = Vec::new();
|
||||
css_paths(&t, &wrapped, &mut found);
|
||||
spans.extend(found.into_iter().map(|(s, e)| (vs + s - 2, vs + e - 2)));
|
||||
}
|
||||
}
|
||||
_ if URL_ATTRIBUTES.contains(&name.as_str()) && !vtext.trim().is_empty() => {
|
||||
spans.push((vs, vs + vtext.len()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
false
|
||||
});
|
||||
}
|
||||
spans.sort_unstable();
|
||||
spans.into_iter().map(|(s, e)| FileReference { range: idx.range(s, e), value: text[s..e].to_owned() }).collect()
|
||||
}
|
||||
@@ -121,6 +121,7 @@ pub fn client_capabilities() -> Value {
|
||||
"honorsChangeAnnotations": false
|
||||
},
|
||||
"codeLens": { "dynamicRegistration": false },
|
||||
"documentLink": { "dynamicRegistration": false, "tooltipSupport": true },
|
||||
"formatting": { "dynamicRegistration": false },
|
||||
"rangeFormatting": { "dynamicRegistration": false },
|
||||
"rename": {
|
||||
@@ -156,6 +157,7 @@ pub fn client_capabilities() -> Value {
|
||||
"augmentsSyntaxTokens": true
|
||||
},
|
||||
"inlayHint": { "dynamicRegistration": false },
|
||||
"inlineCompletion": { "dynamicRegistration": true },
|
||||
"callHierarchy": { "dynamicRegistration": false },
|
||||
"typeHierarchy": { "dynamicRegistration": false }
|
||||
},
|
||||
@@ -203,8 +205,10 @@ pub fn capability_key(method: &str) -> Option<&'static str> {
|
||||
"textDocument/formatting" => "documentFormattingProvider",
|
||||
"textDocument/rangeFormatting" => "documentRangeFormattingProvider",
|
||||
"textDocument/inlayHint" => "inlayHintProvider",
|
||||
"textDocument/inlineCompletion" => "inlineCompletionProvider",
|
||||
"textDocument/semanticTokens" | "textDocument/semanticTokens/full" => "semanticTokensProvider",
|
||||
"textDocument/codeLens" => "codeLensProvider",
|
||||
"textDocument/documentLink" => "documentLinkProvider",
|
||||
"textDocument/prepareCallHierarchy" => "callHierarchyProvider",
|
||||
"textDocument/prepareTypeHierarchy" => "typeHierarchyProvider",
|
||||
_ => return None,
|
||||
|
||||
@@ -434,6 +434,101 @@ pub fn lsp_completion_item(text: &DocText, enc: Encoding, item: &CompletionItem)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- inline completion
|
||||
|
||||
/// `InlineCompletionList | InlineCompletionItem[] | null` → items (malformed ones skipped).
|
||||
pub fn inline_completion_items(conv: &Conv, path: &Path, v: Value, server: ServerId) -> Vec<InlineCompletionItem> {
|
||||
let items = match v {
|
||||
Value::Array(a) => a,
|
||||
Value::Object(mut o) => match o.remove("items") {
|
||||
Some(Value::Array(a)) => a,
|
||||
_ => Vec::new(),
|
||||
},
|
||||
_ => Vec::new(),
|
||||
};
|
||||
items
|
||||
.into_iter()
|
||||
.filter_map(|it| {
|
||||
let insert_text = match it.get("insertText")? {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Object(o) if o.get("kind").and_then(Value::as_str) == Some("snippet") => {
|
||||
snippet_text(o.get("value")?.as_str()?)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let range = it
|
||||
.get("range")
|
||||
.and_then(|r| serde_json::from_value::<lsp::Range>(r.clone()).ok())
|
||||
.map(|r| conv.range(path, r));
|
||||
let filter_text = it.get("filterText").and_then(Value::as_str).map(str::to_owned);
|
||||
let cmd = it.get("command").and_then(|c| serde_json::from_value::<lsp::Command>(c.clone()).ok());
|
||||
Some(InlineCompletionItem { insert_text, range, filter_text, command: cmd.map(command), server })
|
||||
})
|
||||
.filter(|i| !i.insert_text.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text a snippet inserts with every placeholder at its default:
|
||||
/// `foo(${1:a}, $2)$0` → `foo(a, )`; a choice takes its first option.
|
||||
pub fn snippet_text(snippet: &str) -> String {
|
||||
fn parse(chars: &[char], i: &mut usize, out: &mut String, nested: bool) {
|
||||
while let Some(&ch) = chars.get(*i) {
|
||||
let next = chars.get(*i + 1).copied();
|
||||
match ch {
|
||||
'\\' if next.is_some() => {
|
||||
out.extend(next);
|
||||
*i += 2;
|
||||
}
|
||||
'}' if nested => {
|
||||
*i += 1;
|
||||
return;
|
||||
}
|
||||
'$' if next.is_some_and(|c| c.is_ascii_digit()) => {
|
||||
*i += 1;
|
||||
while chars.get(*i).is_some_and(char::is_ascii_digit) {
|
||||
*i += 1;
|
||||
}
|
||||
}
|
||||
'$' if next == Some('{') => {
|
||||
*i += 2;
|
||||
while chars.get(*i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == '_') {
|
||||
*i += 1;
|
||||
}
|
||||
match chars.get(*i) {
|
||||
Some(':') => {
|
||||
*i += 1;
|
||||
parse(chars, i, out, true);
|
||||
}
|
||||
Some('|') => {
|
||||
*i += 1;
|
||||
let mut first = true;
|
||||
while let Some(&c) = chars.get(*i).filter(|c| **c != '|') {
|
||||
first &= c != ',';
|
||||
if first {
|
||||
out.push(c);
|
||||
}
|
||||
*i += 1;
|
||||
}
|
||||
*i = (*i + 2).min(chars.len());
|
||||
}
|
||||
// `${1}`, or a variable without a default.
|
||||
Some('}') => *i += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
out.push(ch);
|
||||
*i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let chars: Vec<char> = snippet.chars().collect();
|
||||
let mut out = String::new();
|
||||
parse(&chars, &mut 0, &mut out, false);
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- commands & actions
|
||||
|
||||
pub fn command(c: lsp::Command) -> Command {
|
||||
@@ -614,6 +709,7 @@ pub fn document_symbols(conv: &Conv, path: &Path, r: lsp::DocumentSymbolResponse
|
||||
range,
|
||||
selection_range: range,
|
||||
children: Vec::new(),
|
||||
visibility: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -632,6 +728,7 @@ fn document_symbol(conv: &Conv, path: &Path, s: lsp::DocumentSymbol) -> OutlineI
|
||||
range: conv.range(path, s.range),
|
||||
selection_range: conv.range(path, s.selection_range),
|
||||
children: s.children.unwrap_or_default().into_iter().map(|c| document_symbol(conv, path, c)).collect(),
|
||||
visibility: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -733,19 +830,34 @@ pub fn signature_help(conv_enc: Encoding, h: lsp::SignatureHelp) -> Option<Signa
|
||||
// ---------------------------------------------------------------- decorations
|
||||
|
||||
pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
|
||||
let label = match h.label {
|
||||
lsp::InlayHintLabel::String(s) => s,
|
||||
lsp::InlayHintLabel::LabelParts(parts) => parts.into_iter().map(|p| p.value).collect(),
|
||||
let tooltip_text = |t: lsp::InlayHintTooltip| match t {
|
||||
lsp::InlayHintTooltip::String(s) => s,
|
||||
lsp::InlayHintTooltip::MarkupContent(m) => m.value,
|
||||
};
|
||||
let (label, parts) = match h.label {
|
||||
lsp::InlayHintLabel::String(s) => (s, Vec::new()),
|
||||
lsp::InlayHintLabel::LabelParts(parts) => {
|
||||
let label = parts.iter().map(|p| p.value.as_str()).collect();
|
||||
let parts = parts
|
||||
.into_iter()
|
||||
.map(|p| InlayLabelPart {
|
||||
value: p.value,
|
||||
tooltip: p.tooltip.map(|t| match t {
|
||||
lsp::InlayHintLabelPartTooltip::String(s) => s,
|
||||
lsp::InlayHintLabelPartTooltip::MarkupContent(m) => m.value,
|
||||
}),
|
||||
location: p.location.as_ref().and_then(|l| conv.location(l)),
|
||||
})
|
||||
.collect();
|
||||
(label, parts)
|
||||
}
|
||||
};
|
||||
let kind = match h.kind {
|
||||
Some(lsp::InlayHintKind::TYPE) => InlayKind::Type,
|
||||
Some(lsp::InlayHintKind::PARAMETER) => InlayKind::Parameter,
|
||||
_ => InlayKind::Other,
|
||||
};
|
||||
let tooltip = h.tooltip.map(|t| match t {
|
||||
lsp::InlayHintTooltip::String(s) => s,
|
||||
lsp::InlayHintTooltip::MarkupContent(m) => m.value,
|
||||
});
|
||||
let tooltip = h.tooltip.map(tooltip_text);
|
||||
InlayHint {
|
||||
position: conv.pos(path, h.position),
|
||||
label,
|
||||
@@ -753,6 +865,7 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
|
||||
padding_left: h.padding_left.unwrap_or(false),
|
||||
padding_right: h.padding_right.unwrap_or(false),
|
||||
tooltip,
|
||||
parts,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -783,6 +896,27 @@ pub fn code_lens(conv: &Conv, path: &Path, l: lsp::CodeLens) -> CodeLens {
|
||||
CodeLens { range: conv.range(path, l.range), command: l.command.map(command) }
|
||||
}
|
||||
|
||||
pub fn document_link(conv: &Conv, path: &Path, l: lsp::DocumentLink) -> Option<DocumentLink> {
|
||||
let target = l.target?;
|
||||
let target = target.as_str();
|
||||
let (file, url) = match uri_to_path(target) {
|
||||
Some(p) => (Some(p), None),
|
||||
None => (None, Some(target.to_owned())),
|
||||
};
|
||||
let fragment = file
|
||||
.as_ref()
|
||||
.and_then(|_| target.split_once('#'))
|
||||
.map(|(_, f)| percent_encoding::percent_decode_str(f).decode_utf8_lossy().into_owned())
|
||||
.filter(|f| !f.is_empty());
|
||||
Some(DocumentLink {
|
||||
range: conv.range(path, l.range),
|
||||
path: file.map(Into::into),
|
||||
fragment,
|
||||
url,
|
||||
tooltip: l.tooltip,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec<Range>) -> Option<HierarchyItem> {
|
||||
let (path, uri) = uri_target(item.uri.as_str());
|
||||
Some(HierarchyItem {
|
||||
@@ -842,6 +976,7 @@ pub fn diagnostic(conv: &Conv, path: &Path, d: lsp::Diagnostic, server_name: &st
|
||||
}),
|
||||
unnecessary: tags.contains(&lsp::DiagnosticTag::UNNECESSARY),
|
||||
deprecated: tags.contains(&lsp::DiagnosticTag::DEPRECATED),
|
||||
server: Some(server_name.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -855,6 +990,25 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn snippet_text_takes_placeholder_defaults() {
|
||||
assert_eq!(snippet_text("foo(${1:a}, $2)$0"), "foo(a, )");
|
||||
assert_eq!(snippet_text("${1:outer ${2:inner}} \\$x ${3|one,two|}${TM_FILENAME}"), "outer inner $x one");
|
||||
assert_eq!(snippet_text("plain"), "plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_completion_shapes() {
|
||||
let conv = Conv::utf16();
|
||||
let path = Path::new("/a.rs");
|
||||
let list = inline_completion_items(&conv, path, json!([{ "insertText": "x" }]), ServerId(1));
|
||||
assert_eq!(list.len(), 1);
|
||||
assert!(inline_completion_items(&conv, path, Value::Null, ServerId(1)).is_empty());
|
||||
assert!(
|
||||
inline_completion_items(&conv, path, json!({ "items": [{ "label": "no text" }] }), ServerId(1)).is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
fn p(l: u32, c: u32) -> Pos {
|
||||
Pos::new(l, c)
|
||||
}
|
||||
@@ -1111,5 +1265,52 @@ mod tests {
|
||||
assert_eq!(h.label, ": Vec<u8>");
|
||||
assert_eq!(h.kind, InlayKind::Type);
|
||||
assert!(h.padding_left && !h.padding_right);
|
||||
assert_eq!(h.parts.len(), 2);
|
||||
assert!(h.parts.iter().all(|p| p.location.is_none()));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn inlay_label_parts_keep_locations() {
|
||||
let conv = Conv::utf16();
|
||||
let h: lsp::InlayHint = serde_json::from_value(json!({
|
||||
"position": {"line": 0, "character": 3},
|
||||
"label": [
|
||||
{"value": ": "},
|
||||
{"value": "Foo", "tooltip": "struct Foo",
|
||||
"location": {"uri": "file:///p/foo.rs", "range": {"start": {"line": 4, "character": 7}, "end": {"line": 4, "character": 10}}}}
|
||||
]
|
||||
}))
|
||||
.unwrap();
|
||||
let h = inlay_hint(&conv, Path::new("/a"), h);
|
||||
assert_eq!(h.label, ": Foo");
|
||||
let part = &h.parts[1];
|
||||
assert_eq!(part.value, "Foo");
|
||||
assert_eq!(part.tooltip.as_deref(), Some("struct Foo"));
|
||||
let loc = part.location.as_ref().unwrap();
|
||||
assert_eq!(loc.path, PathBuf::from("/p/foo.rs"));
|
||||
assert_eq!(loc.range.start, p(4, 7));
|
||||
assert_eq!(h.kind, InlayKind::Other);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn document_links_split_file_targets_and_urls() {
|
||||
let conv = Conv::utf16();
|
||||
let link = |target: Option<&str>| {
|
||||
serde_json::from_value::<lsp::DocumentLink>(json!({
|
||||
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 15 } },
|
||||
"target": target,
|
||||
}))
|
||||
.unwrap()
|
||||
};
|
||||
let here = Path::new("/p/index.html");
|
||||
let file = document_link(&conv, here, link(Some("file:///p/a%20b.md#L12"))).unwrap();
|
||||
assert_eq!(file.path.as_deref(), Some(Path::new("/p/a b.md")));
|
||||
assert_eq!(file.fragment.as_deref(), Some("L12"));
|
||||
assert_eq!(file.range, Range::new(p(0, 6), p(0, 15)));
|
||||
let web = document_link(&conv, here, link(Some("https://example.com/#top"))).unwrap();
|
||||
assert_eq!((web.path, web.url.as_deref(), web.fragment), (None, Some("https://example.com/#top"), None));
|
||||
assert!(document_link(&conv, here, link(None)).is_none());
|
||||
}
|
||||
}
|
||||
@@ -60,9 +60,9 @@ pub enum FileInspection {
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
/// Whether an installed language server is configured for `path` (by file
|
||||
/// name). Missing servers are not started, so a batch run doesn't prompt
|
||||
/// to install every language it meets.
|
||||
/// Whether an installed language server that can run here is configured
|
||||
/// for `path` (by file name). Missing servers are not started, so a batch
|
||||
/// run doesn't prompt to install every language it meets.
|
||||
pub fn serves_path(&self, path: &Path) -> bool {
|
||||
let lang = self.languages.detect(path, None);
|
||||
let Some(config) = self.languages.get(&lang) else { return false };
|
||||
@@ -71,7 +71,7 @@ impl LspManager {
|
||||
if let Some(hook) = self.config_hook.read().clone() {
|
||||
hook(&mut cfg, &self.project_root);
|
||||
}
|
||||
self.launcher.available(&cfg, &self.project_root)
|
||||
cfg.launch_error.is_none() && self.launcher.available(&cfg, &self.project_root)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,10 @@ const BUILD_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
const COMMAND_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
/// How long to retry while the project is still being imported.
|
||||
const IMPORT_WAIT: Duration = Duration::from_secs(90);
|
||||
/// Compile errors listed with a launch; the rest are only counted.
|
||||
const MAX_LAUNCH_ERRORS: usize = 10;
|
||||
/// Build markers can be published just after `java/buildWorkspace` answers.
|
||||
const ERRORS_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Result of `java/buildWorkspace` (jdtls `BuildWorkspaceStatus`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -70,6 +74,43 @@ pub struct JavaLaunchInfo {
|
||||
pub java_home: Option<ide_core::IpcPath>,
|
||||
/// The `java` launcher to use (filled in by the caller from the installed JDKs).
|
||||
pub java_exec: Option<String>,
|
||||
/// First compile errors of the workspace when the build had errors.
|
||||
pub errors: Vec<JavaCompileError>,
|
||||
/// All compile errors (`errors` is capped).
|
||||
pub error_count: u32,
|
||||
/// Likely causes of the errors worth telling the user (e.g. a missing Lombok agent).
|
||||
pub hints: Vec<String>,
|
||||
}
|
||||
|
||||
/// One error diagnostic; `line` / `column` are 1-based for display.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JavaCompileError {
|
||||
pub path: ide_core::IpcPath,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Error diagnostics sorted by file and position, capped at `limit`, and their total.
|
||||
pub fn compile_errors(
|
||||
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
|
||||
limit: usize,
|
||||
) -> (Vec<JavaCompileError>, u32) {
|
||||
let mut errors: Vec<JavaCompileError> = diagnostics
|
||||
.into_iter()
|
||||
.filter(|(_, d)| d.severity == Some(lsp_types::DiagnosticSeverity::ERROR))
|
||||
.map(|(path, d)| JavaCompileError {
|
||||
path: path.into(),
|
||||
line: d.range.start.line + 1,
|
||||
column: d.range.start.character + 1,
|
||||
message: d.message.lines().next().unwrap_or_default().to_owned(),
|
||||
})
|
||||
.collect();
|
||||
errors.sort_by(|a, b| (&a.path, a.line, a.column).cmp(&(&b.path, b.line, b.column)));
|
||||
let count = u32::try_from(errors.len()).unwrap_or(u32::MAX);
|
||||
errors.truncate(limit);
|
||||
(errors, count)
|
||||
}
|
||||
|
||||
/// `java.project.getClasspaths` result.
|
||||
@@ -138,6 +179,9 @@ impl LspManager {
|
||||
ide_core::event::ServerStatus::Missing => {
|
||||
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
|
||||
}
|
||||
ide_core::event::ServerStatus::Misconfigured => {
|
||||
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
|
||||
}
|
||||
_ => format!("jdtls is not ready ({status:?})"),
|
||||
}))
|
||||
}
|
||||
@@ -210,6 +254,10 @@ impl LspManager {
|
||||
/// Builds (when asked), then resolves the classpath and JDK of the module at `module`.
|
||||
pub async fn java_launch(&self, module: &Path, test: bool, build: bool) -> IdeResult<JavaLaunchInfo> {
|
||||
let build = if build { Some(self.java_build(module).await?) } else { None };
|
||||
let (errors, error_count) = match build {
|
||||
Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed) => self.java_compile_errors(module).await,
|
||||
_ => (Vec::new(), 0),
|
||||
};
|
||||
let cp = self.java_classpath(module, test).await?;
|
||||
let java_home = match self.java_vm_location(module).await {
|
||||
Ok(home) => home,
|
||||
@@ -225,9 +273,24 @@ impl LspManager {
|
||||
module_paths: cp.module_paths,
|
||||
java_home: java_home.map(Into::into),
|
||||
java_exec: None,
|
||||
errors,
|
||||
error_count,
|
||||
hints: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Compile errors jdtls reports for its workspace (all modules it imported).
|
||||
async fn java_compile_errors(&self, module: &Path) -> (Vec<JavaCompileError>, u32) {
|
||||
let Ok((server, _)) = self.jdtls(module).await else { return (Vec::new(), 0) };
|
||||
let collect = || compile_errors(server.diagnostics_snapshot(), MAX_LAUNCH_ERRORS);
|
||||
let found = collect();
|
||||
if found.1 > 0 {
|
||||
return found;
|
||||
}
|
||||
let _ = tokio::time::timeout(ERRORS_WAIT, server.published_notify.notified()).await;
|
||||
collect()
|
||||
}
|
||||
|
||||
/// Starts (or reuses) java-debug's DAP server inside jdtls and returns its port.
|
||||
pub async fn java_debug_server(&self, path: &Path) -> IdeResult<u16> {
|
||||
let v = self.jdtls_command(path, "vscode.java.startDebugSession", Vec::new()).await.map_err(|e| {
|
||||
@@ -256,6 +319,28 @@ impl LspManager {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn launch_errors_are_sorted_and_capped() {
|
||||
let diag = |line: u32, severity, message: &str| lsp_types::Diagnostic {
|
||||
range: lsp_types::Range::new(lsp_types::Position::new(line, 4), lsp_types::Position::new(line, 9)),
|
||||
severity: Some(severity),
|
||||
message: message.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let (errors, count) = compile_errors(
|
||||
vec![
|
||||
(PathBuf::from("/p/B.java"), diag(1, lsp_types::DiagnosticSeverity::ERROR, "b")),
|
||||
(PathBuf::from("/p/A.java"), diag(9, lsp_types::DiagnosticSeverity::ERROR, "a2\nmore")),
|
||||
(PathBuf::from("/p/A.java"), diag(2, lsp_types::DiagnosticSeverity::WARNING, "warning")),
|
||||
(PathBuf::from("/p/A.java"), diag(3, lsp_types::DiagnosticSeverity::ERROR, "a1")),
|
||||
],
|
||||
2,
|
||||
);
|
||||
assert_eq!(count, 3);
|
||||
let shown: Vec<(u32, u32, &str)> = errors.iter().map(|e| (e.line, e.column, e.message.as_str())).collect();
|
||||
assert_eq!(shown, [(4, 5, "a1"), (10, 5, "a2")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classpaths() {
|
||||
let v = json!({
|
||||
|
||||
@@ -10,6 +10,8 @@ use std::sync::{Arc, OnceLock};
|
||||
pub enum LaunchError {
|
||||
/// The server binary is not installed / not on `PATH`.
|
||||
Missing,
|
||||
/// The configuration can't be launched (`LanguageServerConfig::launch_error`).
|
||||
Config(String),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
@@ -72,7 +74,7 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> PathBuf {
|
||||
if !is_proxy || command.contains('/') {
|
||||
return binary;
|
||||
}
|
||||
let works = std::process::Command::new(&binary)
|
||||
let works = ide_core::process::no_window(&mut std::process::Command::new(&binary))
|
||||
.arg("--version")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
|
||||
@@ -329,13 +329,19 @@ impl LspManager {
|
||||
async fn run_instance(self: Arc<Self>, server: Arc<Server>, generation: u64) {
|
||||
server.set_status(&self.sink, ide_core::event::ServerStatus::Starting, None);
|
||||
let handler = Arc::new(handler::ClientHandler::new(self.me.clone(), server.clone(), generation));
|
||||
let launcher = self.launcher.clone();
|
||||
let cfg = self.configured(&server);
|
||||
server.set_effective_config(cfg.clone());
|
||||
let root = server.root.clone();
|
||||
let me = self.clone();
|
||||
let tail = server.clone();
|
||||
// The settings hook may touch the filesystem (e.g. scanning for JDKs).
|
||||
let launched = tokio::task::spawn_blocking(move || {
|
||||
launcher.launch(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)))
|
||||
let cfg = me.configured(&tail);
|
||||
tail.set_effective_config(cfg.clone());
|
||||
let root = tail.root.clone();
|
||||
if let Some(message) = &cfg.launch_error {
|
||||
// A missing binary still asks to be installed first.
|
||||
let missing = !me.launcher.available(&cfg, &root);
|
||||
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
|
||||
}
|
||||
me.launcher.launch(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)))
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|e| Err(LaunchError::Failed(e.to_string())));
|
||||
@@ -352,6 +358,13 @@ impl LspManager {
|
||||
}
|
||||
return;
|
||||
}
|
||||
Err(LaunchError::Config(message)) => {
|
||||
tracing::warn!("{}: {message}", server.name);
|
||||
if server.finish_start(generation, Conn::Failed) {
|
||||
server.set_status(&self.sink, ide_core::event::ServerStatus::Misconfigured, Some(message));
|
||||
}
|
||||
return;
|
||||
}
|
||||
Err(LaunchError::Failed(message)) => {
|
||||
tracing::warn!("{}: {message}", server.name);
|
||||
if server.finish_start(generation, Conn::Failed) {
|
||||
@@ -791,6 +804,40 @@ impl LspManager {
|
||||
out.finish(CompletionList { is_incomplete: false, items: Vec::new() })
|
||||
}
|
||||
|
||||
/// LSP 3.18 `textDocument/inlineCompletion` from every server advertising
|
||||
/// `inlineCompletionProvider` (`automatic`: triggered by typing, not explicitly).
|
||||
pub async fn inline_completion(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
automatic: bool,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Vec<InlineCompletionItem>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "inline completion", |c| c.has("inlineCompletionProvider")).await?;
|
||||
let requests = targets.iter().map(|t| {
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["context"] = json!({ "triggerKind": if automatic { 2 } else { 1 } });
|
||||
let cancel = &cancel;
|
||||
async move {
|
||||
let r =
|
||||
self.call::<_, Value>(t, "textDocument/inlineCompletion", params, Some(cancel), COMPLETION_TIMEOUT);
|
||||
(t, r.await)
|
||||
}
|
||||
});
|
||||
let mut out = Outcome::new();
|
||||
for (t, result) in join_all(requests).await {
|
||||
match result {
|
||||
Ok(v) => {
|
||||
let conv = self.conv(t.enc());
|
||||
let items = convert::inline_completion_items(&conv, &snap.path, v, t.server.id);
|
||||
out.value.get_or_insert_with(Vec::new).extend(items);
|
||||
}
|
||||
Err(e) => out.fail(e),
|
||||
}
|
||||
}
|
||||
out.finish(Vec::new())
|
||||
}
|
||||
|
||||
pub async fn resolve_completion(&self, doc: DocId, item: CompletionItem) -> IdeResult<CompletionItem> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let Some(server) = snap.servers.iter().find(|s| s.id == item.server) else { return Ok(item) };
|
||||
@@ -1409,6 +1456,52 @@ impl LspManager {
|
||||
out.finish(Vec::new())
|
||||
}
|
||||
|
||||
/// The document's links; ones without a target are resolved when the server can.
|
||||
pub async fn document_links(&self, doc: DocId) -> IdeResult<Vec<DocumentLink>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "document links", |c| c.has("documentLinkProvider")).await?;
|
||||
let requests = targets.iter().map(|t| {
|
||||
let params = json!({ "textDocument": snap.ident() });
|
||||
async move {
|
||||
let links = self
|
||||
.call::<_, Option<Vec<lsp::DocumentLink>>>(
|
||||
t,
|
||||
"textDocument/documentLink",
|
||||
params,
|
||||
None,
|
||||
DEFAULT_TIMEOUT,
|
||||
)
|
||||
.await?
|
||||
.unwrap_or_default();
|
||||
if !t.caps().has_sub("documentLinkProvider", "resolveProvider") {
|
||||
return Ok::<_, IdeError>((t, links));
|
||||
}
|
||||
let resolved = join_all(links.into_iter().map(|l| async move {
|
||||
if l.target.is_some() {
|
||||
return l;
|
||||
}
|
||||
let original = l.clone();
|
||||
self.call::<_, lsp::DocumentLink>(t, "documentLink/resolve", l, None, DEFAULT_TIMEOUT)
|
||||
.await
|
||||
.unwrap_or(original)
|
||||
}))
|
||||
.await;
|
||||
Ok((t, resolved))
|
||||
}
|
||||
});
|
||||
let mut out = Outcome::new();
|
||||
for r in join_all(requests).await {
|
||||
match r {
|
||||
Ok((t, links)) => {
|
||||
let conv = self.conv(t.enc());
|
||||
let acc = out.value.get_or_insert_with(Vec::new);
|
||||
acc.extend(links.into_iter().filter_map(|l| convert::document_link(&conv, &snap.path, l)));
|
||||
}
|
||||
Err(e) => out.fail(e),
|
||||
}
|
||||
}
|
||||
out.finish(Vec::new())
|
||||
}
|
||||
|
||||
pub async fn call_hierarchy(
|
||||
&self,
|
||||
doc: DocId,
|
||||
@@ -1419,8 +1512,9 @@ impl LspManager {
|
||||
let t = &targets[0];
|
||||
let items: Option<Vec<lsp::CallHierarchyItem>> =
|
||||
self.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
|
||||
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
|
||||
let mut out = Vec::new();
|
||||
for item in items.unwrap_or_default() {
|
||||
for item in items {
|
||||
let params = json!({ "item": item });
|
||||
match direction {
|
||||
HierarchyDirection::Incoming => {
|
||||
@@ -1461,12 +1555,13 @@ impl LspManager {
|
||||
// and lsp-types mistypes `tags` (jdtls sends an array).
|
||||
let items: Option<Vec<serde_json::Value>> =
|
||||
self.call(t, "textDocument/prepareTypeHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
|
||||
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
|
||||
let method = match direction {
|
||||
HierarchyDirection::Incoming => "typeHierarchy/supertypes",
|
||||
HierarchyDirection::Outgoing => "typeHierarchy/subtypes",
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for item in items.unwrap_or_default() {
|
||||
for item in items {
|
||||
let related: Option<Vec<serde_json::Value>> =
|
||||
self.call(t, method, json!({ "item": item }), None, LONG_TIMEOUT).await?;
|
||||
let conv = self.conv(t.enc());
|
||||
@@ -1598,8 +1693,10 @@ impl LspManager {
|
||||
s.reset_for_restart();
|
||||
self.ensure_started(&s);
|
||||
}
|
||||
// Missing / crashed servers retry with the new configuration (e.g. a new PATH).
|
||||
ide_core::event::ServerStatus::Missing | ide_core::event::ServerStatus::Crashed => {
|
||||
// Missing / crashed / misconfigured servers retry with the new configuration (e.g. a new PATH).
|
||||
ide_core::event::ServerStatus::Missing
|
||||
| ide_core::event::ServerStatus::Crashed
|
||||
| ide_core::event::ServerStatus::Misconfigured => {
|
||||
s.reset_for_restart();
|
||||
self.ensure_started(&s);
|
||||
}
|
||||
@@ -1720,6 +1817,12 @@ fn source_actions_only(only: &[String]) -> bool {
|
||||
!only.is_empty() && only.iter().all(|k| k == "source" || k.starts_with("source."))
|
||||
}
|
||||
|
||||
/// Preparing a call / type hierarchy found no symbol at the position: the UI
|
||||
/// then retries at the enclosing declaration.
|
||||
fn no_hierarchy_target() -> IdeError {
|
||||
IdeError::not_found("No symbol to show the hierarchy of at the caret")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod send_check {
|
||||
use super::*;
|
||||
|
||||
@@ -330,6 +330,12 @@ impl Server {
|
||||
self.diagnostics.lock().get(path).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Every published diagnostic, by file.
|
||||
pub fn diagnostics_snapshot(&self) -> Vec<(PathBuf, lsp::Diagnostic)> {
|
||||
let d = self.diagnostics.lock();
|
||||
d.iter().flat_map(|(p, items)| items.iter().map(move |i| (p.clone(), i.clone()))).collect()
|
||||
}
|
||||
|
||||
pub fn take_diagnostic_paths(&self) -> Vec<PathBuf> {
|
||||
self.published.lock().clear();
|
||||
self.diagnostics.lock().drain().map(|(p, _)| p).collect()
|
||||
|
||||
@@ -145,6 +145,21 @@ pub struct Command {
|
||||
pub arguments: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// One `textDocument/inlineCompletion` suggestion (ghost text at the caret).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InlineCompletionItem {
|
||||
/// Text that replaces `range`; snippets arrive as their plain text.
|
||||
pub insert_text: String,
|
||||
/// Replaced range; `None` inserts at the caret.
|
||||
pub range: Option<Range>,
|
||||
/// What the typed text is matched against while the suggestion stays shown (default: `insert_text`).
|
||||
pub filter_text: Option<String>,
|
||||
/// Run after the suggestion is accepted.
|
||||
pub command: Option<Command>,
|
||||
pub server: ServerId,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodeAction {
|
||||
@@ -195,6 +210,19 @@ pub struct InlayHint {
|
||||
pub padding_left: bool,
|
||||
pub padding_right: bool,
|
||||
pub tooltip: Option<String>,
|
||||
/// The label's parts when the server split it (empty for a plain label);
|
||||
/// their values concatenate to `label`.
|
||||
pub parts: Vec<InlayLabelPart>,
|
||||
}
|
||||
|
||||
/// One part of an inlay hint label, e.g. a type name that navigates to its declaration.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InlayLabelPart {
|
||||
pub value: String,
|
||||
pub tooltip: Option<String>,
|
||||
/// Declaration the part stands for (⌘-click navigates there).
|
||||
pub location: Option<Location>,
|
||||
}
|
||||
|
||||
/// Decoded semantic tokens (absolute positions) with the server legend applied.
|
||||
@@ -214,6 +242,21 @@ pub struct CodeLens {
|
||||
pub command: Option<Command>,
|
||||
}
|
||||
|
||||
/// A link in a document (`textDocument/documentLink`): an HTML `href`, a
|
||||
/// Markdown link, an `#include`, a JSON `$schema`…
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocumentLink {
|
||||
pub range: Range,
|
||||
/// A `file:` target.
|
||||
pub path: Option<ide_core::IpcPath>,
|
||||
/// The `#fragment` of a `file:` target (`L12`, `L12,5`, a heading or element id).
|
||||
pub fragment: Option<String>,
|
||||
/// Any other target (`https:`, …).
|
||||
pub url: Option<String>,
|
||||
pub tooltip: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HierarchyDirection {
|
||||
|
||||
@@ -193,6 +193,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
initialization_options: Some(toml::Value::Table(toml::toml! { flag = true nested = { deep = 1 } })),
|
||||
install_hint: Some(format!("install {name}")),
|
||||
fallback: false,
|
||||
launch_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,6 +415,42 @@ async fn completion_mapping_merge_and_resolve() {
|
||||
assert!(b.requested("completionItem/resolve").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn inline_completion_only_from_servers_that_advertise_it() {
|
||||
let h = harness(&[
|
||||
("plain", incremental_caps()),
|
||||
("ghost", json!({ "textDocumentSync": 2, "inlineCompletionProvider": {} })),
|
||||
("late", json!({ "textDocumentSync": 2 })),
|
||||
]);
|
||||
let (doc, _) = h.open("a.mk", "let x = fo");
|
||||
for name in ["plain", "ghost", "late"] {
|
||||
h.wait_status(name, ServerStatus::Ready).await;
|
||||
}
|
||||
let (plain, ghost) = (h.launcher.state("plain"), h.launcher.state("ghost"));
|
||||
let init = &plain.requested("initialize")[0];
|
||||
assert_eq!(init["capabilities"]["textDocument"]["inlineCompletion"], json!({ "dynamicRegistration": true }));
|
||||
ghost.respond(
|
||||
"textDocument/inlineCompletion",
|
||||
json!({ "items": [
|
||||
{ "insertText": "foo(1)", "range": {"start":{"line":0,"character":8},"end":{"line":0,"character":10}},
|
||||
"command": { "title": "accepted", "command": "ghost.accepted", "arguments": [7] } },
|
||||
{ "insertText": { "kind": "snippet", "value": "foo(${1:a}, $2)$0" }, "filterText": "fo" },
|
||||
{ "insertText": "" }
|
||||
] }),
|
||||
);
|
||||
let items = h.mgr.inline_completion(doc, Pos::new(0, 10), true, Default::default()).await.unwrap();
|
||||
assert_eq!(items.len(), 2);
|
||||
assert_eq!(items[0].insert_text, "foo(1)");
|
||||
assert_eq!(items[0].range, Some(rng(0, 8, 0, 10)));
|
||||
assert_eq!(items[0].command.as_ref().unwrap().command, "ghost.accepted");
|
||||
assert_eq!(items[1].insert_text, "foo(a, )");
|
||||
assert_eq!(items[1].filter_text.as_deref(), Some("fo"));
|
||||
let req = &ghost.requested("textDocument/inlineCompletion")[0];
|
||||
assert_eq!(req["context"], json!({ "triggerKind": 2 }));
|
||||
assert_eq!(req["position"], json!({ "line": 0, "character": 10 }));
|
||||
assert!(plain.requested("textDocument/inlineCompletion").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn diagnostics_become_events_and_feed_code_actions() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -703,6 +740,23 @@ async fn missing_server_reports_once() {
|
||||
assert!(h.mgr.semantic_tokens(doc).await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn launch_error_fails_without_starting_the_server() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
h.mgr.set_config_hook(Box::new(|cfg, _| cfg.launch_error = Some("needs JDK 21".into())));
|
||||
assert!(!h.mgr.serves_path(&h.root.join("a.mk")), "batch inspection skips it");
|
||||
h.open("a.mk", "x");
|
||||
// Not a crash: nothing ran, the configuration has to change.
|
||||
h.wait_status("mock", ServerStatus::Misconfigured).await;
|
||||
assert_eq!(h.launcher.state("mock").launches.load(Ordering::SeqCst), 0);
|
||||
let reason = h.events.lock().iter().find_map(|e| match e {
|
||||
IdeEvent::LanguageServer { status: ServerStatus::Misconfigured, message, .. } => message.clone(),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(reason.as_deref(), Some("needs JDK 21"));
|
||||
assert!(!h.statuses("mock").contains(&ServerStatus::Crashed));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
|
||||
// Preferred installed: the alternative is never started.
|
||||
@@ -788,6 +842,11 @@ async fn navigation_rename_format_and_decorations() {
|
||||
assert_eq!(hints[0].label, "x:");
|
||||
assert_eq!(hints[0].kind, InlayKind::Parameter);
|
||||
|
||||
// Nothing to prepare at the position: NotFound, so the UI can retry at the enclosing declaration.
|
||||
s.respond("textDocument/prepareCallHierarchy", json!(null));
|
||||
let err = h.mgr.call_hierarchy(doc, Pos::new(0, 1), HierarchyDirection::Incoming).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
|
||||
|
||||
let item = json!({ "name": "foo", "kind": 12, "uri": uri, "range": r(0,0,0,11), "selectionRange": r(0,3,0,6), "data": "id" });
|
||||
s.respond("textDocument/prepareCallHierarchy", json!([item]));
|
||||
s.respond("callHierarchy/incomingCalls", json!([{ "from": { "name": "main", "kind": 12, "uri": uri, "range": r(1,0,1,6), "selectionRange": r(1,0,1,3) }, "fromRanges": [r(1,0,1,3)] }]));
|
||||
|
||||
@@ -72,6 +72,7 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
initialization_options: None,
|
||||
install_hint: Some("npm i -g nope-ls".into()),
|
||||
fallback: false,
|
||||
launch_error: None,
|
||||
};
|
||||
let (mgr, events) = manager(dir.path(), LanguageRegistry::from_configs(vec![lang("nope", "nope", server)]));
|
||||
let path = dir.path().join("a.nope");
|
||||
@@ -123,7 +124,7 @@ async fn rust_analyzer_end_to_end() {
|
||||
mgr.did_open(doc, &main, &LanguageId::new("rust"), 1, MAIN_RS);
|
||||
retry("rust-analyzer ready", Duration::from_secs(60), || {
|
||||
let s = last_status(&events, "rust-analyzer");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing, msg)) = &s {
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &s {
|
||||
panic!("rust-analyzer failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(s, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
@@ -198,6 +199,7 @@ async fn typescript_language_server_end_to_end() {
|
||||
initialization_options: None,
|
||||
install_hint: None,
|
||||
fallback: false,
|
||||
launch_error: None,
|
||||
};
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
|
||||
let doc = DocId::next();
|
||||
|
||||
@@ -161,7 +161,7 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
|
||||
if !data.is_file() {
|
||||
return Err(nothing_recorded("perf wrote no data"));
|
||||
}
|
||||
let out = Command::new(perf)
|
||||
let out = ide_core::process::no_window(&mut Command::new(perf))
|
||||
.args(["script", "-i"])
|
||||
.arg(data.as_ref() as &Path)
|
||||
.current_dir(cwd)
|
||||
|
||||
@@ -232,6 +232,8 @@ mod tests {
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ specta.workspace = true
|
||||
toml.workspace = true
|
||||
toml_edit.workspace = true
|
||||
tokio.workspace = true
|
||||
portable-pty.workspace = true
|
||||
parking_lot.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
|
||||
@@ -11,9 +11,26 @@
|
||||
//! env = { RUST_LOG = "debug" }
|
||||
//! is-test = false
|
||||
//! debug-adapter = "codelldb"
|
||||
//! allow-parallel = true
|
||||
//! folder = "Servers"
|
||||
//! params = { mode = "command" }
|
||||
//! env-files = [".env"]
|
||||
//! include-system-env = false
|
||||
//! stdin-file = "input.txt"
|
||||
//! output-file = "out/server.log"
|
||||
//! before-launch = [{ kind = "build" }, { kind = "run", target = "user:migrate" }]
|
||||
//! emulate-terminal = true
|
||||
//! stop-command = "docker stop server"
|
||||
//!
|
||||
//! [[templates]] # per-type defaults for new configurations
|
||||
//! kind = "npm"
|
||||
//! env = { NODE_ENV = "development" }
|
||||
//! ```
|
||||
//!
|
||||
//! Configurations not stored as project files live in the same format in the
|
||||
//! workspace-local, git-ignored `run.local.toml`.
|
||||
|
||||
use crate::RunConfig;
|
||||
use crate::{BeforeLaunchTask, RunConfig, RunExtras};
|
||||
use ide_core::{IdeError, IdeResult, project_dir};
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -22,16 +39,30 @@ use std::path::{Path, PathBuf};
|
||||
use toml_edit::{Array, ArrayOfTables, DocumentMut, InlineTable, Item, Table, value};
|
||||
|
||||
const FILE: &str = "run.toml";
|
||||
const LOCAL_FILE: &str = "run.local.toml";
|
||||
const CONFIGURATIONS: &str = "configurations";
|
||||
const TEMPLATES: &str = "templates";
|
||||
|
||||
/// Where run configurations are written.
|
||||
pub(crate) fn config_path(root: &Path) -> PathBuf {
|
||||
project_dir::path(root, FILE)
|
||||
}
|
||||
|
||||
/// Workspace-local configurations ("Store as project file" off).
|
||||
pub(crate) fn local_path(root: &Path) -> PathBuf {
|
||||
project_dir::path(root, LOCAL_FILE)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct FileDoc {
|
||||
#[serde(default)]
|
||||
configurations: Vec<FileConfig>,
|
||||
#[serde(default)]
|
||||
templates: Vec<FileConfig>,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -51,6 +82,35 @@ struct FileConfig {
|
||||
is_test: bool,
|
||||
#[serde(alias = "debugAdapter", alias = "debug_adapter")]
|
||||
debug_adapter: Option<String>,
|
||||
#[serde(default, alias = "allowParallel", alias = "allow_parallel")]
|
||||
allow_parallel: bool,
|
||||
#[serde(default)]
|
||||
params: BTreeMap<String, String>,
|
||||
folder: Option<String>,
|
||||
#[serde(default = "yes", alias = "includeSystemEnv")]
|
||||
include_system_env: bool,
|
||||
#[serde(default, alias = "envFiles")]
|
||||
env_files: Vec<String>,
|
||||
#[serde(alias = "stdinFile")]
|
||||
stdin_file: Option<String>,
|
||||
#[serde(alias = "outputFile")]
|
||||
output_file: Option<String>,
|
||||
#[serde(default, alias = "beforeLaunch")]
|
||||
before_launch: Vec<BeforeLaunchTask>,
|
||||
#[serde(default)]
|
||||
compound: Vec<String>,
|
||||
#[serde(default, alias = "showOnStdout")]
|
||||
show_on_stdout: bool,
|
||||
#[serde(default, alias = "showOnStderr")]
|
||||
show_on_stderr: bool,
|
||||
#[serde(alias = "openToolWindow")]
|
||||
open_tool_window: Option<bool>,
|
||||
#[serde(default, alias = "focusToolWindow")]
|
||||
focus_tool_window: bool,
|
||||
#[serde(default, alias = "emulateTerminal")]
|
||||
emulate_terminal: bool,
|
||||
#[serde(alias = "stopCommand")]
|
||||
stop_command: Option<String>,
|
||||
}
|
||||
|
||||
fn slug(s: &str) -> String {
|
||||
@@ -65,17 +125,22 @@ fn slug(s: &str) -> String {
|
||||
out.trim_matches('-').to_owned()
|
||||
}
|
||||
|
||||
pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
let path = config_path(root);
|
||||
let text = match fs::read_to_string(&path) {
|
||||
fn read_doc(path: &Path) -> IdeResult<Option<FileDoc>> {
|
||||
let text = match fs::read_to_string(path) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let doc: FileDoc =
|
||||
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {}", path.display(), e.message())))?;
|
||||
let mut out = Vec::with_capacity(doc.configurations.len());
|
||||
for (i, c) in doc.configurations.into_iter().enumerate() {
|
||||
toml::from_str(&text).map(Some).map_err(|e| IdeError::invalid(format!("{}: {}", path.display(), e.message())))
|
||||
}
|
||||
|
||||
fn non_empty(s: Option<String>) -> Option<String> {
|
||||
s.filter(|s| !s.trim().is_empty())
|
||||
}
|
||||
|
||||
fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
|
||||
let mut out = Vec::with_capacity(configs.len());
|
||||
for (i, c) in configs.into_iter().enumerate() {
|
||||
let name = c.name.filter(|n| !n.is_empty()).unwrap_or_else(|| {
|
||||
if c.command.is_empty() { format!("Configuration {}", i + 1) } else { c.command.clone() }
|
||||
});
|
||||
@@ -91,11 +156,43 @@ pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
detected: false,
|
||||
is_test: c.is_test,
|
||||
debug_adapter: c.debug_adapter.filter(|d| !d.is_empty()),
|
||||
allow_parallel: c.allow_parallel,
|
||||
extras: RunExtras {
|
||||
params: c.params,
|
||||
folder: non_empty(c.folder),
|
||||
local,
|
||||
include_system_env: c.include_system_env,
|
||||
env_files: c.env_files.into_iter().filter(|f| !f.trim().is_empty()).collect(),
|
||||
stdin_file: non_empty(c.stdin_file),
|
||||
output_file: non_empty(c.output_file),
|
||||
before_launch: c.before_launch.into_iter().filter(|t| !t.kind.is_empty()).collect(),
|
||||
compound: c.compound,
|
||||
show_on_stdout: c.show_on_stdout,
|
||||
show_on_stderr: c.show_on_stderr,
|
||||
open_tool_window: c.open_tool_window,
|
||||
focus_tool_window: c.focus_tool_window,
|
||||
emulate_terminal: c.emulate_terminal,
|
||||
stop_command: non_empty(c.stop_command),
|
||||
},
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Project configurations (`run.toml`) followed by workspace-local ones (`run.local.toml`).
|
||||
pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
let mut out = read_doc(&config_path(root))?.map(|d| convert(d.configurations, false)).unwrap_or_default();
|
||||
if let Some(local) = read_doc(&local_path(root))? {
|
||||
let ids: Vec<String> = out.iter().map(|c| c.id.clone()).collect();
|
||||
out.extend(convert(local.configurations, true).into_iter().filter(|c| !ids.contains(&c.id)));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(crate) fn load_templates(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
Ok(read_doc(&config_path(root))?.map(|d| convert(d.templates, false)).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn to_table(c: &RunConfig) -> Table {
|
||||
let mut t = Table::new();
|
||||
t.insert("id", value(&c.id));
|
||||
@@ -121,12 +218,69 @@ fn to_table(c: &RunConfig) -> Table {
|
||||
if let Some(adapter) = &c.debug_adapter {
|
||||
t.insert("debug-adapter", value(adapter));
|
||||
}
|
||||
if c.allow_parallel {
|
||||
t.insert("allow-parallel", value(true));
|
||||
}
|
||||
let x = &c.extras;
|
||||
if let Some(folder) = &x.folder {
|
||||
t.insert("folder", value(folder));
|
||||
}
|
||||
if !x.params.is_empty() {
|
||||
let mut params = InlineTable::new();
|
||||
for (k, v) in &x.params {
|
||||
params.insert(k, v.into());
|
||||
}
|
||||
t.insert("params", value(params));
|
||||
}
|
||||
if !x.include_system_env {
|
||||
t.insert("include-system-env", value(false));
|
||||
}
|
||||
if !x.env_files.is_empty() {
|
||||
t.insert("env-files", value(x.env_files.iter().collect::<Array>()));
|
||||
}
|
||||
if let Some(f) = &x.stdin_file {
|
||||
t.insert("stdin-file", value(f));
|
||||
}
|
||||
if let Some(f) = &x.output_file {
|
||||
t.insert("output-file", value(f));
|
||||
}
|
||||
if !x.before_launch.is_empty() {
|
||||
let mut tasks = Array::new();
|
||||
for task in &x.before_launch {
|
||||
let mut it = InlineTable::new();
|
||||
it.insert("kind", task.kind.as_str().into());
|
||||
if !task.target.is_empty() {
|
||||
it.insert("target", task.target.as_str().into());
|
||||
}
|
||||
tasks.push(it);
|
||||
}
|
||||
t.insert("before-launch", value(tasks));
|
||||
}
|
||||
if !x.compound.is_empty() {
|
||||
t.insert("compound", value(x.compound.iter().collect::<Array>()));
|
||||
}
|
||||
for (key, on) in [
|
||||
("show-on-stdout", x.show_on_stdout),
|
||||
("show-on-stderr", x.show_on_stderr),
|
||||
("focus-tool-window", x.focus_tool_window),
|
||||
("emulate-terminal", x.emulate_terminal),
|
||||
] {
|
||||
if on {
|
||||
t.insert(key, value(true));
|
||||
}
|
||||
}
|
||||
if let Some(open) = x.open_tool_window {
|
||||
t.insert("open-tool-window", value(open));
|
||||
}
|
||||
if let Some(stop) = &x.stop_command {
|
||||
t.insert("stop-command", value(stop));
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
pub(crate) fn save(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
let path = config_path(root);
|
||||
let existing = match fs::read_to_string(&path) {
|
||||
/// Replaces the `key` array of tables in the file at `path`, keeping unrelated keys and comments.
|
||||
fn write_array(path: &Path, key: &str, configs: &[&RunConfig]) -> IdeResult<()> {
|
||||
let existing = match fs::read_to_string(path) {
|
||||
Ok(t) => Some(t),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e.into()),
|
||||
@@ -134,25 +288,65 @@ pub(crate) fn save(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
if existing.is_none() && configs.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// Keep unrelated keys and comments; a file we cannot parse is replaced.
|
||||
// A file we cannot parse is replaced.
|
||||
let mut doc = existing.as_deref().and_then(|t| t.parse::<DocumentMut>().ok()).unwrap_or_default();
|
||||
let mut array = ArrayOfTables::new();
|
||||
for c in configs {
|
||||
array.push(to_table(c));
|
||||
}
|
||||
if configs.is_empty() {
|
||||
doc.remove("configurations");
|
||||
doc.remove(key);
|
||||
} else {
|
||||
doc.insert("configurations", Item::ArrayOfTables(array));
|
||||
let mut array = ArrayOfTables::new();
|
||||
for c in configs {
|
||||
array.push(to_table(c));
|
||||
}
|
||||
doc.insert(key, Item::ArrayOfTables(array));
|
||||
}
|
||||
let text = doc.to_string();
|
||||
if existing.as_deref() == Some(text.as_str()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
let tmp = path.with_extension("toml.tmp");
|
||||
fs::write(&tmp, doc.to_string())?;
|
||||
fs::rename(&tmp, &path).inspect_err(|_| {
|
||||
fs::write(&tmp, text)?;
|
||||
fs::rename(&tmp, path).inspect_err(|_| {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keeps the workspace-local file out of version control (`.openidea/.gitignore`).
|
||||
fn ignore_local(root: &Path) -> IdeResult<()> {
|
||||
let entry = format!("/{LOCAL_FILE}");
|
||||
let file = project_dir::path(root, ".gitignore");
|
||||
let current = fs::read_to_string(&file).unwrap_or_default();
|
||||
if current.lines().any(|l| l.trim() == entry) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut text = current;
|
||||
if text.is_empty() {
|
||||
text.push_str("# Per-user IDE state\n");
|
||||
} else if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&entry);
|
||||
text.push('\n');
|
||||
if let Some(dir) = file.parent() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
fs::write(file, text)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn save(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
let (local, shared): (Vec<&RunConfig>, Vec<&RunConfig>) = configs.iter().partition(|c| c.extras.local);
|
||||
write_array(&config_path(root), CONFIGURATIONS, &shared)?;
|
||||
if !local.is_empty() {
|
||||
ignore_local(root)?;
|
||||
}
|
||||
write_array(&local_path(root), CONFIGURATIONS, &local)
|
||||
}
|
||||
|
||||
pub(crate) fn save_templates(root: &Path, templates: &[RunConfig]) -> IdeResult<()> {
|
||||
write_array(&config_path(root), TEMPLATES, &templates.iter().collect::<Vec<_>>())
|
||||
}
|
||||
@@ -37,6 +37,8 @@ fn config(id: impl Into<String>, name: impl Into<String>, kind: &str, command: &
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! `.env` files ("Paths to .env files" / EnvFile): `KEY=value` lines, `export`
|
||||
//! prefixes, `#` comments, single- and double-quoted values (escapes in double
|
||||
//! quotes) and `${VAR}` references to earlier variables or the base environment.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Parses `text`; `lookup` resolves `${VAR}` / `$VAR` not defined earlier in the file.
|
||||
pub fn parse(text: &str, lookup: &dyn Fn(&str) -> Option<String>) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
let mut lines = text.lines();
|
||||
while let Some(raw) = lines.next() {
|
||||
let line = raw.trim_start_matches('\u{feff}').trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let line = line.strip_prefix("export ").map(str::trim_start).unwrap_or(line);
|
||||
let Some((key, rest)) = line.split_once('=') else { continue };
|
||||
let key = key.trim();
|
||||
if key.is_empty() || key.contains(char::is_whitespace) {
|
||||
continue;
|
||||
}
|
||||
let rest = rest.trim_start();
|
||||
let value = if let Some(body) = rest.strip_prefix('\'') {
|
||||
quoted(body, '\'', &mut lines).unwrap_or_else(|| rest.to_owned())
|
||||
} else if let Some(body) = rest.strip_prefix('"') {
|
||||
let v = quoted(body, '"', &mut lines).unwrap_or_else(|| rest.to_owned());
|
||||
expand(&unescape(&v), &out, lookup)
|
||||
} else {
|
||||
let v = match rest.find(" #") {
|
||||
Some(i) => &rest[..i],
|
||||
None => rest,
|
||||
};
|
||||
expand(v.trim_end(), &out, lookup)
|
||||
};
|
||||
out.retain(|(k, _)| k != key);
|
||||
out.push((key.to_owned(), value));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body of a quoted value up to the closing `quote`, which may be on a later line.
|
||||
fn quoted<'a>(first: &str, quote: char, lines: &mut impl Iterator<Item = &'a str>) -> Option<String> {
|
||||
let mut text = first.to_owned();
|
||||
loop {
|
||||
let mut escaped = false;
|
||||
for (i, c) in text.char_indices() {
|
||||
if quote == '"' && c == '\\' && !escaped {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if c == quote && !escaped {
|
||||
return Some(text[..i].to_owned());
|
||||
}
|
||||
escaped = false;
|
||||
}
|
||||
text.push('\n');
|
||||
text.push_str(lines.next()?);
|
||||
}
|
||||
}
|
||||
|
||||
fn unescape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut chars = s.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
match chars.next() {
|
||||
Some('n') => out.push('\n'),
|
||||
Some('t') => out.push('\t'),
|
||||
Some('r') => out.push('\r'),
|
||||
Some(other) => out.push(other),
|
||||
None => out.push('\\'),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn expand(value: &str, earlier: &[(String, String)], lookup: &dyn Fn(&str) -> Option<String>) -> String {
|
||||
let resolve = |name: &str| {
|
||||
earlier
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(k, _)| k == name)
|
||||
.map(|(_, v)| v.clone())
|
||||
.or_else(|| lookup(name))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let mut out = String::with_capacity(value.len());
|
||||
let bytes = value.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < value.len() {
|
||||
if bytes[i] == b'$' {
|
||||
if bytes.get(i + 1) == Some(&b'{')
|
||||
&& let Some(end) = value[i + 2..].find('}')
|
||||
{
|
||||
out.push_str(&resolve(&value[i + 2..i + 2 + end]));
|
||||
i += end + 3;
|
||||
continue;
|
||||
}
|
||||
let name_len = value[i + 1..].bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b'_').count();
|
||||
if name_len > 0 {
|
||||
out.push_str(&resolve(&value[i + 1..i + 1 + name_len]));
|
||||
i += name_len + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let c = value[i..].chars().next().unwrap_or_default();
|
||||
out.push(c);
|
||||
i += c.len_utf8();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Variables of every file in order (later files win); unreadable files are an error.
|
||||
pub fn load(
|
||||
paths: &[std::path::PathBuf],
|
||||
base: &BTreeMap<String, String>,
|
||||
) -> std::io::Result<BTreeMap<String, String>> {
|
||||
let mut vars: BTreeMap<String, String> = BTreeMap::new();
|
||||
for path in paths {
|
||||
let text = std::fs::read_to_string(path)
|
||||
.map_err(|e| std::io::Error::new(e.kind(), format!("{}: {e}", path.display())))?;
|
||||
let lookup = |name: &str| vars.get(name).or_else(|| base.get(name)).cloned();
|
||||
let parsed = parse(&text, &lookup);
|
||||
vars.extend(parsed);
|
||||
}
|
||||
Ok(vars)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn none(_: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_common_forms() {
|
||||
let text = "# comment\nA=1\nexport B = two words # trailing\nC='lit $A'\nD=\"x\\ny $A ${B}\"\nE=\"multi\nline\"\n\nbad line\nF=\n";
|
||||
let v = parse(text, &none);
|
||||
let get = |k: &str| v.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
|
||||
assert_eq!(get("A"), Some("1"));
|
||||
assert_eq!(get("B"), Some("two words"));
|
||||
assert_eq!(get("C"), Some("lit $A"));
|
||||
assert_eq!(get("D"), Some("x\ny 1 two words"));
|
||||
assert_eq!(get("E"), Some("multi\nline"));
|
||||
assert_eq!(get("F"), Some(""));
|
||||
assert_eq!(v.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_fall_back_to_base() {
|
||||
let v = parse("P=$HOME/bin:${MISSING}x", &|n| (n == "HOME").then(|| "/h".to_owned()));
|
||||
assert_eq!(v, [("P".to_owned(), "/h/bin:x".to_owned())]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod config;
|
||||
mod detect;
|
||||
pub mod envfile;
|
||||
pub mod junit;
|
||||
mod process;
|
||||
mod utf8;
|
||||
@@ -34,6 +35,117 @@ pub struct RunConfig {
|
||||
pub is_test: bool,
|
||||
/// DAP adapter that can debug this config, if any.
|
||||
pub debug_adapter: Option<String>,
|
||||
/// "Allow multiple instances": Run on a running config starts another one instead of restarting it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub allow_parallel: bool,
|
||||
/// Options of user-defined configurations (all optional; old `run.toml` files load unchanged).
|
||||
#[serde(flatten)]
|
||||
pub extras: RunExtras,
|
||||
}
|
||||
|
||||
/// A step run before a configuration launches; a failing step aborts the launch.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BeforeLaunchTask {
|
||||
/// `run` (another configuration, `target` = its id) | `build` | `tool` (external tool id) |
|
||||
/// `command` (a shell command line) | `toolWindow` (tool window id).
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn is_true(b: &bool) -> bool {
|
||||
*b
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RunExtras {
|
||||
/// Values of the configuration type's own form fields (the command line derives from them).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub params: BTreeMap<String, String>,
|
||||
/// Folder in the Run/Debug Configurations tree.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub folder: Option<String>,
|
||||
/// Stored in the workspace (`.openidea/run.local.toml`, not shared) instead of `run.toml`.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub local: bool,
|
||||
/// Off: the process gets only the configured variables.
|
||||
#[serde(default = "yes", skip_serializing_if = "is_true")]
|
||||
#[specta(optional)]
|
||||
pub include_system_env: bool,
|
||||
/// `.env` files (relative to the project root) loaded before `env`, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub env_files: Vec<String>,
|
||||
/// "Redirect input from": the process reads this file as stdin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub stdin_file: Option<String>,
|
||||
/// "Save console output to file" (overwritten on each run).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub output_file: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub before_launch: Vec<BeforeLaunchTask>,
|
||||
/// Compound configurations: ids of the configurations started together.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub compound: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub show_on_stdout: bool,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub show_on_stderr: bool,
|
||||
/// Overrides Settings › Run › "Show the Run tool window when a process starts".
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub open_tool_window: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub focus_tool_window: bool,
|
||||
/// "Emulate terminal in output console": the process runs on a pseudo-terminal
|
||||
/// (colours, line editing, full-screen programs); the console renders it as a terminal.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub emulate_terminal: bool,
|
||||
/// Shell command line run on Stop before the process is signalled (e.g. `docker stop <name>`),
|
||||
/// with the run's working directory and environment.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub stop_command: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for RunExtras {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
params: BTreeMap::new(),
|
||||
folder: None,
|
||||
local: false,
|
||||
include_system_env: true,
|
||||
env_files: Vec::new(),
|
||||
stdin_file: None,
|
||||
output_file: None,
|
||||
before_launch: Vec::new(),
|
||||
compound: Vec::new(),
|
||||
show_on_stdout: false,
|
||||
show_on_stderr: false,
|
||||
open_tool_window: None,
|
||||
focus_tool_window: false,
|
||||
emulate_terminal: false,
|
||||
stop_command: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -59,6 +171,8 @@ pub struct RunInfo {
|
||||
pub name: String,
|
||||
pub pid: Option<u32>,
|
||||
pub running: bool,
|
||||
/// Runs on a pseudo-terminal: output is raw terminal data, input goes in keystroke by keystroke.
|
||||
pub pty: bool,
|
||||
}
|
||||
|
||||
/// Detects configs from package.json scripts, Cargo.toml targets, build.gradle(.kts),
|
||||
@@ -72,11 +186,26 @@ pub fn load_user_configs(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
config::load(root)
|
||||
}
|
||||
|
||||
/// Writes `<root>/.openidea/run.toml`, preserving unrelated content in the file.
|
||||
/// Writes `<root>/.openidea/run.toml` (and the workspace-local `run.local.toml` for
|
||||
/// configurations not stored as project files), preserving unrelated content.
|
||||
pub fn save_user_configs(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
config::save(root, configs)
|
||||
}
|
||||
|
||||
/// Configuration templates (per-type defaults for new configurations) from `run.toml`.
|
||||
pub fn load_templates(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
config::load_templates(root)
|
||||
}
|
||||
|
||||
pub fn save_templates(root: &Path, templates: &[RunConfig]) -> IdeResult<()> {
|
||||
config::save_templates(root, templates)
|
||||
}
|
||||
|
||||
/// The environment runs inherit (unless "Include system environment variables" is off).
|
||||
pub fn system_env() -> BTreeMap<String, String> {
|
||||
std::env::vars().collect()
|
||||
}
|
||||
|
||||
/// Path of the user run configuration file for `root`.
|
||||
pub fn user_configs_path(root: &Path) -> PathBuf {
|
||||
config::config_path(root)
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
//! Process lifecycle for run configurations: spawn, stream output, stdin, stop.
|
||||
//! Process lifecycle for run configurations: spawn (on pipes, or on a pseudo-terminal
|
||||
//! for "Emulate terminal in output console"), stream output, stdin, stop.
|
||||
|
||||
use crate::utf8::OutputDecoder;
|
||||
use crate::{OutputChunk, RunConfig, RunInfo};
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{ChildStdin, Command, ExitStatus, Stdio};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
||||
@@ -20,15 +22,39 @@ const BATCH_BYTES: usize = 64 * 1024;
|
||||
const EXIT_DRAIN: Duration = Duration::from_millis(500);
|
||||
/// Delay between SIGINT and SIGKILL on [`ProcessManager::stop`].
|
||||
const STOP_GRACE: Duration = Duration::from_secs(3);
|
||||
/// Longest a configuration's stop command (e.g. `docker stop`) may take before signals follow.
|
||||
const STOP_COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// Finished runs kept for [`ProcessManager::list`].
|
||||
const MAX_FINISHED: usize = 20;
|
||||
/// PTY size until the console reports its own.
|
||||
const DEFAULT_PTY: (u16, u16) = (120, 30);
|
||||
|
||||
type OutputFn = Arc<dyn Fn(OutputChunk) + Send + Sync>;
|
||||
|
||||
/// Environment of a launched process: the inherited one (unless cleared) plus `vars`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct LaunchEnv {
|
||||
clear: bool,
|
||||
vars: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A configuration's stop command and where it runs.
|
||||
struct StopCommand {
|
||||
line: String,
|
||||
cwd: PathBuf,
|
||||
env: LaunchEnv,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
id: RunId,
|
||||
config_id: String,
|
||||
name: String,
|
||||
pid: Option<u32>,
|
||||
stdin: Mutex<Option<ChildStdin>>,
|
||||
stdin: Mutex<Option<Box<dyn Write + Send>>>,
|
||||
/// The PTY master of a terminal-emulated run (resize; dropped on exit).
|
||||
pty: Option<Mutex<Option<Box<dyn MasterPty + Send>>>>,
|
||||
stop: Option<StopCommand>,
|
||||
output: OutputFn,
|
||||
exited: AtomicBool,
|
||||
stopping: AtomicBool,
|
||||
}
|
||||
@@ -41,6 +67,7 @@ impl Entry {
|
||||
name: self.name.clone(),
|
||||
pid: self.pid,
|
||||
running: !self.exited.load(Ordering::Acquire),
|
||||
pty: self.pty.is_some(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,9 +90,14 @@ enum Stream {
|
||||
Stderr,
|
||||
}
|
||||
|
||||
enum Exit {
|
||||
Pipes(std::io::Result<ExitStatus>),
|
||||
Pty(std::io::Result<portable_pty::ExitStatus>),
|
||||
}
|
||||
|
||||
enum Msg {
|
||||
Data(Stream, Vec<u8>),
|
||||
Exited(std::io::Result<ExitStatus>),
|
||||
Exited(Exit),
|
||||
}
|
||||
|
||||
/// The program and arguments actually executed, plus the echoed command line.
|
||||
@@ -154,6 +186,23 @@ fn resolve_program(command: &str, cwd: &Path, env: &BTreeMap<String, String>, wi
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
/// "Save console output to file": everything shown in the console is also written to `path`.
|
||||
fn tee_output(path: &Path, on_output: OutputFn) -> IdeResult<OutputFn> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let file = std::fs::File::create(path)
|
||||
.map_err(|e| IdeError::invalid(format!("cannot write console output to {}: {e}", path.display())))?;
|
||||
let file = Mutex::new(std::io::LineWriter::new(file));
|
||||
Ok(Arc::new(move |chunk: OutputChunk| {
|
||||
let text = match &chunk {
|
||||
OutputChunk::Stdout { text } | OutputChunk::Stderr { text } | OutputChunk::System { text } => text,
|
||||
};
|
||||
let _ = file.lock().write_all(text.as_bytes());
|
||||
on_output(chunk);
|
||||
}))
|
||||
}
|
||||
|
||||
fn resolve_cwd(root: &Path, cwd: Option<&Path>) -> PathBuf {
|
||||
match cwd {
|
||||
Some(c) if c.is_absolute() => c.to_path_buf(),
|
||||
@@ -184,6 +233,24 @@ impl ProcessManager {
|
||||
return Err(IdeError::not_found(format!("working directory does not exist: {}", cwd.display())));
|
||||
}
|
||||
let inv = invocation(config, &cwd);
|
||||
let extras = &config.extras;
|
||||
if extras.emulate_terminal && extras.stdin_file.is_some() {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let env = launch_env(root, config)?;
|
||||
let on_output: OutputFn = Arc::from(on_output);
|
||||
let on_output = match extras.output_file.as_deref() {
|
||||
Some(file) => tee_output(&resolve_cwd(root, Some(Path::new(file))), on_output)?,
|
||||
None => on_output,
|
||||
};
|
||||
let stop = extras.stop_command.as_deref().map(str::trim).filter(|l| !l.is_empty()).map(|line| StopCommand {
|
||||
line: line.to_owned(),
|
||||
cwd: cwd.clone(),
|
||||
env: env.clone(),
|
||||
});
|
||||
if extras.emulate_terminal {
|
||||
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output);
|
||||
}
|
||||
|
||||
let mut cmd = Command::new(&inv.program);
|
||||
if inv.raw_args {
|
||||
@@ -191,11 +258,21 @@ impl ProcessManager {
|
||||
} else {
|
||||
cmd.args(&inv.args);
|
||||
}
|
||||
cmd.current_dir(&cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
if matches!(config.kind.as_str(), "python" | "pytest") && !config.env.contains_key("PYTHONUNBUFFERED") {
|
||||
cmd.env("PYTHONUNBUFFERED", "1");
|
||||
}
|
||||
cmd.envs(&config.env);
|
||||
cmd.current_dir(&cwd).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let redirected = match extras.stdin_file.as_deref() {
|
||||
Some(file) => {
|
||||
let path = resolve_cwd(root, Some(Path::new(file)));
|
||||
let f = std::fs::File::open(&path)
|
||||
.map_err(|e| IdeError::not_found(format!("cannot redirect input from {}: {e}", path.display())))?;
|
||||
cmd.stdin(Stdio::from(f));
|
||||
true
|
||||
}
|
||||
None => {
|
||||
cmd.stdin(Stdio::piped());
|
||||
false
|
||||
}
|
||||
};
|
||||
apply_env(&mut cmd, &env);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
@@ -205,8 +282,7 @@ impl ProcessManager {
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
|
||||
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | ide_core::process::CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
let mut child = cmd.spawn().map_err(|e| match e.kind() {
|
||||
@@ -215,12 +291,19 @@ impl ProcessManager {
|
||||
})?;
|
||||
|
||||
let id = RunId::next();
|
||||
let stdin: Option<Box<dyn Write + Send>> = match child.stdin.take() {
|
||||
Some(pipe) if !redirected => Some(Box::new(pipe)),
|
||||
_ => None,
|
||||
};
|
||||
let entry = Arc::new(Entry {
|
||||
id,
|
||||
config_id: config.id.clone(),
|
||||
name: config.name.clone(),
|
||||
pid: Some(child.id()),
|
||||
stdin: Mutex::new(child.stdin.take()),
|
||||
stdin: Mutex::new(stdin),
|
||||
pty: None,
|
||||
stop,
|
||||
output: on_output.clone(),
|
||||
exited: AtomicBool::new(false),
|
||||
stopping: AtomicBool::new(false),
|
||||
});
|
||||
@@ -253,7 +336,7 @@ impl ProcessManager {
|
||||
.name(format!("openidea-run-wait-{}", id.0))
|
||||
.spawn(move || {
|
||||
let status = child.wait();
|
||||
let _ = waiter_tx.send(Msg::Exited(status));
|
||||
let _ = waiter_tx.send(Msg::Exited(Exit::Pipes(status)));
|
||||
})
|
||||
.map_err(|e| IdeError::internal(format!("failed to start waiter thread: {e}")))?;
|
||||
|
||||
@@ -261,6 +344,94 @@ impl ProcessManager {
|
||||
Ok(entry.info())
|
||||
}
|
||||
|
||||
/// [`Self::start`] on a pseudo-terminal: one merged output stream of raw terminal data.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn start_pty(
|
||||
&self,
|
||||
config: &RunConfig,
|
||||
inv: &Invocation,
|
||||
cwd: &Path,
|
||||
env: &LaunchEnv,
|
||||
stop: Option<StopCommand>,
|
||||
options: &StartOptions,
|
||||
sink: SharedSink,
|
||||
on_output: OutputFn,
|
||||
) -> IdeResult<RunInfo> {
|
||||
let pair = native_pty_system()
|
||||
.openpty(pty_size(DEFAULT_PTY.0, DEFAULT_PTY.1))
|
||||
.map_err(|e| IdeError::internal(format!("openpty failed: {e}")))?;
|
||||
let mut cmd = CommandBuilder::new(&inv.program);
|
||||
cmd.args(&inv.args);
|
||||
cmd.cwd(cwd);
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
}
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.env("COLORTERM", "truecolor");
|
||||
for (k, v) in &env.vars {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
let mut child = pair.slave.spawn_command(cmd).map_err(|e| {
|
||||
let text = e.to_string();
|
||||
if text.contains("No such file") || text.contains("not found") {
|
||||
IdeError::unavailable(format!("command not found: {}", config.command))
|
||||
} else {
|
||||
IdeError::unavailable(format!("failed to start `{}`: {text}", config.command))
|
||||
}
|
||||
})?;
|
||||
// The child holds its own copy of the slave; dropping ours lets reads hit EOF on exit.
|
||||
drop(pair.slave);
|
||||
let reader = pair.master.try_clone_reader().map_err(|e| IdeError::internal(format!("pty reader: {e}")))?;
|
||||
let writer = pair.master.take_writer().map_err(|e| IdeError::internal(format!("pty writer: {e}")))?;
|
||||
|
||||
let id = RunId::next();
|
||||
let entry = Arc::new(Entry {
|
||||
id,
|
||||
config_id: config.id.clone(),
|
||||
name: config.name.clone(),
|
||||
pid: child.process_id(),
|
||||
stdin: Mutex::new(Some(writer)),
|
||||
pty: Some(Mutex::new(Some(pair.master))),
|
||||
stop,
|
||||
output: on_output.clone(),
|
||||
exited: AtomicBool::new(false),
|
||||
stopping: AtomicBool::new(false),
|
||||
});
|
||||
self.register(entry.clone());
|
||||
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let result = spawn_reader(id, Stream::Stdout, reader, tx.clone())
|
||||
.and_then(|_| spawn_pump(rx, on_output, entry.clone(), sink, options.encoding.clone()));
|
||||
if let Err(e) = result {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
entry.exited.store(true, Ordering::Release);
|
||||
return Err(IdeError::internal(format!("failed to start output threads: {e}")));
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name(format!("openidea-run-wait-{}", id.0))
|
||||
.spawn(move || {
|
||||
let status = child.wait();
|
||||
let _ = tx.send(Msg::Exited(Exit::Pty(status)));
|
||||
})
|
||||
.map_err(|e| IdeError::internal(format!("failed to start waiter thread: {e}")))?;
|
||||
tracing::debug!(%id, config = %config.id, pid = ?entry.pid, "run started on a pty");
|
||||
Ok(entry.info())
|
||||
}
|
||||
|
||||
/// Resizes the pseudo-terminal of a terminal-emulated run.
|
||||
pub fn resize(&self, id: RunId, cols: u16, rows: u16) -> IdeResult<()> {
|
||||
let entry = self.entry(id)?;
|
||||
let Some(pty) = &entry.pty else { return Err(IdeError::invalid("the process does not run in a terminal")) };
|
||||
match pty.lock().as_ref() {
|
||||
Some(master) => {
|
||||
master.resize(pty_size(cols, rows)).map_err(|e| IdeError::internal(format!("resize failed: {e}")))
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn register(&self, entry: Arc<Entry>) {
|
||||
let mut runs = self.runs.lock();
|
||||
runs.retain(|_, e| !(e.config_id == entry.config_id && e.exited.load(Ordering::Acquire)));
|
||||
@@ -294,9 +465,13 @@ impl ProcessManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Closes the process's stdin (sends EOF).
|
||||
/// Closes the process's stdin (sends EOF; on a terminal, types ^D).
|
||||
pub fn close_stdin(&self, id: RunId) -> IdeResult<()> {
|
||||
self.entry(id)?.stdin.lock().take();
|
||||
let entry = self.entry(id)?;
|
||||
if entry.pty.is_some() {
|
||||
return self.write_stdin(id, "\u{4}");
|
||||
}
|
||||
entry.stdin.lock().take();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -305,7 +480,8 @@ impl ProcessManager {
|
||||
self.stop_with_grace(id, STOP_GRACE)
|
||||
}
|
||||
|
||||
/// [`Self::stop`] with an explicit grace period before the kill.
|
||||
/// [`Self::stop`] with an explicit grace period before the kill. A configuration's
|
||||
/// stop command runs first; signals follow only if the process outlives it.
|
||||
pub fn stop_with_grace(&self, id: RunId, grace: Duration) -> IdeResult<()> {
|
||||
let entry = self.entry(id)?;
|
||||
if entry.exited.load(Ordering::Acquire) {
|
||||
@@ -317,19 +493,31 @@ impl ProcessManager {
|
||||
kill_tree(pid, true);
|
||||
return Ok(());
|
||||
}
|
||||
kill_tree(pid, false);
|
||||
if entry.stop.is_none() {
|
||||
kill_tree(pid, false);
|
||||
}
|
||||
let entry = entry.clone();
|
||||
std::thread::Builder::new()
|
||||
.name(format!("openidea-run-stop-{}", id.0))
|
||||
.spawn(move || {
|
||||
let deadline = Instant::now() + grace;
|
||||
while Instant::now() < deadline {
|
||||
if !group_alive(pid, &entry) {
|
||||
let exits_within = |limit: Duration| {
|
||||
let deadline = Instant::now() + limit;
|
||||
while Instant::now() < deadline {
|
||||
if !group_alive(pid, &entry) {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
!group_alive(pid, &entry)
|
||||
};
|
||||
if let Some(stop) = &entry.stop {
|
||||
run_stop_command(stop, &entry.output);
|
||||
if exits_within(grace) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
kill_tree(pid, false);
|
||||
}
|
||||
if group_alive(pid, &entry) {
|
||||
if !exits_within(grace) {
|
||||
tracing::debug!(id = %entry.id, pid, "process ignored interrupt; killing");
|
||||
kill_tree(pid, true);
|
||||
}
|
||||
@@ -355,6 +543,90 @@ impl Drop for ProcessManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The environment a configuration's process gets on top of the inherited one: `.env`
|
||||
/// files, then the configured variables (later wins).
|
||||
fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
|
||||
let extras = &config.extras;
|
||||
let mut vars = if extras.env_files.is_empty() {
|
||||
BTreeMap::new()
|
||||
} else {
|
||||
let base: BTreeMap<String, String> =
|
||||
if extras.include_system_env { std::env::vars().collect() } else { BTreeMap::new() };
|
||||
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
|
||||
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
|
||||
};
|
||||
if matches!(config.kind.as_str(), "python" | "pytest")
|
||||
&& !config.env.contains_key("PYTHONUNBUFFERED")
|
||||
&& !vars.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
vars.insert("PYTHONUNBUFFERED".into(), "1".into());
|
||||
}
|
||||
vars.extend(config.env.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
Ok(LaunchEnv { clear: !extras.include_system_env, vars })
|
||||
}
|
||||
|
||||
fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
}
|
||||
cmd.envs(&env.vars);
|
||||
}
|
||||
|
||||
/// Runs `stop.line` through the platform shell and waits for it (bounded), echoing it
|
||||
/// and any error output to the console.
|
||||
fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
|
||||
output(OutputChunk::System { text: format!("{}\n", stop.line) });
|
||||
let inv = shell_invocation(&stop.line, cfg!(windows), std::env::var("COMSPEC").ok());
|
||||
let mut cmd = Command::new(&inv.program);
|
||||
if inv.raw_args {
|
||||
add_raw_args(&mut cmd, &inv.args);
|
||||
} else {
|
||||
cmd.args(&inv.args);
|
||||
}
|
||||
cmd.current_dir(&stop.cwd).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped());
|
||||
apply_env(&mut cmd, &stop.env);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
output(OutputChunk::Stderr { text: format!("Cannot run the stop command: {e}\n") });
|
||||
return;
|
||||
}
|
||||
};
|
||||
let stderr = child.stderr.take().map(|mut pipe| {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
})
|
||||
});
|
||||
let deadline = Instant::now() + STOP_COMMAND_TIMEOUT;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break Some(status),
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
}
|
||||
};
|
||||
let err = stderr.and_then(|h| h.join().ok()).unwrap_or_default();
|
||||
if !status.is_some_and(|s| s.success()) && !err.trim().is_empty() {
|
||||
output(OutputChunk::Stderr { text: format!("{}\n", err.trim_end()) });
|
||||
}
|
||||
}
|
||||
|
||||
fn pty_size(cols: u16, rows: u16) -> PtySize {
|
||||
PtySize {
|
||||
cols: if cols == 0 { DEFAULT_PTY.0 } else { cols },
|
||||
rows: if rows == 0 { DEFAULT_PTY.1 } else { rows },
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn group_alive(pid: u32, _entry: &Entry) -> bool {
|
||||
// Signal 0 probes the group; it fails with ESRCH once every member is gone.
|
||||
@@ -400,7 +672,7 @@ fn kill_tree(pid: u32, _force: bool) {
|
||||
// Console children have no reliable graceful signal from outside their console.
|
||||
let _ = Command::new("taskkill")
|
||||
.args(["/T", "/F", "/PID", &pid.to_string()])
|
||||
.creation_flags(0x0800_0000)
|
||||
.creation_flags(ide_core::process::CREATE_NO_WINDOW)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
@@ -441,7 +713,7 @@ fn chunk(stream: Stream, text: String) -> OutputChunk {
|
||||
/// Merges both streams in arrival order, batching consecutive output of the same stream.
|
||||
fn spawn_pump(
|
||||
rx: mpsc::Receiver<Msg>,
|
||||
on_output: Box<dyn Fn(OutputChunk) + Send + Sync>,
|
||||
on_output: OutputFn,
|
||||
entry: Arc<Entry>,
|
||||
sink: SharedSink,
|
||||
encoding: Option<String>,
|
||||
@@ -452,7 +724,7 @@ fn spawn_pump(
|
||||
let mut pending = String::new();
|
||||
let mut pending_stream = Stream::Stdout;
|
||||
let mut batch_started: Option<Instant> = None;
|
||||
let mut status: Option<std::io::Result<ExitStatus>> = None;
|
||||
let mut status: Option<Exit> = None;
|
||||
let mut drain_deadline: Option<Instant> = None;
|
||||
|
||||
let flush = |pending: &mut String, stream: Stream, started: &mut Option<Instant>| {
|
||||
@@ -513,6 +785,9 @@ fn spawn_pump(
|
||||
let (code, message) = describe_exit(status);
|
||||
on_output(OutputChunk::System { text: format!("\n{message}\n") });
|
||||
entry.stdin.lock().take();
|
||||
if let Some(pty) = &entry.pty {
|
||||
pty.lock().take();
|
||||
}
|
||||
entry.exited.store(true, Ordering::Release);
|
||||
tracing::debug!(id = %entry.id, ?code, "run exited");
|
||||
sink.emit(IdeEvent::RunExited { run: entry.id, code });
|
||||
@@ -543,9 +818,9 @@ fn signal_name(sig: i32) -> &'static str {
|
||||
}
|
||||
|
||||
/// IDEA wording: `Process finished with exit code 130 (interrupted by signal 2:SIGINT)`.
|
||||
fn describe_exit(status: Option<std::io::Result<ExitStatus>>) -> (Option<i32>, String) {
|
||||
fn describe_exit(status: Option<Exit>) -> (Option<i32>, String) {
|
||||
match status {
|
||||
Some(Ok(s)) => {
|
||||
Some(Exit::Pipes(Ok(s))) => {
|
||||
if let Some(code) = s.code() {
|
||||
return (Some(code), format!("Process finished with exit code {code}"));
|
||||
}
|
||||
@@ -553,23 +828,55 @@ fn describe_exit(status: Option<std::io::Result<ExitStatus>>) -> (Option<i32>, S
|
||||
{
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
if let Some(sig) = s.signal() {
|
||||
let code = 128 + sig;
|
||||
return (
|
||||
Some(code),
|
||||
format!(
|
||||
"Process finished with exit code {code} (interrupted by signal {sig}:{})",
|
||||
signal_name(sig)
|
||||
),
|
||||
);
|
||||
return signalled(sig);
|
||||
}
|
||||
}
|
||||
(None, "Process finished".to_owned())
|
||||
}
|
||||
Some(Err(e)) => (None, format!("Process finished with unknown exit status: {e}")),
|
||||
Some(Exit::Pty(Ok(s))) => match s.signal() {
|
||||
None => {
|
||||
let code = s.exit_code() as i32;
|
||||
(Some(code), format!("Process finished with exit code {code}"))
|
||||
}
|
||||
Some(name) => match signal_number(name) {
|
||||
Some(sig) => signalled(sig),
|
||||
None => (None, format!("Process finished ({name})")),
|
||||
},
|
||||
},
|
||||
Some(Exit::Pipes(Err(e)) | Exit::Pty(Err(e))) => {
|
||||
(None, format!("Process finished with unknown exit status: {e}"))
|
||||
}
|
||||
None => (None, "Process finished".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn signalled(sig: i32) -> (Option<i32>, String) {
|
||||
let code = 128 + sig;
|
||||
(Some(code), format!("Process finished with exit code {code} (interrupted by signal {sig}:{})", signal_name(sig)))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn signalled(sig: i32) -> (Option<i32>, String) {
|
||||
(Some(128 + sig), format!("Process finished with exit code {}", 128 + sig))
|
||||
}
|
||||
|
||||
/// The number of a signal from the `strsignal` description portable-pty reports.
|
||||
#[cfg(unix)]
|
||||
fn signal_number(description: &str) -> Option<i32> {
|
||||
(1..32).find(|&sig| {
|
||||
// SAFETY: `strsignal` returns a pointer to a NUL-terminated C string that stays
|
||||
// valid until the next call on this thread; it is copied before that.
|
||||
let name = unsafe { libc::strsignal(sig) };
|
||||
!name.is_null() && unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy() == description
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn signal_number(_description: &str) -> Option<i32> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -93,7 +93,7 @@ pub fn find_tool(name: &str, config: &RunConfig, dir: &Path, root: &Path) -> Opt
|
||||
pub fn probe(argv: &[String], dir: &Path, config: &RunConfig) -> bool {
|
||||
let Some((program, args)) = argv.split_first() else { return false };
|
||||
let program = resolve(program, config);
|
||||
Command::new(program)
|
||||
ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.envs(&config.env)
|
||||
@@ -260,6 +260,8 @@ mod tests {
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ fn sample() -> Vec<RunConfig> {
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: Some("codelldb".into()),
|
||||
allow_parallel: true,
|
||||
extras: Default::default(),
|
||||
},
|
||||
RunConfig {
|
||||
id: "user:tests".into(),
|
||||
@@ -28,6 +30,8 @@ fn sample() -> Vec<RunConfig> {
|
||||
detected: false,
|
||||
is_test: true,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -110,3 +114,58 @@ fn invalid_file_is_reported() {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert!(err.message.contains("run.toml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extras_round_trip_and_local_file() {
|
||||
use ide_run::{BeforeLaunchTask, load_templates, save_templates};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut shared = sample().remove(0);
|
||||
shared.extras.folder = Some("Servers".into());
|
||||
shared.extras.params = BTreeMap::from([("mode".into(), "command".into())]);
|
||||
shared.extras.include_system_env = false;
|
||||
shared.extras.env_files = vec![".env".into(), "local.env".into()];
|
||||
shared.extras.stdin_file = Some("in.txt".into());
|
||||
shared.extras.output_file = Some("out.log".into());
|
||||
shared.extras.before_launch = vec![
|
||||
BeforeLaunchTask { kind: "build".into(), target: String::new() },
|
||||
BeforeLaunchTask { kind: "run".into(), target: "user:migrate".into() },
|
||||
];
|
||||
shared.extras.show_on_stderr = true;
|
||||
shared.extras.open_tool_window = Some(false);
|
||||
shared.extras.focus_tool_window = true;
|
||||
shared.extras.emulate_terminal = true;
|
||||
shared.extras.stop_command = Some("docker stop server".into());
|
||||
let mut local = sample().remove(1);
|
||||
local.extras.local = true;
|
||||
let mut compound = sample().remove(1);
|
||||
compound.id = "user:all".into();
|
||||
compound.name = "All".into();
|
||||
compound.kind = "compound".into();
|
||||
compound.command = String::new();
|
||||
compound.extras.compound = vec!["user:server".into(), "user:tests".into()];
|
||||
let configs = vec![shared, compound, local];
|
||||
save_user_configs(dir.path(), &configs).unwrap();
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), configs);
|
||||
|
||||
let project = fs::read_to_string(user_configs_path(dir.path())).unwrap();
|
||||
assert!(!project.contains("\"user:tests\"\n"), "{project}");
|
||||
let private = fs::read_to_string(dir.path().join(".openidea/run.local.toml")).unwrap();
|
||||
assert!(private.contains("id = \"user:tests\""), "{private}");
|
||||
let ignore = fs::read_to_string(dir.path().join(".openidea/.gitignore")).unwrap();
|
||||
assert!(ignore.lines().any(|l| l == "/run.local.toml"), "{ignore}");
|
||||
|
||||
// Making it a project file moves it back.
|
||||
let mut moved = configs.clone();
|
||||
moved[2].extras.local = false;
|
||||
save_user_configs(dir.path(), &moved).unwrap();
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), moved);
|
||||
assert!(!fs::read_to_string(dir.path().join(".openidea/run.local.toml")).unwrap().contains("user:tests"));
|
||||
|
||||
// Templates share run.toml without disturbing configurations.
|
||||
let mut template = sample().remove(1);
|
||||
template.id = "template:npm".into();
|
||||
template.kind = "npm".into();
|
||||
save_templates(dir.path(), std::slice::from_ref(&template)).unwrap();
|
||||
assert_eq!(load_templates(dir.path()).unwrap(), vec![template]);
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), moved);
|
||||
}
|
||||
@@ -42,6 +42,8 @@ fn cfg(id: &str, command: &str, args: &[&str]) -> RunConfig {
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,3 +274,108 @@ fn exit_event_goes_to_the_starters_sink_only() {
|
||||
assert!(other_events.try_recv().is_err());
|
||||
assert!(h.events.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_files_system_env_and_redirects() {
|
||||
let h = harness();
|
||||
let root = h.root.path();
|
||||
std::fs::write(root.join(".env"), "FROM_FILE=file\nOVERRIDDEN=file\n").unwrap();
|
||||
std::fs::write(root.join("input.txt"), "from file\n").unwrap();
|
||||
let mut config = cfg(
|
||||
"t:extras",
|
||||
"/bin/sh",
|
||||
&["-c", "printf '%s|%s|%s|' \"$FROM_FILE\" \"$OVERRIDDEN\" \"${HOME:-unset}\"; cat"],
|
||||
);
|
||||
config.env.insert("OVERRIDDEN".into(), "config".into());
|
||||
config.extras.env_files = vec![".env".into()];
|
||||
config.extras.include_system_env = false;
|
||||
config.extras.stdin_file = Some("input.txt".into());
|
||||
config.extras.output_file = Some("logs/out.log".into());
|
||||
let (id, chunks) = start(&h, &config);
|
||||
// stdin comes from the file: writing to it is refused.
|
||||
assert!(h.pm.write_stdin(id, "x").is_err());
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(0));
|
||||
assert_eq!(text(&chunks, stdout), "file|config|unset|from file\n");
|
||||
let saved = std::fs::read_to_string(root.join("logs/out.log")).unwrap();
|
||||
assert!(saved.contains("file|config|unset|from file\n"), "{saved}");
|
||||
assert!(saved.contains("Process finished with exit code 0"), "{saved}");
|
||||
|
||||
// With the system environment, HOME is inherited.
|
||||
config.extras.include_system_env = true;
|
||||
config.extras.stdin_file = None;
|
||||
config.extras.output_file = None;
|
||||
config.args = vec!["-c".into(), "printf '%s' \"${HOME:+set}\"".into()];
|
||||
let (id, chunks) = start(&h, &config);
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(0));
|
||||
assert_eq!(text(&chunks, stdout), "set");
|
||||
|
||||
config.extras.env_files = vec!["missing.env".into()];
|
||||
assert!(h.pm.start(root, &config, &StartOptions::default(), h.sink.clone(), Box::new(|_| {})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emulated_terminal_is_a_tty_with_input_resize_and_exit_code() {
|
||||
let h = harness();
|
||||
let script = "[ -t 1 ] && echo tty-yes; echo \"term=$TERM\"; read line; echo \"got:$line\"; stty size; exit 3";
|
||||
let mut config = cfg("t:pty", "/bin/sh", &["-c", script]);
|
||||
config.extras.emulate_terminal = true;
|
||||
let (id, chunks) = start(&h, &config);
|
||||
assert!(h.pm.list().iter().any(|r| r.id == id && r.pty));
|
||||
wait_for(&chunks, "term=xterm-256color");
|
||||
h.pm.resize(id, 100, 40).unwrap();
|
||||
h.pm.write_stdin(id, "hello\r").unwrap();
|
||||
let out = wait_for(&chunks, "40 100");
|
||||
assert!(out.contains("tty-yes"), "{out:?}");
|
||||
assert!(out.contains("got:hello"), "{out:?}");
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(3));
|
||||
assert!(text(&chunks, system).contains("Process finished with exit code 3"));
|
||||
// Stdout and stderr share the terminal.
|
||||
assert_eq!(text(&chunks, stderr), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emulated_terminal_stop_reports_the_signal() {
|
||||
let h = harness();
|
||||
let mut config = cfg("t:pty-stop", "/bin/sh", &["-c", "echo ready; sleep 30"]);
|
||||
config.extras.emulate_terminal = true;
|
||||
let (id, chunks) = start(&h, &config);
|
||||
wait_for(&chunks, "ready");
|
||||
h.pm.stop(id).unwrap();
|
||||
let code = wait_exit(&h, id, Duration::from_secs(10));
|
||||
assert_eq!(code, Some(130), "{:?}", text(&chunks, system));
|
||||
assert!(text(&chunks, system).contains("SIGINT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emulated_terminal_refuses_input_redirection() {
|
||||
let h = harness();
|
||||
let mut config = cfg("t:pty-stdin", "/bin/cat", &[]);
|
||||
config.extras.emulate_terminal = true;
|
||||
config.extras.stdin_file = Some("input.txt".into());
|
||||
assert!(h.pm.start(h.root.path(), &config, &StartOptions::default(), h.sink.clone(), Box::new(|_| {})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipe_runs_cannot_be_resized() {
|
||||
let h = harness();
|
||||
let (id, _chunks) = start(&h, &cfg("t:pipes", "/bin/sh", &["-c", "sleep 5"]));
|
||||
assert!(!h.pm.list().iter().find(|r| r.id == id).unwrap().pty);
|
||||
assert!(h.pm.resize(id, 80, 24).is_err());
|
||||
h.pm.stop(id).unwrap();
|
||||
wait_exit(&h, id, Duration::from_secs(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_command_runs_first_with_the_run_environment() {
|
||||
let h = harness();
|
||||
let mut config = cfg("t:stop-cmd", "/bin/sh", &["-c", "echo ready; sleep 30"]);
|
||||
config.env.insert("OPENIDEA_MARKER".into(), "stopped".into());
|
||||
config.extras.stop_command = Some("touch \"$OPENIDEA_MARKER\"".into());
|
||||
let (id, chunks) = start(&h, &config);
|
||||
wait_for(&chunks, "ready");
|
||||
h.pm.stop_with_grace(id, Duration::from_millis(200)).unwrap();
|
||||
// `sleep` ignores nothing: the signals that follow the stop command end it.
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(130));
|
||||
assert!(h.root.path().join("stopped").exists(), "stop command did not run");
|
||||
assert!(text(&chunks, system).contains("touch \"$OPENIDEA_MARKER\""));
|
||||
}
|
||||
@@ -10,11 +10,13 @@ dunce.workspace = true
|
||||
ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
ide-run.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -16,7 +16,7 @@ fn non_empty(s: &str) -> Option<&str> {
|
||||
}
|
||||
|
||||
/// Resolves `~/` and project-relative paths of a setting.
|
||||
fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
|
||||
pub fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
|
||||
let s = non_empty(s)?;
|
||||
let p = match s.strip_prefix("~/") {
|
||||
Some(rest) => crate::home_dir()?.join(rest),
|
||||
@@ -32,12 +32,12 @@ pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// The configured `node` executable's directory.
|
||||
fn node_dir(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
pub(crate) fn node_dir(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
setting_path(root, &s.languages.node.interpreter).and_then(|p| p.parent().map(Path::to_path_buf))
|
||||
}
|
||||
|
||||
/// The configured Rust toolchain's `bin` directory and rustup toolchain name.
|
||||
fn rust_bin(root: &Path, s: &Settings) -> Option<(PathBuf, Option<String>)> {
|
||||
pub(crate) fn rust_bin(root: &Path, s: &Settings) -> Option<(PathBuf, Option<String>)> {
|
||||
let dir = setting_path(root, &s.languages.rust.toolchain)?;
|
||||
let bin = if dir.join("bin").join(exe("rustc")).is_file() || dir.join("bin").join(exe("cargo")).is_file() {
|
||||
dir.join("bin")
|
||||
@@ -52,10 +52,75 @@ fn rust_bin(root: &Path, s: &Settings) -> Option<(PathBuf, Option<String>)> {
|
||||
Some((bin, toolchain))
|
||||
}
|
||||
|
||||
fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
setting_path(root, &s.languages.go.goroot)
|
||||
}
|
||||
|
||||
/// A JDK setting: a JDK home, its `bin` or its `bin/java`.
|
||||
fn jdk_setting(root: &Path, value: &str) -> Option<Result<crate::java::Jdk, PathBuf>> {
|
||||
let p = setting_path(root, value)?;
|
||||
Some(p.ancestors().take(3).find_map(crate::java::jdk_at).ok_or(p))
|
||||
}
|
||||
|
||||
/// The project JDK (`languages.java.jdk`).
|
||||
pub fn project_jdk(root: &Path, s: &Settings) -> Option<crate::java::Jdk> {
|
||||
jdk_setting(root, &s.languages.java.jdk)?
|
||||
.inspect_err(|p| tracing::warn!("project JDK {} is not a JDK home", p.display()))
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// The JDK chosen to run jdtls (`languages.java.jdtlsJdk`): `Ok(None)` when not
|
||||
/// set, `Err` (the message) when it is not a JDK home.
|
||||
pub fn jdtls_jdk(root: &Path, s: &Settings) -> Result<Option<crate::java::Jdk>, String> {
|
||||
match jdk_setting(root, &s.languages.java.jdtls_jdk) {
|
||||
None => Ok(None),
|
||||
Some(Ok(jdk)) => Ok(Some(jdk)),
|
||||
Some(Err(p)) => Err(format!(
|
||||
"The language server JDK {} is not a JDK home (Settings › Languages & Frameworks › Java).",
|
||||
p.display()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `mvn` of the configured Maven home (`languages.java.maven.home`): the
|
||||
/// executable itself, `<home>/bin/mvn` or `<bin>/mvn`.
|
||||
pub fn maven_command(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
let p = setting_path(root, &s.languages.java.maven.home)?;
|
||||
let name = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
|
||||
let found = [p.clone(), p.join("bin").join(name), p.join(name)].into_iter().find(|c| c.is_file());
|
||||
if found.is_none() {
|
||||
tracing::warn!("Maven home {} has no {name}", p.display());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Maven options from settings, placed before the goals: `-s <settings.xml>`
|
||||
/// and `-Dmaven.repo.local=<dir>`.
|
||||
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
|
||||
let m = &s.languages.java.maven;
|
||||
let mut out = Vec::new();
|
||||
if let Some(file) = setting_path(root, &m.user_settings) {
|
||||
out.extend(["-s".to_owned(), file.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if let Some(dir) = setting_path(root, &m.local_repository) {
|
||||
out.push(format!("-Dmaven.repo.local={}", dir.to_string_lossy()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The Maven local repository from settings: the configured one, else
|
||||
/// `<localRepository>` of the configured user `settings.xml`; `None` = Maven's default.
|
||||
pub fn maven_local_repository(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
let m = &s.languages.java.maven;
|
||||
setting_path(root, &m.local_repository).or_else(|| {
|
||||
let text = std::fs::read_to_string(setting_path(root, &m.user_settings)?).ok()?;
|
||||
let repo = crate::java::xml_value(&crate::lombok::strip_xml_comments(&text), "localRepository")?;
|
||||
let home = crate::home_dir().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let repo = repo.replace("${user.home}", &home);
|
||||
(!repo.is_empty() && !repo.contains("${")).then(|| PathBuf::from(repo))
|
||||
})
|
||||
}
|
||||
|
||||
/// TypeScript `lib` directory for the selected version; `None` = the server's bundled one.
|
||||
pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
match s.languages.typescript.version.trim() {
|
||||
@@ -104,6 +169,9 @@ pub(crate) fn merge_init_options(cfg: &mut LanguageServerConfig, layer: Value) {
|
||||
/// server settings (`python.pythonPath`, rust-analyzer `check.command`, `typescript.tsdk`).
|
||||
/// `root` is the project root, `server_root` the server's workspace root.
|
||||
pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
|
||||
if let Some(custom) = s.tool_path(&cfg.command).and_then(|p| setting_path(root, p)) {
|
||||
cfg.command = custom.to_string_lossy().into_owned();
|
||||
}
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
let name = cfg.name.clone();
|
||||
let name = name.as_str();
|
||||
@@ -166,6 +234,20 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
}
|
||||
}
|
||||
|
||||
if name == "jdtls" {
|
||||
// The jdtls launcher forwards `--jvm-arg=` values to the JVM it starts.
|
||||
let args = s.languages.java.jdtls_vm_args.split_whitespace().map(|a| format!("--jvm-arg={a}"));
|
||||
cfg.args.extend(args);
|
||||
// m2e (the Maven import) reads mirrors, servers and `<localRepository>` from it.
|
||||
if let Some(file) = setting_path(root, &s.languages.java.maven.user_settings) {
|
||||
let file = file.to_string_lossy();
|
||||
merge_init_options(
|
||||
cfg,
|
||||
json!({ "settings": { "java": { "configuration": { "maven": { "userSettings": file } } } } }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
|
||||
let lib_s = lib.to_string_lossy().into_owned();
|
||||
match name {
|
||||
@@ -200,7 +282,8 @@ const PY_RUNNERS: [&str; 3] = ["uv", "poetry", "pdm"];
|
||||
|
||||
/// Points run configurations at the selected toolchains: Python configs use the
|
||||
/// project interpreter, npm scripts the chosen package manager and Node.js,
|
||||
/// cargo / go configs the selected toolchain.
|
||||
/// cargo / go configs the selected toolchain, Maven / Gradle the project JDK
|
||||
/// (and Maven the configured home and options).
|
||||
pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings) {
|
||||
let explicit_python = setting_path(root, &s.languages.python.interpreter);
|
||||
let python = python_interpreter(root, s);
|
||||
@@ -209,6 +292,9 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
let rust = rust_bin(root, s);
|
||||
let go = goroot(root, s);
|
||||
let gopath = setting_path(root, &s.languages.go.gopath);
|
||||
let jdk = project_jdk(root, s);
|
||||
let mvn = maven_command(root, s);
|
||||
let mvn_options = maven_options(root, s);
|
||||
|
||||
for c in configs.iter_mut() {
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
@@ -275,6 +361,19 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
c.env.entry("GOPATH".into()).or_insert_with(|| gopath.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
"maven" | "gradle" => {
|
||||
if let Some(jdk) = &jdk {
|
||||
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
|
||||
}
|
||||
if c.kind == "maven" && c.detected {
|
||||
if let Some(mvn) = &mvn {
|
||||
c.command = mvn.to_string_lossy().into_owned();
|
||||
}
|
||||
if !c.args.starts_with(&mvn_options) {
|
||||
c.args.splice(0..0, mvn_options.iter().cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !path_dirs.is_empty() && !c.env.contains_key("PATH") {
|
||||
|
||||
@@ -18,6 +18,8 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
|
||||
SdkKind::Rust => rust(),
|
||||
SdkKind::Go => go(),
|
||||
SdkKind::TypeScript => typescript(root),
|
||||
SdkKind::Jdk => jdk(),
|
||||
SdkKind::Maven => maven(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,3 +384,108 @@ fn typescript(root: Option<&Path>) -> Vec<Sdk> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ jdk
|
||||
|
||||
/// `KEY="value"` of a JDK `release` file.
|
||||
fn release_value(release: &str, key: &str) -> Option<String> {
|
||||
let line = release.lines().find_map(|l| l.trim().strip_prefix(key)?.strip_prefix('='))?;
|
||||
Some(line.trim().trim_matches('"').to_owned()).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
fn jdk() -> Vec<Sdk> {
|
||||
let java_home = std::env::var_os("JAVA_HOME").and_then(|h| dunce::canonicalize(h).ok());
|
||||
crate::java::rescan_jdks()
|
||||
.iter()
|
||||
.map(|j| {
|
||||
let release = std::fs::read_to_string(j.home.join("release")).unwrap_or_default();
|
||||
let version = release_value(&release, "JAVA_VERSION").unwrap_or_else(|| j.major.to_string());
|
||||
let name = match release_value(&release, "IMPLEMENTOR") {
|
||||
Some(vendor) => format!("{vendor} {version}"),
|
||||
None => format!("JDK {version}"),
|
||||
};
|
||||
let source = if java_home.as_ref() == Some(&j.home) { "JAVA_HOME" } else { "system" };
|
||||
Sdk {
|
||||
path: j.home.clone().into(),
|
||||
name,
|
||||
version: Some(version),
|
||||
source: source.to_owned(),
|
||||
home: Some(j.home.clone().into()),
|
||||
extra: None,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ maven
|
||||
|
||||
/// Maven version from `lib/maven-core-<version>.jar`.
|
||||
fn maven_version(home: &Path) -> Option<String> {
|
||||
std::fs::read_dir(home.join("lib")).ok()?.flatten().find_map(|e| {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
Some(name.strip_prefix("maven-core-")?.strip_suffix(".jar")?.to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// A Maven home (`bin/mvn` and `lib/`); Homebrew's formula keeps it in `libexec`.
|
||||
fn maven_home(dir: &Path) -> Option<PathBuf> {
|
||||
let mvn = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
|
||||
[dir.join("libexec"), dir.to_path_buf()]
|
||||
.into_iter()
|
||||
.find(|h| h.join("bin").join(mvn).is_file() && h.join("lib").is_dir())
|
||||
}
|
||||
|
||||
fn maven() -> Vec<Sdk> {
|
||||
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
|
||||
// Windows' Maven ships `mvn.cmd` only (`which` looks for `mvn.exe`).
|
||||
let on_path = if cfg!(windows) {
|
||||
std::env::split_paths(&search_path()).map(|d| d.join("mvn.cmd")).find(|p| p.is_file())
|
||||
} else {
|
||||
which("mvn")
|
||||
};
|
||||
if let Some(mvn) = on_path.and_then(|p| dunce::canonicalize(p).ok())
|
||||
&& let Some(home) = mvn.parent().and_then(Path::parent)
|
||||
{
|
||||
found.push((home.to_path_buf(), "path"));
|
||||
}
|
||||
for var in ["MAVEN_HOME", "M2_HOME"] {
|
||||
if let Some(h) = std::env::var_os(var) {
|
||||
found.push((PathBuf::from(h), "env"));
|
||||
}
|
||||
}
|
||||
for p in ["/opt/homebrew/opt/maven", "/usr/local/opt/maven", "/usr/share/maven", "/opt/maven"] {
|
||||
found.push((PathBuf::from(p), "system"));
|
||||
}
|
||||
if let Some(home) = home_dir() {
|
||||
for d in subdirs(&home.join(".sdkman/candidates/maven")) {
|
||||
found.push((d, "sdkman"));
|
||||
}
|
||||
// Distributions the Maven wrapper downloaded: `dists/apache-maven-3.9.6-bin/<hash>/apache-maven-3.9.6`,
|
||||
// or since wrapper 3.3 the home itself, `dists/apache-maven-3.9.6/<hash>`.
|
||||
for dist in subdirs(&home.join(".m2/wrapper/dists")) {
|
||||
for hash in subdirs(&dist) {
|
||||
found.extend(subdirs(&hash).into_iter().map(|d| (d, "wrapper")));
|
||||
found.push((hash, "wrapper"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for (dir, source) in found {
|
||||
let Some(home) = maven_home(&dir) else { continue };
|
||||
let home = dunce::canonicalize(&home).unwrap_or(home);
|
||||
if !seen.insert(home.clone()) {
|
||||
continue;
|
||||
}
|
||||
let version = maven_version(&home);
|
||||
out.push(Sdk {
|
||||
path: home.clone().into(),
|
||||
name: format!("Maven {}", version.clone().unwrap_or_default()).trim().to_owned(),
|
||||
version,
|
||||
source: source.to_owned(),
|
||||
home: Some(home.into()),
|
||||
extra: None,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -44,9 +44,25 @@ pub(crate) fn which(name: &str) -> Option<PathBuf> {
|
||||
/// Runs `program args` and returns trimmed stdout (stderr when stdout is empty)
|
||||
/// on success; `None` on failure or after `timeout`.
|
||||
pub(crate) fn query(program: &Path, args: &[&str], timeout: Duration) -> Option<String> {
|
||||
let mut child = Command::new(program)
|
||||
query_in(program, args, None, &[], timeout)
|
||||
}
|
||||
|
||||
/// [`query`] in `cwd` with extra environment variables.
|
||||
pub(crate) fn query_in(
|
||||
program: &Path,
|
||||
args: &[&str],
|
||||
cwd: Option<&Path>,
|
||||
env: &[(&str, &str)],
|
||||
timeout: Duration,
|
||||
) -> Option<String> {
|
||||
let mut cmd = Command::new(program);
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
let mut child = ide_core::process::no_window(&mut cmd)
|
||||
.args(args)
|
||||
.env("PATH", search_path())
|
||||
.envs(env.iter().copied())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -96,6 +112,7 @@ pub(crate) fn stream(
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(program);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
cmd.args(args).env("PATH", search_path()).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
cmd.envs(env.iter().map(|(k, v)| (k, v)));
|
||||
if let Some(cwd) = cwd {
|
||||
|
||||
@@ -6,7 +6,8 @@ use ide_language::LanguageServerConfig;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A JDK home and its feature version (8, 11, 17, 21…).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -24,7 +25,8 @@ pub fn parse_release(release: &str) -> Option<u32> {
|
||||
if first == 1 { parts.next()?.parse().ok() } else { Some(first) }
|
||||
}
|
||||
|
||||
fn jdk_at(home: &Path) -> Option<Jdk> {
|
||||
/// The JDK at `home`, if it is one (a `release` file and `bin/java`).
|
||||
pub fn jdk_at(home: &Path) -> Option<Jdk> {
|
||||
let release = std::fs::read_to_string(home.join("release")).ok()?;
|
||||
if !home.join("bin").join(crate::exe("java")).is_file() {
|
||||
return None;
|
||||
@@ -42,13 +44,26 @@ fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Vendor directories JDK installers use on Windows, under `Program Files`
|
||||
/// and (per-user installs) `%LOCALAPPDATA%\Programs`.
|
||||
const WINDOWS_VENDORS: &[&str] =
|
||||
&["Java", "Eclipse Adoptium", "Microsoft", "Zulu", "Amazon Corretto", "BellSoft", "Semeru", "OpenJDK"];
|
||||
|
||||
/// JDK homes in the usual install locations (macOS `JavaVirtualMachines`,
|
||||
/// `/usr/lib/jvm`, SDKMAN, IDEA's `~/.jdks`, Homebrew), `JAVA_HOME` first.
|
||||
/// `/usr/lib/jvm`, SDKMAN, IDEA's `~/.jdks`, Homebrew, Windows vendor
|
||||
/// directories), `JAVA_HOME` first, then the `java` on `PATH`.
|
||||
fn scan() -> Vec<Jdk> {
|
||||
let mut homes: Vec<PathBuf> = Vec::new();
|
||||
if let Some(h) = std::env::var_os("JAVA_HOME") {
|
||||
homes.push(PathBuf::from(h));
|
||||
}
|
||||
let path = std::env::var_os("PATH").unwrap_or_default();
|
||||
if let Some(java) = std::env::split_paths(&path).map(|d| d.join(crate::exe("java"))).find(|j| j.is_file()) {
|
||||
// Through symlinks (`/usr/bin/java`, Homebrew, SDKMAN `current`) to `<home>/bin/java`.
|
||||
if let Some(home) = dunce::canonicalize(java).ok().and_then(|j| j.parent()?.parent().map(Path::to_path_buf)) {
|
||||
homes.push(home);
|
||||
}
|
||||
}
|
||||
let home = home_dir();
|
||||
let mut roots: Vec<PathBuf> = vec![
|
||||
PathBuf::from("/Library/Java/JavaVirtualMachines"),
|
||||
@@ -59,8 +74,21 @@ fn scan() -> Vec<Jdk> {
|
||||
if let Some(h) = &home {
|
||||
roots.extend([h.join("Library/Java/JavaVirtualMachines"), h.join(".jdks"), h.join(".sdkman/candidates/java")]);
|
||||
}
|
||||
for root in roots {
|
||||
for dir in children(&root) {
|
||||
if cfg!(windows) {
|
||||
let bases = ["ProgramFiles", "ProgramW6432", "LOCALAPPDATA"].into_iter().filter_map(|v| {
|
||||
let dir = PathBuf::from(std::env::var_os(v)?);
|
||||
Some(if v == "LOCALAPPDATA" { dir.join("Programs") } else { dir })
|
||||
});
|
||||
for base in bases {
|
||||
roots.extend(WINDOWS_VENDORS.iter().map(|v| base.join(v)));
|
||||
}
|
||||
}
|
||||
for (i, root) in roots.iter().enumerate() {
|
||||
// `ProgramFiles` and `ProgramW6432` are usually the same directory.
|
||||
if roots[..i].contains(root) {
|
||||
continue;
|
||||
}
|
||||
for dir in children(root) {
|
||||
homes.extend([dir.join("Contents/Home"), dir.join("libexec/openjdk.jdk/Contents/Home"), dir]);
|
||||
}
|
||||
}
|
||||
@@ -75,10 +103,130 @@ fn scan() -> Vec<Jdk> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Installed JDKs (scanned once per process).
|
||||
pub fn installed_jdks() -> &'static [Jdk] {
|
||||
static JDKS: OnceLock<Vec<Jdk>> = OnceLock::new();
|
||||
JDKS.get_or_init(scan)
|
||||
/// How long a scan that found no JDK able to run jdtls is reused before
|
||||
/// [`jdtls_jdks`] scans again.
|
||||
const RESCAN_AFTER: Duration = Duration::from_secs(10);
|
||||
|
||||
struct Scan {
|
||||
at: Instant,
|
||||
jdks: Arc<[Jdk]>,
|
||||
}
|
||||
|
||||
static JDKS: Mutex<Option<Scan>> = Mutex::new(None);
|
||||
|
||||
fn rescan(slot: &mut Option<Scan>) -> Arc<[Jdk]> {
|
||||
slot.insert(Scan { at: Instant::now(), jdks: scan().into() }).jdks.clone()
|
||||
}
|
||||
|
||||
/// Scans for installed JDKs again (Settings › Detect again).
|
||||
pub fn rescan_jdks() -> Arc<[Jdk]> {
|
||||
rescan(&mut JDKS.lock().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
|
||||
/// Installed JDKs (scanned on first use; [`jdtls_jdks`] may refresh them).
|
||||
pub fn installed_jdks() -> Arc<[Jdk]> {
|
||||
let mut slot = JDKS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match &*slot {
|
||||
Some(s) => s.jdks.clone(),
|
||||
None => rescan(&mut slot),
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`installed_jdks`], but while none can run jdtls (on Java `min_java`)
|
||||
/// the list is rescanned (at most every [`RESCAN_AFTER`]), so a JDK installed
|
||||
/// after startup is picked up when the server is restarted.
|
||||
pub fn jdtls_jdks(min_java: u32) -> Arc<[Jdk]> {
|
||||
let mut slot = JDKS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match &*slot {
|
||||
Some(s) if jdtls_runtime(&s.jdks, min_java).is_some() || s.at.elapsed() < RESCAN_AFTER => s.jdks.clone(),
|
||||
_ => rescan(&mut slot),
|
||||
}
|
||||
}
|
||||
|
||||
/// Oldest Java version jdtls runs on when its install can't tell (its launcher's check).
|
||||
pub const JDTLS_MIN_JAVA: u32 = 21;
|
||||
|
||||
/// The JDK to run jdtls with: the first found that is new enough (`JAVA_HOME` wins).
|
||||
pub fn jdtls_runtime(jdks: &[Jdk], min_java: u32) -> Option<&Jdk> {
|
||||
jdks.iter().find(|j| j.major >= min_java)
|
||||
}
|
||||
|
||||
/// The Java version the jdtls that `cfg` launches needs: the highest any of its
|
||||
/// bundles requires, never below [`JDTLS_MIN_JAVA`]. Its launcher only checks
|
||||
/// for 21, but the Eclipse platform it ships moves on (1.63 needs 25), and on
|
||||
/// an older JDK the server dies resolving its bundles.
|
||||
pub fn jdtls_min_java(cfg: &LanguageServerConfig) -> u32 {
|
||||
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).or_else(|| std::env::var_os("PATH"));
|
||||
let required = search
|
||||
.and_then(|s| ide_run::which::find_executable(&cfg.command, &s))
|
||||
.and_then(|exe| dunce::canonicalize(exe).ok())
|
||||
.and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
|
||||
.and_then(|home| bundles_min_java(&home));
|
||||
required.map_or(JDTLS_MIN_JAVA, |v| v.max(JDTLS_MIN_JAVA))
|
||||
}
|
||||
|
||||
/// Per install: (plugins directory mtime, its requirement).
|
||||
static BUNDLE_JAVA: Mutex<BTreeMap<PathBuf, (std::time::SystemTime, Option<u32>)>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
/// Highest Java version required by the bundles in `home`'s `plugins` (or Homebrew's
|
||||
/// `libexec/plugins`); `None` when there are none to read.
|
||||
fn bundles_min_java(home: &Path) -> Option<u32> {
|
||||
let plugins = [home.join("plugins"), home.join("libexec").join("plugins")].into_iter().find(|p| p.is_dir())?;
|
||||
let modified = std::fs::metadata(&plugins).and_then(|m| m.modified()).ok()?;
|
||||
let mut cache = BUNDLE_JAVA.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((at, v)) = cache.get(&plugins)
|
||||
&& *at == modified
|
||||
{
|
||||
return *v;
|
||||
}
|
||||
let required = std::fs::read_dir(&plugins)
|
||||
.ok()?
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|x| x == "jar"))
|
||||
.filter_map(|jar| jar_manifest(&jar))
|
||||
.filter_map(|manifest| manifest_min_java(&manifest))
|
||||
.max();
|
||||
cache.insert(plugins, (modified, required));
|
||||
required
|
||||
}
|
||||
|
||||
fn jar_manifest(jar: &Path) -> Option<String> {
|
||||
use std::io::Read;
|
||||
let mut zip = zip::ZipArchive::new(std::fs::File::open(jar).ok()?).ok()?;
|
||||
let mut entry = zip.by_name("META-INF/MANIFEST.MF").ok()?;
|
||||
let mut text = String::new();
|
||||
entry.read_to_string(&mut text).ok()?;
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// The Java version an OSGi bundle manifest requires: its `osgi.ee` capability
|
||||
/// (`version=25`), else the oldest of its `Bundle-RequiredExecutionEnvironment`s.
|
||||
fn manifest_min_java(manifest: &str) -> Option<u32> {
|
||||
// Long headers continue on lines starting with a space.
|
||||
let mut headers: Vec<String> = Vec::new();
|
||||
for line in manifest.lines() {
|
||||
match (line.strip_prefix(' '), headers.last_mut()) {
|
||||
(Some(rest), Some(last)) => last.push_str(rest),
|
||||
_ => headers.push(line.to_owned()),
|
||||
}
|
||||
}
|
||||
let header = |name: &str| headers.iter().find_map(|h| h.strip_prefix(name)?.strip_prefix(':')).map(str::trim);
|
||||
if let Some(caps) = header("Require-Capability") {
|
||||
let ee = caps.split(',').filter(|c| c.trim_start().starts_with("osgi.ee")).find_map(|c| {
|
||||
let v = c.split("version=").nth(1)?;
|
||||
let digits: String = v.chars().take_while(char::is_ascii_digit).collect();
|
||||
digits.parse::<u32>().ok()
|
||||
});
|
||||
if ee.is_some() {
|
||||
return ee;
|
||||
}
|
||||
}
|
||||
header("Bundle-RequiredExecutionEnvironment")?
|
||||
.split(',')
|
||||
.filter_map(|ee| ee.trim().strip_prefix("JavaSE-"))
|
||||
.filter_map(|v| if v == "1.8" { Some(8) } else { v.parse().ok() })
|
||||
.min()
|
||||
}
|
||||
|
||||
/// jdtls `java.configuration.runtimes`: one JDK per Java version (the first
|
||||
@@ -114,20 +262,37 @@ const METADATA_PROPERTY: &str = "java.import.generatesMetadataFilesAtProjectRoot
|
||||
|
||||
/// jdtls: its Eclipse workspace (`-data`) lives under the IDE's data
|
||||
/// directory, one per server root, and no Eclipse metadata is written into
|
||||
/// the project; installed JDKs are registered as runtimes and `bundles`
|
||||
/// (e.g. the java-debug plugin jar) are loaded into the server.
|
||||
/// the project; it runs on a JDK `min_java`+ (via `JAVA_HOME`, which its
|
||||
/// launcher reads), installed JDKs are registered as runtimes and `bundles`
|
||||
/// (e.g. the java-debug plugin jar) are loaded into the server. The project
|
||||
/// JDK, when set, is the default runtime and preferred for running the server;
|
||||
/// `server_jdk` (the user's choice for the server alone) overrides that.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn configure_jdtls(
|
||||
cfg: &mut LanguageServerConfig,
|
||||
server_root: &Path,
|
||||
data_dir: &Path,
|
||||
jdks: &[Jdk],
|
||||
project_jdk: Option<&Jdk>,
|
||||
server_jdk: Option<&Jdk>,
|
||||
min_java: u32,
|
||||
bundles: &[PathBuf],
|
||||
lombok: Option<&Path>,
|
||||
) {
|
||||
if cfg.name != "jdtls" {
|
||||
return;
|
||||
}
|
||||
// A Lombok agent from the user's JVM arguments wins.
|
||||
let own_agent = crate::lombok::agent_in_args(cfg.args.iter().map(String::as_str));
|
||||
let agent = own_agent.as_deref().or(lombok);
|
||||
if !cfg.args.iter().any(|a| a == "-data") {
|
||||
let dir = data_dir.join("lsp").join("jdtls").join(path_key(server_root));
|
||||
// ECJ builds incrementally: classes compiled without (or with another) Lombok
|
||||
// agent would be kept, so each agent gets its own workspace and a full build.
|
||||
let key = match agent {
|
||||
Some(jar) => format!("{}-{}", path_key(server_root), path_key(jar)),
|
||||
None => path_key(server_root),
|
||||
};
|
||||
let dir = data_dir.join("lsp").join("jdtls").join(key);
|
||||
cfg.args.extend(["-data".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
// jdtls reads this one as a system property (its file-system bundle
|
||||
@@ -135,7 +300,40 @@ pub fn configure_jdtls(
|
||||
if !cfg.args.iter().any(|a| a.contains(METADATA_PROPERTY)) {
|
||||
cfg.args.push(format!("--jvm-arg=-D{METADATA_PROPERTY}=false"));
|
||||
}
|
||||
let runtimes = runtimes(jdks);
|
||||
if own_agent.is_none()
|
||||
&& let Some(jar) = lombok
|
||||
{
|
||||
cfg.args.push(format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy()));
|
||||
}
|
||||
let mut all: Vec<Jdk> = Vec::new();
|
||||
for j in project_jdk.into_iter().chain(jdks).chain(server_jdk) {
|
||||
if !all.contains(j) {
|
||||
all.push(j.clone());
|
||||
}
|
||||
}
|
||||
let jdks = all.as_slice();
|
||||
if !cfg.env.contains_key("JAVA_HOME") {
|
||||
let runtime = match server_jdk {
|
||||
Some(jdk) if jdk.major < min_java => Err(server_jdk_too_old_message(jdk, min_java)),
|
||||
Some(jdk) => Ok(jdk),
|
||||
None => jdtls_runtime(jdks, min_java).ok_or_else(|| missing_runtime_message(jdks, min_java)),
|
||||
};
|
||||
match runtime {
|
||||
Ok(jdk) => {
|
||||
cfg.env.insert("JAVA_HOME".to_owned(), jdk.home.to_string_lossy().into_owned());
|
||||
}
|
||||
Err(e) => cfg.launch_error = Some(e),
|
||||
}
|
||||
}
|
||||
let mut runtimes = runtimes(jdks);
|
||||
if let Some(project) = project_jdk {
|
||||
let home = project.home.to_string_lossy();
|
||||
for r in &mut runtimes {
|
||||
if r["path"] == *home {
|
||||
r["default"] = json!(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !runtimes.is_empty() {
|
||||
merge_init_options(cfg, json!({ "settings": { "java": { "configuration": { "runtimes": runtimes } } } }));
|
||||
}
|
||||
@@ -145,6 +343,31 @@ pub fn configure_jdtls(
|
||||
}
|
||||
}
|
||||
|
||||
fn missing_runtime_message(jdks: &[Jdk], min_java: u32) -> String {
|
||||
let mut found: Vec<u32> = jdks.iter().map(|j| j.major).collect();
|
||||
found.sort_unstable();
|
||||
found.dedup();
|
||||
let found = if found.is_empty() {
|
||||
"no JDK was found".to_owned()
|
||||
} else {
|
||||
let list: Vec<String> = found.iter().map(u32::to_string).collect();
|
||||
format!("found JDK {}", list.join(", "))
|
||||
};
|
||||
format!(
|
||||
"jdtls needs JDK {min_java} or newer to run ({found}). Install one (or point JAVA_HOME at it) and \
|
||||
restart the server; the project can still target an older Java version."
|
||||
)
|
||||
}
|
||||
|
||||
fn server_jdk_too_old_message(jdk: &Jdk, min_java: u32) -> String {
|
||||
format!(
|
||||
"The language server JDK ({}, JDK {}) is too old: jdtls needs JDK {min_java} or newer. Choose another \
|
||||
one in Settings › Languages & Frameworks › Java, or set it to Auto.",
|
||||
jdk.home.display(),
|
||||
jdk.major
|
||||
)
|
||||
}
|
||||
|
||||
/// The `java` launcher of a JDK home.
|
||||
pub fn java_executable(home: &Path) -> PathBuf {
|
||||
home.join("bin").join(crate::exe("java"))
|
||||
@@ -201,7 +424,7 @@ pub fn project_java_version(module_dir: &Path) -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
fn xml_value(text: &str, tag: &str) -> Option<String> {
|
||||
pub(crate) fn xml_value(text: &str, tag: &str) -> Option<String> {
|
||||
let open = format!("<{tag}>");
|
||||
let start = text.find(&open)? + open.len();
|
||||
let end = text[start..].find('<')?;
|
||||
@@ -241,7 +464,17 @@ mod tests {
|
||||
Jdk { major: 8, home: PathBuf::from("/jdk8") },
|
||||
];
|
||||
let bundles = [PathBuf::from("/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar")];
|
||||
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, &bundles);
|
||||
configure_jdtls(
|
||||
&mut cfg,
|
||||
Path::new("/p/demo"),
|
||||
Path::new("/data"),
|
||||
&jdks,
|
||||
None,
|
||||
None,
|
||||
JDTLS_MIN_JAVA,
|
||||
&bundles,
|
||||
None,
|
||||
);
|
||||
assert_eq!(cfg.args[0], "-data");
|
||||
assert!(cfg.args[1].starts_with("/data/lsp/jdtls/"), "{}", cfg.args[1]);
|
||||
assert_eq!(cfg.args[2], "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false");
|
||||
@@ -251,17 +484,189 @@ mod tests {
|
||||
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": "/jdk21a" }));
|
||||
assert_eq!(rt[2], json!({ "name": "JavaSE-25", "path": "/jdk25" }));
|
||||
assert_eq!(opts["bundles"], json!(["/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar"]));
|
||||
assert_eq!(cfg.env["JAVA_HOME"], "/jdk25", "first JDK new enough to run jdtls");
|
||||
assert_eq!(cfg.launch_error, None);
|
||||
|
||||
// Deterministic (reconfigure compares configs) and idempotent.
|
||||
let before = cfg.clone();
|
||||
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, &bundles);
|
||||
configure_jdtls(
|
||||
&mut cfg,
|
||||
Path::new("/p/demo"),
|
||||
Path::new("/data"),
|
||||
&jdks,
|
||||
None,
|
||||
None,
|
||||
JDTLS_MIN_JAVA,
|
||||
&bundles,
|
||||
None,
|
||||
);
|
||||
assert_eq!(cfg, before);
|
||||
|
||||
// The project JDK is the default runtime, and runs the server when new enough.
|
||||
let project = Jdk { major: 21, home: PathBuf::from("/jdk21b") };
|
||||
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
|
||||
configure_jdtls(
|
||||
&mut cfg,
|
||||
Path::new("/p"),
|
||||
Path::new("/data"),
|
||||
&jdks,
|
||||
Some(&project),
|
||||
None,
|
||||
JDTLS_MIN_JAVA,
|
||||
&[],
|
||||
None,
|
||||
);
|
||||
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
|
||||
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
|
||||
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": "/jdk21b", "default": true }));
|
||||
assert_eq!(cfg.env["JAVA_HOME"], "/jdk21b");
|
||||
|
||||
let mut other: LanguageServerConfig = toml::from_str("name = \"pyright\"\ncommand = \"x\"").unwrap();
|
||||
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, &bundles);
|
||||
configure_jdtls(
|
||||
&mut other,
|
||||
Path::new("/p"),
|
||||
Path::new("/data"),
|
||||
&jdks,
|
||||
None,
|
||||
None,
|
||||
JDTLS_MIN_JAVA,
|
||||
&bundles,
|
||||
None,
|
||||
);
|
||||
assert!(other.args.is_empty() && other.initialization_options.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_lombok_agent() {
|
||||
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
|
||||
let jar = Path::new("/m2/lombok-1.18.48.jar");
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
let agent = format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy());
|
||||
assert!(cfg.args.contains(&agent), "{:?}", cfg.args);
|
||||
let mut plain = jdtls();
|
||||
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
assert_ne!(cfg.args[1], plain.args[1], "a separate workspace, so everything is rebuilt with the agent");
|
||||
let before = cfg.clone();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
assert_eq!(cfg, before, "idempotent");
|
||||
|
||||
let mut cfg = jdtls();
|
||||
cfg.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
assert!(!cfg.args.contains(&agent), "the user's agent wins");
|
||||
let mut own = jdtls();
|
||||
own.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
|
||||
configure_jdtls(&mut own, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
assert_eq!(cfg.args, own.args, "its workspace follows the agent in use");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_needs_a_new_enough_jdk_to_run() {
|
||||
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
|
||||
let old = [Jdk { major: 17, home: PathBuf::from("/jdk17") }, Jdk { major: 8, home: PathBuf::from("/jdk8") }];
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
assert!(!cfg.env.contains_key("JAVA_HOME"));
|
||||
let err = cfg.launch_error.unwrap();
|
||||
assert!(err.contains("JDK 21 or newer") && err.contains("found JDK 8, 17"), "{err}");
|
||||
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
assert!(cfg.launch_error.unwrap().contains("no JDK was found"));
|
||||
|
||||
// An explicit JAVA_HOME is the user's call.
|
||||
let mut cfg = jdtls();
|
||||
cfg.env.insert("JAVA_HOME".into(), "/custom".into());
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/custom", None));
|
||||
|
||||
let mixed = [old[0].clone(), Jdk { major: 21, home: PathBuf::from("/jdk21") }];
|
||||
assert_eq!(jdtls_runtime(&mixed, 21).unwrap().major, 21);
|
||||
|
||||
// A jdtls whose bundles need 25 doesn't start on 21, and says what it needs.
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, None, None, 25, &[], None);
|
||||
let err = cfg.launch_error.unwrap();
|
||||
assert!(err.contains("JDK 25 or newer") && err.contains("found JDK 17, 21"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_runs_on_the_chosen_server_jdk() {
|
||||
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
|
||||
let jdk = |major: u32, home: &str| Jdk { major, home: PathBuf::from(home) };
|
||||
let installed = [jdk(25, "/jdk25"), jdk(21, "/jdk21"), jdk(17, "/jdk17")];
|
||||
let project = jdk(17, "/jdk17");
|
||||
let run = |server: Option<&Jdk>, min_java: u32| {
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(
|
||||
&mut cfg,
|
||||
Path::new("/p"),
|
||||
Path::new("/data"),
|
||||
&installed,
|
||||
Some(&project),
|
||||
server,
|
||||
min_java,
|
||||
&[],
|
||||
None,
|
||||
);
|
||||
cfg
|
||||
};
|
||||
|
||||
// Project on JDK 17, server on the chosen 21: each keeps its own JDK.
|
||||
let cfg = run(Some(&jdk(21, "/jdk21")), JDTLS_MIN_JAVA);
|
||||
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/jdk21", None));
|
||||
let opts = serde_json::to_value(cfg.initialization_options.unwrap()).unwrap();
|
||||
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
|
||||
assert_eq!(rt[0], json!({ "name": "JavaSE-17", "path": "/jdk17", "default": true }), "still compiles on 17");
|
||||
|
||||
// Not set: the first installed JDK new enough, as before.
|
||||
assert_eq!(run(None, JDTLS_MIN_JAVA).env["JAVA_HOME"], "/jdk25");
|
||||
|
||||
// A chosen JDK outside the scanned locations.
|
||||
let own = jdk(25, "/opt/own-jdk");
|
||||
let cfg = run(Some(&own), 25);
|
||||
assert_eq!(cfg.env["JAVA_HOME"], "/opt/own-jdk");
|
||||
|
||||
// Too old for this jdtls: the user's choice is not overridden, it is explained.
|
||||
let cfg = run(Some(&jdk(21, "/jdk21")), 25);
|
||||
assert!(!cfg.env.contains_key("JAVA_HOME"));
|
||||
let err = cfg.launch_error.unwrap();
|
||||
assert!(err.contains("/jdk21") && err.contains("JDK 25 or newer"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundle_manifests_give_the_java_jdtls_needs() {
|
||||
let ee = |m: &str| manifest_min_java(m);
|
||||
assert_eq!(ee("Bundle-RequiredExecutionEnvironment: JavaSE-25\n"), Some(25));
|
||||
assert_eq!(ee("Bundle-RequiredExecutionEnvironment: JavaSE-17, JavaSE-1.8\n"), Some(8));
|
||||
// The capability wins, also when folded over continuation lines.
|
||||
let folded = "Require-Capability: osgi.service;filter:=\"(x=1)\",osgi.ee;filter:=\"(&(osgi.ee=Ja\r\n \
|
||||
vaSE)(version=21))\"\r\nBundle-RequiredExecutionEnvironment: JavaSE-17\r\n";
|
||||
assert_eq!(ee(folded), Some(21));
|
||||
assert_eq!(ee("Bundle-Name: x\n"), None);
|
||||
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let plugins = home.path().join("plugins");
|
||||
std::fs::create_dir(&plugins).unwrap();
|
||||
let jar = |name: &str, manifest: &str| {
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(plugins.join(name)).unwrap());
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
zip.start_file("META-INF/MANIFEST.MF", opts).unwrap();
|
||||
std::io::Write::write_all(&mut zip, manifest.as_bytes()).unwrap();
|
||||
zip.finish().unwrap();
|
||||
};
|
||||
jar(
|
||||
"org.eclipse.jdt.ls.core_1.63.0.jar",
|
||||
"Require-Capability: osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=21))\"\n",
|
||||
);
|
||||
jar("org.eclipse.core.filesystem_1.12.0.jar", "Bundle-RequiredExecutionEnvironment: JavaSE-25\n");
|
||||
jar("plain.jar", "Manifest-Version: 1.0\n");
|
||||
std::fs::write(plugins.join("notes.txt"), "not a jar").unwrap();
|
||||
assert_eq!(bundles_min_java(home.path()), Some(25));
|
||||
assert_eq!(bundles_min_java(&home.path().join("missing")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_the_jdk_matching_the_project() {
|
||||
let jdks = [
|
||||
|
||||
@@ -9,7 +9,9 @@ pub mod apply;
|
||||
mod discover;
|
||||
mod exec;
|
||||
pub mod java;
|
||||
pub mod libraries;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
pub mod python;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -30,6 +32,10 @@ pub enum SdkKind {
|
||||
Rust,
|
||||
Go,
|
||||
TypeScript,
|
||||
/// JDK homes.
|
||||
Jdk,
|
||||
/// Maven homes.
|
||||
Maven,
|
||||
}
|
||||
|
||||
/// One installed interpreter / toolchain.
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
//! "External Libraries" of a project (IDEA's library / SDK roots in the
|
||||
//! Project view): the folders holding the sources of the project's SDKs and
|
||||
//! dependencies — the Python interpreter's standard library and site-packages,
|
||||
//! the JDK, `node_modules` packages, Cargo crates and the Rust standard
|
||||
//! library, GOROOT and the Go module cache.
|
||||
//!
|
||||
//! Each ecosystem is detected only when the project has its manifest, and its
|
||||
//! result is cached until the manifests (or the relevant settings) change.
|
||||
//!
|
||||
//! Archives are listed as browsable roots (`<archive>!`, see `ide_vfs`): the
|
||||
//! JDK's `src.zip` and the Maven / Gradle dependency jars (sources jars preferred).
|
||||
|
||||
use crate::exe;
|
||||
use crate::exec::{query, query_in, which};
|
||||
use ide_core::settings::Settings;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// One SDK or library with its source folders (`< Python 3.12 (.venv) >`).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryGroup {
|
||||
/// Display name, e.g. `Python 3.12 (.venv)`.
|
||||
pub name: String,
|
||||
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle`.
|
||||
pub kind: String,
|
||||
pub roots: Vec<LibraryRoot>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryRoot {
|
||||
/// Folder name, e.g. `python3.12` or `site-packages`, the package (`serde 1.0.200`)
|
||||
/// or the archive (`src.zip`, `guava-33.0.0-jre-sources.jar`).
|
||||
pub name: String,
|
||||
/// A folder, or an archive's root (`<archive>!`).
|
||||
pub path: ide_core::IpcPath,
|
||||
}
|
||||
|
||||
const QUERY_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// `cargo metadata` / `go list` load the whole dependency graph.
|
||||
const GRAPH_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Prints the interpreter's library folders as JSON: `[stdlib, platstdlib, purelib, platlib]`.
|
||||
const PYTHON_PATHS: &str = "import json,sysconfig;p=sysconfig.get_paths();\
|
||||
print(json.dumps([p.get(k) for k in ('stdlib','platstdlib','purelib','platlib')]))";
|
||||
|
||||
const JAVA_MANIFESTS: &[&str] =
|
||||
&["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"];
|
||||
const NODE_MANIFESTS: &[&str] = &["package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lockb"];
|
||||
const CARGO_MANIFESTS: &[&str] = &["Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml"];
|
||||
const GO_MANIFESTS: &[&str] = &["go.mod", "go.sum", "go.work"];
|
||||
|
||||
/// A Maven / Gradle dependency of the project, from the build model.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct BuildDependency {
|
||||
/// Resolved by Gradle (else Maven): looked up in the Gradle cache first.
|
||||
pub gradle: bool,
|
||||
pub group: String,
|
||||
pub artifact: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// The project's library groups; empty when no SDK is configured. Runs the
|
||||
/// toolchains (in parallel), so call it off the UI / command thread.
|
||||
/// `dependencies` (from the build model) are listed when their jars are in the local repositories.
|
||||
pub fn project_libraries(root: &Path, settings: &Settings, dependencies: &[BuildDependency]) -> Vec<LibraryGroup> {
|
||||
type Detect = fn(&Path, &Settings) -> Vec<LibraryGroup>;
|
||||
let detectors: [Detect; 5] = [python_groups, jdk_groups, node_groups, rust_groups, go_groups];
|
||||
std::thread::scope(|s| {
|
||||
let handles: Vec<_> = detectors.iter().map(|d| s.spawn(move || d(root, settings))).collect();
|
||||
let deps = s.spawn(|| dependency_groups(root, settings, dependencies));
|
||||
handles.into_iter().chain([deps]).flat_map(|h| h.join().unwrap_or_default()).collect()
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ cache
|
||||
|
||||
/// Size and modification time of each manifest (`None`: missing).
|
||||
type Stamp = Vec<(PathBuf, Option<(SystemTime, u64)>)>;
|
||||
|
||||
struct Cached {
|
||||
/// Settings the result depends on.
|
||||
key: String,
|
||||
stamp: Stamp,
|
||||
groups: Vec<LibraryGroup>,
|
||||
}
|
||||
|
||||
static CACHE: LazyLock<Mutex<HashMap<(PathBuf, &'static str), Cached>>> = LazyLock::new(Default::default);
|
||||
|
||||
fn stamp(files: &[PathBuf]) -> Stamp {
|
||||
files
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let meta = std::fs::metadata(f).ok().and_then(|m| Some((m.modified().ok()?, m.len())));
|
||||
(f.clone(), meta)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `detect()` unless the last result for `(root, ecosystem)` was computed with
|
||||
/// the same `key` and unchanged `manifests`.
|
||||
pub(crate) fn cached(
|
||||
root: &Path,
|
||||
ecosystem: &'static str,
|
||||
key: String,
|
||||
manifests: &[PathBuf],
|
||||
detect: impl FnOnce() -> Vec<LibraryGroup>,
|
||||
) -> Vec<LibraryGroup> {
|
||||
let id = (root.to_path_buf(), ecosystem);
|
||||
let now = stamp(manifests);
|
||||
if let Some(c) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).get(&id)
|
||||
&& c.key == key
|
||||
&& c.stamp == now
|
||||
{
|
||||
return c.groups.clone();
|
||||
}
|
||||
let groups = detect();
|
||||
CACHE.lock().unwrap_or_else(|e| e.into_inner()).insert(id, Cached { key, stamp: now, groups: groups.clone() });
|
||||
groups
|
||||
}
|
||||
|
||||
/// `names` below `root` when at least one of them exists (the project uses that ecosystem).
|
||||
fn manifests(root: &Path, names: &[&str]) -> Option<Vec<PathBuf>> {
|
||||
let files: Vec<PathBuf> = names.iter().map(|n| root.join(n)).collect();
|
||||
files.iter().any(|f| f.is_file()).then_some(files)
|
||||
}
|
||||
|
||||
fn group(name: impl Into<String>, kind: &str, roots: Vec<LibraryRoot>) -> Option<LibraryGroup> {
|
||||
(!roots.is_empty()).then(|| LibraryGroup { name: name.into(), kind: kind.into(), roots })
|
||||
}
|
||||
|
||||
/// A configured toolchain `bin` dir's `name`, else `name` on the search path.
|
||||
fn tool(bin: Option<PathBuf>, name: &str) -> Option<PathBuf> {
|
||||
bin.map(|b| b.join(exe(name))).filter(|p| p.is_file()).or_else(|| which(name))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ python
|
||||
|
||||
fn python_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
let Some(python) = crate::apply::python_interpreter(root, s) else { return Vec::new() };
|
||||
let mut files = vec![python.clone()];
|
||||
files.extend(crate::venv_of(&python).map(|v| v.join("pyvenv.cfg")));
|
||||
cached(root, "python", python.display().to_string(), &files, || {
|
||||
python_libraries(&python, Some(root)).into_iter().collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// Standard library and site-packages folders of a Python interpreter.
|
||||
pub fn python_libraries(python: &Path, root: Option<&Path>) -> Option<LibraryGroup> {
|
||||
let out = query(python, &["-c", PYTHON_PATHS], QUERY_TIMEOUT)?;
|
||||
let name = crate::discover::python_sdk(python, "system", root).map(|s| s.name).unwrap_or_else(|| "Python".into());
|
||||
group(name, "python", library_roots(parse_python_paths(&out)))
|
||||
}
|
||||
|
||||
pub(crate) fn parse_python_paths(out: &str) -> Vec<PathBuf> {
|
||||
let json = out.lines().rev().find(|l| l.trim_start().starts_with('[')).unwrap_or("[]");
|
||||
serde_json::from_str::<Vec<Option<String>>>(json)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(PathBuf::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Existing folders among `paths`, deduplicated (also through symlinks), in order.
|
||||
pub(crate) fn library_roots(paths: Vec<PathBuf>) -> Vec<LibraryRoot> {
|
||||
named_roots(
|
||||
paths
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
(p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.display().to_string()), p)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Existing folders among `(name, path)`, deduplicated (also through symlinks), in order.
|
||||
pub(crate) fn named_roots(roots: Vec<(String, PathBuf)>) -> Vec<LibraryRoot> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
roots
|
||||
.into_iter()
|
||||
.filter(|(_, p)| p.is_dir() && seen.insert(dunce::canonicalize(p).unwrap_or_else(|_| p.clone())))
|
||||
.map(|(name, p)| LibraryRoot { name, path: p.into() })
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ jdk
|
||||
|
||||
fn jdk_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
let Some(files) = manifests(root, JAVA_MANIFESTS) else { return Vec::new() };
|
||||
cached(root, "jdk", s.languages.java.jdk.clone(), &files, || {
|
||||
let jdk = crate::apply::project_jdk(root, s).or_else(|| {
|
||||
crate::java::pick_jdk(&crate::java::installed_jdks(), crate::java::project_java_version(root)).cloned()
|
||||
});
|
||||
jdk.and_then(|j| jdk_library(&j)).into_iter().collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// The JDK home and its sources (`lib/src.zip`, `src.zip` in JDK 8) as library roots.
|
||||
pub(crate) fn jdk_library(jdk: &crate::java::Jdk) -> Option<LibraryGroup> {
|
||||
let name = jdk_name(&jdk.home).unwrap_or_else(|| format!("JDK {}", jdk.major));
|
||||
let mut roots = named_roots(vec![(name.clone(), jdk.home.clone())]);
|
||||
if let Some(src) = ["lib/src.zip", "src.zip"].iter().map(|r| jdk.home.join(r)).find(|p| p.is_file()) {
|
||||
roots.push(LibraryRoot { name: "src.zip".into(), path: ide_vfs::archive_root(&src).into() });
|
||||
}
|
||||
group(name, "jdk", roots)
|
||||
}
|
||||
|
||||
/// `temurin-21` for `…/temurin-21.jdk/Contents/Home` (macOS bundles) or `…/temurin-21`.
|
||||
pub(crate) fn jdk_name(home: &Path) -> Option<String> {
|
||||
let dir = if home.ends_with("Contents/Home") { home.parent()?.parent()? } else { home };
|
||||
let name = dir.file_name()?.to_string_lossy();
|
||||
Some(name.strip_suffix(".jdk").unwrap_or(&name).to_owned())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ maven / gradle
|
||||
|
||||
fn dependency_groups(root: &Path, s: &Settings, deps: &[BuildDependency]) -> Vec<LibraryGroup> {
|
||||
if deps.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let maven_repo = crate::apply::maven_local_repository(root, s).or_else(default_maven_repository);
|
||||
let gradle_home = gradle_user_home();
|
||||
let files: Vec<PathBuf> = JAVA_MANIFESTS.iter().map(|n| root.join(n)).collect();
|
||||
let key = format!("{maven_repo:?}\n{gradle_home:?}\n{deps:?}");
|
||||
cached(root, "buildDependencies", key, &files, || {
|
||||
dependency_libraries(deps, maven_repo.as_deref(), gradle_home.as_deref())
|
||||
})
|
||||
}
|
||||
|
||||
/// `~/.m2/repository` (Settings › Maven › Local repository overrides it).
|
||||
fn default_maven_repository() -> Option<PathBuf> {
|
||||
Some(crate::home_dir()?.join(".m2/repository"))
|
||||
}
|
||||
|
||||
/// `$GRADLE_USER_HOME`, else `~/.gradle`.
|
||||
fn gradle_user_home() -> Option<PathBuf> {
|
||||
std::env::var_os("GRADLE_USER_HOME").map(PathBuf::from).or_else(|| Some(crate::home_dir()?.join(".gradle")))
|
||||
}
|
||||
|
||||
/// One `Maven: g:a:v` / `Gradle: g:a:v` group per dependency whose jar is in a
|
||||
/// local repository, its root being the jar (the `-sources.jar` when downloaded).
|
||||
pub(crate) fn dependency_libraries(
|
||||
deps: &[BuildDependency],
|
||||
maven_repo: Option<&Path>,
|
||||
gradle_home: Option<&Path>,
|
||||
) -> Vec<LibraryGroup> {
|
||||
let mut deps: Vec<&BuildDependency> = deps.iter().collect();
|
||||
deps.sort();
|
||||
deps.dedup();
|
||||
deps.into_iter()
|
||||
.filter_map(|d| {
|
||||
let maven = || maven_repo.and_then(|r| maven_jar(r, d));
|
||||
let gradle = || gradle_home.and_then(|h| gradle_jar(h, d));
|
||||
let jar = if d.gradle { gradle().or_else(maven) } else { maven().or_else(gradle) }?;
|
||||
let tool = if d.gradle { "Gradle" } else { "Maven" };
|
||||
let name = jar.file_name()?.to_string_lossy().into_owned();
|
||||
group(
|
||||
format!("{tool}: {}:{}:{}", d.group, d.artifact, d.version),
|
||||
&tool.to_lowercase(),
|
||||
vec![LibraryRoot { name, path: ide_vfs::archive_root(&jar).into() }],
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// No path separators, interpolations or `..` segments (coordinates become paths).
|
||||
fn valid_coordinate(d: &BuildDependency) -> bool {
|
||||
[&d.group, &d.artifact, &d.version]
|
||||
.iter()
|
||||
.all(|p| !p.is_empty() && !p.contains(['/', '\\', '$']) && !p.split('.').any(str::is_empty))
|
||||
}
|
||||
|
||||
/// `<repo>/<group as path>/<artifact>/<version>/<artifact>-<version>(-sources).jar`.
|
||||
pub(crate) fn maven_jar(repo: &Path, d: &BuildDependency) -> Option<PathBuf> {
|
||||
if !valid_coordinate(d) {
|
||||
return None;
|
||||
}
|
||||
let dir = repo.join(d.group.replace('.', "/")).join(&d.artifact).join(&d.version);
|
||||
["-sources.jar", ".jar"]
|
||||
.iter()
|
||||
.map(|suffix| dir.join(format!("{}-{}{suffix}", d.artifact, d.version)))
|
||||
.find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// `<gradle home>/caches/modules-2/files-2.1/<group>/<artifact>/<version>/<hash>/<artifact>-<version>(-sources).jar`.
|
||||
pub(crate) fn gradle_jar(home: &Path, d: &BuildDependency) -> Option<PathBuf> {
|
||||
if !valid_coordinate(d) {
|
||||
return None;
|
||||
}
|
||||
let dir = home.join("caches/modules-2/files-2.1").join(&d.group).join(&d.artifact).join(&d.version);
|
||||
let mut hashes: Vec<PathBuf> = std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).collect();
|
||||
hashes.sort();
|
||||
["-sources.jar", ".jar"].iter().find_map(|suffix| {
|
||||
let file = format!("{}-{}{suffix}", d.artifact, d.version);
|
||||
hashes.iter().map(|h| h.join(&file)).find(|p| p.is_file())
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ node
|
||||
|
||||
fn node_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
let Some(files) = manifests(root, NODE_MANIFESTS) else { return Vec::new() };
|
||||
if !root.join("package.json").is_file() {
|
||||
return Vec::new();
|
||||
}
|
||||
cached(root, "node", s.languages.node.interpreter.clone(), &files, || {
|
||||
let node = tool(crate::apply::node_dir(root, s), "node");
|
||||
node_libraries(root, node.as_deref())
|
||||
})
|
||||
}
|
||||
|
||||
/// `node_modules/<dep>` of the direct dependencies in `package.json`, and the
|
||||
/// Node.js core typings (`@types/node`, from the project or the runtime's global `lib`).
|
||||
pub(crate) fn node_libraries(root: &Path, node: Option<&Path>) -> Vec<LibraryGroup> {
|
||||
let manifest = std::fs::read_to_string(root.join("package.json")).unwrap_or_default();
|
||||
let modules = root.join("node_modules");
|
||||
let deps = named_roots(package_dependencies(&manifest).into_iter().map(|d| (d.clone(), modules.join(d))).collect());
|
||||
let mut core = vec![modules.join("@types/node")];
|
||||
// `<prefix>/bin/node` → `<prefix>/lib/node_modules`.
|
||||
if let Some(prefix) =
|
||||
node.and_then(|n| dunce::canonicalize(n).ok()).and_then(|n| Some(n.parent()?.parent()?.to_path_buf()))
|
||||
{
|
||||
core.push(prefix.join("lib/node_modules/@types/node"));
|
||||
}
|
||||
let mut core = named_roots(core.into_iter().map(|p| ("@types/node".to_owned(), p)).collect());
|
||||
core.truncate(1);
|
||||
[group("Node.js Core", "nodeCore", core), group("node_modules", "nodeModules", deps)]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Names of the direct dependencies (all dependency kinds), sorted, deduplicated.
|
||||
pub(crate) fn package_dependencies(package_json: &str) -> Vec<String> {
|
||||
let Ok(json) = serde_json::from_str::<serde_json::Value>(package_json) else { return Vec::new() };
|
||||
let mut names: Vec<String> = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]
|
||||
.iter()
|
||||
.filter_map(|k| json.get(k)?.as_object())
|
||||
.flat_map(|o| o.keys().cloned())
|
||||
.filter(|n| !n.is_empty() && !n.contains("..") && !n.starts_with('/'))
|
||||
.collect();
|
||||
names.sort();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ rust
|
||||
|
||||
fn rust_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
let Some(files) = manifests(root, CARGO_MANIFESTS) else { return Vec::new() };
|
||||
if !root.join("Cargo.toml").is_file() {
|
||||
return Vec::new();
|
||||
}
|
||||
let r = &s.languages.rust;
|
||||
cached(root, "rust", format!("{}\n{}", r.toolchain, r.stdlib), &files, || {
|
||||
let bin = crate::apply::rust_bin(root, s).map(|(b, _)| b);
|
||||
let mut out = Vec::new();
|
||||
if let Some(rustc) = tool(bin.clone(), "rustc") {
|
||||
let version = query_in(&rustc, &["--version"], Some(root), &[], QUERY_TIMEOUT);
|
||||
let library = crate::apply::setting_path(root, &r.stdlib).or_else(|| {
|
||||
let sysroot = query_in(&rustc, &["--print", "sysroot"], Some(root), &[], QUERY_TIMEOUT)?;
|
||||
Some(PathBuf::from(sysroot).join("lib/rustlib/src/rust/library"))
|
||||
});
|
||||
let name = match version.as_deref().and_then(|v| v.split_whitespace().nth(1)) {
|
||||
Some(v) => format!("Rust {v}"),
|
||||
None => "Rust".into(),
|
||||
};
|
||||
out.extend(library.and_then(|l| group(name, "rust", library_roots(vec![l]))));
|
||||
}
|
||||
if let Some(cargo) = tool(bin, "cargo")
|
||||
&& let Some(json) =
|
||||
query_in(&cargo, &["metadata", "--format-version", "1", "--offline"], Some(root), &[], GRAPH_TIMEOUT)
|
||||
{
|
||||
out.extend(group("Cargo dependencies", "cargo", named_roots(parse_cargo_metadata(&json))));
|
||||
}
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
/// `(name version, source dir)` of the non-workspace packages in `cargo metadata` output, by name.
|
||||
pub(crate) fn parse_cargo_metadata(json: &str) -> Vec<(String, PathBuf)> {
|
||||
#[derive(Deserialize)]
|
||||
struct Package {
|
||||
name: String,
|
||||
version: String,
|
||||
source: Option<String>,
|
||||
manifest_path: PathBuf,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Metadata {
|
||||
packages: Vec<Package>,
|
||||
}
|
||||
let Ok(meta) = serde_json::from_str::<Metadata>(json) else { return Vec::new() };
|
||||
let mut out: Vec<(String, PathBuf)> = meta
|
||||
.packages
|
||||
.into_iter()
|
||||
.filter(|p| p.source.is_some())
|
||||
.filter_map(|p| Some((format!("{} {}", p.name, p.version), p.manifest_path.parent()?.to_path_buf())))
|
||||
.collect();
|
||||
out.sort_by_cached_key(|(name, _)| name.to_lowercase());
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ go
|
||||
|
||||
fn go_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
let Some(files) = manifests(root, GO_MANIFESTS) else { return Vec::new() };
|
||||
if !root.join("go.mod").is_file() && !root.join("go.work").is_file() {
|
||||
return Vec::new();
|
||||
}
|
||||
let g = &s.languages.go;
|
||||
cached(root, "go", format!("{}\n{}", g.goroot, g.gopath), &files, || {
|
||||
let goroot = crate::apply::goroot(root, s);
|
||||
let Some(go) = tool(goroot.as_ref().map(|r| r.join("bin")), "go") else { return Vec::new() };
|
||||
let goroot_s = goroot.as_ref().map(|p| p.to_string_lossy().into_owned());
|
||||
let gopath = crate::apply::setting_path(root, &g.gopath).map(|p| p.to_string_lossy().into_owned());
|
||||
// Never download modules or toolchains just to list libraries.
|
||||
let mut env = vec![("GOPROXY", "off"), ("GOTOOLCHAIN", "local")];
|
||||
env.extend(goroot_s.as_deref().map(|v| ("GOROOT", v)));
|
||||
env.extend(gopath.as_deref().map(|v| ("GOPATH", v)));
|
||||
let mut out = Vec::new();
|
||||
if let Some(vars) = query_in(&go, &["env", "GOROOT", "GOVERSION"], Some(root), &env, QUERY_TIMEOUT) {
|
||||
let mut lines = vars.lines().map(str::trim);
|
||||
let (dir, version) = (lines.next().unwrap_or_default(), lines.next().unwrap_or_default());
|
||||
let name = match version.strip_prefix("go") {
|
||||
Some(v) if !v.is_empty() => format!("Go SDK {v}"),
|
||||
_ => "Go SDK".into(),
|
||||
};
|
||||
if !dir.is_empty() {
|
||||
out.extend(group(name, "go", library_roots(vec![Path::new(dir).join("src")])));
|
||||
}
|
||||
}
|
||||
if let Some(text) = query_in(&go, &["list", "-m", "-e", "-json", "all"], Some(root), &env, GRAPH_TIMEOUT) {
|
||||
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text))));
|
||||
}
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
/// `(path@version, dir)` of the downloaded non-main modules in `go list -m -json` output.
|
||||
pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Module {
|
||||
path: String,
|
||||
version: Option<String>,
|
||||
dir: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
main: bool,
|
||||
}
|
||||
serde_json::Deserializer::from_str(text)
|
||||
.into_iter::<Module>()
|
||||
.map_while(Result::ok)
|
||||
.filter(|m| !m.main)
|
||||
.filter_map(|m| {
|
||||
let name = match &m.version {
|
||||
Some(v) => format!("{}@{v}", m.path),
|
||||
None => m.path.clone(),
|
||||
};
|
||||
Some((name, m.dir?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Lombok for jdtls: ECJ only generates Lombok members when the language
|
||||
//! server's JVM runs `-javaagent:lombok.jar`, so a project using Lombok gets the
|
||||
//! newest jar available, managed (installed by the IDE) or in the Maven / Gradle caches.
|
||||
|
||||
use crate::home_dir;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Oldest Lombok whose ECJ handlers work in current jdtls builds (Eclipse 2024-06 support);
|
||||
/// older ones throw `NoSuchMethodError` and drop every annotation of the compilation unit.
|
||||
pub const LOMBOK_MIN: [u32; 3] = [1, 18, 34];
|
||||
|
||||
/// What a jdtls instance gets for Lombok.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LombokAgent {
|
||||
/// The project doesn't use Lombok.
|
||||
Unused,
|
||||
/// The project uses Lombok but no jar was found.
|
||||
Missing,
|
||||
Found {
|
||||
jar: PathBuf,
|
||||
/// `None` for the managed jar (the latest release when installed).
|
||||
version: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl LombokAgent {
|
||||
pub fn jar(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Found { jar, .. } => Some(jar),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Too old for current jdtls.
|
||||
pub fn outdated(&self) -> bool {
|
||||
matches!(self, Self::Found { version: Some(v), .. } if parse_version(v).is_some_and(|v| v < LOMBOK_MIN))
|
||||
}
|
||||
|
||||
/// Why Lombok-generated members may be missing, if they may be.
|
||||
pub fn problem(&self) -> Option<String> {
|
||||
const INSTALL: &str =
|
||||
"Install Lombok in Settings › Languages & Frameworks › Language Servers (jdtls restarts with it)";
|
||||
match self {
|
||||
Self::Missing => Some(format!(
|
||||
"The project uses Lombok, but no lombok.jar was found for the Java language server, so Lombok-generated \
|
||||
members are missing. {INSTALL}."
|
||||
)),
|
||||
Self::Found { version: Some(v), .. } if self.outdated() => Some(format!(
|
||||
"Lombok {v} is too old for the Java language server (needs {}.{}.{} or newer): classes using it may \
|
||||
miss generated members. {INSTALL}.",
|
||||
LOMBOK_MIN[0], LOMBOK_MIN[1], LOMBOK_MIN[2]
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Lombok jar of a `-javaagent:` among JVM arguments (bare or as `--jvm-arg=`).
|
||||
pub fn agent_in_args<'a>(args: impl IntoIterator<Item = &'a str>) -> Option<PathBuf> {
|
||||
args.into_iter().find_map(|a| {
|
||||
let jar = a.split_once("-javaagent:")?.1;
|
||||
jar.to_ascii_lowercase().contains("lombok").then(|| PathBuf::from(jar))
|
||||
})
|
||||
}
|
||||
|
||||
/// The Lombok agent for the project at `root`: the user's own (`own`, from the JVM
|
||||
/// options) wins, then `managed` (the IDE-installed jar), then the build caches
|
||||
/// (`maven_repo`, the configured Maven local repository, else the default one).
|
||||
pub fn lombok_agent(
|
||||
root: &Path,
|
||||
own: Option<PathBuf>,
|
||||
managed: Option<PathBuf>,
|
||||
maven_repo: Option<PathBuf>,
|
||||
) -> LombokAgent {
|
||||
if let Some(jar) = own {
|
||||
let version = jar
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str()?.strip_prefix("lombok-"))
|
||||
.filter(|v| parse_version(v).is_some())
|
||||
.map(str::to_owned);
|
||||
return LombokAgent::Found { jar, version };
|
||||
}
|
||||
if !uses_lombok(root) {
|
||||
return LombokAgent::Unused;
|
||||
}
|
||||
if let Some(jar) = managed {
|
||||
return LombokAgent::Found { jar, version: None };
|
||||
}
|
||||
let home = home_dir();
|
||||
let mut dirs = Vec::new();
|
||||
if let Some(repo) = maven_repo.or_else(|| maven_repository(home.as_deref())) {
|
||||
dirs.push(repo.join("org").join("projectlombok").join("lombok"));
|
||||
}
|
||||
if let Some(gradle) =
|
||||
std::env::var_os("GRADLE_USER_HOME").map(PathBuf::from).or_else(|| home.map(|h| h.join(".gradle")))
|
||||
{
|
||||
dirs.push(gradle.join("caches").join("modules-2").join("files-2.1").join("org.projectlombok").join("lombok"));
|
||||
}
|
||||
match newest_cached(&dirs) {
|
||||
Some((version, jar)) => LombokAgent::Found { jar, version: Some(version) },
|
||||
None => LombokAgent::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build files under `root` (a few levels, for multi-module builds) mentioning Lombok.
|
||||
pub fn uses_lombok(root: &Path) -> bool {
|
||||
const FILES: [&str; 4] = ["pom.xml", "build.gradle", "build.gradle.kts", "libs.versions.toml"];
|
||||
const SKIP: [&str; 7] = ["target", "build", "node_modules", "out", "bin", "src", ".gradle"];
|
||||
fn walk(dir: &Path, depth: usize) -> bool {
|
||||
if dir.join("lombok.config").is_file() {
|
||||
return true;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
let mut subdirs = Vec::new();
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let Ok(ty) = e.file_type() else { continue };
|
||||
if ty.is_dir() {
|
||||
if depth > 0 && !name.starts_with('.') && !SKIP.contains(&name.as_ref()) {
|
||||
subdirs.push(e.path());
|
||||
}
|
||||
} else if FILES.contains(&name.as_ref())
|
||||
&& std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("lombok"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
subdirs.iter().any(|d| walk(d, depth - 1))
|
||||
}
|
||||
// `gradle/libs.versions.toml` sits one level down, modules usually no deeper than three.
|
||||
walk(root, 3)
|
||||
}
|
||||
|
||||
/// `<localRepository>` of `~/.m2/settings.xml`, else `~/.m2/repository`.
|
||||
fn maven_repository(home: Option<&Path>) -> Option<PathBuf> {
|
||||
let m2 = home?.join(".m2");
|
||||
let custom = std::fs::read_to_string(m2.join("settings.xml"))
|
||||
.ok()
|
||||
.and_then(|s| crate::java::xml_value(&strip_xml_comments(&s), "localRepository"))
|
||||
.filter(|v| !v.is_empty() && !v.contains("${"))
|
||||
.map(PathBuf::from);
|
||||
Some(custom.unwrap_or_else(|| m2.join("repository")))
|
||||
}
|
||||
|
||||
pub(crate) fn strip_xml_comments(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(i) = rest.find("<!--") {
|
||||
out.push_str(&rest[..i]);
|
||||
rest = rest[i..].find("-->").map_or("", |j| &rest[i + j + 3..]);
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Highest release `<dir>/<version>/…/lombok-<version>.jar` (Maven: directly in
|
||||
/// the version directory; Gradle: one hash directory below it).
|
||||
fn newest_cached(dirs: &[PathBuf]) -> Option<(String, PathBuf)> {
|
||||
let mut best: Option<([u32; 3], String, PathBuf)> = None;
|
||||
for dir in dirs {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { continue };
|
||||
for e in entries.flatten() {
|
||||
let version = e.file_name().to_string_lossy().into_owned();
|
||||
let Some(parsed) = parse_version(&version) else { continue };
|
||||
if best.as_ref().is_some_and(|(b, ..)| *b >= parsed) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("lombok-{version}.jar");
|
||||
let direct = e.path().join(&name);
|
||||
let jar = if direct.is_file() {
|
||||
Some(direct)
|
||||
} else {
|
||||
std::fs::read_dir(e.path())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|h| h.path().join(&name))
|
||||
.find(|p| p.is_file())
|
||||
};
|
||||
if let Some(jar) = jar {
|
||||
best = Some((parsed, version, jar));
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, v, jar)| (v, jar))
|
||||
}
|
||||
|
||||
/// `1.18.34` → `[1, 18, 34]`; snapshots and other qualifiers don't count as releases.
|
||||
fn parse_version(v: &str) -> Option<[u32; 3]> {
|
||||
let mut parts = v.split('.').map(|p| p.parse::<u32>().ok());
|
||||
let out = [parts.next()??, parts.next()??, parts.next().unwrap_or(Some(0))?];
|
||||
parts.next().is_none().then_some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn detects_lombok_in_build_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
fs::write(root.join("pom.xml"), "<project><modules><module>api</module></modules></project>").unwrap();
|
||||
assert!(!uses_lombok(root));
|
||||
fs::create_dir_all(root.join("api/src/main")).unwrap();
|
||||
fs::write(root.join("api/src/main/pom.xml"), "<artifactId>lombok</artifactId>").unwrap();
|
||||
assert!(!uses_lombok(root), "sources are not scanned");
|
||||
fs::write(root.join("api/pom.xml"), "<artifactId>lombok</artifactId>").unwrap();
|
||||
assert!(uses_lombok(root));
|
||||
|
||||
let gradle = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(gradle.path().join("gradle")).unwrap();
|
||||
fs::write(gradle.path().join("gradle/libs.versions.toml"), "lombok = \"org.projectlombok:lombok:1.18.30\"")
|
||||
.unwrap();
|
||||
assert!(uses_lombok(gradle.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_the_newest_cached_release() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let m2 = tmp.path().join("m2");
|
||||
let gradle = tmp.path().join("gradle");
|
||||
for v in ["1.18.26", "1.18.36", "1.18.99-SNAPSHOT"] {
|
||||
fs::create_dir_all(m2.join(v)).unwrap();
|
||||
fs::write(m2.join(v).join(format!("lombok-{v}.jar")), b"PK").unwrap();
|
||||
}
|
||||
fs::create_dir_all(m2.join("1.18.40")).unwrap(); // only a .pom: not usable
|
||||
fs::create_dir_all(gradle.join("1.18.38/abc123")).unwrap();
|
||||
fs::write(gradle.join("1.18.38/abc123/lombok-1.18.38.jar"), b"PK").unwrap();
|
||||
let (v, jar) = newest_cached(&[m2.clone(), gradle.clone()]).unwrap();
|
||||
assert_eq!(v, "1.18.38");
|
||||
assert_eq!(jar, gradle.join("1.18.38/abc123/lombok-1.18.38.jar"));
|
||||
assert_eq!(newest_cached(std::slice::from_ref(&m2)).unwrap().0, "1.18.36");
|
||||
assert_eq!(newest_cached(&[tmp.path().join("none")]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_versions_are_reported() {
|
||||
let found = |v: Option<&str>| LombokAgent::Found { jar: "/l.jar".into(), version: v.map(Into::into) };
|
||||
assert!(found(Some("1.18.26")).outdated());
|
||||
assert!(found(Some("1.18.26")).problem().unwrap().contains("1.18.26 is too old"));
|
||||
assert!(!found(Some("1.18.34")).outdated());
|
||||
assert_eq!(found(None).problem(), None);
|
||||
assert!(LombokAgent::Missing.problem().is_some());
|
||||
assert_eq!(LombokAgent::Unused.problem(), None);
|
||||
assert_eq!(parse_version("1.18"), Some([1, 18, 0]));
|
||||
assert_eq!(parse_version("edge-SNAPSHOT"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_users_agent_wins() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let own = agent_in_args(["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok-1.18.26.jar"]);
|
||||
assert_eq!(own.as_deref(), Some(Path::new("/opt/lombok-1.18.26.jar")));
|
||||
assert_eq!(agent_in_args(["-javaagent:/opt/other.jar"]), None);
|
||||
let agent = lombok_agent(tmp.path(), own, Some("/managed/lombok.jar".into()), None);
|
||||
assert_eq!(agent.jar(), Some(Path::new("/opt/lombok-1.18.26.jar")));
|
||||
assert!(agent.outdated(), "its version is read from the file name");
|
||||
let plain = lombok_agent(tmp.path(), agent_in_args(["-javaagent:/opt/lombok.jar"]), None, None);
|
||||
assert_eq!(plain.problem(), None, "a user agent is never reported missing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_settings_local_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path();
|
||||
assert_eq!(maven_repository(Some(home)), Some(home.join(".m2/repository")));
|
||||
fs::create_dir_all(home.join(".m2")).unwrap();
|
||||
fs::write(
|
||||
home.join(".m2/settings.xml"),
|
||||
"<settings><!-- <localRepository>/old</localRepository> --><localRepository>/repo</localRepository></settings>",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(maven_repository(Some(home)), Some(PathBuf::from("/repo")));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::apply::{apply_to_run_configs, configure_server, python_interpreter, terminal_activation, tsdk};
|
||||
use crate::apply::{
|
||||
apply_to_run_configs, configure_server, jdtls_jdk, maven_command, maven_options, project_jdk, python_interpreter,
|
||||
terminal_activation, tsdk,
|
||||
};
|
||||
use crate::python::parse_pip_list;
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
use ide_core::settings::Settings;
|
||||
@@ -27,6 +30,7 @@ fn server(name: &str) -> LanguageServerConfig {
|
||||
initialization_options: None,
|
||||
install_hint: None,
|
||||
fallback: false,
|
||||
launch_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +46,8 @@ fn run(kind: &str, command: &str, args: &[&str]) -> RunConfig {
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +79,16 @@ fn pyright_gets_python_path_and_venv_env() {
|
||||
assert!(cfg.env["PATH"].starts_with(&*tmp.path().join(".venv").join(bin_dir()).to_string_lossy()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_vm_args() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.languages.java.jdtls_vm_args = " -Xmx2g -javaagent:/opt/lombok.jar ".into();
|
||||
let mut cfg = server("jdtls");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(cfg.args, ["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok.jar"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_analyzer_check_command_and_toolchain() {
|
||||
if cfg!(windows) {
|
||||
@@ -142,6 +158,71 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
assert_eq!(configs[4].command, "python3", "shell configs are left alone");
|
||||
}
|
||||
|
||||
fn fake_jdk(dir: &Path) {
|
||||
std::fs::create_dir_all(dir.join("bin")).unwrap();
|
||||
std::fs::write(dir.join("bin").join(exe("java")), "").unwrap();
|
||||
std::fs::write(dir.join("release"), "JAVA_VERSION=\"17.0.9\"\n").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_jdk_and_maven_settings() {
|
||||
if cfg!(windows) {
|
||||
return; // Unix paths and shells
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let jdk = tmp.path().join("jdk17");
|
||||
fake_jdk(&jdk);
|
||||
let maven = tmp.path().join("maven");
|
||||
std::fs::create_dir_all(maven.join("bin")).unwrap();
|
||||
std::fs::write(maven.join("bin/mvn"), "").unwrap();
|
||||
|
||||
let mut s = Settings::default();
|
||||
assert_eq!(project_jdk(tmp.path(), &s), None);
|
||||
assert_eq!(maven_command(tmp.path(), &s), None);
|
||||
assert!(maven_options(tmp.path(), &s).is_empty());
|
||||
|
||||
// Project-relative paths, a JDK's `bin/java`, a Maven home.
|
||||
s.languages.java.jdk = "jdk17/bin/java".into();
|
||||
s.languages.java.maven.home = maven.to_string_lossy().into_owned();
|
||||
s.languages.java.maven.user_settings = "/m2/settings.xml".into();
|
||||
s.languages.java.maven.local_repository = "/m2/repo".into();
|
||||
assert_eq!(project_jdk(tmp.path(), &s).map(|j| j.major), Some(17));
|
||||
assert_eq!(maven_command(tmp.path(), &s), Some(maven.join("bin/mvn")));
|
||||
assert_eq!(maven_options(tmp.path(), &s), ["-s", "/m2/settings.xml", "-Dmaven.repo.local=/m2/repo"]);
|
||||
|
||||
let mut configs = vec![run("maven", "./mvnw", &["package"]), run("gradle", "./gradlew", &["build"])];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
let home = project_jdk(tmp.path(), &s).unwrap().home.to_string_lossy().into_owned();
|
||||
assert_eq!(configs[0].command, maven.join("bin/mvn").to_string_lossy());
|
||||
assert_eq!(configs[0].args, ["-s", "/m2/settings.xml", "-Dmaven.repo.local=/m2/repo", "package"]);
|
||||
assert_eq!(configs[0].env["JAVA_HOME"], home);
|
||||
assert_eq!(configs[1].env["JAVA_HOME"], home);
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(configs[0].args.len(), 4, "applied once");
|
||||
|
||||
s.languages.java.jdk = "missing".into();
|
||||
assert_eq!(project_jdk(tmp.path(), &s), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_jdk_setting() {
|
||||
if cfg!(windows) {
|
||||
return; // Unix paths
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
fake_jdk(&tmp.path().join("jdk17"));
|
||||
let mut s = Settings::default();
|
||||
assert_eq!(jdtls_jdk(tmp.path(), &s), Ok(None));
|
||||
// Separate from the project JDK, which run configurations keep using.
|
||||
s.languages.java.jdk = "jdk17".into();
|
||||
assert_eq!(jdtls_jdk(tmp.path(), &s), Ok(None));
|
||||
s.languages.java.jdtls_jdk = "jdk17/bin".into();
|
||||
assert_eq!(jdtls_jdk(tmp.path(), &s).unwrap().map(|j| j.major), Some(17));
|
||||
// A chosen path that is not a JDK is an error, not a silent fallback.
|
||||
s.languages.java.jdtls_jdk = "missing".into();
|
||||
assert!(jdtls_jdk(tmp.path(), &s).unwrap_err().contains("is not a JDK home"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_activation_for_project_venv() {
|
||||
if cfg!(windows) {
|
||||
@@ -173,7 +254,7 @@ fn excluded_folders_become_anchored_globs() {
|
||||
s.project_structure.excluded = vec!["build/".into(), " ".into()];
|
||||
let globs = s.exclude_globs();
|
||||
assert!(globs.contains(&"/build".to_owned()));
|
||||
assert_eq!(globs.len(), s.files.exclude.len() + 1);
|
||||
assert_eq!(globs.len(), s.file_excludes().len() + 1);
|
||||
}
|
||||
|
||||
/// Prints what this machine has installed.
|
||||
@@ -195,3 +276,188 @@ fn detect_on_this_machine() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_tool_path_replaces_the_command() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.tools.insert("elixir-ls".into(), ide_core::settings::ToolSettings { path: "tools/ls/language_server.sh".into() });
|
||||
s.tools.insert("zls".into(), ide_core::settings::ToolSettings { path: " ".into() });
|
||||
let mut cfg = server("elixir-ls");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(Path::new(&cfg.command), tmp.path().join("tools/ls/language_server.sh"));
|
||||
// A blank path keeps auto-detection.
|
||||
let mut cfg = server("zls");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(cfg.command, "zls");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_library_paths_are_parsed_and_deduplicated() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let stdlib = tmp.path().join("lib/python3.12");
|
||||
let site = stdlib.join("site-packages");
|
||||
std::fs::create_dir_all(&site).unwrap();
|
||||
let json = serde_json::to_string(&[Some(&stdlib), Some(&stdlib), Some(&site), None]).unwrap();
|
||||
let paths = crate::libraries::parse_python_paths(&format!("warning: something\n{json}"));
|
||||
assert_eq!(paths.len(), 3);
|
||||
let roots = crate::libraries::library_roots([paths, vec![tmp.path().join("gone")]].concat());
|
||||
assert_eq!(roots.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), ["python3.12", "site-packages"]);
|
||||
assert!(crate::libraries::parse_python_paths("not json").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_libraries_without_an_interpreter() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(crate::libraries::project_libraries(tmp.path(), &Settings::default(), &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_libraries_list_direct_dependencies_and_core_typings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::write(
|
||||
root.join("package.json"),
|
||||
r#"{"dependencies":{"react":"^18","@scope/ui":"1"},"devDependencies":{"vitest":"2","react":"^18"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
for dir in ["react", "@scope/ui", "@types/node", "transitive"] {
|
||||
std::fs::create_dir_all(root.join("node_modules").join(dir)).unwrap();
|
||||
}
|
||||
let groups = crate::libraries::node_libraries(root, None);
|
||||
let summary: Vec<(&str, &str, Vec<&str>)> = groups
|
||||
.iter()
|
||||
.map(|g| (g.name.as_str(), g.kind.as_str(), g.roots.iter().map(|r| r.name.as_str()).collect()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
summary,
|
||||
[
|
||||
("Node.js Core", "nodeCore", vec!["@types/node"]),
|
||||
("node_modules", "nodeModules", vec!["@scope/ui", "react"])
|
||||
]
|
||||
);
|
||||
assert_eq!(crate::libraries::package_dependencies("{"), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cargo_metadata_lists_registry_packages_only() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let serde = tmp.path().join("registry/src/index/serde-1.0.200");
|
||||
let json = serde_json::json!({ "packages": [
|
||||
{ "name": "app", "version": "0.1.0", "source": null, "manifest_path": tmp.path().join("Cargo.toml") },
|
||||
{ "name": "serde", "version": "1.0.200", "source": "registry+https://github.com/rust-lang/crates.io-index",
|
||||
"manifest_path": serde.join("Cargo.toml") },
|
||||
]});
|
||||
assert_eq!(crate::libraries::parse_cargo_metadata(&json.to_string()), [("serde 1.0.200".to_owned(), serde)]);
|
||||
assert!(crate::libraries::parse_cargo_metadata("error: no Cargo.toml").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_modules_skip_the_main_module_and_missing_downloads() {
|
||||
let out = r#"{"Path":"example.com/app","Main":true,"Dir":"/p"}
|
||||
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}
|
||||
{"Path":"example.com/missing","Version":"v1.0.0","Error":{"Err":"module lookup disabled"}}"#;
|
||||
assert_eq!(
|
||||
crate::libraries::parse_go_modules(out),
|
||||
[(
|
||||
"golang.org/x/[email protected]".to_owned(),
|
||||
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdk_library_is_the_jdk_home() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("temurin-21.jdk/Contents/Home");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
assert_eq!(crate::libraries::jdk_name(&home).as_deref(), Some("temurin-21"));
|
||||
assert_eq!(crate::libraries::jdk_name(&tmp.path().join("jdk-17")).as_deref(), Some("jdk-17"));
|
||||
let group = crate::libraries::jdk_library(&crate::java::Jdk { major: 21, home: home.clone() }).unwrap();
|
||||
assert_eq!((group.name.as_str(), group.kind.as_str()), ("temurin-21", "jdk"));
|
||||
assert_eq!(group.roots[0].path, ide_core::IpcPath::from(home.clone()));
|
||||
assert_eq!(group.roots.len(), 1, "no sources archive");
|
||||
|
||||
std::fs::create_dir_all(home.join("lib")).unwrap();
|
||||
std::fs::write(home.join("lib/src.zip"), "").unwrap();
|
||||
let group = crate::libraries::jdk_library(&crate::java::Jdk { major: 21, home: home.clone() }).unwrap();
|
||||
assert_eq!(group.roots[1].name, "src.zip");
|
||||
assert_eq!(group.roots[1].path, ide_core::IpcPath::from(ide_vfs::archive_root(&home.join("lib/src.zip"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_dependencies_resolve_to_local_jars() {
|
||||
use crate::libraries::{BuildDependency, dependency_libraries};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (m2, gradle) = (tmp.path().join("m2"), tmp.path().join("gradle"));
|
||||
let touch = |p: std::path::PathBuf| {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, "").unwrap();
|
||||
p
|
||||
};
|
||||
touch(m2.join("com/google/guava/guava/33.0/guava-33.0.jar"));
|
||||
let guava_src = touch(m2.join("com/google/guava/guava/33.0/guava-33.0-sources.jar"));
|
||||
let junit = touch(m2.join("junit/junit/4.13/junit-4.13.jar"));
|
||||
let files = gradle.join("caches/modules-2/files-2.1/org.slf4j/slf4j-api/2.0.9");
|
||||
touch(files.join("a1b2/slf4j-api-2.0.9.jar"));
|
||||
let slf4j_src = touch(files.join("c3d4/slf4j-api-2.0.9-sources.jar"));
|
||||
let dep = |gradle: bool, g: &str, a: &str, v: &str| BuildDependency {
|
||||
gradle,
|
||||
group: g.into(),
|
||||
artifact: a.into(),
|
||||
version: v.into(),
|
||||
};
|
||||
let deps = [
|
||||
dep(false, "junit", "junit", "4.13"),
|
||||
dep(false, "com.google.guava", "guava", "33.0"),
|
||||
dep(false, "com.google.guava", "guava", "33.0"),
|
||||
dep(true, "org.slf4j", "slf4j-api", "2.0.9"),
|
||||
dep(false, "missing", "nope", "1.0"),
|
||||
dep(false, "..", "evil", "1"),
|
||||
];
|
||||
let groups = dependency_libraries(&deps, Some(&m2), Some(&gradle));
|
||||
let shown: Vec<(&str, &str, &str)> =
|
||||
groups.iter().map(|g| (g.name.as_str(), g.kind.as_str(), g.roots[0].name.as_str())).collect();
|
||||
assert_eq!(
|
||||
shown,
|
||||
[
|
||||
("Maven: com.google.guava:guava:33.0", "maven", "guava-33.0-sources.jar"),
|
||||
("Maven: junit:junit:4.13", "maven", "junit-4.13.jar"),
|
||||
("Gradle: org.slf4j:slf4j-api:2.0.9", "gradle", "slf4j-api-2.0.9-sources.jar"),
|
||||
]
|
||||
);
|
||||
assert_eq!(groups[0].roots[0].path, ide_core::IpcPath::from(ide_vfs::archive_root(&guava_src)));
|
||||
assert_eq!(groups[1].roots[0].path, ide_core::IpcPath::from(ide_vfs::archive_root(&junit)));
|
||||
assert_eq!(groups[2].roots[0].path, ide_core::IpcPath::from(ide_vfs::archive_root(&slf4j_src)));
|
||||
// A Gradle build also finds jars installed in the Maven local repository (`mavenLocal()`).
|
||||
let groups = dependency_libraries(&[dep(true, "junit", "junit", "4.13")], Some(&m2), Some(&gradle));
|
||||
assert_eq!(groups[0].name, "Gradle: junit:junit:4.13");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_detection_is_cached_until_a_manifest_changes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let manifest = tmp.path().join("package.json");
|
||||
std::fs::write(&manifest, "{}").unwrap();
|
||||
let runs = std::cell::Cell::new(0);
|
||||
let detect = || {
|
||||
runs.set(runs.get() + 1);
|
||||
Vec::new()
|
||||
};
|
||||
let files = [manifest.clone()];
|
||||
crate::libraries::cached(tmp.path(), "test", "a".into(), &files, detect);
|
||||
crate::libraries::cached(tmp.path(), "test", "a".into(), &files, detect);
|
||||
assert_eq!(runs.get(), 1);
|
||||
std::fs::write(&manifest, r#"{"dependencies":{}}"#).unwrap();
|
||||
crate::libraries::cached(tmp.path(), "test", "a".into(), &files, detect);
|
||||
assert_eq!(runs.get(), 2);
|
||||
crate::libraries::cached(tmp.path(), "test", "b".into(), &files, detect);
|
||||
assert_eq!(runs.get(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ecosystem_libraries_without_manifests() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("node_modules/react")).unwrap();
|
||||
assert!(crate::libraries::project_libraries(tmp.path(), &Settings::default(), &[]).is_empty());
|
||||
}
|
||||
@@ -7,6 +7,7 @@ license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
grep-searcher.workspace = true
|
||||
|
||||
@@ -35,6 +35,7 @@ fn query(pattern: &str, is_regex: bool) -> SearchQuery {
|
||||
exclude: vec![],
|
||||
scope: SearchScope::Project,
|
||||
max_matches: 0,
|
||||
context: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,12 @@
|
||||
use crate::iter::for_each_match;
|
||||
use crate::line::line_match;
|
||||
use crate::mask::FileMask;
|
||||
use crate::pattern::ScopePattern;
|
||||
use crate::query::{Compiled, line_terminator};
|
||||
use crate::{FileMatches, LineMatch, Overlay, PathFilter, SearchScope, SearchSummary};
|
||||
use crate::{
|
||||
FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, Overlay, PathFilter, SearchContext, SearchScope,
|
||||
SearchSummary,
|
||||
};
|
||||
use grep_regex::RegexMatcher;
|
||||
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
@@ -24,7 +28,10 @@ pub(crate) struct Request<'a> {
|
||||
pub scope: &'a SearchScope,
|
||||
pub compiled: Compiled,
|
||||
pub mask: FileMask,
|
||||
pub pattern: Option<ScopePattern>,
|
||||
pub filter: Option<PathFilter<'a>>,
|
||||
pub context: SearchContext,
|
||||
pub literals: Option<Literals<'a>>,
|
||||
pub max_matches: u32,
|
||||
pub overlay: Overlay<'a>,
|
||||
pub cancel: &'a CancellationToken,
|
||||
@@ -85,7 +92,10 @@ impl Control<'_> {
|
||||
struct Ctx<'a> {
|
||||
root: &'a Path,
|
||||
mask: &'a FileMask,
|
||||
pattern: Option<&'a ScopePattern>,
|
||||
filter: Option<PathFilter<'a>>,
|
||||
context: SearchContext,
|
||||
literals: Option<Literals<'a>>,
|
||||
overlay: Overlay<'a>,
|
||||
on_file: &'a (dyn Fn(FileMatches) + Sync),
|
||||
ctl: Control<'a>,
|
||||
@@ -97,7 +107,10 @@ pub(crate) fn run(req: Request<'_>) -> IdeResult<SearchSummary> {
|
||||
let ctx = Ctx {
|
||||
root: req.root,
|
||||
mask: &req.mask,
|
||||
pattern: req.pattern.as_ref(),
|
||||
filter: req.filter,
|
||||
context: req.context,
|
||||
literals: if req.context == SearchContext::Any { None } else { req.literals },
|
||||
overlay: req.overlay,
|
||||
on_file: req.on_file,
|
||||
ctl: Control {
|
||||
@@ -161,7 +174,8 @@ pub(crate) fn run(req: Request<'_>) -> IdeResult<SearchSummary> {
|
||||
return WalkState::Continue;
|
||||
}
|
||||
};
|
||||
if entry.file_type().is_some_and(|t| t.is_file()) {
|
||||
// Archives (jar, zip) are browsed, not searched (IDEA skips them too).
|
||||
if entry.file_type().is_some_and(|t| t.is_file()) && !ide_vfs::is_archive_file(entry.path()) {
|
||||
ctx.search_file(entry.path(), &matcher, &mut searcher);
|
||||
}
|
||||
if ctx.ctl.stopped() { WalkState::Quit } else { WalkState::Continue }
|
||||
@@ -190,7 +204,7 @@ pub(crate) fn roots(root: &Path, scope: &SearchScope) -> IdeResult<Vec<PathBuf>>
|
||||
}
|
||||
};
|
||||
Ok(match scope {
|
||||
SearchScope::Project | SearchScope::FileSet { .. } => vec![dir(Path::new(""))?],
|
||||
SearchScope::Project | SearchScope::FileSet { .. } | SearchScope::Pattern { .. } => vec![dir(Path::new(""))?],
|
||||
SearchScope::Directory { path } => vec![dir(path)?],
|
||||
SearchScope::Files { paths } => {
|
||||
let mut out: Vec<PathBuf> = Vec::with_capacity(paths.len());
|
||||
@@ -222,9 +236,31 @@ pub(crate) fn rel_path(root: &Path, path: &Path) -> String {
|
||||
impl Ctx<'_> {
|
||||
fn search_file(&self, path: &Path, matcher: &RegexMatcher, searcher: &mut Searcher) {
|
||||
let rel = rel_path(self.root, path);
|
||||
if !self.mask.matches(&rel) || self.filter.is_some_and(|keep| !keep(&rel)) {
|
||||
if !self.mask.matches(&rel)
|
||||
|| self.pattern.is_some_and(|p| !p.matches(&rel))
|
||||
|| self.filter.is_some_and(|keep| !keep(&rel))
|
||||
{
|
||||
return;
|
||||
}
|
||||
// The search context needs the whole text to find comments and string literals.
|
||||
let in_context = match self.literals {
|
||||
Some(literals) => {
|
||||
let text = match (self.overlay)(path) {
|
||||
Some(text) => text,
|
||||
// Unreadable or not UTF-8 (binary): nothing to classify.
|
||||
None => match std::fs::read_to_string(path) {
|
||||
Ok(text) => text,
|
||||
Err(_) => return,
|
||||
},
|
||||
};
|
||||
let ranges = literals(path, &text);
|
||||
if ranges.is_none() && self.context.needs_literals() {
|
||||
return;
|
||||
}
|
||||
Some((text, ranges.unwrap_or_default()))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let mut sink = FileSink {
|
||||
matcher,
|
||||
ctl: &self.ctl,
|
||||
@@ -234,12 +270,16 @@ impl Ctx<'_> {
|
||||
ticks: 0,
|
||||
found: Vec::new(),
|
||||
ranges: Vec::new(),
|
||||
context: in_context.as_ref().map(|(_, ranges)| (self.context, ranges.as_slice())),
|
||||
};
|
||||
let result = match (self.overlay)(path) {
|
||||
Some(text) => searcher.search_slice(matcher, text.as_bytes(), &mut sink),
|
||||
None => match std::fs::File::open(path) {
|
||||
Ok(file) => searcher.search_reader(matcher, StopReader { inner: file, ctl: &self.ctl }, &mut sink),
|
||||
Err(err) => Err(err),
|
||||
let result = match &in_context {
|
||||
Some((text, _)) => searcher.search_slice(matcher, text.as_bytes(), &mut sink),
|
||||
None => match (self.overlay)(path) {
|
||||
Some(text) => searcher.search_slice(matcher, text.as_bytes(), &mut sink),
|
||||
None => match std::fs::File::open(path) {
|
||||
Ok(file) => searcher.search_reader(matcher, StopReader { inner: file, ctl: &self.ctl }, &mut sink),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
},
|
||||
};
|
||||
if let Err(err) = result {
|
||||
@@ -288,6 +328,14 @@ struct FileSink<'a> {
|
||||
/// Scratch buffers reused across lines.
|
||||
found: Vec<(usize, usize)>,
|
||||
ranges: Vec<(usize, usize)>,
|
||||
/// Search context filter and the file's comments / string literals.
|
||||
context: Option<(SearchContext, &'a [LiteralRange])>,
|
||||
}
|
||||
|
||||
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
|
||||
fn literal_at(literals: &[LiteralRange], pos: usize) -> Option<LiteralKind> {
|
||||
let i = literals.partition_point(|l| l.start <= pos);
|
||||
literals[..i].last().filter(|l| pos < l.end).map(|l| l.kind)
|
||||
}
|
||||
|
||||
impl Sink for FileSink<'_> {
|
||||
@@ -311,6 +359,10 @@ impl Sink for FileSink<'_> {
|
||||
for_each_match(self.matcher, &buffer[..range.end], range.start, |mm| {
|
||||
found.push((mm.start() - range.start, mm.end() - range.start));
|
||||
});
|
||||
if let Some((context, literals)) = self.context {
|
||||
let block_start = usize::try_from(m.absolute_byte_offset()).unwrap_or(usize::MAX);
|
||||
found.retain(|&(a, _)| context.accepts(literal_at(literals, block_start.saturating_add(a))));
|
||||
}
|
||||
|
||||
let mut next = found.iter().copied().peekable();
|
||||
let mut line_start = 0;
|
||||
|
||||
@@ -27,7 +27,10 @@ pub fn scope_files(
|
||||
filter: Option<PathFilter<'_>>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<ScopeFile>> {
|
||||
let keep = |rel: &str| mask.matches(rel) && filter.is_none_or(|f| f(rel));
|
||||
let pattern = scope.pattern()?;
|
||||
let keep = |rel: &str| {
|
||||
mask.matches(rel) && pattern.as_ref().is_none_or(|p| p.matches(rel)) && filter.is_none_or(|f| f(rel))
|
||||
};
|
||||
let found = Mutex::new(Vec::new());
|
||||
let mut on_disk = Vec::new();
|
||||
for path in roots(root, scope)? {
|
||||
@@ -63,7 +66,7 @@ pub fn scope_files(
|
||||
return WalkState::Quit;
|
||||
}
|
||||
let Ok(entry) = entry else { return WalkState::Continue };
|
||||
if entry.file_type().is_some_and(|t| t.is_file()) {
|
||||
if entry.file_type().is_some_and(|t| t.is_file()) && !ide_vfs::is_archive_file(entry.path()) {
|
||||
let rel = rel_path(root, entry.path());
|
||||
if keep(&rel) {
|
||||
found
|
||||
@@ -139,4 +142,15 @@ mod tests {
|
||||
vec!["src/a.rs", "src/new.rs"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_scope() {
|
||||
let dir = tree();
|
||||
let none = FileMask::new(&[], &[]).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let scope = SearchScope::Pattern { pattern: "file:src//*.rs&&!file:src/sub//*".into() };
|
||||
assert_eq!(rels(&scope_files(dir.path(), &scope, &none, None, &cancel).unwrap()), vec!["src/a.rs"]);
|
||||
let bad = SearchScope::Pattern { pattern: "(".into() };
|
||||
assert!(scope_files(dir.path(), &bad, &none, None, &cancel).is_err());
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,13 @@ mod files;
|
||||
mod iter;
|
||||
mod line;
|
||||
mod mask;
|
||||
mod pattern;
|
||||
mod query;
|
||||
mod replace;
|
||||
|
||||
pub use files::{ScopeFile, scope_files};
|
||||
pub use mask::FileMask;
|
||||
pub use pattern::ScopePattern;
|
||||
pub use replace::{
|
||||
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
|
||||
replace_files, replacement_edits,
|
||||
@@ -41,8 +43,64 @@ pub struct SearchQuery {
|
||||
pub scope: SearchScope,
|
||||
/// Stop after this many matches overall (0 = 10 000).
|
||||
pub max_matches: u32,
|
||||
/// Where in the code a match may lie (IDEA's search context filter).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub context: SearchContext,
|
||||
}
|
||||
|
||||
/// IDEA's search context: matches anywhere, only in, or outside comments and
|
||||
/// string literals. Files whose language has no syntax tree contain neither.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SearchContext {
|
||||
#[default]
|
||||
Any,
|
||||
InComments,
|
||||
InStringLiterals,
|
||||
ExceptComments,
|
||||
ExceptStringLiterals,
|
||||
ExceptCommentsAndStringLiterals,
|
||||
}
|
||||
|
||||
/// What a [`LiteralRange`] is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LiteralKind {
|
||||
Comment,
|
||||
String,
|
||||
}
|
||||
|
||||
/// Byte range of a comment or string literal in a file's text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct LiteralRange {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: LiteralKind,
|
||||
}
|
||||
|
||||
impl SearchContext {
|
||||
/// Whether a match starting in `kind` (`None`: plain code) is kept.
|
||||
pub fn accepts(self, kind: Option<LiteralKind>) -> bool {
|
||||
match self {
|
||||
Self::Any => true,
|
||||
Self::InComments => kind == Some(LiteralKind::Comment),
|
||||
Self::InStringLiterals => kind == Some(LiteralKind::String),
|
||||
Self::ExceptComments => kind != Some(LiteralKind::Comment),
|
||||
Self::ExceptStringLiterals => kind != Some(LiteralKind::String),
|
||||
Self::ExceptCommentsAndStringLiterals => kind.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Only matches inside comments / string literals: files without any are skipped.
|
||||
fn needs_literals(self) -> bool {
|
||||
matches!(self, Self::InComments | Self::InStringLiterals)
|
||||
}
|
||||
}
|
||||
|
||||
/// Comments and string literals of a file's text (sorted, non-overlapping),
|
||||
/// or `None` when its language has no syntax tree.
|
||||
pub type Literals<'a> = &'a (dyn Fn(&Path, &str) -> Option<Vec<LiteralRange>> + Sync);
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum SearchScope {
|
||||
@@ -58,6 +116,21 @@ pub enum SearchScope {
|
||||
FileSet {
|
||||
set: ProjectFileSet,
|
||||
},
|
||||
/// A custom scope: the project's files matching a [`ScopePattern`]
|
||||
/// (`file:src//*.ts&&!file:*test*`).
|
||||
Pattern {
|
||||
pattern: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl SearchScope {
|
||||
/// The file pattern of a [`SearchScope::Pattern`].
|
||||
pub fn pattern(&self) -> IdeResult<Option<ScopePattern>> {
|
||||
match self {
|
||||
Self::Pattern { pattern } => ScopePattern::parse(pattern).map(Some),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -131,6 +204,20 @@ pub fn search_filtered(
|
||||
overlay: Overlay<'_>,
|
||||
cancel: &CancellationToken,
|
||||
on_file: &(dyn Fn(FileMatches) + Sync),
|
||||
) -> IdeResult<SearchSummary> {
|
||||
search_in_context(root, query, filter, None, overlay, cancel, on_file)
|
||||
}
|
||||
|
||||
/// [`search_filtered`] honouring [`SearchQuery::context`] with the comments and
|
||||
/// string literals `literals` finds; without it every match is plain code.
|
||||
pub fn search_in_context(
|
||||
root: &Path,
|
||||
query: &SearchQuery,
|
||||
filter: Option<PathFilter<'_>>,
|
||||
literals: Option<Literals<'_>>,
|
||||
overlay: Overlay<'_>,
|
||||
cancel: &CancellationToken,
|
||||
on_file: &(dyn Fn(FileMatches) + Sync),
|
||||
) -> IdeResult<SearchSummary> {
|
||||
let mask = FileMask::new(&query.include, &query.exclude)?;
|
||||
if query.pattern.is_empty() {
|
||||
@@ -141,7 +228,10 @@ pub fn search_filtered(
|
||||
scope: &query.scope,
|
||||
compiled: query::compile(query)?,
|
||||
mask,
|
||||
pattern: query.scope.pattern()?,
|
||||
filter,
|
||||
context: query.context,
|
||||
literals,
|
||||
max_matches: query.max_matches,
|
||||
overlay,
|
||||
cancel,
|
||||
@@ -153,6 +243,7 @@ pub fn search_filtered(
|
||||
/// invalid regex while the user types.
|
||||
pub fn validate_query(query: &SearchQuery) -> IdeResult<()> {
|
||||
FileMask::new(&query.include, &query.exclude)?;
|
||||
query.scope.pattern()?;
|
||||
if !query.pattern.is_empty() {
|
||||
query::compile(query)?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
//! IDEA-style scope patterns for custom (named) scopes:
|
||||
//! `file:src//*.ts&&!file:*test*`, `file:*.rs||file:docs//*`, `!(file:gen//*)`.
|
||||
//!
|
||||
//! A term is `file:<glob>` (the `file:` prefix and a `[module]` qualifier are
|
||||
//! optional); `//` means "any depth" (`src//*` = `src/**/*`), a trailing `/`
|
||||
//! means everything below. Globs without a `/` match the file name, others the
|
||||
//! project-relative path, like [`crate::FileMask`]. Terms combine with `!`,
|
||||
//! `&&`, `||` (in that precedence) and parentheses.
|
||||
|
||||
use globset::{GlobBuilder, GlobMatcher};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ScopePattern(Node);
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Node {
|
||||
Glob { glob: GlobMatcher, by_name: bool },
|
||||
Not(Box<Node>),
|
||||
And(Vec<Node>),
|
||||
Or(Vec<Node>),
|
||||
}
|
||||
|
||||
impl ScopePattern {
|
||||
pub fn parse(source: &str) -> IdeResult<Self> {
|
||||
let mut p = Parser { s: source, pos: 0 };
|
||||
p.skip_ws();
|
||||
if p.at_end() {
|
||||
return Err(IdeError::invalid("Empty scope pattern"));
|
||||
}
|
||||
let node = p.or()?;
|
||||
p.skip_ws();
|
||||
if !p.at_end() {
|
||||
return Err(p.error("Unexpected input"));
|
||||
}
|
||||
Ok(Self(node))
|
||||
}
|
||||
|
||||
/// `rel_path` is project-relative and `/`-separated.
|
||||
pub fn matches(&self, rel_path: &str) -> bool {
|
||||
self.0.matches(rel_path, rel_path.rsplit('/').next().unwrap_or(rel_path))
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
fn matches(&self, rel: &str, name: &str) -> bool {
|
||||
match self {
|
||||
Self::Glob { glob, by_name } => glob.is_match(if *by_name { name } else { rel }),
|
||||
Self::Not(n) => !n.matches(rel, name),
|
||||
Self::And(all) => all.iter().all(|n| n.matches(rel, name)),
|
||||
Self::Or(any) => any.iter().any(|n| n.matches(rel, name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
s: &'a str,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn rest(&self) -> &str {
|
||||
&self.s[self.pos..]
|
||||
}
|
||||
|
||||
fn at_end(&self) -> bool {
|
||||
self.pos >= self.s.len()
|
||||
}
|
||||
|
||||
fn skip_ws(&mut self) {
|
||||
let rest = self.rest();
|
||||
self.pos += rest.len() - rest.trim_start().len();
|
||||
}
|
||||
|
||||
fn eat(&mut self, token: &str) -> bool {
|
||||
self.skip_ws();
|
||||
if self.rest().starts_with(token) {
|
||||
self.pos += token.len();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn error(&self, what: &str) -> IdeError {
|
||||
IdeError::invalid(format!("{what} at column {} of the scope pattern", self.s[..self.pos].chars().count() + 1))
|
||||
}
|
||||
|
||||
fn or(&mut self) -> IdeResult<Node> {
|
||||
let mut items = vec![self.and()?];
|
||||
while self.eat("||") {
|
||||
items.push(self.and()?);
|
||||
}
|
||||
Ok(if items.len() == 1 { items.remove(0) } else { Node::Or(items) })
|
||||
}
|
||||
|
||||
fn and(&mut self) -> IdeResult<Node> {
|
||||
let mut items = vec![self.unary()?];
|
||||
while self.eat("&&") {
|
||||
items.push(self.unary()?);
|
||||
}
|
||||
Ok(if items.len() == 1 { items.remove(0) } else { Node::And(items) })
|
||||
}
|
||||
|
||||
fn unary(&mut self) -> IdeResult<Node> {
|
||||
if self.eat("!") {
|
||||
return Ok(Node::Not(Box::new(self.unary()?)));
|
||||
}
|
||||
if self.eat("(") {
|
||||
let node = self.or()?;
|
||||
if !self.eat(")") {
|
||||
return Err(self.error("Missing `)`"));
|
||||
}
|
||||
return Ok(node);
|
||||
}
|
||||
self.term()
|
||||
}
|
||||
|
||||
fn term(&mut self) -> IdeResult<Node> {
|
||||
self.skip_ws();
|
||||
let rest = self.rest();
|
||||
let end = ["&&", "||", ")"].iter().filter_map(|t| rest.find(t)).min().unwrap_or(rest.len());
|
||||
let raw = rest[..end].trim();
|
||||
if raw.is_empty() {
|
||||
return Err(self.error("Expected a file pattern"));
|
||||
}
|
||||
let glob = strip_prefix(raw);
|
||||
if glob.is_empty() {
|
||||
return Err(self.error("Expected a file pattern"));
|
||||
}
|
||||
let node = glob_node(glob)?;
|
||||
self.pos += end;
|
||||
Ok(node)
|
||||
}
|
||||
}
|
||||
|
||||
/// `file:x`, `file[module]:x` → `x`.
|
||||
fn strip_prefix(term: &str) -> &str {
|
||||
let Some(rest) = term.strip_prefix("file") else { return term };
|
||||
let rest = match rest.strip_prefix('[') {
|
||||
Some(r) => match r.find(']') {
|
||||
Some(i) => &r[i + 1..],
|
||||
None => return term,
|
||||
},
|
||||
None => rest,
|
||||
};
|
||||
rest.strip_prefix(':').map_or(term, str::trim)
|
||||
}
|
||||
|
||||
fn glob_node(pattern: &str) -> IdeResult<Node> {
|
||||
let mut glob = pattern.trim_start_matches("./").replace("//", "/**/");
|
||||
if glob.ends_with('/') {
|
||||
glob.push_str("**");
|
||||
}
|
||||
let by_name = !glob.contains('/');
|
||||
let glob = if by_name { glob } else { glob.trim_start_matches('/').to_owned() };
|
||||
let matcher = GlobBuilder::new(&glob)
|
||||
.literal_separator(true)
|
||||
.backslash_escape(true)
|
||||
.case_insensitive(cfg!(any(target_os = "macos", target_os = "windows")))
|
||||
.build()
|
||||
.map_err(|e| IdeError::invalid(format!("Invalid file pattern `{pattern}`: {}", e.kind())))?
|
||||
.compile_matcher();
|
||||
Ok(Node::Glob { glob: matcher, by_name })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn p(s: &str) -> ScopePattern {
|
||||
ScopePattern::parse(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idea_recursive_directory_globs() {
|
||||
let s = p("file:src//*.ts");
|
||||
assert!(s.matches("src/a.ts"));
|
||||
assert!(s.matches("src/x/y/a.ts"));
|
||||
assert!(!s.matches("lib/a.ts"));
|
||||
assert!(!s.matches("src/a.rs"));
|
||||
assert!(p("src/").matches("src/deep/a.rs"));
|
||||
assert!(!p("file:src/*").matches("src/deep/a.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_operators_and_grouping() {
|
||||
let s = p("file:src//*&&!file:*test*");
|
||||
assert!(s.matches("src/main.rs"));
|
||||
assert!(!s.matches("src/main_test.rs"));
|
||||
let s = p("*.md || file[app]:docs//*");
|
||||
assert!(s.matches("README.md"));
|
||||
assert!(s.matches("docs/x/y.txt"));
|
||||
assert!(!s.matches("src/a.rs"));
|
||||
let s = p("!(file:gen//* || *.lock) && *.*");
|
||||
assert!(s.matches("src/a.rs"));
|
||||
assert!(!s.matches("gen/a.rs"));
|
||||
assert!(!s.matches("Cargo.lock"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors() {
|
||||
for bad in ["", " ", "file:", "a &&", "(a", "a)", "file:a["] {
|
||||
assert!(ScopePattern::parse(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,7 @@ mod tests {
|
||||
exclude: vec![],
|
||||
scope: SearchScope::Project,
|
||||
max_matches: 0,
|
||||
context: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ fn query(pattern: &str) -> SearchQuery {
|
||||
exclude: vec![],
|
||||
scope: SearchScope::Project,
|
||||
max_matches: 0,
|
||||
context: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 900 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача