дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 06:42:54 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
a466ec7425 | ||
|
|
98e375f524 | ||
|
|
04a4d98d68 | ||
|
|
9a984f64a3 | ||
|
|
e35a607556 | ||
|
|
3fa990fce2 | ||
|
|
11e520dedb | ||
|
|
a0c0b69b4a | ||
|
|
b89128649f | ||
|
|
9973cad74c | ||
|
|
8cb7a2fe06 | ||
|
|
5d867d7d2d | ||
|
|
70f6678271 | ||
|
|
530388a79d | ||
|
|
98cb85003a | ||
|
|
dfae46868c | ||
|
|
635da15486 | ||
|
|
249d0526f0 | ||
|
|
181bbdfdc2 | ||
|
|
c7172184ad | ||
|
|
8380732e60 | ||
|
|
42fcbb336a | ||
|
|
93a450aa8c | ||
|
|
8e0a36fb1c | ||
|
|
11da3ecce7 | ||
|
|
53d295d785 | ||
|
|
9f1380cf04 | ||
|
|
338e1a5b02 | ||
|
|
092cde1319 | ||
|
|
fc1e1838ca | ||
|
|
9a9a536525 | ||
|
|
2d7928374e | ||
|
|
58eb5ae667 | ||
|
|
0698ebb9b0 | ||
|
|
647e564127 | ||
|
|
38a964040b | ||
|
|
edd2e90b9b | ||
|
|
5bfefff5e1 | ||
|
|
49097bf5c0 | ||
|
|
09a44bebbe | ||
|
|
7237a37104 | ||
|
|
c864cec32f | ||
|
|
f7f2efaace | ||
|
|
e8cb141d86 |
No files matched your search
Створено
+11
@@ -4684,6 +4684,7 @@ dependencies = [
|
||||
"tree-sitter-make",
|
||||
"tree-sitter-md",
|
||||
"tree-sitter-nix",
|
||||
"tree-sitter-objc",
|
||||
"tree-sitter-ocaml",
|
||||
"tree-sitter-php",
|
||||
"tree-sitter-prisma-io",
|
||||
@@ -10642,6 +10643,16 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-objc"
|
||||
version = "3.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ca8bb556423fc176f0535e79d525f783a6684d3c9da81bf9d905303c129e1d2"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-ocaml"
|
||||
version = "0.26.0"
|
||||
|
||||
@@ -2762,7 +2762,6 @@ impl AgentManager {
|
||||
}
|
||||
s.task.title = title;
|
||||
s.title_renamed = true;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
@@ -3126,7 +3125,6 @@ impl AgentManager {
|
||||
let changed = s.task.mcp_overrides != cleaned;
|
||||
if changed {
|
||||
s.task.mcp_overrides = cleaned;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
(changed, s.busy, !s.background_tasks.is_empty(), s.snapshot())
|
||||
};
|
||||
@@ -3158,7 +3156,6 @@ impl AgentManager {
|
||||
let changed = s.task.skill_overrides != cleaned;
|
||||
if changed {
|
||||
s.task.skill_overrides = cleaned;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
|
||||
};
|
||||
@@ -3194,7 +3191,6 @@ impl AgentManager {
|
||||
let changed = s.task.memory_overrides != next_boxed;
|
||||
if changed {
|
||||
s.task.memory_overrides = next_boxed;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
|
||||
};
|
||||
|
||||
@@ -6928,3 +6928,36 @@ async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_e
|
||||
mgr2.shutdown();
|
||||
mgr3.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn metadata_edits_do_not_bump_updated_ms() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let fixed_ms = 1_234.0;
|
||||
handle.state.lock().task.updated_ms = fixed_ms;
|
||||
|
||||
mgr.rename(&task.id, "Custom Title").unwrap();
|
||||
assert_eq!(handle.state.lock().task.updated_ms, fixed_ms);
|
||||
|
||||
let after_mcp = mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false)])).unwrap();
|
||||
assert_eq!(after_mcp.updated_ms, fixed_ms);
|
||||
|
||||
let after_skill =
|
||||
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
|
||||
assert_eq!(after_skill.updated_ms, fixed_ms);
|
||||
|
||||
let after_memory = mgr
|
||||
.set_memory_overrides(
|
||||
&task.id,
|
||||
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(after_memory.updated_ms, fixed_ms);
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
//! same way into the test output, which also sees the production classes.
|
||||
use super::*;
|
||||
use ide_core::settings::{
|
||||
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
|
||||
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
|
||||
split_jar_glob,
|
||||
};
|
||||
use std::fs;
|
||||
|
||||
@@ -104,13 +105,17 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve
|
||||
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
|
||||
if wanted(scope) {
|
||||
for class in &lib.classes {
|
||||
add(class_entry(root, class));
|
||||
for entry in class_entries(root, class) {
|
||||
add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
|
||||
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
|
||||
add(class_entry(root, &dep.target));
|
||||
for entry in class_entries(root, &dep.target) {
|
||||
add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
|
||||
@@ -133,29 +138,50 @@ fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
|
||||
root.join(dir)
|
||||
}
|
||||
|
||||
/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars).
|
||||
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
|
||||
let entry = class_entry(root, value);
|
||||
match entry.strip_suffix('*') {
|
||||
Some(dir) => {
|
||||
let mut jars: Vec<PathBuf> = fs::read_dir(dir)
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect())
|
||||
.unwrap_or_default();
|
||||
jars.sort();
|
||||
jars
|
||||
/// The folders under `dir` (itself included) that hold `.jar` files, in walk order.
|
||||
fn jar_dirs(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = Vec::new();
|
||||
for jar in jar_files(dir, true) {
|
||||
if let Some(parent) = jar.parent().filter(|p| !dirs.iter().any(|d| d == p)) {
|
||||
dirs.push(parent.to_path_buf());
|
||||
}
|
||||
None => vec![PathBuf::from(entry)],
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
/// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands.
|
||||
fn class_entry(root: &Path, value: &str) -> String {
|
||||
let path = root.join(value.trim());
|
||||
let text = path.to_string_lossy().into_owned();
|
||||
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
|
||||
return text[..text.len() - 4].to_owned();
|
||||
/// The class archives and folders of a library path (`lib/*.jar`, `lib/**/*.jar`, or a folder
|
||||
/// containing JARs expands to those JARs; a folder without JARs stays a class folder).
|
||||
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
|
||||
if let Some((base, recursive)) = split_jar_glob(value) {
|
||||
return jar_files(&root.join(base), recursive);
|
||||
}
|
||||
text
|
||||
let path = root.join(value.trim());
|
||||
if path.is_dir() {
|
||||
let jars = jar_files(&path, true);
|
||||
if !jars.is_empty() {
|
||||
return jars;
|
||||
}
|
||||
}
|
||||
vec![path]
|
||||
}
|
||||
|
||||
/// Classpath entries for a library path: `lib/*.jar` stays `lib/*` for javac to expand; a
|
||||
/// directory containing JARs expands to `<dir>/*` per folder holding JARs.
|
||||
fn class_entries(root: &Path, value: &str) -> Vec<String> {
|
||||
let wildcard = |dir: &Path| format!("{}{}*", dir.to_string_lossy(), std::path::MAIN_SEPARATOR);
|
||||
if let Some((base, recursive)) = split_jar_glob(value) {
|
||||
let dir = root.join(base);
|
||||
let dirs = if recursive { jar_dirs(&dir) } else { Vec::new() };
|
||||
return if dirs.is_empty() { vec![wildcard(&dir)] } else { dirs.iter().map(|d| wildcard(d)).collect() };
|
||||
}
|
||||
let path = root.join(value.trim());
|
||||
if path.is_dir() {
|
||||
let dirs = jar_dirs(&path);
|
||||
if !dirs.is_empty() {
|
||||
return dirs.iter().map(|d| wildcard(d)).collect();
|
||||
}
|
||||
}
|
||||
vec![path.to_string_lossy().into_owned()]
|
||||
}
|
||||
|
||||
fn classpath(entries: &[String]) -> String {
|
||||
@@ -440,7 +466,10 @@ pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactCo
|
||||
ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect()
|
||||
}
|
||||
|
||||
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
|
||||
/// A build of `artifact` for Tomcat's deployment, compiling production classes first.
|
||||
/// When `war` is `Some`, packs a WAR archive at that path; when `None`, writes to the
|
||||
/// artifact's own output (`artifact_file`: a `.war` archive for `War`, or the exploded
|
||||
/// directory for `WarExploded`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn structure_war_plan(
|
||||
root: &Path,
|
||||
@@ -449,7 +478,7 @@ pub fn structure_war_plan(
|
||||
jdk: Option<&StructureJdk>,
|
||||
language_level: &str,
|
||||
artifact: &ArtifactConfig,
|
||||
war: &Path,
|
||||
war: Option<&Path>,
|
||||
cache: &Path,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
|
||||
@@ -459,7 +488,7 @@ pub fn structure_war_plan(
|
||||
plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args")));
|
||||
plan.steps
|
||||
.retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out)));
|
||||
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
|
||||
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, war, cache));
|
||||
plan.title = artifact.name.clone();
|
||||
Ok(plan)
|
||||
}
|
||||
@@ -1144,4 +1173,53 @@ mod tests {
|
||||
bad_result.messages
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_jar_directory_libraries_for_javac_and_artifacts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
let cache = tmp.path().join("cache");
|
||||
write(&root.join("src/A.java"), "class A {}");
|
||||
write(&root.join("WebRoot/WEB-INF/lib/gson.jar"), "jar1");
|
||||
write(&root.join("WebRoot/WEB-INF/lib/sub/extra.jar"), "jar2");
|
||||
fs::create_dir_all(root.join("plain-classes")).unwrap();
|
||||
write(&root.join("plain-classes/Helper.class"), "");
|
||||
|
||||
let ps = ProjectStructureSettings {
|
||||
libraries: vec![
|
||||
ProjectLibrary {
|
||||
name: "web-libs".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
..Default::default()
|
||||
},
|
||||
ProjectLibrary { name: "classes".into(), classes: vec!["plain-classes".into()], ..Default::default() },
|
||||
],
|
||||
artifacts: vec![ArtifactConfig {
|
||||
name: "app:war exploded".into(),
|
||||
kind: ArtifactKind::WarExploded,
|
||||
module: ".".into(),
|
||||
output_directory: "out/artifacts/app_war_exploded".into(),
|
||||
main_class: String::new(),
|
||||
include_libraries: vec!["web-libs".into()],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
|
||||
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Artifacts, &cache).unwrap().unwrap();
|
||||
let javac = &plan.steps[0];
|
||||
let cp = &javac.args[javac.args.iter().position(|a| a == "-cp").unwrap() + 1];
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
assert!(cp.contains(&format!("lib{sep}*")), "expected JAR dir wildcard in cp: {cp}");
|
||||
assert!(cp.contains(&format!("sub{sep}*")), "expected nested JAR dir wildcard in cp: {cp}");
|
||||
assert!(cp.contains("plain-classes") && !cp.contains(&format!("plain-classes{sep}*")), "cp={cp}");
|
||||
|
||||
let layout = plan.steps.iter().find_map(|s| match &s.action {
|
||||
Some((Action::Layout { entries, .. }, _)) => Some(entries),
|
||||
_ => None,
|
||||
});
|
||||
let entries = layout.expect("layout step");
|
||||
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/gson.jar")), "{entries:?}");
|
||||
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/extra.jar")), "{entries:?}");
|
||||
assert!(!entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/lib")), "{entries:?}");
|
||||
}
|
||||
}
|
||||
@@ -314,6 +314,30 @@ pub struct SmartKeysSettings {
|
||||
pub insert_doc_stub: bool,
|
||||
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
|
||||
pub backspace_unindent: String,
|
||||
/// The styles Cycle Identifier Case goes through.
|
||||
pub cycle_case: CycleCaseSettings,
|
||||
}
|
||||
|
||||
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CycleCaseSettings {
|
||||
/// `snake_case`
|
||||
pub snake: bool,
|
||||
/// `SCREAMING_SNAKE_CASE`
|
||||
pub screaming: bool,
|
||||
/// `kebab-case`
|
||||
pub kebab: bool,
|
||||
/// `camelCase`
|
||||
pub camel: bool,
|
||||
/// `PascalCase`
|
||||
pub pascal: bool,
|
||||
}
|
||||
|
||||
impl Default for CycleCaseSettings {
|
||||
fn default() -> Self {
|
||||
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SmartKeysSettings {
|
||||
@@ -335,6 +359,7 @@ impl Default for SmartKeysSettings {
|
||||
smart_indent: true,
|
||||
insert_doc_stub: true,
|
||||
backspace_unindent: "autoindent".into(),
|
||||
cycle_case: CycleCaseSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,35 @@
|
||||
//! Returning freed heap pages to the OS.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
|
||||
/// closing a project or a batch of tabs frees memory in bursts, released once.
|
||||
pub fn release_free_pages_soon() {
|
||||
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
debounce(&DUE, Duration::from_secs(2), release_free_pages);
|
||||
}
|
||||
|
||||
/// Runs `run` on a background thread once `delay` passes after the last call.
|
||||
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
|
||||
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
|
||||
if idle {
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
let mut slot = due.lock().unwrap();
|
||||
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
|
||||
if left.is_zero() {
|
||||
*slot = None;
|
||||
drop(slot);
|
||||
return run();
|
||||
}
|
||||
drop(slot);
|
||||
std::thread::sleep(left);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
|
||||
/// short-lived allocations (a full index scan); until then they still count towards the
|
||||
/// process's memory footprint.
|
||||
@@ -18,3 +48,28 @@ pub fn release_free_pages() {
|
||||
libc::malloc_trim(0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
|
||||
|
||||
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
static RUNS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn count() {
|
||||
RUNS.fetch_add(1, SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_calls_runs_once_after_the_delay() {
|
||||
for _ in 0..5 {
|
||||
debounce(&DUE, Duration::from_millis(100), count);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(RUNS.load(SeqCst), 0);
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
release_free_pages_soon();
|
||||
}
|
||||
}
|
||||
@@ -2054,6 +2054,37 @@ pub struct ProjectLibrary {
|
||||
pub scope: DependencyScope,
|
||||
}
|
||||
|
||||
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
|
||||
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
|
||||
let entry = entry.trim();
|
||||
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
|
||||
return Some((base, true));
|
||||
}
|
||||
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
|
||||
}
|
||||
|
||||
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
|
||||
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
|
||||
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
let mut entries: Vec<_> = entries.flatten().collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
match entry.file_type() {
|
||||
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
|
||||
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
|
||||
out.push(path)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, recursive, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
|
||||
@@ -448,18 +448,39 @@ pub async fn format(
|
||||
options: FormatOptions,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let project = host.project(window)?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let source = FormatSource {
|
||||
path: snap.path,
|
||||
language: snap.language,
|
||||
text: snap.text,
|
||||
doc: Some(doc),
|
||||
version: snap.version,
|
||||
read_only: snap.read_only,
|
||||
// A notebook cell is a document of the language servers only: `documents` holds what the
|
||||
// editor opened, so ⌥⌘L in a cell used to answer "document DocId#N is not open".
|
||||
let source = match project.documents.snapshot(doc) {
|
||||
Ok(snap) => FormatSource {
|
||||
path: snap.path,
|
||||
language: snap.language,
|
||||
text: snap.text,
|
||||
doc: Some(doc),
|
||||
version: snap.version,
|
||||
read_only: snap.read_only,
|
||||
},
|
||||
Err(e) => match project.lsp.cell_text(doc) {
|
||||
Some(cell) => FormatSource {
|
||||
path: cell_script_path(&cell.path).into(),
|
||||
language: cell.language,
|
||||
text: cell.text,
|
||||
doc: Some(doc),
|
||||
version: cell.version,
|
||||
read_only: false,
|
||||
},
|
||||
None => return Err(e),
|
||||
},
|
||||
};
|
||||
format_source(host, window, &project, source, range, options).await
|
||||
}
|
||||
|
||||
/// The file name a formatter is given for a cell's text. It only picks the language and the
|
||||
/// settings: the text arrives on stdin. The notebook's own `.ipynb` would make Ruff parse the
|
||||
/// cell as notebook JSON instead of Python.
|
||||
fn cell_script_path(notebook: &Path) -> PathBuf {
|
||||
notebook.with_extension("py")
|
||||
}
|
||||
|
||||
/// Format a separate snapshot using the file's language, settings and formatter.
|
||||
pub async fn format_text(
|
||||
host: &Host,
|
||||
@@ -1385,6 +1406,14 @@ mod tests {
|
||||
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cell_is_formatted_as_python_rather_than_as_notebook_json() {
|
||||
// Ruff reads the extension of `--stdin-filename` to decide what the text is; `.ipynb`
|
||||
// made it expect notebook JSON and fail on the cell's source.
|
||||
assert_eq!(cell_script_path(Path::new("/p/notebooks/a.ipynb")), Path::new("/p/notebooks/a.py"));
|
||||
assert_eq!(cell_script_path(Path::new("/p/a.b.ipynb")), Path::new("/p/a.b.py"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -27,6 +27,7 @@ pub mod relay;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
mod swiftlint;
|
||||
pub mod trust;
|
||||
mod ts_code_style;
|
||||
mod tsc_watch;
|
||||
@@ -464,6 +465,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.stop();
|
||||
}
|
||||
if let Some(swiftlint) = &project.swiftlint {
|
||||
swiftlint.stop();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.stop();
|
||||
}
|
||||
@@ -547,6 +551,8 @@ impl Host {
|
||||
if let Some(retired) = retired {
|
||||
let _ = retired.join();
|
||||
}
|
||||
// The project's buffers, index and caches are dropped: hand their pages back.
|
||||
ide_core::memory::release_free_pages_soon();
|
||||
})
|
||||
}
|
||||
|
||||
@@ -704,6 +710,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.stop();
|
||||
}
|
||||
if let Some(swiftlint) = &project.swiftlint {
|
||||
swiftlint.stop();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.stop();
|
||||
}
|
||||
|
||||
@@ -172,15 +172,15 @@ impl Policy {
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path)
|
||||
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path, within)
|
||||
}
|
||||
}
|
||||
|
||||
/// The root of the project that serves `path` in the background under the current
|
||||
/// settings and trust decisions. Opens nothing.
|
||||
pub(crate) fn serving_root(host: &Host, path: &Path) -> Option<PathBuf> {
|
||||
Policy::current(host)?.resolve(path)
|
||||
/// settings and trust decisions; with `within`, only a root strictly inside it. Opens nothing.
|
||||
pub(crate) fn serving_root(host: &Host, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
Policy::current(host)?.resolve(path, within)
|
||||
}
|
||||
|
||||
/// How long a project may stay idle; `None` when `minutes` is 0 (never unloaded).
|
||||
@@ -283,7 +283,7 @@ impl BackgroundProjects {
|
||||
state.opening = Some(root.to_path_buf());
|
||||
Opening(self)
|
||||
};
|
||||
if serving_root(host, root).as_deref() != Some(root) {
|
||||
if serving_root(host, root, None).as_deref() != Some(root) {
|
||||
return Err(IdeError::unavailable(format!("{} is not served in the background", root.display())));
|
||||
}
|
||||
let limit = project_limit(host.global_settings.effective().mcp_server.background_project_limit);
|
||||
@@ -463,7 +463,7 @@ impl Host {
|
||||
}
|
||||
let policy = Policy::current(self);
|
||||
for root in roots {
|
||||
if policy.as_ref().and_then(|policy| policy.resolve(&root)).as_deref() != Some(&root) {
|
||||
if policy.as_ref().and_then(|policy| policy.resolve(&root, None)).as_deref() != Some(&root) {
|
||||
self.mcp_background.detach(self, &root, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,9 @@ use std::path::{Path, PathBuf};
|
||||
/// folders containing it and, in `Trusted` mode, of the trusted projects, the trusted recent
|
||||
/// projects and the nearest trusted folder with a project marker. `None` when the mode is
|
||||
/// `Off`, when `path` is relative or missing, and when no folder qualifies. Listed and
|
||||
/// recent folders that are gone or not absolute paths are skipped.
|
||||
/// recent folders that are gone or not absolute paths are skipped. With `within` (the root
|
||||
/// of the open project containing `path`) only folders strictly inside it count, and the
|
||||
/// others aren't looked up on disk.
|
||||
pub(crate) fn resolve(
|
||||
mode: McpBackgroundProjects,
|
||||
listed: &[PathBuf],
|
||||
@@ -18,6 +20,7 @@ pub(crate) fn resolve(
|
||||
recents: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
path: &Path,
|
||||
within: Option<&Path>,
|
||||
) -> Option<PathBuf> {
|
||||
let by_trust = match mode {
|
||||
McpBackgroundProjects::Off => return None,
|
||||
@@ -28,23 +31,37 @@ pub(crate) fn resolve(
|
||||
return None;
|
||||
}
|
||||
let path = dunce::canonicalize(path).ok()?;
|
||||
let within = within.map(|root| (root, dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf())));
|
||||
let open = within.as_ref().map(|(_, root)| root.as_path());
|
||||
// Only folders strictly inside `within` count. An entry is checked by its text before it
|
||||
// is canonicalized, so folders elsewhere (a network mount among them) aren't touched; one
|
||||
// that reaches inside through a link from elsewhere is left out.
|
||||
let inside = |entry: &Path, canonical: bool| {
|
||||
within.as_ref().is_none_or(|(raw, root)| {
|
||||
(entry.starts_with(root) && entry != root) || (!canonical && entry.starts_with(raw) && entry != *raw)
|
||||
})
|
||||
};
|
||||
// A relative entry would be read against the working directory, which says nothing
|
||||
// about the user's folders (`/` for an app started from the Finder).
|
||||
let existing = |entry: &PathBuf| entry.is_absolute().then(|| dunce::canonicalize(entry).ok()).flatten();
|
||||
let existing = |entry: &PathBuf| {
|
||||
(entry.is_absolute() && inside(entry, false)).then(|| dunce::canonicalize(entry).ok()).flatten()
|
||||
};
|
||||
// A listed folder serves its subtree whether or not it is trusted: it opens restricted then.
|
||||
let mut candidates: Vec<PathBuf> = listed.iter().filter_map(existing).collect();
|
||||
if by_trust {
|
||||
candidates.extend(decisions.projects.iter().filter(|p| trusted_here(decisions, p)).cloned());
|
||||
let projects = decisions.projects.iter().filter(|p| inside(p, true));
|
||||
candidates.extend(projects.filter(|p| trusted_here(decisions, p)).cloned());
|
||||
// Remote projects are recorded as locations (`ssh://…`), not as folders of this machine.
|
||||
let local = recents.iter().filter(|p| !p.to_string_lossy().contains("://"));
|
||||
candidates.extend(local.filter_map(existing).filter(|p| trusted_here(decisions, p)));
|
||||
let home = home.map(|h| dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf()));
|
||||
// A trusted location and the home folder hold projects; neither is one.
|
||||
candidates
|
||||
.extend(marker_root(&path).filter(|a| {
|
||||
.extend(marker_root(&path, open).filter(|a| {
|
||||
trusted_here(decisions, a) && !decisions.locations.contains(a) && home.as_ref() != Some(a)
|
||||
}));
|
||||
}
|
||||
candidates.retain(|candidate| inside(candidate, true));
|
||||
innermost(&candidates, &path).cloned()
|
||||
}
|
||||
|
||||
@@ -64,9 +81,10 @@ fn trusted_here(decisions: &TrustDecisions, root: &Path) -> bool {
|
||||
|
||||
/// The first ancestor of `path`, itself included, that looks like a project: it holds an
|
||||
/// `.openidea` folder, or a `.git` or `.jj` entry (a linked worktree's `.git` is a file).
|
||||
fn marker_root(path: &Path) -> Option<PathBuf> {
|
||||
/// The search stops short of `within`.
|
||||
fn marker_root(path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
let marked = |dir: &&Path| dir.join(".openidea").is_dir() || dir.join(".git").exists() || dir.join(".jj").exists();
|
||||
path.ancestors().find(marked).map(Path::to_path_buf)
|
||||
path.ancestors().take_while(|dir| Some(*dir) != within).find(marked).map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -159,7 +177,35 @@ mod tests {
|
||||
restricted: paths(restricted),
|
||||
};
|
||||
let home = base.join("home");
|
||||
let found = resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path));
|
||||
let found =
|
||||
resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path), None);
|
||||
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_an_open_project_only_a_folder_below_its_root_serves_a_path() {
|
||||
let (_tmp, base) = tree();
|
||||
let at = |folders: &[&str]| folders.iter().map(|folder| base.join(folder)).collect::<Vec<_>>();
|
||||
let trusted = |projects: &[&str], locations: &[&str]| TrustDecisions {
|
||||
projects: at(projects),
|
||||
locations: at(locations),
|
||||
..Default::default()
|
||||
};
|
||||
let within = base.join("code/app");
|
||||
let (none, root, location) = (trusted(&[], &[]), trusted(&["code/app"], &[]), trusted(&[], &["code"]));
|
||||
let (src, nested) = ("code/app/src", "code/app/.wt/feature");
|
||||
let below = trusted(&[nested], &[]);
|
||||
let nested_src = "code/app/.wt/feature/src";
|
||||
for (what, mode, listed, decisions, path, expected) in [
|
||||
("a listed folder below the root", Listed, &[src][..], &none, src, Some(src)),
|
||||
("the listed root and a listed folder around it", Listed, &["code", "code/app"], &none, src, None),
|
||||
("the trusted root", Trusted, &[], &root, src, None),
|
||||
("the root's own marker", Trusted, &[], &location, src, None),
|
||||
("a repository below the root", Trusted, &[], &location, nested_src, Some(nested)),
|
||||
("a trusted project below the root", Trusted, &[], &below, nested_src, Some(nested)),
|
||||
] {
|
||||
let found = resolve(mode, &at(listed), decisions, &[], None, &base.join(path), Some(&within));
|
||||
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
|
||||
}
|
||||
}
|
||||
@@ -170,7 +216,7 @@ mod tests {
|
||||
let listed = [base.join("code/app"), PathBuf::from("code/app"), PathBuf::from(".")];
|
||||
let none = TrustDecisions::default();
|
||||
for path in ["code/app/src", ".", "src"] {
|
||||
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path)), None, "{path}");
|
||||
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path), None), None, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +234,7 @@ mod tests {
|
||||
("the same folder listed by its full path", Listed, absolute, &none, &[][..], Some(&here)),
|
||||
("the same folder recent by its full path", Trusted, &[][..], &around, absolute, Some(&here)),
|
||||
] {
|
||||
assert_eq!(resolve(mode, listed, decisions, recents, None, &here).as_ref(), expected, "{what}");
|
||||
assert_eq!(resolve(mode, listed, decisions, recents, None, &here, None).as_ref(), expected, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,13 +246,13 @@ mod tests {
|
||||
let none = TrustDecisions::default();
|
||||
// Listed by the link, asked for by the real path, and the other way round (`/tmp` and `/private/tmp`).
|
||||
for (listed, path) in [("link/app", "code/app/src"), ("code/app", "link/app/src"), ("link/app", "link/app")] {
|
||||
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path));
|
||||
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path), None);
|
||||
assert_eq!(found, Some(base.join("code/app")), "{listed} for {path}");
|
||||
}
|
||||
let trusted = TrustDecisions { locations: vec![base.join("code")], ..Default::default() };
|
||||
let recent = [base.join("link/plain")];
|
||||
assert_eq!(
|
||||
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src")),
|
||||
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src"), None),
|
||||
Some(base.join("code/plain"))
|
||||
);
|
||||
}
|
||||
@@ -219,10 +265,10 @@ mod tests {
|
||||
std::fs::create_dir_all(base.join("ssh:/box/app/src")).unwrap();
|
||||
let recent = [PathBuf::from(format!("{}/ssh://box/app", base.display()))];
|
||||
let trusted = TrustDecisions { locations: vec![base.clone()], ..Default::default() };
|
||||
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src")), None);
|
||||
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src"), None), None);
|
||||
let local = [base.join("ssh:/box/app")];
|
||||
assert_eq!(
|
||||
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src")),
|
||||
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src"), None),
|
||||
Some(base.join("ssh:/box/app"))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -708,7 +708,7 @@ async fn a_host_that_serves_none_refuses_every_folder_whatever_the_settings_say(
|
||||
let root = f.root("inventory");
|
||||
f.host.mcp_background.serve_none();
|
||||
let registry = crate::mcp::Registry::new(f.host.clone());
|
||||
assert_eq!(registry.resolve(&root.join("parts")), None);
|
||||
assert_eq!(registry.resolve(&root.join("parts"), None), None);
|
||||
assert_eq!(f.refused("inventory"), format!("{} is not served in the background", root.display()));
|
||||
assert!(f.loaded().is_empty());
|
||||
assert!(f.host.projects().is_empty());
|
||||
@@ -726,11 +726,11 @@ async fn a_call_that_arrives_after_the_server_was_turned_off_opens_nothing() {
|
||||
assert!(f.loaded().is_empty());
|
||||
assert!(f.host.projects().is_empty());
|
||||
let registry = crate::mcp::Registry::new(f.host.clone());
|
||||
assert_eq!(registry.resolve(&root.join("parts")), None, "no folder is served with the server off");
|
||||
assert_eq!(registry.resolve(&root.join("parts"), None), None, "no folder is served with the server off");
|
||||
assert!(registry.tools(&root).is_err());
|
||||
|
||||
f.set("enabled", json!(true));
|
||||
assert_eq!(registry.resolve(&root.join("parts")), Some(root));
|
||||
assert_eq!(registry.resolve(&root.join("parts"), None), Some(root));
|
||||
f.open("inventory");
|
||||
assert_eq!(f.loaded(), ["inventory"]);
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ impl Registry {
|
||||
if let Some(project) = self.0.mcp_background.project(&self.0, root) {
|
||||
return Ok(project.is_trusted());
|
||||
}
|
||||
if background::serving_root(&self.0, root).as_deref() == Some(root) {
|
||||
if background::serving_root(&self.0, root, None).as_deref() == Some(root) {
|
||||
return Ok(self.0.trust.window_trusted(root).unwrap_or(false));
|
||||
}
|
||||
Err("project is no longer open".into())
|
||||
@@ -138,8 +138,13 @@ impl ToolRegistry for Registry {
|
||||
let attached: Vec<_> = open.iter().flat_map(|p| tool::attached_projects(&p.root)).collect();
|
||||
open.into_iter().map(|p| p.root.clone()).chain(attached).chain(self.0.mcp_reports.remote_roots()).collect()
|
||||
}
|
||||
fn resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
background::serving_root(&self.0, path)
|
||||
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
// A remote window's project holds that host's folders, even where this computer has
|
||||
// folders at the same paths.
|
||||
if within.is_some_and(|root| self.0.mcp_reports.remote_roots().iter().any(|remote| remote == root)) {
|
||||
return None;
|
||||
}
|
||||
background::serving_root(&self.0, path, within)
|
||||
}
|
||||
fn tools(&self, root: &Path) -> Result<Vec<ide_mcp::Tool>, String> {
|
||||
let trusted = self.lists_as_trusted(root)?;
|
||||
|
||||
@@ -1115,11 +1115,16 @@ pub async fn agent_mcp_test(host: &Host, window: &str, id: String) -> IdeResult<
|
||||
let cwd = project.as_ref().map(|p| p.root.clone()).or_else(dirs::home_dir).unwrap_or_else(std::env::temp_dir);
|
||||
match server.transport {
|
||||
McpTransport::Stdio => Ok(ide_agent::mcp::probe_stdio_server(&server, &cwd).await),
|
||||
McpTransport::Http | McpTransport::Sse => Ok(probe_http_mcp_server(&server).await),
|
||||
McpTransport::Http | McpTransport::Sse => {
|
||||
Ok(probe_http_mcp_server(&server, &ide_core::proxy_settings::proxy()).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> McpProbeResult {
|
||||
async fn probe_http_mcp_server(
|
||||
server: &ide_core::settings::AgentMcpServer,
|
||||
proxy: &ide_core::proxy_settings::ProxySettings,
|
||||
) -> McpProbeResult {
|
||||
let started = std::time::Instant::now();
|
||||
let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
let Some(url) = server.url.as_deref().map(str::trim).filter(|u| !u.is_empty()) else {
|
||||
@@ -1145,31 +1150,36 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
|
||||
headers.insert(name, val);
|
||||
}
|
||||
}
|
||||
let client =
|
||||
match reqwest::Client::builder().default_headers(headers).timeout(std::time::Duration::from_secs(12)).build() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(format!("HTTP client error: {e}")),
|
||||
};
|
||||
}
|
||||
};
|
||||
let client = match ide_http::client::build(proxy) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(format!("HTTP client error: {}", e.message)),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// The shared client has no MCP headers or 12 s limit of its own. The protocol's headers win over the
|
||||
// configured ones, as they did over the client's default headers.
|
||||
let post = |client: &reqwest::Client, url: &str, session_id: Option<&str>| {
|
||||
let mut headers = headers.clone();
|
||||
headers.insert(reqwest::header::CONTENT_TYPE, reqwest::header::HeaderValue::from_static("application/json"));
|
||||
if let Some(value) = session_id.and_then(|sid| reqwest::header::HeaderValue::from_str(sid).ok()) {
|
||||
headers.insert("mcp-session-id", value);
|
||||
}
|
||||
client.post(url).headers(headers).timeout(std::time::Duration::from_secs(12))
|
||||
};
|
||||
let post_rpc = |session_id: Option<String>, body: serde_json::Value| {
|
||||
let client = client.clone();
|
||||
let url = url.to_owned();
|
||||
async move {
|
||||
let mut req =
|
||||
client.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string());
|
||||
if let Some(sid) = session_id.as_deref() {
|
||||
req = req.header("Mcp-Session-Id", sid);
|
||||
}
|
||||
let req = post(&client, &url, session_id.as_deref()).body(body.to_string());
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
@@ -1218,7 +1228,7 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
|
||||
};
|
||||
|
||||
// Best-effort `notifications/initialized` + `tools/list`.
|
||||
let mut not_req = client.post(url).header(reqwest::header::CONTENT_TYPE, "application/json").body(
|
||||
let not_req = post(&client, url, session_id.as_deref()).body(
|
||||
serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
@@ -1226,9 +1236,6 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
if let Some(sid) = session_id.as_deref() {
|
||||
not_req = not_req.header("Mcp-Session-Id", sid);
|
||||
}
|
||||
let _ = not_req.send().await;
|
||||
|
||||
let tools_res = post_rpc(
|
||||
@@ -1866,6 +1873,112 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_mcp_probe_goes_through_the_manual_proxy_and_keeps_its_headers() {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let settings = ide_core::proxy_settings::ProxySettings {
|
||||
mode: ide_core::proxy_settings::ProxyMode::Manual,
|
||||
host: "127.0.0.1".into(),
|
||||
port: address.port(),
|
||||
..Default::default()
|
||||
};
|
||||
let proxy = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut head = String::new();
|
||||
while !head.ends_with("\r\n\r\n") {
|
||||
if reader.read_line(&mut head).unwrap() == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
head
|
||||
});
|
||||
let server = ide_core::settings::AgentMcpServer {
|
||||
transport: McpTransport::Http,
|
||||
url: Some("http://mcp-target.invalid/mcp".into()),
|
||||
headers: [("X-Test".to_owned(), "1".to_owned())].into(),
|
||||
..Default::default()
|
||||
};
|
||||
let result = probe_http_mcp_server(&server, &settings).await;
|
||||
assert!(!result.ok);
|
||||
// A probe that bypassed the proxy leaves it waiting in `accept`; a dummy connection releases it.
|
||||
let _ = std::net::TcpStream::connect(address);
|
||||
let head = proxy.join().unwrap().to_ascii_lowercase();
|
||||
assert!(head.starts_with("post http://mcp-target.invalid/mcp http/1.1"), "{head}");
|
||||
assert!(head.contains("accept: application/json, text/event-stream"), "{head}");
|
||||
assert!(head.contains("x-test: 1"), "{head}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_protocol_headers_win_over_configured_ones_in_all_three_requests() {
|
||||
use std::io::{Read, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut heads = Vec::new();
|
||||
for reply in [
|
||||
r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{},"serverInfo":{"name":"t","version":"1"}}}"#,
|
||||
"",
|
||||
r#"{"jsonrpc":"2.0","id":2,"result":{"tools":[]}}"#,
|
||||
] {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut raw = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while !raw.ends_with(b"\r\n\r\n") {
|
||||
stream.read_exact(&mut byte).unwrap();
|
||||
raw.push(byte[0]);
|
||||
}
|
||||
let head = String::from_utf8(raw).unwrap().to_ascii_lowercase();
|
||||
let length = head
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length: "))
|
||||
.map_or(0, |value| value.trim().parse().unwrap());
|
||||
let mut body = vec![0u8; length];
|
||||
stream.read_exact(&mut body).unwrap();
|
||||
heads.push(head);
|
||||
let _ = stream.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nMcp-Session-Id: s1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
|
||||
reply.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
}
|
||||
heads
|
||||
});
|
||||
let settings = ide_core::proxy_settings::ProxySettings {
|
||||
mode: ide_core::proxy_settings::ProxyMode::None,
|
||||
..Default::default()
|
||||
};
|
||||
let server_config = ide_core::settings::AgentMcpServer {
|
||||
transport: McpTransport::Http,
|
||||
url: Some(format!("http://127.0.0.1:{port}/mcp")),
|
||||
headers: [
|
||||
("Content-Type".to_owned(), "text/plain".to_owned()),
|
||||
("Mcp-Session-Id".to_owned(), "configured".to_owned()),
|
||||
("Accept".to_owned(), "text/x-configured".to_owned()),
|
||||
]
|
||||
.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let result = probe_http_mcp_server(&server_config, &settings).await;
|
||||
assert!(result.ok, "{:?}", result.error);
|
||||
let heads = server.join().unwrap();
|
||||
let values = |head: &str, name: &str| -> Vec<String> {
|
||||
head.lines().filter_map(|line| line.strip_prefix(name)).map(|v| v.trim().to_owned()).collect()
|
||||
};
|
||||
for (i, head) in heads.iter().enumerate() {
|
||||
assert_eq!(values(head, "content-type:"), ["application/json"], "request {i}: {head}");
|
||||
assert_eq!(values(head, "accept:"), ["text/x-configured"], "request {i}: {head}");
|
||||
// The first request has no session yet, so the configured value stands.
|
||||
let session = if i == 0 { "configured" } else { "s1" };
|
||||
assert_eq!(values(head, "mcp-session-id:"), [session], "request {i}: {head}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_installs_once_at_a_time() {
|
||||
let first = Installing::begin("test-agent").unwrap();
|
||||
|
||||
@@ -26,6 +26,7 @@ pub async fn doc_close(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.documents.close(doc);
|
||||
ide_core::memory::release_free_pages_soon();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -8,9 +8,9 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// The available iOS simulators, booted first; `None` outside macOS or when the project has no
|
||||
/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
|
||||
/// no change feed, and one listing takes a fraction of a second.
|
||||
/// The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside
|
||||
/// macOS or when the project has no Xcode project or workspace at its root. Asked again whenever
|
||||
/// the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<IosSimulator>>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
|
||||
@@ -695,8 +695,10 @@ fn apply_library_classpath(
|
||||
DependencyScope::Compile | DependencyScope::Runtime => true,
|
||||
DependencyScope::Test | DependencyScope::Provided => test,
|
||||
};
|
||||
lib.classes.iter().filter_map(move |entry| {
|
||||
ide_sdk::apply::setting_path(root, entry).map(|path| (path.to_string_lossy().into_owned(), allowed))
|
||||
lib.classes.iter().flat_map(move |entry| {
|
||||
ide_sdk::libraries::library_class_paths(root, entry)
|
||||
.into_iter()
|
||||
.map(move |p| (p.to_string_lossy().into_owned(), allowed))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -1492,6 +1494,26 @@ mod tests {
|
||||
let mut info = JavaLaunchInfo::default();
|
||||
apply_library_classpath(&mut info, root.path(), &libraries, false);
|
||||
assert_eq!(info.class_paths, &paths[..2]);
|
||||
|
||||
// Directory library roots expand to the JAR files inside them.
|
||||
let web_lib = root.path().join("WebRoot/WEB-INF/lib");
|
||||
std::fs::create_dir_all(&web_lib).unwrap();
|
||||
let a_jar = web_lib.join("a.jar");
|
||||
let b_jar = web_lib.join("b.jar");
|
||||
std::fs::write(&a_jar, b"").unwrap();
|
||||
std::fs::write(&b_jar, b"").unwrap();
|
||||
let dir_libs = vec![ProjectLibrary {
|
||||
name: "web".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
scope: DependencyScope::Compile,
|
||||
..Default::default()
|
||||
}];
|
||||
let mut dir_info = JavaLaunchInfo::default();
|
||||
apply_library_classpath(&mut dir_info, root.path(), &dir_libs, false);
|
||||
assert_eq!(
|
||||
dir_info.class_paths,
|
||||
vec![a_jar.to_string_lossy().into_owned(), b_jar.to_string_lossy().into_owned()]
|
||||
);
|
||||
}
|
||||
|
||||
/// JDT LS and our build model spell a module output differently on Windows; the
|
||||
|
||||
@@ -521,11 +521,19 @@ pub async fn nav_python_library_imports(
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.language.as_str() != "python" {
|
||||
// A notebook cell is a document of the language servers only: `documents` holds what the
|
||||
// editor opened, so ⌥↵ on a cell's unresolved name used to answer nothing.
|
||||
let (language, path) = match project.documents.snapshot(doc) {
|
||||
Ok(snap) => (snap.language, snap.path.0),
|
||||
Err(e) => match project.lsp.cell_text(doc) {
|
||||
Some(cell) => (cell.language, cell.path),
|
||||
None => return Err(e),
|
||||
},
|
||||
};
|
||||
if language.as_str() != "python" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
|
||||
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&path)) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let roots = interpreter_site_packages(&python);
|
||||
|
||||
@@ -253,8 +253,10 @@ fn project_web_artifacts(ps: &ide_core::settings::ProjectStructureSettings) -> V
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Compiles the project and packs the Project Structure artifact `name` as the WAR Tomcat
|
||||
/// deploys, recorded in `base` like a build tool's archive.
|
||||
/// Compiles the project and builds the Project Structure artifact `name` for Tomcat to
|
||||
/// deploy, recording its output path in `base` like a build tool's archive.
|
||||
/// The artifact lives outside `base` (at `artifact_file`), so `tomcat::prepare` recreating
|
||||
/// the runtime directory does not delete what was just built.
|
||||
fn build_project_war(
|
||||
root: &std::path::Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
@@ -270,10 +272,7 @@ fn build_project_war(
|
||||
.iter()
|
||||
.find(|a| a.name == name)
|
||||
.ok_or_else(|| IdeError::invalid(format!("No artifact named {name} in Project Structure › Artifacts")))?;
|
||||
let war = base.join("artifact").join(format!(
|
||||
"{}.war",
|
||||
name.split(':').next().unwrap_or(name).replace(|c: char| !c.is_alphanumeric() && c != '-', "_")
|
||||
));
|
||||
let target = compile::artifact_file(root, artifact);
|
||||
let plan = compile::structure_war_plan(
|
||||
root,
|
||||
&ps,
|
||||
@@ -281,7 +280,7 @@ fn build_project_war(
|
||||
jdk.as_ref(),
|
||||
&settings.languages.java.language_level,
|
||||
artifact,
|
||||
&war,
|
||||
None,
|
||||
cache,
|
||||
)?;
|
||||
let result = compile::run(root, &plan, &ide_core::CancellationToken::new(), &|_| {})?;
|
||||
@@ -300,7 +299,7 @@ fn build_project_war(
|
||||
}
|
||||
std::fs::create_dir_all(base)?;
|
||||
std::fs::write(base.join("artifact-id.txt"), format!("{PROJECT_ARTIFACT}{name}"))?;
|
||||
std::fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes())?;
|
||||
std::fs::write(base.join("artifact-path.txt"), target.to_string_lossy().as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -332,8 +331,14 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
|
||||
let artifacts = ide_build::web::artifacts(&project.root, &model);
|
||||
let settings = project.settings.effective();
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &settings);
|
||||
let mut artifacts = ide_build::web::artifacts(&project.root, &model);
|
||||
if model.maven.is_none() && model.gradle.is_empty() {
|
||||
let detected = project.detected_roots.read().clone();
|
||||
let (ps, _, _) = crate::ops::build::structure_inputs(&project.root, &settings, &detected);
|
||||
artifacts.extend(project_web_artifacts(&ps));
|
||||
}
|
||||
let id = config
|
||||
.extras
|
||||
.params
|
||||
@@ -345,7 +350,6 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
|
||||
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
|
||||
let base = ide_run::tomcat::state_dir(&base, &config);
|
||||
if let Some(name) = id.strip_prefix(PROJECT_ARTIFACT) {
|
||||
let settings = project.settings.effective();
|
||||
let detected = project.detected_roots.read().clone();
|
||||
build_project_war(&project.root, &settings, &detected, name, &base, &project.build_cache_dir())?;
|
||||
return Ok(None);
|
||||
@@ -467,3 +471,100 @@ ide_command::domain!(
|
||||
run_tomcat_sync,
|
||||
run_tomcat_update,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::settings::{ArtifactConfig, ArtifactKind, FacetConfig, Settings};
|
||||
use std::io::Write;
|
||||
|
||||
fn fake_tomcat(home: &std::path::Path) {
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::create_dir_all(home.join("conf")).unwrap();
|
||||
std::fs::create_dir_all(home.join("lib")).unwrap();
|
||||
std::fs::write(home.join("bin/catalina.sh"), "").unwrap();
|
||||
std::fs::write(home.join("bin/catalina.bat"), "").unwrap();
|
||||
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
|
||||
std::fs::write(home.join("conf/server.xml"), server).unwrap();
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(home.join("lib/catalina.jar")).unwrap());
|
||||
zip.start_file("org/apache/catalina/util/ServerInfo.properties", zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(b"server.info=Apache Tomcat/10.1").unwrap();
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_structure_war_and_exploded_artifacts_survive_tomcat_prepare() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("EJSH");
|
||||
let cache = root.parent().unwrap().join("cache");
|
||||
let tomcat_home = root.parent().unwrap().join("tomcat-home");
|
||||
fake_tomcat(&tomcat_home);
|
||||
|
||||
std::fs::create_dir_all(root.join("WebRoot/WEB-INF")).unwrap();
|
||||
std::fs::write(root.join("WebRoot/WEB-INF/web.xml"), "<web-app/>").unwrap();
|
||||
std::fs::write(root.join("WebRoot/index.jsp"), "<h1>ok</h1>").unwrap();
|
||||
|
||||
let mut settings = Settings::default();
|
||||
settings.project_structure.facets.push(FacetConfig {
|
||||
kind: "web".into(),
|
||||
module: ".".into(),
|
||||
descriptor: "WebRoot/WEB-INF/web.xml".into(),
|
||||
web_root: "WebRoot".into(),
|
||||
});
|
||||
settings.project_structure.artifacts.push(ArtifactConfig {
|
||||
name: "EJSH:war exploded".into(),
|
||||
kind: ArtifactKind::WarExploded,
|
||||
module: ".".into(),
|
||||
output_directory: "out/artifacts/EJSH_war_exploded".into(),
|
||||
..Default::default()
|
||||
});
|
||||
settings.project_structure.artifacts.push(ArtifactConfig {
|
||||
name: "EJSH:war".into(),
|
||||
kind: ArtifactKind::War,
|
||||
module: ".".into(),
|
||||
output_directory: "out/artifacts/EJSH_war".into(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
for (artifact_name, expect_exploded_dir) in [("EJSH:war exploded", true), ("EJSH:war", false)] {
|
||||
let mut config = RunConfig {
|
||||
id: format!("tomcat-{artifact_name}"),
|
||||
name: "Tomcat".into(),
|
||||
kind: "tomcat".into(),
|
||||
command: "catalina".into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
config.extras.params.insert("tomcatHome".into(), tomcat_home.to_string_lossy().into_owned());
|
||||
config.extras.params.insert("deployment".into(), "artifact".into());
|
||||
config.extras.params.insert("artifact".into(), format!("{PROJECT_ARTIFACT}{artifact_name}"));
|
||||
config.extras.params.insert("artifactName".into(), "EJSH".into());
|
||||
config.extras.params.insert("httpPort".into(), "8080".into());
|
||||
|
||||
let base = ide_run::tomcat::effective_base_dir(&root, &cache, &config).unwrap();
|
||||
let state = ide_run::tomcat::state_dir(&base, &config);
|
||||
build_project_war(&root, &settings, &[], artifact_name, &state, &cache.join("build")).unwrap();
|
||||
|
||||
// `prepare` deletes and recreates `base`; the built artifact must remain intact.
|
||||
ide_run::tomcat::prepare(&root, &cache, &mut config).unwrap();
|
||||
let catalina_base = std::path::PathBuf::from(&config.env["CATALINA_BASE"]);
|
||||
let ctx = std::fs::read_to_string(catalina_base.join("conf/Catalina/localhost/EJSH.xml")).unwrap();
|
||||
if expect_exploded_dir {
|
||||
let expected = root.join("out/artifacts/EJSH_war_exploded");
|
||||
assert!(expected.join("WEB-INF/web.xml").is_file());
|
||||
assert!(ctx.contains(expected.to_string_lossy().as_ref()), "{ctx}");
|
||||
} else {
|
||||
assert!(root.join("out/artifacts/EJSH_war/EJSH.war").is_file());
|
||||
assert!(catalina_base.join("deployment/WEB-INF/web.xml").is_file());
|
||||
assert!(ctx.contains("deployment"), "{ctx}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -422,6 +422,10 @@ pub struct PluginHost {
|
||||
initial_load: (Mutex<bool>, Condvar),
|
||||
/// `on-startup-finished` has fired.
|
||||
startup_finished: AtomicBool,
|
||||
/// Language, file and view activation events fired so far (with their project), so a plugin
|
||||
/// installed or synced afterwards (a remote server gets its packages after the window opened
|
||||
/// files) still activates for a Twig file that is already open.
|
||||
fired_activations: Mutex<Vec<(ActivationEvent, Option<PathBuf>)>>,
|
||||
/// The theme last announced with `ThemeChanged`.
|
||||
announced_theme: Mutex<Option<ActiveTheme>>,
|
||||
/// [`PluginLanguages::revision`] last announced with `LanguagesChanged`.
|
||||
@@ -541,6 +545,7 @@ impl PluginHost {
|
||||
lifecycle: Mutex::new(()),
|
||||
initial_load: (Mutex::new(false), Condvar::new()),
|
||||
startup_finished: AtomicBool::new(false),
|
||||
fired_activations: Mutex::new(Vec::new()),
|
||||
announced_theme: Mutex::new(None),
|
||||
announced_languages: AtomicU64::new(0),
|
||||
announced_skills: AtomicU64::new(0),
|
||||
@@ -699,6 +704,16 @@ impl PluginHost {
|
||||
|
||||
/// Fires an activation event from the UI (`on-language:rust`, `on-file:…`, `on-view:…`).
|
||||
pub fn activation_event(&self, event: &ActivationEvent, project: Option<&Path>) {
|
||||
{
|
||||
let mut fired = self.fired_activations.lock();
|
||||
let entry = (event.clone(), project.map(Path::to_path_buf));
|
||||
if !fired.contains(&entry) {
|
||||
if fired.len() >= MAX_FIRED_ACTIVATIONS {
|
||||
fired.remove(0);
|
||||
}
|
||||
fired.push(entry);
|
||||
}
|
||||
}
|
||||
let targets: Vec<_> = self
|
||||
.plugins
|
||||
.read()
|
||||
@@ -3096,8 +3111,12 @@ impl PluginHost {
|
||||
meta.pending = pending;
|
||||
meta.status = if plugin.manifest().wasm.is_some() { PluginStatus::Inactive } else { PluginStatus::Static };
|
||||
}
|
||||
let eager = plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
|
||||
&& self.startup_finished.load(Ordering::Acquire);
|
||||
let eager = (plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
|
||||
&& self.startup_finished.load(Ordering::Acquire))
|
||||
|| self.fired_activations.lock().iter().any(|(event, project)| {
|
||||
(plugin.dev_root.is_none() || plugin.dev_root == *project)
|
||||
&& plugin.manifest().activation.iter().any(|a| activation_matches(a, event))
|
||||
});
|
||||
if eager {
|
||||
let _ = self.ensure_active(plugin, None);
|
||||
}
|
||||
@@ -3725,6 +3744,9 @@ fn counts(m: &Manifest) -> Vec<ContributionCount> {
|
||||
m.declaration_counts().into_iter().map(|(point, count)| ContributionCount { point, count }).collect()
|
||||
}
|
||||
|
||||
/// How many fired activation events [`PluginHost::activation_event`] remembers (oldest dropped first).
|
||||
const MAX_FIRED_ACTIVATIONS: usize = 512;
|
||||
|
||||
fn activation_matches(declared: &ActivationEvent, fired: &ActivationEvent) -> bool {
|
||||
match (declared, fired) {
|
||||
(ActivationEvent::Language(a), ActivationEvent::Language(b)) => a == b || a == "*",
|
||||
|
||||
@@ -5,6 +5,10 @@ use super::{
|
||||
network_inbox::{Inbox, Push},
|
||||
};
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use ide_core::{
|
||||
IdeResult,
|
||||
proxy_settings::{ProxyMode, ProxySettings},
|
||||
};
|
||||
use ide_plugin::WebSocketBatch;
|
||||
use parking_lot::Mutex;
|
||||
use std::{
|
||||
@@ -17,7 +21,7 @@ use std::{
|
||||
};
|
||||
use tokio::sync::{Notify, watch};
|
||||
use tokio_tungstenite::{
|
||||
Connector, connect_async_tls_with_config,
|
||||
Connector, client_async_tls_with_config,
|
||||
tungstenite::{
|
||||
Message,
|
||||
client::IntoClientRequest,
|
||||
@@ -128,11 +132,20 @@ impl WebSocketHub {
|
||||
.map(Arc::new)
|
||||
.map(Connector::Rustls)
|
||||
.map_err(|error| ConnectError::Failed(error.message))?;
|
||||
let (socket, response) =
|
||||
tokio::time::timeout(timeout, connect_async_tls_with_config(request, Some(config), false, Some(tls)))
|
||||
let target = reqwest::Url::parse(url).map_err(|_| ConnectError::Invalid("invalid WebSocket URL".into()))?;
|
||||
// Through the IDE's proxy settings, like the Jupyter kernel channels.
|
||||
let (socket, response) = tokio::time::timeout(timeout, async {
|
||||
// The tunnel's reason (a proxy that needs a login, refuses or is unreachable) helps the user.
|
||||
let stream = open_stream(&target, &ide_core::proxy_settings::proxy())
|
||||
.await
|
||||
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
|
||||
.map_err(|_| ConnectError::Failed("WebSocket connection failed".into()))?;
|
||||
.map_err(|error| format!("WebSocket connection failed: {}", error.message))?;
|
||||
client_async_tls_with_config(request, stream, Some(config), Some(tls))
|
||||
.await
|
||||
.map_err(|_| "WebSocket connection failed".to_owned())
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
|
||||
.map_err(ConnectError::Failed)?;
|
||||
if !subprotocol.is_empty()
|
||||
&& response.headers().get("sec-websocket-protocol").and_then(|value| value.to_str().ok())
|
||||
!= Some(subprotocol)
|
||||
@@ -257,14 +270,30 @@ impl WebSocketHub {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_url(url: &str) -> Result<(), String> {
|
||||
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
|
||||
// `host_str` keeps an IPv6 address in brackets.
|
||||
let loopback = parsed.host_str().is_some_and(|host| {
|
||||
/// `host_str` keeps an IPv6 address in brackets.
|
||||
fn is_loopback(url: &reqwest::Url) -> bool {
|
||||
url.host_str().is_some_and(|host| {
|
||||
let host = host.trim_start_matches('[').trim_end_matches(']');
|
||||
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
|
||||
});
|
||||
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && loopback) {
|
||||
})
|
||||
}
|
||||
|
||||
/// The TCP stream to `url` under `settings`. Loopback stays direct in every mode (plaintext `ws://` is
|
||||
/// loopback-only); a proxy the tunnel cannot speak to (SOCKS) keeps the direct connection plugins had before.
|
||||
async fn open_stream(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult<tokio::net::TcpStream> {
|
||||
if is_loopback(url) {
|
||||
return ide_http::tunnel::connect_best_effort(
|
||||
url,
|
||||
&ProxySettings { mode: ProxyMode::None, ..Default::default() },
|
||||
)
|
||||
.await;
|
||||
}
|
||||
ide_http::tunnel::connect_best_effort(url, settings).await
|
||||
}
|
||||
|
||||
fn validate_url(url: &str) -> Result<(), String> {
|
||||
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
|
||||
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && is_loopback(&parsed)) {
|
||||
return Err("WebSocket requires WSS outside loopback".into());
|
||||
}
|
||||
if !parsed.username().is_empty() || parsed.password().is_some() || parsed.fragment().is_some() {
|
||||
@@ -392,6 +421,84 @@ mod tests {
|
||||
(url, task)
|
||||
}
|
||||
|
||||
fn manual(port: u16) -> ProxySettings {
|
||||
ProxySettings { mode: ProxyMode::Manual, host: "127.0.0.1".into(), port, ..Default::default() }
|
||||
}
|
||||
|
||||
async fn head_of_first_connection(listener: TcpListener) -> String {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let (mut client, _) = listener.accept().await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
client.read_exact(&mut byte).await.unwrap();
|
||||
head.push(byte[0]);
|
||||
}
|
||||
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await.unwrap();
|
||||
String::from_utf8(head).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_manual_proxy_carries_the_connection() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let settings = manual(listener.local_addr().unwrap().port());
|
||||
let proxy = tokio::spawn(head_of_first_connection(listener));
|
||||
let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap();
|
||||
assert!(open_stream(&url, &settings).await.is_err());
|
||||
// A connection that bypasses the proxy leaves it waiting, so bound the wait.
|
||||
let asked = tokio::time::timeout(Duration::from_secs(2), proxy).await.expect("the proxy was never asked");
|
||||
assert!(asked.unwrap().starts_with("CONNECT ws-target.invalid:443 HTTP/1.1\r\n"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loopback_stays_direct_in_every_mode() {
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy_port = proxy.local_addr().unwrap().port();
|
||||
let proxy_task = tokio::spawn(head_of_first_connection(proxy));
|
||||
let target = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url =
|
||||
reqwest::Url::parse(&format!("ws://localhost:{}/socket", target.local_addr().unwrap().port())).unwrap();
|
||||
let settings = manual(proxy_port);
|
||||
open_stream(&url, &settings).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap();
|
||||
// Auto mode asks the system proxy, which may be set in the environment: loopback must not.
|
||||
open_stream(&url, &ProxySettings::default()).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap();
|
||||
assert!(tokio::time::timeout(Duration::from_millis(200), proxy_task).await.is_err(), "the proxy was asked");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_ipv6_loopback_websocket_connects() {
|
||||
let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here
|
||||
let url = format!("ws://[::1]:{}/socket", listener.local_addr().unwrap().port());
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
|
||||
socket.send(Message::Binary(vec![7].into())).await.unwrap();
|
||||
socket.close(None).await.unwrap();
|
||||
});
|
||||
let hub = WebSocketHub::default();
|
||||
hub.connect("plugin", "/project", &url, &[], "", Duration::from_secs(2)).await.unwrap();
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refusing_proxy_says_why() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let settings = manual(listener.local_addr().unwrap().port());
|
||||
let proxy = tokio::spawn(async move {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let (mut client, _) = listener.accept().await.unwrap();
|
||||
client.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").await.unwrap();
|
||||
// Keep the socket open until the client has read the reply.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
});
|
||||
let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap();
|
||||
let error = open_stream(&url, &settings).await.unwrap_err();
|
||||
assert!(error.message.contains("needs a login"), "{}", error.message);
|
||||
proxy.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn outbound_message_reaches_the_websocket_server() {
|
||||
let (url, server) = server().await;
|
||||
|
||||
@@ -77,6 +77,7 @@ pub struct Project {
|
||||
pub(crate) widget_preview: ide_flutter::ToolServer,
|
||||
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
|
||||
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
|
||||
pub(crate) swiftlint: Option<Arc<crate::swiftlint::SwiftLint>>,
|
||||
pub(crate) tsc_watch: Option<Arc<crate::tsc_watch::TscWatch>>,
|
||||
pub(crate) watcher: Arc<Watcher>,
|
||||
/// Watchers of the Project Structure content roots outside the project folder.
|
||||
@@ -419,6 +420,8 @@ impl Host {
|
||||
trusted.clone(),
|
||||
);
|
||||
documents.add_observer(phpstan.clone());
|
||||
let swiftlint = crate::swiftlint::SwiftLint::new(root.clone(), sink.clone(), trusted.clone());
|
||||
documents.add_observer(swiftlint.clone());
|
||||
let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone());
|
||||
documents.add_observer(tsc_watch.clone());
|
||||
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
|
||||
@@ -441,6 +444,7 @@ impl Host {
|
||||
let window = window.to_owned();
|
||||
let kotlin_bridge = kotlin_bridge.clone();
|
||||
let phpstan = phpstan.clone();
|
||||
let swiftlint = swiftlint.clone();
|
||||
let repos = repos.clone();
|
||||
let git_metadata = git_metadata.clone();
|
||||
let settings = settings.clone();
|
||||
@@ -470,6 +474,7 @@ impl Host {
|
||||
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
|
||||
kotlin_bridge.files_changed(changed.iter().chain(&batch.removed));
|
||||
phpstan.files_removed(batch.removed.iter());
|
||||
swiftlint.files_removed(batch.removed.iter());
|
||||
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
|
||||
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
@@ -720,6 +725,7 @@ impl Host {
|
||||
notebooks,
|
||||
kotlin_bridge: Some(kotlin_bridge),
|
||||
phpstan: Some(phpstan),
|
||||
swiftlint: Some(swiftlint),
|
||||
tsc_watch: Some(tsc_watch),
|
||||
watcher,
|
||||
content_watchers: Mutex::new(content_watchers),
|
||||
@@ -786,6 +792,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.start(&self.runtime);
|
||||
}
|
||||
if let Some(swiftlint) = &project.swiftlint {
|
||||
swiftlint.start(&self.runtime);
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.apply(&self.runtime);
|
||||
}
|
||||
@@ -1017,6 +1026,7 @@ impl Host {
|
||||
notebooks,
|
||||
kotlin_bridge: None,
|
||||
phpstan: None,
|
||||
swiftlint: None,
|
||||
tsc_watch: None,
|
||||
watcher: Arc::new(watcher),
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! Swift files below a `.swiftlint.yml` -> `swiftlint lint --reporter json` -> `swiftlint` diagnostics.
|
||||
//!
|
||||
//! A file as saved is linted by its path, so the configuration's `excluded` paths and nested
|
||||
//! configurations apply; an edited buffer is linted through stdin, unless its saved file was excluded.
|
||||
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::output_encoding::decode_tool_output;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
|
||||
use ide_text::AppliedChange;
|
||||
use ide_workspace::documents::{DocumentInfo, DocumentObserver};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Output, Stdio};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
const DELAY: Duration = Duration::from_millis(400);
|
||||
const SOURCE: &str = "swiftlint";
|
||||
const CONFIG: &str = ".swiftlint.yml";
|
||||
|
||||
/// What to lint: the saved file, or the text of its edited buffer.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Job {
|
||||
Saved,
|
||||
Buffer(String),
|
||||
}
|
||||
|
||||
pub(crate) struct SwiftLint {
|
||||
root: PathBuf,
|
||||
sink: SharedSink,
|
||||
trusted: Arc<AtomicBool>,
|
||||
lifetime: CancellationToken,
|
||||
/// The latest job per file; a newer one replaces it, and its result is dropped.
|
||||
pending: Mutex<BTreeMap<PathBuf, Job>>,
|
||||
changed: Notify,
|
||||
/// Files with SwiftLint diagnostics, the only ones a clean result or a close clears.
|
||||
shown: Mutex<HashSet<PathBuf>>,
|
||||
/// Files the configuration excludes, as found by their last saved-file lint.
|
||||
excluded: Mutex<HashSet<PathBuf>>,
|
||||
/// Failures already reported (a missing `swiftlint` included), each once until a run succeeds.
|
||||
reported: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
impl SwiftLint {
|
||||
pub(crate) fn new(root: PathBuf, sink: SharedSink, trusted: Arc<AtomicBool>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
root,
|
||||
sink,
|
||||
trusted,
|
||||
lifetime: CancellationToken::new(),
|
||||
pending: Mutex::new(BTreeMap::new()),
|
||||
changed: Notify::new(),
|
||||
shown: Mutex::new(HashSet::new()),
|
||||
excluded: Mutex::new(HashSet::new()),
|
||||
reported: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn start(self: &Arc<Self>, runtime: &tokio::runtime::Handle) {
|
||||
let linter = self.clone();
|
||||
runtime.spawn(async move { linter.run().await });
|
||||
}
|
||||
|
||||
pub(crate) fn stop(&self) {
|
||||
self.lifetime.cancel();
|
||||
}
|
||||
|
||||
fn queue(&self, path: &Path, job: Job) {
|
||||
if self.lifetime.is_cancelled() || !path.extension().is_some_and(|e| e == "swift") {
|
||||
return;
|
||||
}
|
||||
self.pending.lock().insert(path.to_path_buf(), job);
|
||||
self.changed.notify_one();
|
||||
}
|
||||
|
||||
/// Trusting the project lints its open files; Restricted Mode drops what was shown.
|
||||
pub(crate) fn trust_changed(&self, trusted: bool, open: impl Iterator<Item = DocumentInfo>) {
|
||||
if trusted {
|
||||
open.for_each(|info| self.opened(&info));
|
||||
} else {
|
||||
self.pending.lock().clear();
|
||||
let shown: Vec<PathBuf> = self.shown.lock().iter().cloned().collect();
|
||||
for path in shown {
|
||||
self.publish(path, Vec::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deleted files and folders lose their diagnostics.
|
||||
pub(crate) fn files_removed<'a>(&self, removed: impl Iterator<Item = &'a PathBuf>) {
|
||||
let removed: Vec<&PathBuf> = removed.collect();
|
||||
self.excluded.lock().retain(|p| !removed.iter().any(|r| p.starts_with(r)));
|
||||
let gone: Vec<PathBuf> =
|
||||
self.shown.lock().iter().filter(|p| removed.iter().any(|r| p.starts_with(r))).cloned().collect();
|
||||
for path in gone {
|
||||
self.publish(path, Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
fn publish(&self, path: PathBuf, items: Vec<Diagnostic>) {
|
||||
let mut shown = self.shown.lock();
|
||||
if items.is_empty() {
|
||||
if !shown.remove(&path) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
shown.insert(path.clone());
|
||||
}
|
||||
self.sink.emit(IdeEvent::Diagnostics { path: path.into(), source: SOURCE.into(), items });
|
||||
}
|
||||
|
||||
async fn run(self: Arc<Self>) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = self.lifetime.cancelled() => return,
|
||||
_ = self.changed.notified() => {},
|
||||
}
|
||||
// Typing keeps replacing the pending job: lint once it pauses.
|
||||
tokio::select! {
|
||||
_ = self.lifetime.cancelled() => return,
|
||||
_ = tokio::time::sleep(DELAY) => {},
|
||||
}
|
||||
loop {
|
||||
let Some((path, job)) = self.pending.lock().pop_first() else { break };
|
||||
if !self.trusted.load(Ordering::Acquire) {
|
||||
continue;
|
||||
}
|
||||
let Some(dir) = config_dir(&self.root, &path) else {
|
||||
self.publish(path, Vec::new());
|
||||
continue;
|
||||
};
|
||||
if job != Job::Saved && self.excluded.lock().contains(&path) {
|
||||
continue;
|
||||
}
|
||||
let text = match &job {
|
||||
Job::Saved => None,
|
||||
Job::Buffer(text) => Some(text.as_str()),
|
||||
};
|
||||
let Some(output) = lint(&dir, &path, text, &self.lifetime).await else { return };
|
||||
// Edited again meanwhile: the newer job's result replaces this one. Restricted
|
||||
// meanwhile: `trust_changed` already cleared the findings.
|
||||
if self.pending.lock().contains_key(&path) || !self.trusted.load(Ordering::Acquire) {
|
||||
continue;
|
||||
}
|
||||
let result = output.map_err(|e| {
|
||||
if e.kind() == std::io::ErrorKind::NotFound {
|
||||
"swiftlint was not found on PATH. Install SwiftLint (brew install swiftlint), \
|
||||
or from Settings › Languages & Frameworks › Language Servers."
|
||||
.to_string()
|
||||
} else {
|
||||
format!("Cannot run swiftlint: {e}")
|
||||
}
|
||||
});
|
||||
let result = result.and_then(|o| parse(&decode_tool_output(&o.stdout), &decode_tool_output(&o.stderr)));
|
||||
match result {
|
||||
Ok(Report::Excluded) => {
|
||||
self.excluded.lock().insert(path.clone());
|
||||
self.publish(path, Vec::new());
|
||||
*self.reported.lock() = None;
|
||||
}
|
||||
Ok(Report::Violations(violations)) => {
|
||||
if job == Job::Saved {
|
||||
self.excluded.lock().remove(&path);
|
||||
}
|
||||
let text = match job {
|
||||
Job::Buffer(text) => text,
|
||||
Job::Saved => std::fs::read(&path)
|
||||
.map(|b| String::from_utf8_lossy(&b).into_owned())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let items = violations.into_iter().map(|v| diagnostic(v, &text)).collect();
|
||||
self.publish(path, items);
|
||||
*self.reported.lock() = None;
|
||||
}
|
||||
Err(text) => {
|
||||
self.publish(path, Vec::new());
|
||||
self.failure(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(&self, text: String) {
|
||||
let mut reported = self.reported.lock();
|
||||
if reported.as_ref() == Some(&text) {
|
||||
return;
|
||||
}
|
||||
self.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Error,
|
||||
title: "SwiftLint check failed".into(),
|
||||
body: Some(text.clone()),
|
||||
});
|
||||
*reported = Some(text);
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentObserver for SwiftLint {
|
||||
fn opened(&self, info: &DocumentInfo) {
|
||||
let path = info.path.to_path_buf();
|
||||
self.queue(&path, if info.dirty { Job::Buffer(info.text.clone()) } else { Job::Saved });
|
||||
}
|
||||
|
||||
fn changed(
|
||||
&self,
|
||||
_doc: ide_core::DocId,
|
||||
path: &Path,
|
||||
_version: u32,
|
||||
_changes: &[AppliedChange],
|
||||
full_text: &dyn Fn() -> String,
|
||||
) {
|
||||
if path.extension().is_some_and(|e| e == "swift") {
|
||||
self.queue(path, Job::Buffer(full_text()));
|
||||
}
|
||||
}
|
||||
|
||||
fn saved(&self, _doc: ide_core::DocId, path: &Path, _text: &str) {
|
||||
self.queue(path, Job::Saved);
|
||||
}
|
||||
|
||||
/// A closed buffer's unsaved text is gone, and with it what its diagnostics described.
|
||||
fn closed(&self, _doc: ide_core::DocId, path: &Path) {
|
||||
self.pending.lock().remove(path);
|
||||
self.publish(path.to_path_buf(), Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder of the `.swiftlint.yml` nearest to `file` within the project, where SwiftLint
|
||||
/// runs so it finds that configuration. Files outside the project, or below no configuration,
|
||||
/// are not linted.
|
||||
fn config_dir(root: &Path, file: &Path) -> Option<PathBuf> {
|
||||
file.ancestors()
|
||||
.skip(1)
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find(|d| d.join(CONFIG).is_file())
|
||||
.map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// Runs `swiftlint lint` in `dir` on the saved `file`, or on `text` through stdin;
|
||||
/// `None` when `cancel` fires first, which kills it.
|
||||
async fn lint(
|
||||
dir: &Path,
|
||||
file: &Path,
|
||||
text: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<std::io::Result<Output>> {
|
||||
let mut cmd = std::process::Command::new("swiftlint");
|
||||
cmd.args(["lint", "--reporter", "json", "--quiet", "--no-cache"]).current_dir(dir);
|
||||
match text {
|
||||
Some(_) => cmd.arg("--use-stdin"),
|
||||
None => cmd.arg("--force-exclude").arg(file),
|
||||
};
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
cmd.stdin(if text.is_some() { Stdio::piped() } else { Stdio::null() });
|
||||
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut cmd = tokio::process::Command::from(cmd);
|
||||
cmd.kill_on_drop(true);
|
||||
let run = async {
|
||||
let mut child = cmd.spawn()?;
|
||||
if let (Some(text), Some(mut stdin)) = (text, child.stdin.take()) {
|
||||
stdin.write_all(text.as_bytes()).await?;
|
||||
}
|
||||
child.wait_with_output().await
|
||||
};
|
||||
tokio::select! {
|
||||
output = run => Some(output),
|
||||
() = cancel.cancelled() => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of SwiftLint's JSON report; `line` and `character` are 1-based, the
|
||||
/// character counted in UTF-16 units.
|
||||
#[derive(Debug, Deserialize, PartialEq)]
|
||||
struct Violation {
|
||||
line: Option<u32>,
|
||||
character: Option<u32>,
|
||||
reason: String,
|
||||
rule_id: String,
|
||||
severity: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Report {
|
||||
Violations(Vec<Violation>),
|
||||
/// `--force-exclude` dropped the file: the configuration's `excluded` lists it.
|
||||
Excluded,
|
||||
}
|
||||
|
||||
/// The `--reporter json` report (SwiftLint exits with 2 when it has errors), or the text
|
||||
/// to report when there is none.
|
||||
fn parse(stdout: &str, stderr: &str) -> Result<Report, String> {
|
||||
if let Ok(violations) = serde_json::from_str::<Vec<Violation>>(stdout.trim()) {
|
||||
return Ok(Report::Violations(violations));
|
||||
}
|
||||
if stderr.contains("No lintable files found") {
|
||||
return Ok(Report::Excluded);
|
||||
}
|
||||
let lines: Vec<&str> = stderr.lines().chain(stdout.lines()).map(str::trim).filter(|l| !l.is_empty()).collect();
|
||||
if lines.is_empty() {
|
||||
return Err("SwiftLint ended with no report".into());
|
||||
}
|
||||
Err(lines.iter().take(20).copied().collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
|
||||
fn diagnostic(v: Violation, text: &str) -> Diagnostic {
|
||||
Diagnostic {
|
||||
range: range(text, v.line, v.character),
|
||||
severity: if v.severity.eq_ignore_ascii_case("error") { Severity::Error } else { Severity::Warning },
|
||||
message: v.reason,
|
||||
source: Some("SwiftLint".into()),
|
||||
server: Some(SOURCE.into()),
|
||||
code: Some(v.rule_id),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The word at the reported position, or the line from its first non-blank character when
|
||||
/// SwiftLint gives no column (or the column has no word: a semicolon, a brace).
|
||||
fn range(text: &str, line: Option<u32>, character: Option<u32>) -> Range {
|
||||
let line = line.unwrap_or(1).max(1) - 1;
|
||||
let content = text.strip_prefix('\u{feff}').unwrap_or(text).split('\n').nth(line as usize).unwrap_or("");
|
||||
let content: Vec<u16> = content.trim_end().encode_utf16().collect();
|
||||
let len = u32::try_from(content.len()).unwrap_or(u32::MAX);
|
||||
let Some(start) = character.map(|c| c.max(1) - 1).filter(|&c| c < len) else {
|
||||
let indent = content.iter().take_while(|&&u| u == u16::from(b' ') || u == u16::from(b'\t')).count();
|
||||
return Range { start: Pos { line, col: indent as u32 }, end: Pos { line, col: len } };
|
||||
};
|
||||
let word = |u: &u16| char::from_u32(u32::from(*u)).is_some_and(|c| c.is_alphanumeric() || c == '_');
|
||||
let run = content[start as usize..].iter().take_while(|u| word(u)).count() as u32;
|
||||
Range { start: Pos { line, col: start }, end: Pos { line, col: start + run.max(1) } }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const REPORT: &str = r#"[
|
||||
{"character": 5, "file": null, "line": 1, "reason": "Variable name 'a_b' should only contain alphanumeric characters",
|
||||
"rule_id": "identifier_name", "severity": "Error", "type": "Identifier Name"},
|
||||
{"character": null, "file": "/p/A.swift", "line": 3, "reason": "Line should be 40 characters or less",
|
||||
"rule_id": "line_length", "severity": "Warning", "type": "Line Length"},
|
||||
{"character": 13, "file": null, "line": 2, "reason": "Lines should not have trailing semicolons",
|
||||
"rule_id": "trailing_semicolon", "severity": "Warning", "type": "Trailing Semicolon"}
|
||||
]"#;
|
||||
|
||||
#[test]
|
||||
fn violations_map_to_diagnostics() {
|
||||
let Ok(Report::Violations(violations)) = parse(REPORT, "") else { panic!() };
|
||||
let text = "let a_b = 1\nlet 😀x = 1 ;\n let long = 2\n";
|
||||
let items: Vec<Diagnostic> = violations.into_iter().map(|v| diagnostic(v, text)).collect();
|
||||
let summary: Vec<_> = items.iter().map(|d| (d.code.as_deref().unwrap(), d.severity, d.range)).collect();
|
||||
let r = |line, a, b| Range { start: Pos { line, col: a }, end: Pos { line, col: b } };
|
||||
assert_eq!(
|
||||
summary,
|
||||
[
|
||||
("identifier_name", Severity::Error, r(0, 4, 7)),
|
||||
// No column: the line from its first non-blank character.
|
||||
("line_length", Severity::Warning, r(2, 4, 16)),
|
||||
// UTF-16 columns: the emoji takes two, and a semicolon gets one.
|
||||
("trailing_semicolon", Severity::Warning, r(1, 12, 13)),
|
||||
]
|
||||
);
|
||||
assert_eq!((items[0].source.as_deref(), items[0].server.as_deref()), (Some("SwiftLint"), Some("swiftlint")));
|
||||
assert!(items[0].message.starts_with("Variable name 'a_b'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_files_and_failures_are_told_apart() {
|
||||
assert_eq!(parse("[]\n", ""), Ok(Report::Violations(vec![])));
|
||||
let excluded = "Error: No lintable files found at paths: 'Gen/g.swift'\n";
|
||||
assert_eq!(parse("", excluded), Ok(Report::Excluded));
|
||||
assert_eq!(parse("", "Fatal error: crashed\n\n"), Err("Fatal error: crashed".into()));
|
||||
assert_eq!(parse("", ""), Err("SwiftLint ended with no report".into()));
|
||||
// A bad column or line stays on the text.
|
||||
assert_eq!(
|
||||
range("x", Some(9), Some(40)),
|
||||
Range { start: Pos { line: 8, col: 0 }, end: Pos { line: 8, col: 0 } }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearest_configuration_in_the_project_wins() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("p");
|
||||
std::fs::create_dir_all(root.join("Sources/App")).unwrap();
|
||||
std::fs::create_dir_all(root.join("Pkg/Sources")).unwrap();
|
||||
let file = root.join("Sources/App/A.swift");
|
||||
assert_eq!(config_dir(&root, &file), None);
|
||||
std::fs::write(dir.path().join(CONFIG), "").unwrap();
|
||||
assert_eq!(config_dir(&root, &file), None, "a configuration above the project is not the project's");
|
||||
std::fs::write(root.join(CONFIG), "").unwrap();
|
||||
std::fs::write(root.join("Pkg").join(CONFIG), "").unwrap();
|
||||
assert_eq!(config_dir(&root, &file), Some(root.clone()));
|
||||
assert_eq!(config_dir(&root, &root.join("Pkg/Sources/B.swift")), Some(root.join("Pkg")));
|
||||
}
|
||||
}
|
||||
@@ -267,6 +267,10 @@ impl crate::Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.interrupt();
|
||||
}
|
||||
if let Some(swiftlint) = &project.swiftlint {
|
||||
let docs = project.documents.open_documents();
|
||||
swiftlint.trust_changed(trusted, docs.into_iter().filter_map(|d| project.documents.snapshot(d).ok()));
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.apply(&self.runtime);
|
||||
}
|
||||
|
||||
@@ -1603,14 +1603,15 @@ async fn post(server: &ide_mcp::McpServer, body: &Value) -> Value {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_open_in_a_window_answers_before_any_background_project() {
|
||||
async fn a_project_open_in_a_window_answers_for_its_folders_that_no_nested_project_holds() {
|
||||
let h = Harness::new();
|
||||
let inventory = h.serve_inventory();
|
||||
// A listed folder inside the open project: the window's project answers for it.
|
||||
h.set("backgroundProjectPaths", json!([inventory, h.root.join("src")]));
|
||||
// A listed folder around the open project leaves the project's folders to its window.
|
||||
let around = h.root.parent().unwrap().to_path_buf();
|
||||
h.set("backgroundProjectPaths", json!([inventory, around]));
|
||||
let (server, discovery) = h.server();
|
||||
let inside = json!({"projectPath": h.root.join("src"), "file_path": "src/b.txt"});
|
||||
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside.clone()}));
|
||||
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside}));
|
||||
let replies = bridged(&discovery, &inventory, &[read]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
|
||||
assert!(h.background().is_empty());
|
||||
@@ -1621,13 +1622,13 @@ async fn a_project_open_in_a_window_answers_before_any_background_project() {
|
||||
let unnamed = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/b.txt"}}));
|
||||
let reply = post(&server, &unnamed).await;
|
||||
assert_eq!(reply["result"]["content"][0]["text"], "L1: needle\nL2: ", "{reply}");
|
||||
// Nor does a background project loaded inside the window's project take its folder over.
|
||||
// A folder listed inside the window's project is a project of its own (#7040).
|
||||
let nested = h.root.join("src");
|
||||
h.call_at(&nested, "read_file", json!({"file_path":"b.txt"})).await.unwrap();
|
||||
assert_eq!(h.background(), [inventory.clone(), nested]);
|
||||
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":inside}));
|
||||
h.set("backgroundProjectPaths", json!([inventory, around, nested]));
|
||||
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"projectPath":nested,"file_path":"b.txt"}}));
|
||||
let replies = bridged(&discovery, &inventory, &[read]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
|
||||
assert_eq!(h.background(), [inventory.clone(), nested]);
|
||||
// A second window on another root is served as before.
|
||||
let second = h.root.parent().unwrap().join("second");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
@@ -1638,6 +1639,61 @@ async fn a_project_open_in_a_window_answers_before_any_background_project() {
|
||||
assert_eq!(h.background().len(), 2);
|
||||
}
|
||||
|
||||
/// The layout of #7040: `marker.txt` in the window's project and in `contracts`, a trusted
|
||||
/// repository inside it that trusted mode serves in the background.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_nested_trusted_project_answers_for_its_folders_whether_or_not_a_window_is_open_around_it() {
|
||||
let h = Harness::new();
|
||||
std::fs::write(h.root.join("marker.txt"), "from packages").unwrap();
|
||||
let contracts = h.root.join("contracts");
|
||||
std::fs::create_dir_all(contracts.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(contracts.join("src")).unwrap();
|
||||
std::fs::write(contracts.join("marker.txt"), "from contracts").unwrap();
|
||||
std::fs::write(contracts.join("src/only.txt"), "only in contracts").unwrap();
|
||||
h.trust().await;
|
||||
h.host.trust.decide(&contracts, true, false).unwrap();
|
||||
h.set("enabled", json!(true));
|
||||
h.set("backgroundProjects", json!("trusted"));
|
||||
let (server, discovery) = h.server();
|
||||
let read = |file: &str| {
|
||||
let arguments = json!({"projectPath": contracts, "file_path": file});
|
||||
rpc(1, "tools/call", json!({"name":"read_file","arguments":arguments}))
|
||||
};
|
||||
let text = |reply: Value| reply["result"]["content"][0]["text"].as_str().map(str::to_owned).ok_or(reply);
|
||||
|
||||
h.host.close_project("main");
|
||||
assert_eq!(text(post(&server, &read("marker.txt")).await), Ok("L1: from contracts".to_owned()));
|
||||
// A window opens on the folder around it between two calls.
|
||||
h.host.open_project("main", &h.root).unwrap();
|
||||
assert_eq!(text(post(&server, &read("marker.txt")).await), Ok("L1: from contracts".to_owned()));
|
||||
assert_eq!(text(post(&server, &read("src/only.txt")).await), Ok("L1: only in contracts".to_owned()));
|
||||
let roots = rpc(2, "tools/call", json!({"name":"get_workspace_roots","arguments":{"projectPath":contracts}}));
|
||||
let roots = post(&server, &roots).await;
|
||||
assert_eq!(roots["result"]["structuredContent"]["projectRoot"], json!(contracts), "{roots}");
|
||||
// The stdio bridge started in the nested project reaches it too.
|
||||
let unnamed = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"file_path":"marker.txt"}}));
|
||||
let replies = bridged(&discovery, &contracts.join("src"), &[unnamed]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: from contracts", "{replies:?}");
|
||||
assert_eq!(h.background(), std::slice::from_ref(&contracts));
|
||||
|
||||
// A folder of the window's project that no nested project holds stays with the window.
|
||||
let outside = json!({"projectPath": h.root.join("src"), "file_path": "marker.txt"});
|
||||
let reply = post(&server, &rpc(4, "tools/call", json!({"name":"read_file","arguments":outside}))).await;
|
||||
assert_eq!(text(reply), Ok("L1: from packages".to_owned()));
|
||||
assert_eq!(h.background(), std::slice::from_ref(&contracts), "it loads nothing");
|
||||
|
||||
// A remote window's project at the same path keeps its folders, the nested one included:
|
||||
// they are that host's.
|
||||
h.host.close_project("main");
|
||||
h.host.mcp_reports.set_remote("remote", h.root.clone());
|
||||
let reply = post(&server, &read("marker.txt")).await;
|
||||
assert_eq!(
|
||||
reply["result"]["content"][0]["text"],
|
||||
"project is on a remote host; connect to the MCP server on that host"
|
||||
);
|
||||
h.host.close_project_detached("remote");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
|
||||
let h = Harness::new();
|
||||
|
||||
@@ -1590,6 +1590,28 @@ fn misbehave_with_language(dir: &Path) -> PathBuf {
|
||||
pkg
|
||||
}
|
||||
|
||||
/// A language activation fired before the plugin was there (a remote server gets the desktop's
|
||||
/// packages after the window opened its files; a plugin installed with such a file open)
|
||||
/// activates it once it loads; one that never fired doesn't.
|
||||
#[test]
|
||||
fn plugins_loaded_after_their_activation_event_fired_activate() {
|
||||
use ide_extension::ActivationEvent;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = Arc::new(
|
||||
PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
|
||||
);
|
||||
host.load_all();
|
||||
host.startup_finished();
|
||||
host.activation_event(&ActivationEvent::Language("other".into()), None);
|
||||
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
|
||||
assert_eq!(host.info_of("misbehave").unwrap().status, PluginStatus::Inactive);
|
||||
host.uninstall("misbehave").unwrap();
|
||||
|
||||
host.activation_event(&ActivationEvent::Language("mis".into()), None);
|
||||
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
|
||||
assert!(eventually(|| host.info_of("misbehave").is_ok_and(|i| i.status == PluginStatus::Active)));
|
||||
}
|
||||
|
||||
/// Edit-path calls stop waiting at the soft deadline (the result is
|
||||
/// dropped, the instance kept) and are interrupted at the hard one.
|
||||
#[test]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use base64::Engine;
|
||||
use hyper_util::client::proxy::matcher::Matcher;
|
||||
use ide_core::proxy_settings::ProxyRoute;
|
||||
use ide_core::proxy_settings::{ProxyRoute, ProxySettings};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -21,28 +21,41 @@ const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = |_| None;
|
||||
/// (or, in Auto mode, the system) routes that host to.
|
||||
pub async fn connect(url: &reqwest::Url) -> IdeResult<TcpStream> {
|
||||
let route = ide_core::proxy_settings::proxy().route(url.host_str());
|
||||
connect_with(url, route, SYSTEM_PAC, Matcher::from_system).await
|
||||
connect_with(url, route, SYSTEM_PAC, Matcher::from_system, false).await
|
||||
}
|
||||
|
||||
/// [`connect`] under explicit proxy `settings`; a proxy the tunnel cannot speak to (SOCKS) is skipped and
|
||||
/// the connection goes direct, as it did before the proxy was consulted at all.
|
||||
pub async fn connect_best_effort(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult<TcpStream> {
|
||||
connect_with(url, settings.route(url.host_str()), SYSTEM_PAC, Matcher::from_system, true).await
|
||||
}
|
||||
|
||||
/// `host:port`; `host_str` already brackets an IPv6 address (the same rule as `pac.rs`'s `authority`).
|
||||
fn authority(host: &str, port: u16) -> String {
|
||||
if host.contains(':') && !host.starts_with('[') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }
|
||||
}
|
||||
|
||||
/// The URI the system proxy settings are asked about: the scheme reqwest would use (`ws` → `http`).
|
||||
fn system_uri(url: &reqwest::Url) -> IdeResult<http::Uri> {
|
||||
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
|
||||
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
|
||||
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let target = authority(host, port);
|
||||
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
|
||||
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))
|
||||
}
|
||||
|
||||
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected.
|
||||
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected;
|
||||
/// `skip_unusable` sends a route the tunnel cannot speak to direct instead of failing.
|
||||
async fn connect_with(
|
||||
url: &reqwest::Url,
|
||||
route: ProxyRoute,
|
||||
pac: impl FnOnce(&str) -> Option<ProxyRoute> + Send + 'static,
|
||||
matcher: impl FnOnce() -> Matcher,
|
||||
skip_unusable: bool,
|
||||
) -> IdeResult<TcpStream> {
|
||||
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
|
||||
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
|
||||
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let target = authority(host, port);
|
||||
let proxy = match route {
|
||||
ProxyRoute::Direct => None,
|
||||
ProxyRoute::Via(via) => Some(via),
|
||||
@@ -75,6 +88,7 @@ async fn connect_with(
|
||||
}
|
||||
}
|
||||
};
|
||||
let proxy = proxy.filter(|proxy| !skip_unusable || proxy.starts_with("http://"));
|
||||
let connecting = async {
|
||||
let Some(proxy) = proxy else {
|
||||
return TcpStream::connect(&target).await.map_err(|error| reach(&target, &error));
|
||||
@@ -219,7 +233,7 @@ mod tests {
|
||||
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
|
||||
};
|
||||
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap();
|
||||
assert_eq!(*seen.lock().unwrap(), "http://pac-target.invalid:8080/");
|
||||
assert!(asked(pac_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
|
||||
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
|
||||
@@ -235,7 +249,7 @@ mod tests {
|
||||
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
|
||||
};
|
||||
let url = reqwest::Url::parse("wss://pac-target.invalid/s").unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build()).await.unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build(), false).await.unwrap();
|
||||
assert_eq!(*seen.lock().unwrap(), "https://pac-target.invalid:443/");
|
||||
}
|
||||
|
||||
@@ -244,7 +258,7 @@ mod tests {
|
||||
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
|
||||
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy))
|
||||
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy), false)
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::timeout(Duration::from_millis(300), listener.accept())
|
||||
@@ -259,10 +273,30 @@ mod tests {
|
||||
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
|
||||
let pac = |_: &str| Some(ProxyRoute::Via("socks5h://127.0.0.1:1080".into()));
|
||||
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap();
|
||||
assert!(asked(matcher_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unusable_proxy_is_skipped_only_when_asked() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
|
||||
let socks = || ProxyRoute::Via("socks5h://127.0.0.1:1".into());
|
||||
let none = || Matcher::builder().build();
|
||||
assert!(connect_with(&url, socks(), |_| None, none, false).await.unwrap_err().message.contains("socks5h"));
|
||||
connect_with(&url, socks(), |_| None, none, true).await.unwrap();
|
||||
listener.accept().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_ipv6_literal_is_connected_to() {
|
||||
let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here
|
||||
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
|
||||
connect_with(&url, ProxyRoute::Direct, |_| None, || Matcher::builder().build(), false).await.unwrap();
|
||||
listener.accept().await.unwrap();
|
||||
assert_eq!(authority("[::1]", 9), "[::1]:9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_credentials_are_percent_decoded() {
|
||||
assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c");
|
||||
|
||||
@@ -32,6 +32,7 @@ tree-sitter-java = "0.23.5"
|
||||
tree-sitter-kotlin-ng = "1.1.0"
|
||||
tree-sitter-c = "0.24.2"
|
||||
tree-sitter-cpp = "0.23.4"
|
||||
tree-sitter-objc = "3.0.2"
|
||||
tree-sitter-c-sharp = "0.23.5"
|
||||
tree-sitter-ruby = "0.23.1"
|
||||
tree-sitter-php = "0.25.1"
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
(class_interface . (identifier) @name category: (identifier) @detail) @def.extension
|
||||
(class_implementation . (identifier) @name category: (identifier) @detail) @def.extension
|
||||
(class_interface . (identifier) @name) @def.class
|
||||
(class_implementation . (identifier) @name) @def.class
|
||||
(protocol_declaration . (identifier) @name) @def.interface
|
||||
|
||||
(method_declaration ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method
|
||||
(method_definition ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method
|
||||
(property_declaration (struct_declaration (struct_declarator [
|
||||
(identifier) @name
|
||||
(pointer_declarator declarator: (identifier) @name)
|
||||
(function_declarator declarator: (parenthesized_declarator (block_pointer_declarator declarator: (identifier) @name)))
|
||||
]))) @def.property
|
||||
(instance_variable (struct_declaration (struct_declarator [
|
||||
(identifier) @name
|
||||
(pointer_declarator declarator: (identifier) @name)
|
||||
]))) @def.field
|
||||
|
||||
(preproc_call directive: (preproc_directive) @_d argument: (preproc_arg) @name
|
||||
(#eq? @_d "#pragma") (#match? @name "^mark\\s")) @outline.heading
|
||||
|
||||
(function_definition
|
||||
declarator: [
|
||||
(function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)
|
||||
(pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))
|
||||
(pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)))
|
||||
]) @def.function
|
||||
(translation_unit (declaration
|
||||
declarator: [
|
||||
(function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)
|
||||
(pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))
|
||||
]) @def.function)
|
||||
|
||||
(struct_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct
|
||||
(union_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct
|
||||
(enum_specifier name: (type_identifier) @name body: (enumerator_list)) @def.enum
|
||||
(enumerator name: (identifier) @name) @def.enum_member
|
||||
(field_declaration_list (field_declaration declarator: [
|
||||
(field_identifier) @name
|
||||
(pointer_declarator declarator: (field_identifier) @name)
|
||||
(array_declarator declarator: (field_identifier) @name)
|
||||
]) @def.field)
|
||||
(type_definition declarator: (type_identifier) @name) @def.type
|
||||
(preproc_def name: (identifier) @name) @def.macro
|
||||
(preproc_function_def name: (identifier) @name parameters: (preproc_params) @detail) @def.macro
|
||||
(translation_unit (declaration declarator: [
|
||||
(identifier) @name
|
||||
(init_declarator declarator: (identifier) @name)
|
||||
(init_declarator declarator: (pointer_declarator declarator: (identifier) @name))
|
||||
]) @def.variable)
|
||||
@@ -90,6 +90,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("slint", include_str!("../../../languages/slint.toml")),
|
||||
("sql", include_str!("../../../languages/sql.toml")),
|
||||
("svelte", include_str!("../../../languages/svelte.toml")),
|
||||
("strings", include_str!("../../../languages/strings.toml")),
|
||||
("swift", include_str!("../../../languages/swift.toml")),
|
||||
("terraform", include_str!("../../../languages/terraform.toml")),
|
||||
("terraform-vars", include_str!("../../../languages/terraform-vars.toml")),
|
||||
@@ -98,6 +99,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("typescriptreact", include_str!("../../../languages/typescriptreact.toml")),
|
||||
("typst", include_str!("../../../languages/typst.toml")),
|
||||
("vue", include_str!("../../../languages/vue.toml")),
|
||||
("xcconfig", include_str!("../../../languages/xcconfig.toml")),
|
||||
("xml", include_str!("../../../languages/xml.toml")),
|
||||
("yaml", include_str!("../../../languages/yaml.toml")),
|
||||
("zig", include_str!("../../../languages/zig.toml")),
|
||||
@@ -1277,6 +1279,11 @@ mod tests {
|
||||
("P.cs", "csharp"),
|
||||
("V.swift", "swift"),
|
||||
("AppDelegate.m", "objective-c"),
|
||||
("App.entitlements", "xml"),
|
||||
("PrivacyInfo.xcprivacy", "xml"),
|
||||
("Localizable.xcstrings", "json"),
|
||||
("Debug.xcconfig", "xcconfig"),
|
||||
("en.lproj/Localizable.strings", "strings"),
|
||||
("a.rb", "ruby"),
|
||||
("Gemfile", "ruby"),
|
||||
("show.html.erb", "erb"),
|
||||
|
||||
@@ -156,6 +156,24 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
imports: &["preproc_include", "using_declaration"],
|
||||
constructors: NONE,
|
||||
},
|
||||
Spec {
|
||||
name: "objc",
|
||||
language: tree_sitter_objc::LANGUAGE,
|
||||
outline: outline!("objc"),
|
||||
highlights: None,
|
||||
// `@interface` / `@implementation` / `@protocol` ... `@end` have no brackets.
|
||||
fold_nodes: &[
|
||||
"class_interface",
|
||||
"class_implementation",
|
||||
"protocol_declaration",
|
||||
"preproc_if",
|
||||
"preproc_ifdef",
|
||||
"preproc_function_def",
|
||||
],
|
||||
fold_bodies: NONE,
|
||||
imports: &["preproc_include", "module_import"],
|
||||
constructors: NONE,
|
||||
},
|
||||
Spec {
|
||||
name: "csharp",
|
||||
language: tree_sitter_c_sharp::LANGUAGE,
|
||||
|
||||
@@ -180,7 +180,11 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
|
||||
}
|
||||
names.sort_by_key(|n| n.start_byte());
|
||||
names.dedup_by_key(|n| n.id());
|
||||
let base = names.iter().map(|n| name_text(n, text)).collect::<Vec<_>>().join(".");
|
||||
let mut base = names.iter().map(|n| name_text(n, text)).collect::<Vec<_>>().join(".");
|
||||
// Objective-C selectors: `- (id)initWithName:(id)n age:(int)a` is `initWithName:age:`.
|
||||
if g.spec.name == "objc" && node.children(&mut node.walk()).any(|c| c.kind() == "method_parameter") {
|
||||
base = names.iter().map(|n| format!("{}:", name_text(n, text))).collect();
|
||||
}
|
||||
if base.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -539,6 +543,12 @@ fn name_text(n: &Node, text: &str) -> String {
|
||||
let t = node_text(n, text);
|
||||
// Ruby / Elixir symbols: `:total` -> `total`.
|
||||
let t = if matches!(n.kind(), "simple_symbol" | "atom") { t.trim_start_matches(':') } else { t };
|
||||
// Objective-C `#pragma mark - Lifecycle` -> `Lifecycle` (a bare `mark -` is a separator, so empty).
|
||||
let t = if n.kind() == "preproc_arg" {
|
||||
t.trim().trim_start_matches("mark").trim_start().trim_start_matches('-')
|
||||
} else {
|
||||
t
|
||||
};
|
||||
clean(t, 120)
|
||||
}
|
||||
|
||||
|
||||
@@ -546,6 +546,119 @@ int main() { return 0; }
|
||||
assert_eq!(t.iter().filter(|(n, k, _)| n == "draw" && *k == SymbolKind::Method).count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_objc() {
|
||||
let src = r#"#import <Foundation/Foundation.h>
|
||||
#define MAX 10
|
||||
@protocol Greeting <NSObject>
|
||||
- (NSString *)greet;
|
||||
@optional
|
||||
@property (nonatomic) int level;
|
||||
@end
|
||||
|
||||
@interface Person : NSObject <Greeting> {
|
||||
int _age;
|
||||
}
|
||||
@property (nonatomic, copy) NSString *name;
|
||||
+ (instancetype)personWithName:(NSString *)name age:(int)age;
|
||||
- (void)run;
|
||||
@end
|
||||
|
||||
@interface Person (Extra)
|
||||
- (void)extra;
|
||||
@end
|
||||
|
||||
@implementation Person
|
||||
#pragma mark - Lifecycle
|
||||
+ (instancetype)personWithName:(NSString *)name age:(int)age {
|
||||
return nil;
|
||||
}
|
||||
- (void)run {
|
||||
}
|
||||
@end
|
||||
|
||||
static int helper(int x) { return x; }
|
||||
"#;
|
||||
check_outline(
|
||||
"objective-c",
|
||||
src,
|
||||
"
|
||||
Macro MAX
|
||||
Interface Greeting
|
||||
Method greet
|
||||
Property level
|
||||
Class Person
|
||||
Field _age
|
||||
Property name
|
||||
Method personWithName:age:
|
||||
Method run
|
||||
Namespace Person
|
||||
Method extra
|
||||
Class Person
|
||||
Key Lifecycle
|
||||
Method personWithName:age:
|
||||
Method run
|
||||
Function helper
|
||||
",
|
||||
);
|
||||
let t = tags("objective-c", src);
|
||||
assert!(has_tag(&t, "greet", SymbolKind::Method, Some("Greeting")));
|
||||
assert!(has_tag(&t, "personWithName:age:", SymbolKind::Method, Some("Person")));
|
||||
assert!(has_tag(&t, "extra", SymbolKind::Method, Some("Person")));
|
||||
assert!(has_tag(&t, "name", SymbolKind::Property, Some("Person")));
|
||||
assert!(!t.iter().any(|(n, _, _)| n == "Lifecycle"));
|
||||
let t = tags("objective-c", "@interface A\n@property (copy) void (^onTap)(int i);\n@end\n");
|
||||
assert!(has_tag(&t, "onTap", SymbolKind::Property, Some("A")), "{t:?}");
|
||||
// `@interface` / `@protocol` / `@implementation` ... `@end` fold like a braced body.
|
||||
let f = folds("objective-c", src);
|
||||
for range in [(2, 6), (8, 14), (16, 18), (20, 27), (22, 24)] {
|
||||
assert!(f.contains(&(range.0, range.1, FoldKind::Region)), "{range:?} not in {f:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_objective_cpp_keeps_the_objc_structure() {
|
||||
// C++ declarations outside the ObjC blocks are lost to error recovery; the ObjC
|
||||
// classes and methods, which are why a file is `.mm`, stay.
|
||||
check_outline(
|
||||
"objective-cpp",
|
||||
r#"#import "Bridge.h"
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
namespace engine {
|
||||
class Renderer {
|
||||
public:
|
||||
void draw(const std::vector<int> &xs);
|
||||
};
|
||||
}
|
||||
|
||||
@implementation Bridge {
|
||||
std::unique_ptr<engine::Renderer> _renderer;
|
||||
}
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
_renderer = std::make_unique<engine::Renderer>();
|
||||
return self;
|
||||
}
|
||||
- (void)drawValues:(NSArray<NSNumber *> *)values {
|
||||
std::vector<int> xs;
|
||||
for (NSNumber *n in values) { xs.push_back(n.intValue); }
|
||||
_renderer->draw(xs);
|
||||
}
|
||||
@end
|
||||
|
||||
static std::string helper() { return "x"; }
|
||||
"#,
|
||||
"
|
||||
Class Bridge
|
||||
Method init
|
||||
Method drawValues:
|
||||
Function helper
|
||||
",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_csharp() {
|
||||
check_outline(
|
||||
|
||||
@@ -122,10 +122,24 @@ pub fn configure_project_structure(
|
||||
// JDT resolves relative library globs against its own root, which may be a submodule.
|
||||
Some(root.join(trimmed).to_string_lossy().replace('\\', "/"))
|
||||
};
|
||||
let normalize_class = |entry: &str| -> Option<String> {
|
||||
let trimmed = entry.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let resolved = root.join(trimmed);
|
||||
let path = resolved.to_string_lossy().replace('\\', "/");
|
||||
// A directory library root (e.g. `WebRoot/WEB-INF/lib`) needs a `**/*.jar` glob so jdtls
|
||||
// indexes the JAR archives inside it rather than ignoring the bare folder path.
|
||||
if resolved.is_dir() && !ide_core::settings::jar_files(&resolved, true).is_empty() {
|
||||
return Some(format!("{}/**/*.jar", path.trim_end_matches('/')));
|
||||
}
|
||||
Some(path)
|
||||
};
|
||||
let mut include: Vec<String> = Vec::new();
|
||||
let mut sources = serde_json::Map::new();
|
||||
for lib in &structure.libraries {
|
||||
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize(c)).collect();
|
||||
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize_class(c)).collect();
|
||||
let source_entries: Vec<String> = lib.sources.iter().filter_map(|s| normalize(s)).collect();
|
||||
for c in &class_entries {
|
||||
if !include.contains(c) {
|
||||
@@ -133,7 +147,9 @@ pub fn configure_project_structure(
|
||||
}
|
||||
}
|
||||
for (class, source) in class_entries.iter().zip(&source_entries) {
|
||||
sources.insert(class.clone(), json!(source));
|
||||
if !class.contains('*') {
|
||||
sources.insert(class.clone(), json!(source));
|
||||
}
|
||||
}
|
||||
}
|
||||
for facet in &structure.facets {
|
||||
@@ -1953,4 +1969,51 @@ mod tests {
|
||||
configure_project_structure(&mut cfg, tmp.path(), tmp.path(), &structure);
|
||||
assert!(cfg.launch_error.as_deref().unwrap().contains("inside its module"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_library_root_expands_to_recursive_jar_glob_for_jdtls() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let web_lib = root.join("WebRoot/WEB-INF/lib");
|
||||
std::fs::create_dir_all(&web_lib).unwrap();
|
||||
std::fs::write(web_lib.join("gson.jar"), b"").unwrap();
|
||||
|
||||
let structure = ide_core::settings::ProjectStructureSettings {
|
||||
libraries: vec![ide_core::settings::ProjectLibrary {
|
||||
name: "lib".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
sources: vec![],
|
||||
javadocs: vec![],
|
||||
scope: ide_core::settings::DependencyScope::Runtime,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mut cfg: ide_language::LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
|
||||
configure_project_structure(&mut cfg, root, root, &structure);
|
||||
|
||||
let include = cfg
|
||||
.settings
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.pointer("/java/project/referencedLibraries/include")
|
||||
.and_then(Value::as_array)
|
||||
.unwrap();
|
||||
let expected = format!("{}/**/*.jar", web_lib.to_string_lossy().replace('\\', "/"));
|
||||
assert!(include.contains(&json!(expected)), "include={include:?}");
|
||||
// A class folder without jars stays a plain path.
|
||||
let classes = root.join("classes");
|
||||
std::fs::create_dir_all(&classes).unwrap();
|
||||
let structure = ide_core::settings::ProjectStructureSettings {
|
||||
libraries: vec![ide_core::settings::ProjectLibrary {
|
||||
name: "classes".into(),
|
||||
classes: vec!["classes".into()],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mut cfg: ide_language::LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
|
||||
configure_project_structure(&mut cfg, root, root, &structure);
|
||||
let include = cfg.settings.as_ref().unwrap().pointer("/java/project/referencedLibraries/include").cloned();
|
||||
assert!(!format!("{include:?}").contains("classes/**"), "include={include:?}");
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ pub use jdtls::stream_trace::JdtStreamTracer;
|
||||
pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
|
||||
pub use launch::{LaunchError, Launcher, ProcessLauncher};
|
||||
pub use message_requests::answer as answer_message_request;
|
||||
pub use notebook::{NotebookCell, NotebookCellDoc, cell_uri};
|
||||
pub use notebook::{NotebookCell, NotebookCellDoc, NotebookCellText, cell_uri};
|
||||
pub use plugin_requests::plugin_method_allowed;
|
||||
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
|
||||
pub use uri::{path_to_uri_string, uri_target, uri_to_path};
|
||||
|
||||
@@ -40,6 +40,14 @@ pub struct NotebookCellDoc {
|
||||
pub uri: String,
|
||||
}
|
||||
|
||||
/// A cell document's buffer, as the notebook service keeps it.
|
||||
pub struct NotebookCellText {
|
||||
pub path: std::path::PathBuf,
|
||||
pub language: LanguageId,
|
||||
pub text: String,
|
||||
pub version: u32,
|
||||
}
|
||||
|
||||
pub(crate) struct NotebookState {
|
||||
uri: lsp::Uri,
|
||||
language: LanguageId,
|
||||
@@ -154,6 +162,22 @@ impl LspManager {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A cell document's buffer, for work that runs without asking a server — formatting reads
|
||||
/// it from `documents`, which only holds files the editor opened, never a notebook's cells.
|
||||
pub fn cell_text(&self, doc: DocId) -> Option<NotebookCellText> {
|
||||
let docs = self.docs.lock();
|
||||
let d = docs.get(&doc)?;
|
||||
// The notebook file, not the cell's own `vscode-notebook-cell:` uri: a formatter
|
||||
// looks the file up to find the project's settings and the language of the file.
|
||||
let path = d.notebook.clone()?;
|
||||
Some(NotebookCellText {
|
||||
path,
|
||||
language: d.language.clone(),
|
||||
text: d.text.as_str().to_owned(),
|
||||
version: d.version.max(0) as u32,
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens the notebooks of `server`'s language on its instance that just became ready.
|
||||
pub(crate) fn reopen_notebooks(&self, server: &Arc<Server>, run: &Running) {
|
||||
let mut pull = Vec::new();
|
||||
@@ -384,4 +408,27 @@ mod tests {
|
||||
assert!(is_cell_uri(&uri) && parse_uri(&uri).is_some());
|
||||
assert!(!is_cell_uri("file:///a.ipynb") && !is_cell_uri("vscode-notebook-cellx:/a"));
|
||||
}
|
||||
|
||||
/// A cell lives in `docs` only, never in `documents`; formatting asks for its buffer here.
|
||||
#[test]
|
||||
fn cell_text_answers_for_a_cell_document_and_nothing_else() {
|
||||
let manager = LspManager::new(
|
||||
PathBuf::from("/work"),
|
||||
std::sync::Arc::new(crate::LanguageRegistry::load(None).unwrap()),
|
||||
std::sync::Arc::new(|_: ide_core::IdeEvent| {}),
|
||||
);
|
||||
let path = PathBuf::from("/work/a.ipynb");
|
||||
let cells = [NotebookCell { id: "cell-a".into(), source: "x=1".into() }];
|
||||
manager.sync_notebook(&path, &LanguageId::new("python"), &cells);
|
||||
|
||||
let doc = manager.notebook_cells(&path)[0].doc;
|
||||
let text = manager.cell_text(doc).expect("a cell document answers");
|
||||
assert_eq!(text.text, "x=1");
|
||||
// The notebook file, so a formatter finds the project's settings for it.
|
||||
assert_eq!(text.path, path);
|
||||
assert_eq!(text.language.as_str(), "python");
|
||||
|
||||
// A document the notebook service does not know stays unknown.
|
||||
assert!(manager.cell_text(DocId(9999)).is_none());
|
||||
}
|
||||
}
|
||||
@@ -8824,3 +8824,51 @@ async fn switch_source_header_asks_clangd_and_only_clangd() {
|
||||
assert!(h.launcher.state("mock").requested("textDocument/switchSourceHeader").is_empty());
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// C-family files go to sourcekit-lsp in an Xcode project with a BSP config (`buildServer.json`),
|
||||
/// which hands them to clangd with the build's flags; elsewhere, and when sourcekit-lsp is missing,
|
||||
/// to plain clangd. Uses the shipped language definitions.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
for (language, ext) in [("c", "h"), ("cpp", "cpp"), ("objective-c", "m"), ("objective-cpp", "mm")] {
|
||||
let shipped = registry.get(&LanguageId::new(language)).unwrap().language_servers;
|
||||
let names: Vec<_> = shipped.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(names, ["sourcekit-lsp", "clangd"], "{language}");
|
||||
let servers = [("sourcekit-lsp", incremental_caps()), ("clangd", incremental_caps())];
|
||||
let as_shipped = |cfg: &mut LanguageServerConfig| {
|
||||
let real = shipped.iter().find(|c| c.name == cfg.name).unwrap();
|
||||
cfg.root_markers = real.root_markers.clone();
|
||||
cfg.require_root_marker = real.require_root_marker;
|
||||
cfg.replaces = real.replaces.clone();
|
||||
};
|
||||
let file = format!("Foo.{ext}");
|
||||
|
||||
// A plain folder, or one with only compile_commands.json: clangd alone.
|
||||
let h = harness_configured(language, ext, &servers, as_shipped);
|
||||
std::fs::write(h.root.join("compile_commands.json"), "[]").unwrap();
|
||||
h.open(&file, "");
|
||||
h.wait_status("clangd", ServerStatus::Ready).await;
|
||||
assert!(h.statuses("sourcekit-lsp").is_empty(), "{language}");
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// An Xcode project with buildServer.json: sourcekit-lsp alone, rooted at the config.
|
||||
let h = harness_configured(language, ext, &servers, as_shipped);
|
||||
std::fs::write(h.root.join("buildServer.json"), "{}").unwrap();
|
||||
let (_, path) = h.open(&file, "");
|
||||
h.wait_status("sourcekit-lsp", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("sourcekit-lsp").docs.lock().contains_key(&uri_of(&path))).await;
|
||||
assert!(h.statuses("clangd").is_empty(), "{language}");
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::<Vec<_>>(), std::slice::from_ref(&h.root));
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// sourcekit-lsp not installed: clangd still serves.
|
||||
let h = harness_configured(language, ext, &servers, as_shipped);
|
||||
h.launcher.state("sourcekit-lsp").missing.store(true, Ordering::SeqCst);
|
||||
std::fs::write(h.root.join("buildServer.json"), "{}").unwrap();
|
||||
h.open(&file, "");
|
||||
h.wait_status("sourcekit-lsp", ServerStatus::Missing).await;
|
||||
h.wait_status("clangd", ServerStatus::Ready).await;
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
}
|
||||
@@ -67,9 +67,10 @@ pub trait ToolRegistry: Send + Sync + 'static {
|
||||
/// Roots of the projects open in a window of the IDE that the server serves.
|
||||
fn projects(&self) -> Vec<PathBuf>;
|
||||
/// The root of the project the IDE serves `path` from without a window (a background
|
||||
/// project), asked when no project of [`Self::projects`] contains `path`. Opens nothing:
|
||||
/// the first call for that root does.
|
||||
fn resolve(&self, _path: &Path) -> Option<PathBuf> {
|
||||
/// project). `within` is the root of the innermost project of [`Self::projects`] that
|
||||
/// contains `path`, when one does: then only a root strictly inside it answers, and the
|
||||
/// open project keeps the path otherwise. Opens nothing: the first call for that root does.
|
||||
fn resolve(&self, _path: &Path, _within: Option<&Path>) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
/// The tools callable for `project` (one of [`Self::projects`] or a root
|
||||
|
||||
@@ -223,9 +223,7 @@ impl Session<'_> {
|
||||
roots.sort();
|
||||
roots.dedup();
|
||||
if let Some(requested) = requested.filter(|p| !p.trim().is_empty()) {
|
||||
let path = Path::new(requested);
|
||||
// An open project wins; the registry is asked only for a folder outside all of them.
|
||||
return resolve(&roots, path).or_else(|| self.registry.resolve(path)).ok_or_else(|| {
|
||||
return self.serving_root(&roots, Path::new(requested)).ok_or_else(|| {
|
||||
RpcError::new(
|
||||
NOT_OPEN,
|
||||
format!(
|
||||
@@ -247,10 +245,30 @@ impl Session<'_> {
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
/// The innermost project containing `path`, whether a window has it open (one of `roots`)
|
||||
/// or the registry serves it in the background, so the answer doesn't depend on which
|
||||
/// windows are open. Inside an open project the registry is asked only for a path below
|
||||
/// its root, about the folders inside that root: a folder of a window's project that no
|
||||
/// nested project holds loads nothing.
|
||||
fn serving_root(&self, roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
|
||||
let Some(open) = resolve(roots, path) else { return self.registry.resolve(path, None) };
|
||||
let nested = if open.below { self.registry.resolve(path, Some(&open.root)) } else { None };
|
||||
Some(nested.unwrap_or(open.root))
|
||||
}
|
||||
}
|
||||
|
||||
/// The innermost open project containing a path.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct OpenRoot {
|
||||
/// As the registry lists it.
|
||||
root: PathBuf,
|
||||
/// Whether the path lies below the root rather than at it.
|
||||
below: bool,
|
||||
}
|
||||
|
||||
/// The project among `roots` containing `path` (the innermost one).
|
||||
fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
|
||||
fn resolve(roots: &[PathBuf], path: &Path) -> Option<OpenRoot> {
|
||||
if !path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
@@ -274,7 +292,7 @@ fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
|
||||
path.starts_with(&canonical).then(|| (canonical.components().count(), root))
|
||||
})
|
||||
.max_by_key(|(depth, _)| *depth)
|
||||
.map(|(_, root)| root.clone())
|
||||
.map(|(depth, root)| OpenRoot { root: root.clone(), below: path.components().count() > depth })
|
||||
}
|
||||
|
||||
fn tool_json(tool: &Tool) -> Value {
|
||||
@@ -299,11 +317,15 @@ mod tests {
|
||||
let inner = outer.join("inner");
|
||||
std::fs::create_dir_all(inner.join("src")).unwrap();
|
||||
let roots = [outer.clone(), inner.clone()];
|
||||
assert_eq!(resolve(&roots, &inner.join("src")), Some(inner.clone()));
|
||||
assert_eq!(resolve(&roots, &outer.join("other")), Some(outer.clone()));
|
||||
assert_eq!(resolve(&roots[1..], &outer), None);
|
||||
assert_eq!(resolve(&roots, Path::new("relative/path")), None);
|
||||
let root = |roots: &[PathBuf], path: &Path| resolve(roots, path).map(|open| open.root);
|
||||
assert_eq!(root(&roots, &inner.join("src")), Some(inner.clone()));
|
||||
assert_eq!(root(&roots, &outer.join("other")), Some(outer.clone()));
|
||||
assert_eq!(root(&roots[1..], &outer), None);
|
||||
assert_eq!(root(&roots, Path::new("relative/path")), None);
|
||||
// Siblings sharing a prefix are not inside.
|
||||
assert_eq!(resolve(&roots[1..], &outer.join("inner-two")), None);
|
||||
assert_eq!(root(&roots[1..], &outer.join("inner-two")), None);
|
||||
// Only a path below the root is below it.
|
||||
assert_eq!(resolve(&roots, &inner), Some(OpenRoot { root: inner.clone(), below: false }));
|
||||
assert_eq!(resolve(&roots, &inner.join("src")), Some(OpenRoot { root: inner.clone(), below: true }));
|
||||
}
|
||||
}
|
||||
@@ -225,18 +225,22 @@ async fn folders_that_are_not_open_are_named_in_the_error() {
|
||||
assert!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"].is_array());
|
||||
}
|
||||
|
||||
/// One project open in a window and, optionally, one folder served without a window.
|
||||
/// One project open in a window and the folders served without a window.
|
||||
struct WithBackground {
|
||||
open: PathBuf,
|
||||
background: Option<PathBuf>,
|
||||
background: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl ToolRegistry for WithBackground {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
}
|
||||
fn resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
self.background.clone().filter(|root| path.starts_with(root))
|
||||
/// The innermost served folder containing `path`, strictly inside `within`, as the
|
||||
/// background policy answers.
|
||||
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
let inside = |root: &&PathBuf| within.is_none_or(|open| root.starts_with(open) && *root != open);
|
||||
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
|
||||
served.max_by_key(|root| root.components().count()).cloned()
|
||||
}
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(vec![Tool {
|
||||
@@ -253,13 +257,16 @@ impl ToolRegistry for WithBackground {
|
||||
}
|
||||
}
|
||||
|
||||
/// The server over [`WithBackground`]; the folder `inventory` next to the open project.
|
||||
fn setup_with_background(served: bool) -> (Setup, PathBuf) {
|
||||
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
|
||||
/// that holds the open project; the folder `inventory` next to the open project.
|
||||
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
|
||||
let mut s = setup();
|
||||
s.server.take().unwrap().stop();
|
||||
let inventory = s.project.parent().unwrap().join("inventory");
|
||||
let base = s.project.parent().unwrap().to_path_buf();
|
||||
let inventory = base.join("inventory");
|
||||
std::fs::create_dir_all(inventory.join("src")).unwrap();
|
||||
let registry = WithBackground { open: s.project.clone(), background: served.then(|| inventory.clone()) };
|
||||
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
|
||||
let registry = WithBackground { open: s.project.clone(), background };
|
||||
s.server = Some(
|
||||
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
|
||||
.unwrap(),
|
||||
@@ -277,7 +284,7 @@ async fn rpc_for(s: &Setup, folder: &Path, method: &str, params: Value) -> Value
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
let (s, inventory) = setup_with_background(true);
|
||||
let (s, inventory) = setup_with_background(&["inventory"]);
|
||||
let inside = inventory.join("src");
|
||||
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
@@ -296,9 +303,37 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
assert_eq!(open["result"]["structuredContent"]["project"], json!(s.project), "{open}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_served_in_the_background() {
|
||||
// The layout of #7040: a window on `project` and `contracts` inside it served in the
|
||||
// background. The policy serves the window's root and the folder around it as well, as
|
||||
// trusted projects and listed folders do.
|
||||
let (s, _) = setup_with_background(&["", "project", "project/contracts"]);
|
||||
let contracts = s.project.join("contracts");
|
||||
std::fs::create_dir_all(contracts.join("src")).unwrap();
|
||||
let base = s.project.parent().unwrap().to_path_buf();
|
||||
for (folder, served) in [
|
||||
(contracts.join("src"), &contracts),
|
||||
(contracts.clone(), &contracts),
|
||||
// Folders of the window's project that no nested project holds stay with the window.
|
||||
(s.project.join("src"), &s.project),
|
||||
(s.project.clone(), &s.project),
|
||||
(base.join("elsewhere"), &base),
|
||||
] {
|
||||
let at = folder.display();
|
||||
let call = rpc(&s, "tools/call", json!({ "name": "where", "arguments": { "projectPath": folder } })).await;
|
||||
assert_eq!(call["result"]["structuredContent"]["project"], json!(served), "{at}: {call}");
|
||||
let list = rpc_for(&s, &folder, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", served.display()), "{at}: {list}");
|
||||
let init = rpc_for(&s, &folder, "initialize", json!({})).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains(&format!("serves at {}:", served.display())), "{at}: {instructions}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
|
||||
let (s, inventory) = setup_with_background(false);
|
||||
let (s, inventory) = setup_with_background(&[]);
|
||||
for (method, params) in [("tools/list", json!({})), ("tools/call", json!({ "name": "where" }))] {
|
||||
let reply = rpc_for(&s, &inventory, method, params).await;
|
||||
assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! iOS Simulators, through `xcrun simctl` (macOS only): the devices an Xcode project can run on.
|
||||
//! iOS Simulators, through `xcrun simctl`, and connected iPhones and iPads, through
|
||||
//! `xcrun devicectl` (macOS only): the devices an Xcode project can run on.
|
||||
//!
|
||||
//! Flutter projects get theirs from `flutter daemon` (`ide-flutter`), so only native Xcode
|
||||
//! projects use this.
|
||||
@@ -11,7 +12,8 @@ use specta::Type;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
/// One simulator `simctl list devices available` reports.
|
||||
/// One simulator `simctl list devices available` reports, or one physical device
|
||||
/// `devicectl list devices` knows.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IosSimulator {
|
||||
@@ -19,10 +21,18 @@ pub struct IosSimulator {
|
||||
pub name: String,
|
||||
/// The runtime, as Xcode shows it: `iOS 27.0`.
|
||||
pub runtime: String,
|
||||
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`.
|
||||
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`],
|
||||
/// [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`].
|
||||
pub state: String,
|
||||
/// An iPhone or iPad rather than a simulator.
|
||||
pub physical: bool,
|
||||
}
|
||||
|
||||
/// The states of a physical device.
|
||||
pub const AVAILABLE: &str = "Available";
|
||||
pub const UNAVAILABLE: &str = "Unavailable";
|
||||
pub const DEVELOPER_MODE_OFF: &str = "Developer Mode Off";
|
||||
|
||||
/// An Xcode project or workspace directly in `root`, outside a Flutter project (whose
|
||||
/// `ios/Runner.xcodeproj` sits one level down and whose devices come from Flutter).
|
||||
pub fn is_xcode_project(root: &Path) -> bool {
|
||||
@@ -54,7 +64,8 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
|
||||
for d in list.as_array().into_iter().flatten() {
|
||||
let text = |key| d.get(key).and_then(Value::as_str).map(str::to_owned);
|
||||
let (Some(udid), Some(name), Some(state)) = (text("udid"), text("name"), text("state")) else { continue };
|
||||
devices.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state }));
|
||||
devices
|
||||
.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state, physical: false }));
|
||||
}
|
||||
}
|
||||
devices.sort_by(|(va, a), (vb, b)| {
|
||||
@@ -67,6 +78,67 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
|
||||
Ok(devices.into_iter().map(|(_, d)| d).collect())
|
||||
}
|
||||
|
||||
/// The physical iOS and iPadOS devices in `devicectl list devices --json-output` output, by name.
|
||||
/// Reads the fields Xcode 15 and later write, falling back to the `properties` that replace them.
|
||||
pub fn parse_devices(json: &str) -> IdeResult<Vec<IosSimulator>> {
|
||||
let value: Value = serde_json::from_str(json).map_err(|e| IdeError::internal(format!("devicectl list: {e}")))?;
|
||||
let mut devices = Vec::new();
|
||||
for d in value.pointer("/result/devices").and_then(Value::as_array).into_iter().flatten() {
|
||||
let text = |old: &str, new: &str| {
|
||||
d.pointer(old).or_else(|| d.pointer(new)).and_then(Value::as_str).unwrap_or_default().to_owned()
|
||||
};
|
||||
let reality = text("/hardwareProperties/reality", "/properties/hardware/reality");
|
||||
let platform = text("/hardwareProperties/platform", "/properties/hardware/platform");
|
||||
let udid = text("/hardwareProperties/udid", "/properties/hardware/udid");
|
||||
if reality != "physical" || !matches!(&*platform, "iOS" | "iPadOS") || udid.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let version = d
|
||||
.pointer("/deviceProperties/osVersionNumber")
|
||||
.or_else(|| d.pointer("/properties/software/osVersionNumber/stringValue"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
// `tunnelState` (`connected`, `disconnected`: reachable, connects on use) or `state`.
|
||||
let connection = text("/connectionProperties/tunnelState", "/properties/connection/state");
|
||||
let developer_mode = d
|
||||
.pointer("/deviceProperties/developerModeStatus")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.or_else(|| d.pointer("/properties/state/developerModeStatus")?.as_object()?.keys().next().cloned());
|
||||
let state = if connection == "unavailable" || connection.is_empty() {
|
||||
UNAVAILABLE
|
||||
} else if developer_mode.as_deref() == Some("disabled") {
|
||||
DEVELOPER_MODE_OFF
|
||||
} else {
|
||||
AVAILABLE
|
||||
};
|
||||
devices.push(IosSimulator {
|
||||
udid,
|
||||
name: text("/deviceProperties/name", "/properties/state/name"),
|
||||
runtime: format!("{platform} {version}").trim().to_owned(),
|
||||
state: state.to_owned(),
|
||||
physical: true,
|
||||
});
|
||||
}
|
||||
devices.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.udid.cmp(&b.udid)));
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
/// The physical devices paired with this Mac, as [`parse_devices`] reads them; none when
|
||||
/// `devicectl` (Xcode 15 and later) is missing or fails. `dir` picks the project's Xcode.
|
||||
pub fn devices(dir: &Path) -> Vec<IosSimulator> {
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos();
|
||||
let file = std::env::temp_dir().join(format!("openidea-devicectl-{}-{stamp}.json", std::process::id()));
|
||||
let path = file.to_string_lossy().into_owned();
|
||||
let listed = run_in(Some(dir), "xcrun", &["devicectl", "list", "devices", "--quiet", "--json-output", &path]);
|
||||
let json = std::fs::read_to_string(&file);
|
||||
let _ = std::fs::remove_file(&file);
|
||||
match (listed, json) {
|
||||
(Ok(_), Ok(json)) => parse_devices(&json).unwrap_or_default(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `dir`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
|
||||
fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(program);
|
||||
@@ -82,10 +154,12 @@ fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult<String>
|
||||
Err(IdeError::unavailable(format!("{program} {} failed: {}", args.join(" "), stderr.trim())))
|
||||
}
|
||||
|
||||
/// The available iOS simulators, sorted as [`parse_list`] does.
|
||||
/// The available iOS simulators of the Xcode the project at `root` uses.
|
||||
/// The available iOS simulators of the Xcode the project at `root` uses, sorted as
|
||||
/// [`parse_list`] does, then the physical devices.
|
||||
pub fn list(root: &Path) -> IdeResult<Vec<IosSimulator>> {
|
||||
parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)
|
||||
let mut list = parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)?;
|
||||
list.extend(devices(root));
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// Boots a simulator; returns once `simctl` has it booted.
|
||||
@@ -142,6 +216,42 @@ mod tests {
|
||||
assert_eq!(parse_list("{}").unwrap(), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_physical_devices_by_name_from_old_and_new_fields() {
|
||||
// Trimmed `devicectl list devices --json-output` (Xcode 27): one device with the
|
||||
// deprecated fields too, one with `properties` only, a simulator and a Mac.
|
||||
let json = r#"{"info": {"outcome": "success"}, "result": {"devices": [
|
||||
{"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"},
|
||||
"deviceProperties": {"name": "Work iPhone", "osVersionNumber": "27.3", "developerModeStatus": "enabled"},
|
||||
"connectionProperties": {"tunnelState": "disconnected"},
|
||||
"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"},
|
||||
"connection": {"state": "disconnected"}}},
|
||||
{"properties": {"hardware": {"reality": "physical", "platform": "iPadOS", "udid": "00008103-BBB"},
|
||||
"software": {"osVersionNumber": {"stringValue": "26.1"}},
|
||||
"state": {"name": "Test iPad", "developerModeStatus": {"disabled": {"mode": 0}}},
|
||||
"connection": {"state": "connected"}}},
|
||||
{"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008150-CCC"},
|
||||
"state": {"name": "Away iPhone", "developerModeStatus": {"enabled": {"mode": 1}}},
|
||||
"connection": {"state": "unavailable"}}},
|
||||
{"hardwareProperties": {"reality": "simulated", "platform": "iOS", "udid": "SIM"},
|
||||
"connectionProperties": {"tunnelState": "disconnected"}},
|
||||
{"hardwareProperties": {"reality": "physical", "platform": "macOS", "udid": "MAC"},
|
||||
"connectionProperties": {"tunnelState": "connected"}}
|
||||
]}}"#;
|
||||
let devices = parse_devices(json).unwrap();
|
||||
let rows: Vec<_> = devices.iter().map(|d| (&*d.name, &*d.udid, &*d.runtime, &*d.state, d.physical)).collect();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
("Away iPhone", "00008150-CCC", "iOS", UNAVAILABLE, true),
|
||||
("Test iPad", "00008103-BBB", "iPadOS 26.1", DEVELOPER_MODE_OFF, true),
|
||||
("Work iPhone", "00008110-AAA", "iOS 27.3", AVAILABLE, true),
|
||||
]
|
||||
);
|
||||
assert!(parse_devices("not json").is_err());
|
||||
assert_eq!(parse_devices(r#"{"info": {"outcome": "failed"}}"#).unwrap(), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_xcode_projects_at_the_root_only() {
|
||||
let dir = std::env::temp_dir().join(format!("ide-run-simulator-{}", std::process::id()));
|
||||
|
||||
@@ -1027,13 +1027,13 @@ pub fn artifact_is_current(root: &Path, base: &Path, config: &RunConfig, modules
|
||||
let id_matches = selected.is_none_or(|id| recorded_id.as_deref().map(str::trim) == Some(id.as_str()));
|
||||
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
|
||||
let war = match recorded.filter(|_| id_matches) {
|
||||
Some(war) if war.is_file() && is_war(&war) => war,
|
||||
Some(war) if (war.is_file() && is_war(&war)) || war.is_dir() => war,
|
||||
_ => match find_built_war(root, Some(&module)) {
|
||||
Some(war) => war,
|
||||
None => return false,
|
||||
},
|
||||
};
|
||||
let Ok(war_time) = fs::metadata(&war).and_then(|m| m.modified()) else { return false };
|
||||
let Some(war_time) = newest_mtime_under(&war) else { return false };
|
||||
let mut newest = newest_mtime_under(&module.join("src"));
|
||||
// Web content packaged from outside `src` (a custom `warSourceDirectory`, `webResources`
|
||||
// directories, a custom Gradle web app dir) also lands in the WAR — the running-session
|
||||
@@ -1077,12 +1077,10 @@ pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only:
|
||||
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
|
||||
let module = artifact_module_dir(root, config);
|
||||
let war = match recorded.filter(|_| id_matches) {
|
||||
Some(war) => {
|
||||
if war.is_file() && is_war(&war) {
|
||||
war
|
||||
} else {
|
||||
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.display())));
|
||||
}
|
||||
Some(path) if path.is_file() && is_war(&path) => path,
|
||||
Some(path) if path.is_dir() => return Ok(path),
|
||||
Some(path) => {
|
||||
return Err(invalid(format!("The built WAR artifact does not exist: {}", path.display())));
|
||||
}
|
||||
None => find_built_war(root, Some(module.as_path())).ok_or_else(|| {
|
||||
invalid("No built WAR artifact found - build the project first, or add 'Build' to Before launch")
|
||||
@@ -2417,4 +2415,45 @@ mod tests {
|
||||
let error = prepare(root, &cache, &mut c).unwrap_err().to_string();
|
||||
assert!(error.contains("Two deployments use the application context /"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deploys_recorded_exploded_artifact_directory_directly() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let home = root.join("Tomcat Home");
|
||||
fs::create_dir_all(home.join("bin")).unwrap();
|
||||
fs::create_dir_all(home.join("conf")).unwrap();
|
||||
fs::write(home.join("bin/catalina.sh"), "").unwrap();
|
||||
fs::write(home.join("bin/catalina.bat"), "").unwrap();
|
||||
archive(
|
||||
&home.join("lib/catalina.jar"),
|
||||
&[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1")],
|
||||
);
|
||||
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
|
||||
fs::write(home.join("conf/server.xml"), server).unwrap();
|
||||
let exploded = root.join("out/artifacts/EJSH_war_exploded");
|
||||
fs::create_dir_all(exploded.join("WEB-INF")).unwrap();
|
||||
fs::write(exploded.join("WEB-INF/web.xml"), "<web-app/>").unwrap();
|
||||
|
||||
let mut c = config();
|
||||
for (k, v) in [
|
||||
("tomcatHome", "Tomcat Home"),
|
||||
("deployment", "artifact"),
|
||||
("artifact", "project:EJSH:war exploded"),
|
||||
("artifactName", "EJSH"),
|
||||
] {
|
||||
c.extras.params.insert(k.into(), v.into());
|
||||
}
|
||||
let cache = root.join("cache");
|
||||
let base = base_dir(&cache, &c.id);
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
fs::write(base.join("artifact-id.txt"), "project:EJSH:war exploded").unwrap();
|
||||
fs::write(base.join("artifact-path.txt"), exploded.to_string_lossy().as_bytes()).unwrap();
|
||||
|
||||
prepare(root, &cache, &mut c).unwrap();
|
||||
let runtime = PathBuf::from(&c.env["CATALINA_BASE"]);
|
||||
let ctx = fs::read_to_string(runtime.join("conf/Catalina/localhost/EJSH.xml")).unwrap();
|
||||
assert!(ctx.contains(&format!("docBase=\"{}\"", escape(&exploded.to_string_lossy()))), "{ctx}");
|
||||
assert!(artifact_is_current(root, &runtime, &c, &[]));
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//! projects without any, but it takes a second or two, too slow for detection.
|
||||
//!
|
||||
//! A scheme's run configuration builds it for the iOS Simulator and launches the app there with
|
||||
//! `simctl`, or, for a macOS app, builds it for the Mac and runs its executable;
|
||||
//! `simctl`, for a connected iPhone or iPad and launches it there with `devicectl`, or, for a
|
||||
//! macOS app, builds it for the Mac and runs its executable;
|
||||
//! [`prepare`] turns the configuration into that process when it starts.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -305,17 +306,32 @@ pub fn mac_executable(settings: &str) -> Result<PathBuf, String> {
|
||||
}
|
||||
|
||||
/// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the
|
||||
/// scheme's first application target.
|
||||
pub fn built_app(settings: &str) -> Result<(PathBuf, String), String> {
|
||||
/// scheme's first application target for the iOS Simulator, or with `device` for an iPhone or
|
||||
/// iPad, which runs only an app signed with a development team.
|
||||
pub fn built_app(settings: &str, device: bool) -> Result<(PathBuf, String), String> {
|
||||
let apps = app_settings(settings)?;
|
||||
let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else {
|
||||
let (platform, target) =
|
||||
if device { ("iphoneos", "an iOS device") } else { ("iphonesimulator", "the iOS Simulator") };
|
||||
let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == platform) else {
|
||||
return Err(match apps.first().and_then(|b| b["PLATFORM_NAME"].as_str()) {
|
||||
Some(platform) => format!("The scheme builds an app for {platform}, not the iOS Simulator"),
|
||||
Some(platform) => format!("The scheme builds an app for {platform}, not {target}"),
|
||||
None => "The scheme builds no application".to_owned(),
|
||||
});
|
||||
};
|
||||
let get =
|
||||
|key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}"));
|
||||
if device && app["CODE_SIGNING_ALLOWED"] == "NO" {
|
||||
return Err(format!(
|
||||
"{} is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps",
|
||||
get("WRAPPER_NAME")?
|
||||
));
|
||||
}
|
||||
if device && app["CODE_SIGN_STYLE"] == "Automatic" && get("DEVELOPMENT_TEAM").is_err() {
|
||||
return Err(format!(
|
||||
"Signing {} for a device needs a development team: choose one under Signing & Capabilities in Xcode",
|
||||
get("WRAPPER_NAME")?
|
||||
));
|
||||
}
|
||||
Ok((Path::new(get("TARGET_BUILD_DIR")?).join(get("WRAPPER_NAME")?), get("PRODUCT_BUNDLE_IDENTIFIER")?.to_owned()))
|
||||
}
|
||||
|
||||
@@ -372,6 +388,49 @@ fn announce_suspended(udid: &str, bundle_id: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The script a run on a physical device executes: build with the project's signing (letting
|
||||
/// Xcode register the device and fetch profiles, as its own Run does), install, then launch with
|
||||
/// the app's output on the console. The app's arguments follow the script as `$@`. A Stop's
|
||||
/// SIGINT becomes a SIGTERM to `devicectl` (a background job ignores SIGINT), which passes it on
|
||||
/// to the app. When `devicectl` itself fails to launch the app
|
||||
/// (its JSON outcome is not `success`) and no Stop was asked for, a hint about a locked device
|
||||
/// follows its error.
|
||||
pub fn device_launch_script(build_args: &[String], udid: &str, name: &str, app: &Path, bundle_id: &str) -> String {
|
||||
let build: Vec<String> = build_args.iter().map(|a| sh_quote(a)).collect();
|
||||
let (udid, app, bundle_id) = (sh_quote(udid), sh_quote(&app.to_string_lossy()), sh_quote(bundle_id));
|
||||
let hint = sh_quote(&format!("Could not launch the app on {name}. If it is locked, unlock it and run again."));
|
||||
format!(
|
||||
"set -e\n\
|
||||
xcodebuild {} -allowProvisioningUpdates build\n\
|
||||
xcrun devicectl device install app --device {udid} {app}\n\
|
||||
set +e\n\
|
||||
result=$(mktemp)\n\
|
||||
xcrun devicectl device process launch --console --terminate-existing --json-output \"$result\" --device {udid} {bundle_id} -- \"$@\" &\n\
|
||||
launch=$!\n\
|
||||
trap 'stopped=1; kill -TERM $launch 2>/dev/null' INT TERM\n\
|
||||
wait $launch; status=$?\n\
|
||||
while kill -0 $launch 2>/dev/null; do wait $launch; status=$?; done\n\
|
||||
if [ -z \"$stopped\" ] && ! grep -q '\"outcome\" *: *\"success\"' \"$result\" 2>/dev/null; then echo {hint} >&2; fi\n\
|
||||
rm -f \"$result\"\n\
|
||||
exit $status\n",
|
||||
build.join(" "),
|
||||
)
|
||||
}
|
||||
|
||||
/// Why a run cannot start on `device`, a physical one [`crate::simulator::devices`] listed.
|
||||
fn device_unready(device: &crate::simulator::IosSimulator) -> Option<String> {
|
||||
let name = &device.name;
|
||||
match device.state.as_str() {
|
||||
crate::simulator::UNAVAILABLE => Some(format!(
|
||||
"{name} is not connected. Connect it with a cable or to this Mac's network, unlock it, and run again."
|
||||
)),
|
||||
crate::simulator::DEVELOPER_MODE_OFF => Some(format!(
|
||||
"Developer Mode is off on {name}. Turn it on in Settings > Privacy & Security > Developer Mode, restart the device, and run again."
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The script a macOS run executes: build, then become the app's executable, so its output
|
||||
/// reaches the console and a Stop's SIGINT reaches the app. Its arguments follow as `$@`.
|
||||
pub fn mac_launch_script(build_args: &[String], executable: &Path) -> String {
|
||||
@@ -417,7 +476,7 @@ pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data:
|
||||
}
|
||||
|
||||
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
|
||||
/// its scheme on the simulator. `dir` is the run's working directory; DerivedData goes under
|
||||
/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; DerivedData goes under
|
||||
/// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
|
||||
/// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
@@ -443,11 +502,32 @@ pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> I
|
||||
return Ok(());
|
||||
}
|
||||
let udid = destination.trim_start_matches("id=").to_owned();
|
||||
let device = crate::simulator::devices(dir).into_iter().find(|d| d.udid == udid);
|
||||
if let Some(reason) = device.as_ref().and_then(device_unready) {
|
||||
return Err(IdeError::unavailable(reason));
|
||||
}
|
||||
let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?;
|
||||
let settings = show(&args)?;
|
||||
let (app, bundle_id) = built_app(&settings).map_err(IdeError::invalid)?;
|
||||
let (app, bundle_id) = built_app(&settings, device.is_some()).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
let wait = params.get(WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
|
||||
if let Some(device) = device {
|
||||
if wait {
|
||||
return Err(IdeError::unavailable("Debugging an app on a physical device is not supported yet"));
|
||||
}
|
||||
config.command = "/bin/sh".into();
|
||||
config.args = [
|
||||
"-c".to_owned(),
|
||||
device_launch_script(&args, &udid, &device.name, &app, &bundle_id),
|
||||
"xcode-run".to_owned(),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(app_args)
|
||||
.collect();
|
||||
let env = std::mem::take(&mut config.env);
|
||||
config.env = env.into_iter().map(|(k, v)| (format!("DEVICECTL_CHILD_{k}"), v)).collect();
|
||||
return Ok(());
|
||||
}
|
||||
config.command = "/bin/sh".into();
|
||||
config.args = ["-c".to_owned(), launch_script(&args, &udid, &app, &bundle_id, wait), "xcode-run".to_owned()]
|
||||
.into_iter()
|
||||
@@ -625,14 +705,66 @@ mod tests {
|
||||
)
|
||||
};
|
||||
assert_eq!(
|
||||
built_app(&settings("iphonesimulator")).unwrap(),
|
||||
built_app(&settings("iphonesimulator"), false).unwrap(),
|
||||
(PathBuf::from("/dd/Build/Products/Debug-iphonesimulator/App.app"), "dev.example.App".to_owned())
|
||||
);
|
||||
assert_eq!(
|
||||
built_app(&settings("macosx")).unwrap_err(),
|
||||
built_app(&settings("macosx"), false).unwrap_err(),
|
||||
"The scheme builds an app for macosx, not the iOS Simulator"
|
||||
);
|
||||
assert_eq!(built_app("[]").unwrap_err(), "The scheme builds no application");
|
||||
assert_eq!(built_app("[]", false).unwrap_err(), "The scheme builds no application");
|
||||
assert_eq!(
|
||||
built_app(&settings("iphonesimulator"), true).unwrap_err(),
|
||||
"The scheme builds an app for iphonesimulator, not an iOS device"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_app_must_be_signed_with_a_team() {
|
||||
let settings = |signing: &str| {
|
||||
format!(
|
||||
r#"[{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application",
|
||||
"PLATFORM_NAME": "iphoneos", "TARGET_BUILD_DIR": "/dd/Debug-iphoneos", "WRAPPER_NAME": "App.app",
|
||||
"PRODUCT_BUNDLE_IDENTIFIER": "dev.example.App", {signing}}}}}]"#
|
||||
)
|
||||
};
|
||||
let signed = settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": "ABCDE12345""#);
|
||||
assert_eq!(
|
||||
built_app(&signed, true).unwrap(),
|
||||
(PathBuf::from("/dd/Debug-iphoneos/App.app"), "dev.example.App".to_owned())
|
||||
);
|
||||
let manual = settings(r#""CODE_SIGN_STYLE": "Manual", "DEVELOPMENT_TEAM": """#);
|
||||
assert!(built_app(&manual, true).is_ok(), "manual signing names its profile; xcodebuild checks it");
|
||||
assert_eq!(
|
||||
built_app(&settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": """#), true).unwrap_err(),
|
||||
"Signing App.app for a device needs a development team: choose one under Signing & Capabilities in Xcode"
|
||||
);
|
||||
assert_eq!(
|
||||
built_app(&settings(r#""CODE_SIGNING_ALLOWED": "NO""#), true).unwrap_err(),
|
||||
"App.app is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unready_device_says_what_to_do() {
|
||||
let device = |state: &str| crate::simulator::IosSimulator {
|
||||
udid: "U".into(),
|
||||
name: "Test iPhone".into(),
|
||||
runtime: "iOS 27.3".into(),
|
||||
state: state.into(),
|
||||
physical: true,
|
||||
};
|
||||
assert_eq!(device_unready(&device(crate::simulator::AVAILABLE)), None);
|
||||
assert!(
|
||||
device_unready(&device(crate::simulator::UNAVAILABLE))
|
||||
.unwrap()
|
||||
.starts_with("Test iPhone is not connected.")
|
||||
);
|
||||
assert!(
|
||||
device_unready(&device(crate::simulator::DEVELOPER_MODE_OFF))
|
||||
.unwrap()
|
||||
.starts_with("Developer Mode is off on Test iPhone.")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -772,6 +904,82 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The device script builds, installs and launches through devicectl, turns a Stop's SIGINT
|
||||
/// into a SIGTERM to it, and adds the locked-device hint only when devicectl itself failed to launch.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn device_launch_script_installs_launches_and_explains_a_failed_launch() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let log = dir.path().join("log");
|
||||
let stub = |tool: &str, then: &str| {
|
||||
let path = dir.path().join(tool);
|
||||
let body = format!(
|
||||
"#!/bin/sh\nprintf '{tool}' >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}"
|
||||
);
|
||||
fs::write(&path, body).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
stub("xcodebuild", "");
|
||||
// `launch` writes its JSON result to the path after `--json-output` ($8), then either
|
||||
// fails at once or runs until a SIGINT reaches it.
|
||||
stub(
|
||||
"xcrun",
|
||||
"[ \"$4\" = launch ] || exit 0\n\
|
||||
printf '{\"info\" : {\"outcome\" : \"%s\"}}' \"$OUTCOME\" > \"$8\"\n\
|
||||
[ \"$OUTCOME\" = success ] || { echo 'ERROR: the device was not unlocked' >&2; exit 1; }\n\
|
||||
trap 'echo terminated >> \"$LOG\"; exit 0' TERM\n\
|
||||
while :; do sleep 0.05; done\n",
|
||||
);
|
||||
let build = ["-project".to_owned(), "App.xcodeproj".to_owned()];
|
||||
let script =
|
||||
device_launch_script(&build, "00008110-AAA", "Test iPhone", Path::new("/dd/My App.app"), "dev.example.App");
|
||||
let run = |outcome: &str| {
|
||||
let _ = fs::remove_file(&log);
|
||||
std::process::Command::new("/bin/sh")
|
||||
.args(["-c", &script, "xcode-run", "--greeting", "hi there"])
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
|
||||
.env("LOG", &log)
|
||||
.env("OUTCOME", outcome)
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let failed = run("failed").wait_with_output().unwrap();
|
||||
assert_eq!(failed.status.code(), Some(1));
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&failed.stderr),
|
||||
"ERROR: the device was not unlocked\n\
|
||||
Could not launch the app on Test iPhone. If it is locked, unlock it and run again.\n"
|
||||
);
|
||||
|
||||
let child = run("success");
|
||||
let launched = || fs::read_to_string(&log).unwrap_or_default().contains("[launch]");
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while !launched() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
unsafe { libc::kill(child.id() as i32, libc::SIGINT) };
|
||||
let stopped = child.wait_with_output().unwrap();
|
||||
assert!(stopped.status.success());
|
||||
assert_eq!(String::from_utf8_lossy(&stopped.stderr), "");
|
||||
let log = fs::read_to_string(&log).unwrap();
|
||||
let json = log.split("[--json-output] [").nth(1).unwrap().split(']').next().unwrap().to_owned();
|
||||
assert_eq!(
|
||||
log,
|
||||
format!(
|
||||
"xcodebuild [-project] [App.xcodeproj] [-allowProvisioningUpdates] [build]\n\
|
||||
xcrun [devicectl] [device] [install] [app] [--device] [00008110-AAA] [/dd/My App.app]\n\
|
||||
xcrun [devicectl] [device] [process] [launch] [--console] [--terminate-existing] [--json-output] [{json}] \
|
||||
[--device] [00008110-AAA] [dev.example.App] [--] [--greeting] [hi there]\n\
|
||||
terminated\n"
|
||||
)
|
||||
);
|
||||
assert!(!Path::new(&json).exists(), "the launch result file is removed");
|
||||
}
|
||||
|
||||
/// A debug launch passes `--wait-for-debugger` and prints the pid of the suspended app (not of
|
||||
/// a running copy, nor of a process outside its bundle) right away, while simctl keeps running.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -506,7 +506,8 @@ fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationT
|
||||
let java = [".classpath", ".project"].iter().any(|f| root.join(f).is_file())
|
||||
|| idea_java_project(root)
|
||||
|| !s.languages.java.jdk.trim().is_empty()
|
||||
|| !s.project_structure.source_roots.is_empty();
|
||||
|| !s.project_structure.source_roots.is_empty()
|
||||
|| !s.project_structure.libraries.is_empty();
|
||||
if !java {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -521,11 +522,45 @@ fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationT
|
||||
})
|
||||
}
|
||||
|
||||
/// The class roots of Project Structure library entry `entry`: `dir/*.jar` and `dir/**/*.jar` list the
|
||||
/// folder's jars, a folder holding jars (e.g. `WEB-INF/lib`) lists them all, anything else is itself.
|
||||
pub fn library_class_paths(root: &Path, entry: &str) -> Vec<PathBuf> {
|
||||
if let Some((base, recursive)) = ide_core::settings::split_jar_glob(entry) {
|
||||
return crate::apply::setting_path(root, base)
|
||||
.map(|dir| ide_core::settings::jar_files(&dir, recursive))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
let Some(path) = crate::apply::setting_path(root, entry.trim()) else { return Vec::new() };
|
||||
if path.is_dir() {
|
||||
let jars = ide_core::settings::jar_files(&path, true);
|
||||
if !jars.is_empty() {
|
||||
return jars;
|
||||
}
|
||||
}
|
||||
vec![path]
|
||||
}
|
||||
|
||||
fn project_structure_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
let mut out = Vec::new();
|
||||
let push_archive = |roots: &mut Vec<LibraryRoot>, path: &Path| {
|
||||
let label =
|
||||
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
|
||||
roots.push(LibraryRoot { name: label, path: ide_vfs::archive_root(path).into() });
|
||||
};
|
||||
for lib in &s.project_structure.libraries {
|
||||
let mut roots = Vec::new();
|
||||
for entry in lib.classes.iter().chain(&lib.sources) {
|
||||
for path in lib.classes.iter().flat_map(|entry| library_class_paths(root, entry)) {
|
||||
if path.is_file() {
|
||||
push_archive(&mut roots, &path);
|
||||
} else if path.is_dir() {
|
||||
let label = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| path.display().to_string());
|
||||
roots.push(LibraryRoot { name: label, path: path.into() });
|
||||
}
|
||||
}
|
||||
for entry in &lib.sources {
|
||||
let Some(path) = crate::apply::setting_path(root, entry) else { continue };
|
||||
let label = path
|
||||
.file_name()
|
||||
|
||||
@@ -64,16 +64,25 @@ pub enum ComposerInstall {
|
||||
Outdated,
|
||||
}
|
||||
|
||||
/// The Composer project `file` belongs to (the nearest `composer.json` at or below `root`), and
|
||||
/// whether its dependencies need `composer install`.
|
||||
/// Whether the nearest enclosing Composer project needs `composer install`. A manifest inside
|
||||
/// that project's vendor directory belongs to an installed package.
|
||||
pub fn composer_install(file: &Path, root: &Path) -> Option<(PathBuf, ComposerInstall)> {
|
||||
let dir = file.ancestors().filter(|d| d.starts_with(root)).find(|d| d.join("composer.json").is_file())?;
|
||||
let composer: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("composer.json")).ok()?).ok()?;
|
||||
let vendor = dir.join(composer.pointer("/config/vendor-dir").and_then(Value::as_str).unwrap_or("vendor"));
|
||||
let read = |path: PathBuf| std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
|
||||
let ancestors: Vec<_> = file.ancestors().take_while(|dir| dir.starts_with(root)).collect();
|
||||
let mut project = None;
|
||||
for dir in ancestors.into_iter().rev() {
|
||||
let Some(composer) = read(dir.join("composer.json")) else { continue };
|
||||
let vendor = dir.join(composer.pointer("/config/vendor-dir").and_then(Value::as_str).unwrap_or("vendor"));
|
||||
let in_vendor = file.starts_with(&vendor);
|
||||
project = Some((dir, vendor));
|
||||
if in_vendor {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (dir, vendor) = project?;
|
||||
if !vendor.join("autoload.php").is_file() {
|
||||
return Some((dir.to_path_buf(), ComposerInstall::Missing));
|
||||
}
|
||||
let read = |path: PathBuf| std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
|
||||
let lock = read(dir.join("composer.lock"))?;
|
||||
let installed = read(vendor.join("composer/installed.json")).unwrap_or(Value::Null);
|
||||
// Composer 2 writes `{"packages": [...], "dev": bool}`, Composer 1 the list itself.
|
||||
@@ -352,6 +361,32 @@ mod tests {
|
||||
assert_eq!(composer_install(&root.join("other.php"), root), None, "outside the Composer project");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_install_checks_the_owning_project_for_vendor_files() {
|
||||
for (vendor, manifest) in [("vendor", "{}"), ("deps", r#"{"config":{"vendor-dir":"deps"}}"#)] {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let vendor = root.join(vendor);
|
||||
let package = vendor.join("symfony/console");
|
||||
let nested = root.join("apps/console");
|
||||
for dir in [&package, &nested, &vendor.join("composer")] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("composer.json"), manifest).unwrap();
|
||||
std::fs::write(package.join("composer.json"), "{}").unwrap();
|
||||
std::fs::write(nested.join("composer.json"), "{}").unwrap();
|
||||
let file = package.join("Application.php");
|
||||
assert_eq!(composer_install(&file, root), Some((root.to_path_buf(), ComposerInstall::Missing)));
|
||||
|
||||
std::fs::write(vendor.join("autoload.php"), "<?php").unwrap();
|
||||
let packages = r#"{"packages":[{"name":"symfony/console","version":"v7.4.0"}]}"#;
|
||||
std::fs::write(root.join("composer.lock"), packages).unwrap();
|
||||
std::fs::write(vendor.join("composer/installed.json"), packages).unwrap();
|
||||
assert_eq!(composer_install(&file, root), None);
|
||||
assert_eq!(composer_install(&nested.join("Command.php"), root), Some((nested, ComposerInstall::Missing)));
|
||||
}
|
||||
}
|
||||
|
||||
fn level(composer: Option<&str>, explicit: &str) -> Option<String> {
|
||||
levels(composer, explicit).0.map(|l| l.version)
|
||||
}
|
||||
|
||||
@@ -3655,6 +3655,22 @@ fn project_structure_module_jdk_language_level_and_external_libraries() {
|
||||
});
|
||||
let groups = crate::libraries::project_libraries(root, &settings, &[]);
|
||||
assert!(groups.iter().any(|g| g.name == "servlet-api" && g.kind == "library" && g.roots.len() == 1));
|
||||
|
||||
let web_lib = root.join("WebRoot/WEB-INF/lib");
|
||||
std::fs::create_dir_all(&web_lib).unwrap();
|
||||
std::fs::write(web_lib.join("a.jar"), b"").unwrap();
|
||||
std::fs::write(web_lib.join("b.jar"), b"").unwrap();
|
||||
settings.project_structure.libraries.push(ide_core::settings::ProjectLibrary {
|
||||
name: "web-lib".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
sources: vec![],
|
||||
javadocs: vec![],
|
||||
scope: ide_core::settings::DependencyScope::Runtime,
|
||||
});
|
||||
let groups = crate::libraries::project_libraries(root, &settings, &[]);
|
||||
let web = groups.iter().find(|g| g.name == "web-lib" && g.kind == "library").unwrap();
|
||||
let names: Vec<&str> = web.roots.iter().map(|r| r.name.as_str()).collect();
|
||||
assert_eq!(names, vec!["a.jar", "b.jar"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -383,6 +383,9 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
|
||||
u.companion = true;
|
||||
}
|
||||
}
|
||||
for (tool, lang) in registry::LANGUAGE_CLIS {
|
||||
map.entry(tool.to_string()).or_default().languages.push(lang.to_string());
|
||||
}
|
||||
for (plugin, host) in registry::PLUGIN_HOSTS {
|
||||
let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default();
|
||||
map.entry(plugin.to_string()).or_default().languages = languages;
|
||||
|
||||
@@ -210,6 +210,28 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
needs: &[],
|
||||
homepage: "https://cli.github.com",
|
||||
},
|
||||
// Run by the IDE on Swift files below a `.swiftlint.yml` (not a language server).
|
||||
ToolSpec {
|
||||
name: "swiftlint",
|
||||
display: "SwiftLint",
|
||||
kind: Cli,
|
||||
commands: &["swiftlint"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "realm/SwiftLint" },
|
||||
assets: &[
|
||||
any_arch(Mac, "portable_swiftlint.zip"),
|
||||
rule(Linux, X64, "swiftlint_linux_amd64.zip"),
|
||||
rule(Linux, Arm64, "swiftlint_linux_arm64.zip"),
|
||||
rule(Windows, X64, "SwiftLint.amd64.zip"),
|
||||
rule(Windows, Arm64, "SwiftLint.arm64.zip"),
|
||||
],
|
||||
locate: &["swiftlint"],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("swiftlint"),
|
||||
needs: &[],
|
||||
homepage: "https://realm.github.io/SwiftLint/",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "oxfmt",
|
||||
display: "oxfmt",
|
||||
@@ -1410,6 +1432,9 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
pub const PLUGIN_HOSTS: &[(&str, &str)] =
|
||||
&[("lombok", "jdtls"), ("css-modules-kit", "vtsls"), ("typescript-styled-plugin", "vtsls")];
|
||||
|
||||
/// Command-line tools the IDE runs on one language's files, listed with that language.
|
||||
pub const LANGUAGE_CLIS: &[(&str, &str)] = &[("swiftlint", "Swift")];
|
||||
|
||||
pub fn find(name: &str) -> Option<&'static ToolSpec> {
|
||||
TOOLS.iter().find(|t| t.name == name)
|
||||
}
|
||||
|
||||
@@ -1458,6 +1458,15 @@ fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() {
|
||||
assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swiftlint_is_an_installable_tool_of_swift() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "curl", "exit 0");
|
||||
let tool = env.tools().info("swiftlint", &[]).unwrap();
|
||||
assert_eq!((tool.kind, tool.status, tool.can_install), (ToolKind::Cli, ToolStatus::Missing, true));
|
||||
assert_eq!(tool.languages, ["Swift"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_npm_tsserver_plugin_is_installed_at_its_pinned_version_only() {
|
||||
let env = Env::new();
|
||||
|
||||
@@ -920,6 +920,7 @@ fn log_indexed_rows(
|
||||
text,
|
||||
matches: HashMap::new(),
|
||||
projected: HashMap::new(),
|
||||
pruned: HashMap::new(),
|
||||
cancel,
|
||||
index,
|
||||
table: table.as_ref(),
|
||||
@@ -1010,6 +1011,7 @@ fn sort_subset(
|
||||
let mut children = vec![0usize; ids.len()];
|
||||
let mut times = Vec::with_capacity(ids.len());
|
||||
let mut projected: HashMap<ObjectId, Vec<usize>> = HashMap::new();
|
||||
let mut pruned: HashMap<ObjectId, Vec<ObjectId>> = HashMap::new();
|
||||
for id in &ids {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -1071,11 +1073,27 @@ fn sort_subset(
|
||||
.collect()
|
||||
};
|
||||
if !expanded {
|
||||
let ancestors = without_redundant_parents(ancestors, cancel, |id| {
|
||||
if let Some((ps, time)) = nodes.get(&id) {
|
||||
return Ok(Some((
|
||||
if shallow.contains(&id) { Vec::new() } else { ps.clone() },
|
||||
*time,
|
||||
)));
|
||||
}
|
||||
let Ok(commit) = repo.find_commit(id) else { return Ok(None) };
|
||||
let parents = if shallow.contains(&id) {
|
||||
Vec::new()
|
||||
} else {
|
||||
commit.parent_ids().map(|p| p.detach()).collect()
|
||||
};
|
||||
Ok(Some((parents, commit.time().map(|t| t.seconds).unwrap_or(0))))
|
||||
})?;
|
||||
stack.push((curr, true));
|
||||
stack.extend(ancestors.iter().rev().map(|&p| (p, false)));
|
||||
pruned.insert(curr, ancestors);
|
||||
} else {
|
||||
let mut combined = Vec::new();
|
||||
for a in ancestors {
|
||||
for a in pruned.remove(&curr).unwrap_or(ancestors) {
|
||||
for &p in projected.get(&a).into_iter().flatten() {
|
||||
if !combined.contains(&p) {
|
||||
combined.push(p);
|
||||
@@ -1177,6 +1195,70 @@ fn sort_subset(
|
||||
/// Visibility and graph projection share exactly the same predicates. Revision parents
|
||||
/// remain immutable; only graph parents skip hidden commits. Memoisation avoids walking
|
||||
/// the same hidden ancestry for each visible child, without a truncation limit.
|
||||
/// How many commits one ancestry check of [`without_redundant_parents`] may walk.
|
||||
const REDUNDANT_PARENT_WALK: usize = 2_000;
|
||||
|
||||
/// `parents` of a commit the graph hides, without those that are ancestors of another of them:
|
||||
/// whatever such a parent leads to is reached through the other one too. Without this, hiding the
|
||||
/// merges of a pull-request history (`M_k = merge(M_k-1, F_k)`) projects every merge onto all older
|
||||
/// features, so the projection grows with each merge and a long history never finishes.
|
||||
/// `lookup` gives a commit's parents and time (`None`: not available). Each check walks back from
|
||||
/// the other parent, skipping commits older than the candidate, for at most
|
||||
/// [`REDUNDANT_PARENT_WALK`] commits; when unsure the parent is kept.
|
||||
fn without_redundant_parents(
|
||||
mut parents: Vec<ObjectId>,
|
||||
cancel: &CancellationToken,
|
||||
mut lookup: impl FnMut(ObjectId) -> IdeResult<Option<(Vec<ObjectId>, i64)>>,
|
||||
) -> IdeResult<Vec<ObjectId>> {
|
||||
let mut seen = HashSet::new();
|
||||
parents.retain(|p| seen.insert(*p));
|
||||
if parents.len() < 2 {
|
||||
return Ok(parents);
|
||||
}
|
||||
let mut times = Vec::with_capacity(parents.len());
|
||||
for p in &parents {
|
||||
times.push(lookup(*p)?.map(|(_, t)| t));
|
||||
}
|
||||
let mut keep = vec![true; parents.len()];
|
||||
for i in 0..parents.len() {
|
||||
let Some(target_time) = times[i] else { continue };
|
||||
for j in 0..parents.len() {
|
||||
if i == j || !keep[j] || times[j].is_some_and(|t| t < target_time) {
|
||||
continue;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let (mut stack, mut visited) = (vec![parents[j]], HashSet::new());
|
||||
let mut found = false;
|
||||
while let Some(id) = stack.pop() {
|
||||
if visited.len() >= REDUNDANT_PARENT_WALK {
|
||||
break;
|
||||
}
|
||||
if !visited.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let Some((ps, time)) = lookup(id)? else { continue };
|
||||
if id != parents[j] && time < target_time {
|
||||
continue;
|
||||
}
|
||||
if ps.contains(&parents[i]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
stack.extend(ps);
|
||||
}
|
||||
if found {
|
||||
keep[i] = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keep = keep.into_iter();
|
||||
parents.retain(|_| keep.next().unwrap_or(true));
|
||||
Ok(parents)
|
||||
}
|
||||
|
||||
struct Visibility<'a> {
|
||||
speed_refs: &'a HashMap<ObjectId, Vec<String>>,
|
||||
query: &'a LogQuery,
|
||||
@@ -1186,6 +1268,8 @@ struct Visibility<'a> {
|
||||
text: Option<TextFilter>,
|
||||
matches: HashMap<ObjectId, bool>,
|
||||
projected: HashMap<ObjectId, Vec<ObjectId>>,
|
||||
/// The parents a hidden commit projects through, between its two visits.
|
||||
pruned: HashMap<ObjectId, Vec<ObjectId>>,
|
||||
cancel: &'a CancellationToken,
|
||||
index: &'a mut crate::log_index::LogIndex,
|
||||
table: Option<&'a redb::ReadOnlyTable<&'static str, &'static [u8]>>,
|
||||
@@ -1272,6 +1356,26 @@ impl Visibility<'_> {
|
||||
Ok(shown)
|
||||
}
|
||||
|
||||
/// `parents` of a hidden commit without those reachable through another of them.
|
||||
fn prune(&mut self, repo: &gix::Repository, parents: Vec<ObjectId>) -> IdeResult<Vec<ObjectId>> {
|
||||
let (index, table, shallow) = (&mut *self.index, self.table, &self.shallow);
|
||||
without_redundant_parents(parents, self.cancel, |id| {
|
||||
if let Some((ps, time)) = index.nodes.get(&id) {
|
||||
return Ok(Some((if shallow.contains(&id) { Vec::new() } else { ps.clone() }, *time)));
|
||||
}
|
||||
if !index.has_cached(&id) && !repo.has_object(id) {
|
||||
return Ok(None);
|
||||
}
|
||||
let commit = index.get_with_table(repo, id, table)?;
|
||||
let parents = if shallow.contains(&id) {
|
||||
Vec::new()
|
||||
} else {
|
||||
commit.parents.iter().map(|p| ObjectId::from_hex(p.as_bytes()).map_err(gx)).collect::<IdeResult<_>>()?
|
||||
};
|
||||
Ok(Some((parents, (commit.commit_time_ms / 1000.0) as i64)))
|
||||
})
|
||||
}
|
||||
|
||||
fn parents(&mut self, repo: &gix::Repository, parents: &[ObjectId]) -> IdeResult<Vec<ObjectId>> {
|
||||
let parents = if self.query.first_parent { &parents[..parents.len().min(1)] } else { parents };
|
||||
let mut out = Vec::new();
|
||||
@@ -1301,11 +1405,13 @@ impl Visibility<'_> {
|
||||
.collect::<IdeResult<Vec<_>>>()?
|
||||
};
|
||||
if !expanded {
|
||||
let ancestors = self.prune(repo, ancestors)?;
|
||||
stack.push((id, true));
|
||||
stack.extend(ancestors.iter().rev().map(|p| (*p, false)));
|
||||
self.pruned.insert(id, ancestors);
|
||||
} else {
|
||||
let mut nearest = Vec::new();
|
||||
for p in ancestors {
|
||||
for p in self.pruned.remove(&id).unwrap_or(ancestors) {
|
||||
for ancestor in self.projected.get(&p).into_iter().flatten() {
|
||||
if !nearest.contains(ancestor) {
|
||||
nearest.push(*ancestor);
|
||||
|
||||
@@ -267,3 +267,57 @@ fn a_user_filter_links_shown_commits_past_hidden_ones() {
|
||||
assert_eq!(next.iter().map(|c| c.id.clone()).collect::<Vec<_>>(), std::slice::from_ref(&m1));
|
||||
let _ = m3;
|
||||
}
|
||||
|
||||
/// A pull-request history: each feature commit `F_k` branches from merge `M_k-1` and is merged
|
||||
/// back as `M_k = merge(M_k-1, F_k)`, written with `git fast-import`. Returns the feature commits
|
||||
/// newest first.
|
||||
fn pull_request_history(dir: &Path, merges: usize) -> Vec<String> {
|
||||
git(dir, &["init", "-q"], None);
|
||||
let mut stream =
|
||||
String::from("commit refs/heads/main\nmark :1\ncommitter T <[email protected]> 1000 +0000\ndata 4\nroot\n");
|
||||
let mut prev = 1;
|
||||
let mut mark = 1;
|
||||
for k in 0..merges {
|
||||
let t = 1001 + 2 * k as i64;
|
||||
let feature = mark + 1;
|
||||
let merge = mark + 2;
|
||||
stream += &format!(
|
||||
"commit refs/heads/main\nmark :{feature}\ncommitter T <[email protected]> {t} +0000\ndata 1\nf\nfrom :{prev}\n\
|
||||
commit refs/heads/main\nmark :{merge}\ncommitter T <t@example.com> {} +0000\ndata 1\nm\nfrom :{prev}\nmerge :{feature}\n",
|
||||
t + 1
|
||||
);
|
||||
prev = merge;
|
||||
mark = merge;
|
||||
}
|
||||
let mut child = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["fast-import", "--quiet", "--export-marks=marks"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
std::io::Write::write_all(child.stdin.as_mut().unwrap(), stream.as_bytes()).unwrap();
|
||||
assert!(child.wait().unwrap().success());
|
||||
let marks: std::collections::HashMap<usize, String> = std::fs::read_to_string(dir.join("marks"))
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix(':')?.split_once(' ').map(|(m, id)| (m.parse().unwrap(), id.to_string())))
|
||||
.collect();
|
||||
(0..merges).rev().map(|k| marks[&(2 + 2 * k)].clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_merges_on_a_long_pull_request_history_links_each_feature_to_the_previous_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let features = pull_request_history(tmp.path(), 3000);
|
||||
let repo = Repo::discover(tmp.path()).unwrap().unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
let out = repo
|
||||
.log(&LogQuery { branches: vec!["main".into()], no_merges: true, limit: 100, ..Default::default() })
|
||||
.unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
assert_eq!(ids(&out)[..3], features[..3]);
|
||||
// Every older feature is reachable through the previous one, so it is the only graph parent.
|
||||
assert_eq!(parents_of(&out, &features[0]), vec![features[1].clone()]);
|
||||
assert_eq!(parents_of(&out, &features[1]), vec![features[2].clone()]);
|
||||
assert!(elapsed < std::time::Duration::from_secs(10), "took {elapsed:?}");
|
||||
}
|
||||
@@ -276,11 +276,11 @@ fn expand_jetbrains_path(raw: &str, home: Option<&Path>, config: &Path) -> Optio
|
||||
return None;
|
||||
}
|
||||
let rest = if cfg!(windows) { rest.replace('/', "\\") } else { rest.to_owned() };
|
||||
let path = match base {
|
||||
Some(base) => base.join(rest.trim_start_matches(['/', '\\'])),
|
||||
None => PathBuf::from(rest),
|
||||
};
|
||||
path.is_absolute().then_some(path)
|
||||
// `home` and `config` are absolute already; only a path without a variable is checked.
|
||||
match base {
|
||||
Some(base) => Some(base.join(rest.trim_start_matches(['/', '\\']))),
|
||||
None => Some(PathBuf::from(rest)).filter(|p| p.is_absolute()),
|
||||
}
|
||||
}
|
||||
|
||||
impl RecentProjects {
|
||||
|
||||
@@ -77,7 +77,7 @@ The stdio configuration looks like this (the path is the one on your machine):
|
||||
|
||||
Use the executable path from **Copy Stdio Config**; the macOS path above is only an example. On Windows it is `openidea.exe` in the installation (or portable) folder.
|
||||
|
||||
OpenIDEA must be running for the tools to work, and the project must be open in a window or served as a [background project](#background-projects). A client may name any folder inside such a project; the server picks the project that contains it. HTTP clients name it with the `X-OpenIDEA-Project` header or the `?project=` query.
|
||||
OpenIDEA must be running for the tools to work, and the project must be open in a window or served as a [background project](#background-projects). A client may name any folder inside such a project, and the server picks the innermost project that contains it, whether a window has it open or it is served in the background. A project served in the background inside a project open in a window answers for its own folders, so relative paths in a call are relative to its root. For example, with **Trusted projects** a repository inside a trusted location, a Git submodule among them, loads as a background project of its own when a call names its folder, even while a window has the project around it open. HTTP clients name it with the `X-OpenIDEA-Project` header or the `?project=` query.
|
||||
|
||||
While the server runs, OpenIDEA writes its port and token to `mcp/server.json` in its application data directory (readable only by you); the stdio bridge reads it from there.
|
||||
|
||||
|
||||
@@ -12,7 +12,9 @@ OpenIDEA supports C, C++, Objective-C and Objective-C++ through [clangd](https:/
|
||||
| Objective-C | `.m` | clangd | lldb-dap |
|
||||
| Objective-C++ | `.mm` | clangd | lldb-dap |
|
||||
|
||||
`.h` files open as C. To treat headers as C++, change the association in **Settings › Editor › File Types**.
|
||||
`.h` files open as C. To treat headers as C++, or Objective-C headers as Objective-C so the outline shows their `@interface` and `@protocol` blocks, change the association in **Settings › Editor › File Types**.
|
||||
|
||||
The outline of Objective-C files lists `@interface`, `@implementation` and `@protocol` blocks, categories, methods by selector (`initWithName:age:`), properties, instance variables, C functions and `#pragma mark` labels. Objective-C++ files use the same grammar, so their C++ declarations outside Objective-C blocks (namespaces, classes) are not listed.
|
||||
|
||||
## Language server
|
||||
|
||||
@@ -32,6 +34,10 @@ clangd needs the flags each file is compiled with. Without them it guesses, and
|
||||
clangd looks for `compile_commands.json` in the file's parent directories and in a `build/` subdirectory of each. If your build directory has another name (for example `cmake-build-debug` from a CMake profile), add a `.clangd` file with `CompileFlags: { CompilationDatabase: cmake-build-debug }` or copy or link the file to the project root.
|
||||
</Tip>
|
||||
|
||||
### Xcode projects
|
||||
|
||||
In a folder with a `buildServer.json` (the build server config for Xcode projects, see [Swift › Xcode projects](/en/languages/swift#xcode-projects)), C, C++, Objective-C and Objective-C++ files use sourcekit-lsp instead of clangd. sourcekit-lsp gets each file's flags from the build server and passes them to its own clangd, so headers on the target's search paths and the generated `<Module>-Swift.h` resolve. Swift and C-family files of the project share one sourcekit-lsp. A build server config only under `.bsp/` is not used for this, because sbt, Mill and Bazel write that folder too. Without `buildServer.json`, or when sourcekit-lsp is not installed, clangd serves the files as described above.
|
||||
|
||||
### Header and source
|
||||
|
||||
**Switch Header/Source** (in Find Action; `F10`, `⌥O` / `Alt+O` in the VS Code keymaps) opens the counterpart of the current file: `Foo.m` or `Foo.cpp` from `Foo.h`, and back. It asks clangd first (`textDocument/switchSourceHeader`, which also finds a source file in another folder). When clangd is not running for the file or has no answer, it opens a project file with the same name and a counterpart extension, preferring the same folder. **Related Symbol…** (`⌃⌘↑` / `Ctrl+Alt+Home`) lists every match by name instead.
|
||||
|
||||
@@ -147,8 +147,8 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | Yes | Yes | **marksman** | — |
|
||||
| MDX | `mdx` | `.mdx` | Yes | Yes | **mdx-language-server** | — |
|
||||
| Nix | `nix` | `.nix` | Yes | Yes | nil → nixd | — |
|
||||
| Objective-C | `objective-c` | `.m` | Yes | — | **clangd** | lldb-dap |
|
||||
| Objective-C++ | `objective-cpp` | `.mm` | Yes | — | **clangd** | lldb-dap |
|
||||
| Objective-C | `objective-c` | `.m` | Yes | Yes | **clangd** | lldb-dap |
|
||||
| Objective-C++ | `objective-cpp` | `.mm` | Yes | Yes | **clangd** | lldb-dap |
|
||||
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
|
||||
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
|
||||
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
|
||||
@@ -170,6 +170,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| Slint | `slint` | `.slint` | Yes | — | **slint-lsp** | — |
|
||||
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | Yes | — | **sqls** | — |
|
||||
| Svelte | `svelte` | `.svelte` | Yes | — | **svelte-language-server** + **oxlint** | — |
|
||||
| Strings | `strings` | `.strings` | Yes | — | — | — |
|
||||
| Swift | `swift` | `.swift`, `.swiftinterface` | Yes | Yes | sourcekit-lsp | lldb-dap |
|
||||
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | Yes | Yes | **terraform-ls** | — |
|
||||
| Terraform Variables | `terraform-vars` | `.tfvars` | Yes | Yes | **terraform-ls** | — |
|
||||
@@ -178,6 +179,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
|
||||
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
|
||||
| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — |
|
||||
| Xcode Config | `xcconfig` | `.xcconfig` | Yes | — | — | — |
|
||||
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — |
|
||||
| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — |
|
||||
| Zig | `zig` | `.zig`, `.zon` | Yes | Yes | **zls** | **codelldb** |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Swift"
|
||||
description: "Swift code intelligence with sourcekit-lsp for SwiftPM and Xcode projects, formatting, single-file runs and debugging with lldb-dap."
|
||||
description: "Swift code intelligence with sourcekit-lsp for SwiftPM and Xcode projects, formatting, SwiftLint, single-file runs and debugging with lldb-dap."
|
||||
---
|
||||
|
||||
OpenIDEA supports Swift through [sourcekit-lsp](https://github.com/swiftlang/sourcekit-lsp), the language server that ships with the Swift toolchain. Highlighting, folding and the outline work without any setup. Completion, navigation, diagnostics, refactorings and formatting come from sourcekit-lsp. For the other languages, see the [support matrix](/en/languages/index).
|
||||
@@ -90,6 +90,17 @@ Everything the IDE starts in the project gets it as `DEVELOPER_DIR`: sourcekit-l
|
||||
|
||||
**Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`) uses sourcekit-lsp, which formats with [swift-format](https://github.com/swiftlang/swift-format) from the same toolchain. swift-format reads its options from a `.swift-format` file in the file's folder or a parent folder.
|
||||
|
||||
## SwiftLint
|
||||
|
||||
In a project with a `.swiftlint.yml`, the IDE checks Swift files with [SwiftLint](https://realm.github.io/SwiftLint/) as you type and shows its findings as warnings and errors in the editor and in the **Problems** tool window, with the rule name (for example `line_length`) as the code.
|
||||
|
||||
- **Configuration**: SwiftLint runs in the folder of the `.swiftlint.yml` nearest to the file, up to the project folder, and uses that file. Swift files below no `.swiftlint.yml` in the project are not checked.
|
||||
- **Saved and unsaved text**: an opened or saved file is checked by its path, so the configuration's `excluded` paths and nested configurations apply. Unsaved edits are sent to SwiftLint through stdin (`--use-stdin`), which checks them against the nearest configuration only; a file that `excluded` lists stays unchecked while you edit it.
|
||||
- **Installing**: the IDE runs the `swiftlint` it finds on `PATH` or in its tools folder, and never installs it on its own. Install it with `brew install swiftlint`, or with **Install** next to SwiftLint (under Swift, **Command-Line Tools**) in **Settings › Languages & Frameworks › Language Servers**. When `swiftlint` is missing in a project that has a `.swiftlint.yml`, the IDE says so once.
|
||||
- **Restricted Mode**: SwiftLint does not run in projects you have not trusted.
|
||||
|
||||
To fix what SwiftLint can correct, run `swiftlint --fix` in the terminal. The IDE does not offer SwiftLint quick fixes yet.
|
||||
|
||||
## Run and debug
|
||||
|
||||
### Single files
|
||||
@@ -127,3 +138,4 @@ To debug another Swift executable, add a **Program** configuration with **Execut
|
||||
- **Expand Macro** does nothing: sourcekit-lsp shows the expansion in a new document, which the IDE does not open yet.
|
||||
- There is no SwiftUI Preview, Interface Builder, asset catalog editor or simulator integration. Use Xcode for those.
|
||||
- sourcekit-lsp and lldb-dap are not installed by the IDE.
|
||||
- SwiftLint findings have no quick fixes; run `swiftlint --fix` yourself.
|
||||
@@ -76,7 +76,7 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
请以 **复制 Stdio 配置** 得到的可执行文件路径为准,上面的 macOS 路径只是示例。在 Windows 上,它是安装目录(或便携版目录)中的 `openidea.exe`。
|
||||
|
||||
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的那个项目。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
|
||||
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的最内层项目,无论该项目在窗口中打开还是作为后台项目提供服务。位于窗口项目之内的后台项目负责它自己的目录,调用中的相对路径以它的根目录为准。例如在 **受信任的项目** 模式下,受信任位置中的仓库(包括 Git 子模块)在调用指定它的目录时会作为单独的后台项目加载,即使外层项目已在窗口中打开。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
|
||||
|
||||
服务器运行期间,OpenIDEA 会把端口和令牌写入应用数据目录下的 `mcp/server.json`(只有你自己可读),stdio 转发程序从这里读取。
|
||||
|
||||
|
||||
@@ -12,7 +12,9 @@ OpenIDEA 通过 [clangd](https://clangd.llvm.org) 支持 C、C++、Objective-C
|
||||
| Objective-C | `.m` | clangd | lldb-dap |
|
||||
| Objective-C++ | `.mm` | clangd | lldb-dap |
|
||||
|
||||
`.h` 文件默认按 C 打开。如果希望头文件按 C++ 处理,在 **设置 › 编辑器 › 文件类型** 中修改关联。
|
||||
`.h` 文件默认按 C 打开。如果希望头文件按 C++ 处理,或把 Objective-C 头文件按 Objective-C 处理(这样结构视图能列出其中的 `@interface` 和 `@protocol`),在 **设置 › 编辑器 › 文件类型** 中修改关联。
|
||||
|
||||
Objective-C 文件的结构视图列出 `@interface`、`@implementation`、`@protocol` 块、分类(category)、按选择器命名的方法(`initWithName:age:`)、属性、实例变量、C 函数和 `#pragma mark` 标记。Objective-C++ 文件使用同一个语法,因此 Objective-C 块之外的 C++ 声明(命名空间、类)不会列出。
|
||||
|
||||
## 语言服务器
|
||||
|
||||
@@ -32,6 +34,10 @@ clangd 需要知道每个文件的编译参数,否则只能猜测,常见的
|
||||
clangd 会在文件的各级父目录以及这些目录下的 `build/` 子目录里查找 `compile_commands.json`。如果构建目录叫别的名字(例如 CMake 配置生成的 `cmake-build-debug`),在项目根目录添加一个 `.clangd`,写上 `CompileFlags: { CompilationDatabase: cmake-build-debug }`,或者把该文件复制或链接到项目根目录。
|
||||
</Tip>
|
||||
|
||||
### Xcode 项目
|
||||
|
||||
文件夹里有 `buildServer.json`(Xcode 项目的构建服务器配置,见 [Swift › Xcode 项目](/zh/languages/swift#xcode-项目))时,C、C++、Objective-C 和 Objective-C++ 文件改由 sourcekit-lsp 处理,不再用 clangd。sourcekit-lsp 从构建服务器拿到每个文件的编译参数,再交给它自带的 clangd,因此 target 搜索路径里的头文件和生成的 `<Module>-Swift.h` 都能找到。同一项目的 Swift 文件和 C 系文件共用一个 sourcekit-lsp。只放在 `.bsp/` 下的构建服务器配置不在此列,因为 sbt、Mill 和 Bazel 也会写这个文件夹。没有 `buildServer.json`,或者没有安装 sourcekit-lsp 时,仍由 clangd 处理,方式同上。
|
||||
|
||||
### 头文件与源文件
|
||||
|
||||
**切换头文件/源文件**(可在“查找操作”中运行;`F10`,VS Code 键位下为 `⌥O` / `Alt+O`)打开当前文件对应的另一半:在 `Foo.h` 中打开 `Foo.m` 或 `Foo.cpp`,反之亦然。它先询问 clangd(`textDocument/switchSourceHeader`,能找到放在其他文件夹里的源文件);clangd 没有为该文件运行或没有给出结果时,打开项目中同名、扩展名对应的文件,优先同一文件夹。**相关符号…**(`⌃⌘↑` / `Ctrl+Alt+Home`)则按名称列出所有匹配。
|
||||
|
||||
@@ -142,8 +142,8 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | 是 | 是 | **marksman** | — |
|
||||
| MDX | `mdx` | `.mdx` | 是 | 是 | **mdx-language-server** | — |
|
||||
| Nix | `nix` | `.nix` | 是 | 是 | nil → nixd | — |
|
||||
| Objective-C | `objective-c` | `.m` | 是 | — | **clangd** | lldb-dap |
|
||||
| Objective-C++ | `objective-cpp` | `.mm` | 是 | — | **clangd** | lldb-dap |
|
||||
| Objective-C | `objective-c` | `.m` | 是 | 是 | **clangd** | lldb-dap |
|
||||
| Objective-C++ | `objective-cpp` | `.mm` | 是 | 是 | **clangd** | lldb-dap |
|
||||
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
|
||||
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
|
||||
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
|
||||
@@ -165,6 +165,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| Slint | `slint` | `.slint` | 是 | — | **slint-lsp** | — |
|
||||
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | 是 | — | **sqls** | — |
|
||||
| Svelte | `svelte` | `.svelte` | 是 | — | **svelte-language-server** + **oxlint** | — |
|
||||
| Strings | `strings` | `.strings` | 是 | — | — | — |
|
||||
| Swift | `swift` | `.swift`, `.swiftinterface` | 是 | 是 | sourcekit-lsp | lldb-dap |
|
||||
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | 是 | 是 | **terraform-ls** | — |
|
||||
| Terraform Variables | `terraform-vars` | `.tfvars` | 是 | 是 | **terraform-ls** | — |
|
||||
@@ -173,6 +174,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
|
||||
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
|
||||
| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — |
|
||||
| Xcode Config | `xcconfig` | `.xcconfig` | 是 | — | — | — |
|
||||
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — |
|
||||
| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — |
|
||||
| Zig | `zig` | `.zig`, `.zon` | 是 | 是 | **zls** | **codelldb** |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Swift"
|
||||
description: "基于 sourcekit-lsp 的 Swift 代码智能(SwiftPM 与 Xcode 项目),代码格式化,单文件运行,以及用 lldb-dap 调试。"
|
||||
description: "基于 sourcekit-lsp 的 Swift 代码智能(SwiftPM 与 Xcode 项目),代码格式化,SwiftLint,单文件运行,以及用 lldb-dap 调试。"
|
||||
---
|
||||
|
||||
OpenIDEA 通过 Swift 工具链自带的语言服务器 [sourcekit-lsp](https://github.com/swiftlang/sourcekit-lsp) 支持 Swift。语法高亮、折叠和结构视图无需任何配置即可使用;补全、导航、诊断、重构和格式化由 sourcekit-lsp 提供。其他语言见[语言支持总览](/zh/languages/index)。
|
||||
@@ -90,6 +90,17 @@ IDE 在项目中启动的所有进程都会以 `DEVELOPER_DIR` 得到它:sourc
|
||||
|
||||
**重新格式化代码**(`⌥⌘L` / `Ctrl+Alt+L`)交给 sourcekit-lsp,它使用同一工具链中的 [swift-format](https://github.com/swiftlang/swift-format) 格式化。swift-format 从文件所在文件夹或上级文件夹中的 `.swift-format` 文件读取选项。
|
||||
|
||||
## SwiftLint
|
||||
|
||||
在有 `.swiftlint.yml` 的项目中,IDE 会在你输入时用 [SwiftLint](https://realm.github.io/SwiftLint/) 检查 Swift 文件,把结果作为警告和错误显示在编辑器和 **问题** 工具窗口中,并以规则名(例如 `line_length`)作为代码。
|
||||
|
||||
- **配置**:SwiftLint 在离文件最近的 `.swiftlint.yml` 所在文件夹中运行(最多向上找到项目文件夹),并使用这个文件。项目中不在任何 `.swiftlint.yml` 之下的 Swift 文件不检查。
|
||||
- **已保存和未保存的文本**:打开或保存的文件按路径检查,因此配置中的 `excluded` 路径和嵌套配置会生效。未保存的编辑通过 stdin(`--use-stdin`)交给 SwiftLint,只按最近的配置检查;被 `excluded` 列出的文件在编辑时也不检查。
|
||||
- **安装**:IDE 运行在 `PATH` 或自己的工具文件夹中找到的 `swiftlint`,不会自动安装。可以用 `brew install swiftlint` 安装,或在 **设置 › 语言和框架 › 语言服务器** 中 Swift 下的 **命令行工具** 里点 SwiftLint 旁的 **安装**。项目有 `.swiftlint.yml` 但找不到 `swiftlint` 时,IDE 会提示一次。
|
||||
- **受限模式**:未信任的项目不运行 SwiftLint。
|
||||
|
||||
要修正 SwiftLint 能自动修正的问题,请在终端运行 `swiftlint --fix`。IDE 目前还不提供 SwiftLint 的快速修复。
|
||||
|
||||
## 运行和调试
|
||||
|
||||
### 单个文件
|
||||
@@ -127,3 +138,4 @@ IDE 在项目中启动的所有进程都会以 `DEVELOPER_DIR` 得到它:sourc
|
||||
- **Expand Macro** 不起作用:sourcekit-lsp 会在新文档中显示展开结果,而 IDE 目前还不会打开它。
|
||||
- 没有 SwiftUI 预览、Interface Builder、资源目录编辑器和模拟器集成,这些请使用 Xcode。
|
||||
- sourcekit-lsp 和 lldb-dap 不由 IDE 安装。
|
||||
- SwiftLint 的结果没有快速修复,请自己运行 `swiftlint --fix`。
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "composer-icons",
|
||||
title: "Composer icons",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
|
||||
for (const theme of ["light", "dark"] as const) {
|
||||
test(`${theme}: Skills uses the same icon colour and size as peer composer actions`, async ({
|
||||
workbench: page,
|
||||
}, testInfo) => {
|
||||
await page.evaluate(
|
||||
async ({ task, theme }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const themePath = "/src/workbench/theme.ts";
|
||||
const store = await import(storePath);
|
||||
await (await import(themePath)).setTheme(theme);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([[task.id, []]]),
|
||||
sessionLocation: "editor",
|
||||
});
|
||||
store.openTask(task.id);
|
||||
},
|
||||
{ task, theme },
|
||||
);
|
||||
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
|
||||
await page.getByRole("button", { name: "Add Context" }).click();
|
||||
const menu = page.getByRole("menu", { name: "Add Context" });
|
||||
const skills = menu.getByRole("menuitem", { name: "Skills…" });
|
||||
const memory = menu.getByRole("menuitem", { name: "Memory…" });
|
||||
const peerColour = await memory.locator("svg circle").evaluate((el) => getComputedStyle(el).stroke);
|
||||
await expect(skills.locator("svg path")).toHaveCSS("stroke", peerColour);
|
||||
const peerSize = await memory.locator("svg").evaluate((el) => {
|
||||
const { width, height } = getComputedStyle(el);
|
||||
return { width, height };
|
||||
});
|
||||
await expect(skills.locator("svg")).toHaveCSS("width", peerSize.width);
|
||||
await expect(skills.locator("svg")).toHaveCSS("height", peerSize.height);
|
||||
await skills.hover();
|
||||
await expect(skills.locator("svg path")).toHaveCSS("stroke", peerColour);
|
||||
await menu.screenshot({ path: testInfo.outputPath("add-context.png"), animations: "disabled" });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(menu).toBeHidden();
|
||||
});
|
||||
}
|
||||
@@ -284,6 +284,84 @@ async function expectNoSubmission(page: Page) {
|
||||
expect(await ipcCalls(page, "agent_create")).toEqual([]);
|
||||
}
|
||||
|
||||
test("effort descriptions share a column regardless of label and description length", async ({
|
||||
workbench: page,
|
||||
}, testInfo) => {
|
||||
const values = [
|
||||
["Low", "Fast responses with lighter reasoning"],
|
||||
["Medium", "Balances speed and reasoning depth for everyday tasks"],
|
||||
["High", "Greater reasoning depth for complex problems"],
|
||||
["Extra high", "Extra high reasoning depth for complex problems"],
|
||||
["Max", "Maximum reasoning depth for the hardest problems"],
|
||||
["Ultra", "Maximum reasoning with automatic task delegation"],
|
||||
];
|
||||
const effort = {
|
||||
...atlas,
|
||||
current: "high",
|
||||
values: values.map(([name, description]) => ({
|
||||
value: name!.toLowerCase(),
|
||||
name: name!,
|
||||
description: description!,
|
||||
})),
|
||||
};
|
||||
const fast = option(
|
||||
"fast",
|
||||
"model_config",
|
||||
[
|
||||
["false", "Off"],
|
||||
["true", "On"],
|
||||
],
|
||||
"false",
|
||||
);
|
||||
fast.name = "Fast";
|
||||
await seed(page, "editor", "task", "atlas", "ready", false, {
|
||||
...provider,
|
||||
thoughtLevels: { ...provider.thoughtLevels, atlas: [effort, fast] },
|
||||
});
|
||||
await effortLabel(page).click();
|
||||
const dialog = page.getByRole("dialog", { name: "Model settings" });
|
||||
const list = dialog.getByRole("listbox", { name: "Effort Level" });
|
||||
await expect(list.getByRole("option")).toHaveCount(values.length);
|
||||
await list.getByRole("option", { name: /^Low/ }).hover();
|
||||
await dialog.screenshot({ path: testInfo.outputPath("effort-descriptions.png"), scale: "css" });
|
||||
const columns = () =>
|
||||
list.getByRole("option").evaluateAll((rows) =>
|
||||
rows.map((row) => {
|
||||
const label = row.querySelectorAll<HTMLElement>("[title]")[0]!.getBoundingClientRect();
|
||||
const detail = row.querySelectorAll<HTMLElement>("[title]")[1]!.getBoundingClientRect();
|
||||
return {
|
||||
label: label.left,
|
||||
labelWidth: label.width,
|
||||
detail: detail.left,
|
||||
detailRight: detail.right,
|
||||
rowRight: row.getBoundingClientRect().right,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const assertAligned = async () => {
|
||||
const cells = await columns();
|
||||
expect(cells).toHaveLength(values.length);
|
||||
for (const cell of cells) {
|
||||
expect(cell.label).toBeCloseTo(cells[0]!.label);
|
||||
expect(cell.detail).toBeCloseTo(cells[0]!.detail);
|
||||
expect(cell.detailRight).toBeLessThanOrEqual(cell.rowRight);
|
||||
}
|
||||
return cells[0]!.labelWidth;
|
||||
};
|
||||
const originalWidth = await assertAligned();
|
||||
// The width is based on rendered text, not a hard-coded number of characters.
|
||||
await dialog.evaluate((element) => {
|
||||
element.style.fontSize = "18px";
|
||||
});
|
||||
await expect.poll(async () => (await columns())[0]!.labelWidth).toBeGreaterThan(originalWidth);
|
||||
await assertAligned();
|
||||
await dialog.evaluate((element) => {
|
||||
element.style.width = "240px";
|
||||
});
|
||||
await expect.poll(async () => (await dialog.boundingBox())!.width).toBeCloseTo(240, 0);
|
||||
await assertAligned();
|
||||
});
|
||||
|
||||
for (const surface of ["new", "task"] as const) {
|
||||
test(`${surface}: switch models from the list, then set effort and context from the settings chip`, async ({
|
||||
workbench: page,
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { AgentEntry, AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const base: AgentTask = {
|
||||
id: "recovery-style",
|
||||
title: "Recovery",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
|
||||
const question: AgentEntry = {
|
||||
type: "question",
|
||||
id: "question-style",
|
||||
title: "Choose the implementation",
|
||||
chosen: null,
|
||||
questions: [
|
||||
{
|
||||
header: "Implementation",
|
||||
question: "Which approach should I use?",
|
||||
options: [
|
||||
{
|
||||
label: "Reuse existing controls (Recommended)",
|
||||
description: "Keep the existing behavior and theme.",
|
||||
preview: "Use shared Button and Input components.",
|
||||
},
|
||||
{
|
||||
label: "Create a custom control",
|
||||
description: "Requires additional maintenance.",
|
||||
preview: "Introduce a new component.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
header: "Tests",
|
||||
question: "Which tests should I run?",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "Unit tests", description: "Run focused component tests." },
|
||||
{ label: "Browser tests", description: "Verify the rendered workflow." },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
for (const theme of ["light", "dark"] as const) {
|
||||
test(`${theme}: agent recovery and question controls follow the workbench style`, async ({
|
||||
workbench: page,
|
||||
}, testInfo) => {
|
||||
await page.evaluate(
|
||||
async ({ base, question, theme }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const themePath = "/src/workbench/theme.ts";
|
||||
const store = await import(storePath);
|
||||
await (await import(themePath)).setTheme(theme);
|
||||
const recovery: AgentTask = { ...base, interrupted: { reason: "quit", atMs: Date.now() - 120_000 } };
|
||||
const ask: AgentTask = { ...base, id: "ask-style", title: "Question" };
|
||||
const entries: AgentEntry[] = [
|
||||
{ type: "user", text: "Continue with the implementation.", attachments: [], recovery: "windowClose" },
|
||||
{ type: "agent", text: "The implementation is ready to continue." },
|
||||
];
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
tasks: new Map([
|
||||
[recovery.id, recovery],
|
||||
[ask.id, ask],
|
||||
]),
|
||||
entries: new Map([
|
||||
[recovery.id, entries],
|
||||
[ask.id, [question]],
|
||||
]),
|
||||
sessionLocation: "editor",
|
||||
});
|
||||
store.openTask(recovery.id);
|
||||
},
|
||||
{ base, question, theme },
|
||||
);
|
||||
const resume = page.getByRole("button", { name: "Resume", exact: true });
|
||||
await expect(resume).toBeVisible();
|
||||
const resumeColor = await resume.evaluate((el) => getComputedStyle(el).color);
|
||||
await expect(resume.locator("svg path")).toHaveCSS("stroke", resumeColor);
|
||||
const record = page.getByRole("separator").filter({ hasText: "Resumed after window close" });
|
||||
const recordColor = await record.evaluate((el) => getComputedStyle(el).color);
|
||||
await expect(record.locator("svg path")).toHaveCSS("stroke", recordColor);
|
||||
await page
|
||||
.getByRole("tabpanel", { name: "Recovery" })
|
||||
.screenshot({ path: testInfo.outputPath("recovery.png"), animations: "disabled" });
|
||||
await page.evaluate(async () => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const { useAgents } = await import(storePath);
|
||||
const tasks = new Map(useAgents.getState().tasks);
|
||||
const current = tasks.get("recovery-style") as AgentTask;
|
||||
tasks.set(current.id, {
|
||||
...current,
|
||||
status: "running",
|
||||
interrupted: null,
|
||||
retry: {
|
||||
attempt: 1,
|
||||
maxRetries: null,
|
||||
retryAtMs: Date.now() + 30_000,
|
||||
deadlineMs: Date.now() + 3_600_000,
|
||||
error: "Connection lost",
|
||||
},
|
||||
});
|
||||
useAgents.setState({ tasks });
|
||||
});
|
||||
const resumeNow = page.getByRole("button", { name: "Resume Now", exact: true });
|
||||
await expect(resumeNow).toBeVisible();
|
||||
await expect(resumeNow.locator("svg path")).toHaveCSS("stroke", resumeColor);
|
||||
await page.evaluate(async () => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
(await import(storePath)).openTask("ask-style");
|
||||
});
|
||||
const card = page.getByRole("form", { name: "Choose the implementation" });
|
||||
await expect(card).toBeVisible();
|
||||
await expect(card.getByRole("button", { name: "Submit" })).toBeDisabled();
|
||||
const buttonHeight = await card
|
||||
.getByRole("button", { name: "Submit" })
|
||||
.evaluate((el) => getComputedStyle(el).height);
|
||||
await expect(card.getByRole("button", { name: "Next" })).toHaveCSS("height", buttonHeight);
|
||||
await expect(card.getByRole("button", { name: "Previous" })).toHaveCSS("height", buttonHeight);
|
||||
await expect(card.getByText("Implementation", { exact: true })).toHaveCount(1);
|
||||
const choice = card.getByRole("radio", { name: /^Reuse existing controls/ });
|
||||
const row = choice.locator("xpath=ancestor::label");
|
||||
await expect(row).toHaveCSS("border-top-width", "0px");
|
||||
await card.screenshot({ path: testInfo.outputPath("question.png"), animations: "disabled" });
|
||||
await row.click();
|
||||
await expect(card.getByRole("tab", { name: "Tests" })).toHaveAttribute("aria-selected", "true");
|
||||
const checkbox = card.getByRole("checkbox", { name: /^Unit tests/ });
|
||||
const checkboxRow = checkbox.locator("xpath=ancestor::label");
|
||||
await checkboxRow.click();
|
||||
await expect(checkbox).toBeChecked();
|
||||
const selectionColor = await page.evaluate(() => {
|
||||
const probe = document.createElement("span");
|
||||
probe.style.backgroundColor = "var(--bg-tree-selected)";
|
||||
document.body.append(probe);
|
||||
const color = getComputedStyle(probe).backgroundColor;
|
||||
probe.remove();
|
||||
return color;
|
||||
});
|
||||
await expect(checkboxRow).toHaveCSS("background-color", selectionColor);
|
||||
await expect(card.getByRole("button", { name: "Submit" })).toBeEnabled();
|
||||
await card.screenshot({ path: testInfo.outputPath("question-selected.png"), animations: "disabled" });
|
||||
await page.setViewportSize({ width: 900, height: 800 });
|
||||
const composer = card.locator("xpath=following-sibling::div[1]").locator("[data-owns-file-drop]:visible");
|
||||
const cardBounds = await card.boundingBox();
|
||||
const composerBounds = await composer.boundingBox();
|
||||
expect(cardBounds).not.toBeNull();
|
||||
expect(composerBounds).not.toBeNull();
|
||||
expect(Math.abs(cardBounds!.x - composerBounds!.x)).toBeLessThan(2);
|
||||
expect(Math.abs(cardBounds!.width - composerBounds!.width)).toBeLessThan(2);
|
||||
await card.screenshot({ path: testInfo.outputPath("question-narrow.png"), animations: "disabled" });
|
||||
});
|
||||
}
|
||||
@@ -20,6 +20,96 @@ async function ratio(editor: Locator, preview: Locator, axis: "height" | "width"
|
||||
return source![axis] / (source![axis] + rendered![axis]);
|
||||
}
|
||||
|
||||
test("opens a repository version with all three read-only Markdown layouts", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const repo = "/dev/acme-api";
|
||||
const revision = "a".repeat(40);
|
||||
const path = "docs/history.md";
|
||||
const source = "# Committed heading\n\nThis text belongs to the selected commit.\n";
|
||||
const revisionInput = "/src/features/vcs/revisionInput.ts";
|
||||
const vcsStore = "/src/features/vcs/store.ts";
|
||||
const editorBackend = "/src/editor/core/backend.ts";
|
||||
const { openRevisionFile } = await import(revisionInput);
|
||||
const { useVcs } = await import(vcsStore);
|
||||
const { docBackend } = await import(editorBackend);
|
||||
|
||||
docBackend().files.set(`${repo}/${path}`, "# Working copy heading\n");
|
||||
useVcs.setState({ root: repo });
|
||||
window.__ipc.handlers.lsp_virtual_document = ({ uri }) => {
|
||||
docBackend().files.set(uri, source);
|
||||
return {
|
||||
uri,
|
||||
text: source,
|
||||
title: "history.md",
|
||||
description: revision,
|
||||
languageId: "markdown",
|
||||
decompiled: false,
|
||||
encoding: "utf-8",
|
||||
hasBom: false,
|
||||
canReloadEncoding: true,
|
||||
};
|
||||
};
|
||||
openRevisionFile(repo, revision, path);
|
||||
});
|
||||
|
||||
const editor = page.locator(".cm-content").filter({ hasText: "Committed heading" });
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await expect(editor).toBeVisible();
|
||||
await expect(editor).toHaveAttribute("aria-readonly", "true");
|
||||
|
||||
await page.getByRole("button", { name: "Preview Only", exact: true }).click();
|
||||
await expect(editor).toBeHidden();
|
||||
await expect(preview.getByRole("heading", { name: "Committed heading", exact: true })).toBeVisible();
|
||||
await expect(preview).toContainText("This text belongs to the selected commit.");
|
||||
|
||||
await page.getByRole("button", { name: "Editor and Preview", exact: true }).click();
|
||||
await expect(editor).toBeVisible();
|
||||
await expect(preview).toBeVisible();
|
||||
await editor.click();
|
||||
await page.keyboard.type("unexpected edit");
|
||||
await expect(editor).not.toContainText("unexpected edit");
|
||||
await expect(preview).not.toContainText("unexpected edit");
|
||||
|
||||
await page.getByRole("button", { name: "Editor Only", exact: true }).click();
|
||||
await expect(editor).toBeVisible();
|
||||
await expect(preview).toBeHidden();
|
||||
});
|
||||
|
||||
test("follows explicit Markdown anchors before generated heading IDs", async ({ workbench: page }) => {
|
||||
const source = [
|
||||
"[Reference](#ref-1) and [Heading](#ref-1-heading)",
|
||||
...Array.from({ length: 30 }, (_, index) => `Paragraph ${index + 1}`),
|
||||
"## Ref 1",
|
||||
...Array.from({ length: 30 }, (_, index) => `More text ${index + 1}`),
|
||||
'<a id="ref-1"></a>',
|
||||
"Reference text",
|
||||
...Array.from({ length: 30 }, (_, index) => `Further text ${index + 1}`),
|
||||
"## Ref 1 heading",
|
||||
].join("\n\n");
|
||||
await page.evaluate(async (source) => {
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const servicePath = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(backendPath);
|
||||
const { editorService } = await import(servicePath);
|
||||
const path = "/dev/acme-api/references.md";
|
||||
docBackend().files.set(path, source);
|
||||
await editorService().openFile(path);
|
||||
}, source);
|
||||
|
||||
await page.getByRole("button", { name: "Preview Only", exact: true }).click();
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
const referenceText = preview.getByText("Reference text", { exact: true });
|
||||
const heading = preview.getByRole("heading", { name: "Ref 1 heading", exact: true });
|
||||
await expect(preview.locator('[id="ref-1"]')).toHaveCount(1);
|
||||
await expect(referenceText).not.toBeInViewport();
|
||||
await preview.getByRole("link", { name: "Reference", exact: true }).click();
|
||||
await expect(referenceText).toBeInViewport();
|
||||
await expect(heading).not.toBeInViewport();
|
||||
await preview.getByRole("link", { name: "Heading", exact: true }).click();
|
||||
await expect(heading).toBeInViewport();
|
||||
});
|
||||
|
||||
test("copies fenced Markdown code with hover or keyboard in both preview layouts", async ({
|
||||
workbench: page,
|
||||
context,
|
||||
|
||||
@@ -51,6 +51,60 @@ test("suggests and configures a project-scoped GitHub account in Settings › Ve
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
|
||||
});
|
||||
|
||||
test("Update failure offers project-scoped GitHub account selection", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
let configuredAccount = "";
|
||||
const status = (): GhProjectAccountStatus => ({
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
],
|
||||
configuredAccount,
|
||||
effectiveAccount: configuredAccount || "alice",
|
||||
suggestedAccount: configuredAccount ? null : "alice-work",
|
||||
});
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
vcs_branch_info: () => ({ head: "main", upstream: "origin/main", headCommit: "c1", operation: null }),
|
||||
vcs_remote: () => {
|
||||
throw {
|
||||
kind: "invalid",
|
||||
message: "remote: Repository not found.\nfatal: repository 'https://github.com/acme/private.git/' not found",
|
||||
};
|
||||
},
|
||||
gh_project_account_status: () => status(),
|
||||
gh_set_project_account: ({ account }: { account: string }) => {
|
||||
configuredAccount = account;
|
||||
return status();
|
||||
},
|
||||
settings_get_global: () => ({}),
|
||||
window_open_settings: () => {
|
||||
throw { kind: "unavailable", message: "separate settings window disabled in browser test" };
|
||||
},
|
||||
});
|
||||
const opsModule = "/src/features/vcs/ops.ts";
|
||||
const { runRemote } = await import(/* @vite-ignore */ opsModule);
|
||||
await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/dev/acme-api"]);
|
||||
});
|
||||
|
||||
await expect(page.getByText("Update failed", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/Repository not found/)).toBeVisible();
|
||||
await expect(page.getByText(/alice may not have access/)).toBeVisible();
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([]);
|
||||
const settingsLink = page.getByRole("button", { name: "GitHub Settings", exact: true });
|
||||
await expect(settingsLink).toBeVisible();
|
||||
if (process.env.CAPTURE_GH_AUTH_FAILURE) {
|
||||
await page.screenshot({ path: process.env.CAPTURE_GH_AUTH_FAILURE, animations: "disabled" });
|
||||
}
|
||||
await settingsLink.click();
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("Automatic (alice)");
|
||||
await dialog.getByRole("button", { name: "Use alice-work for this project" }).click();
|
||||
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("alice-work");
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
|
||||
});
|
||||
|
||||
test("adds a GitHub account in Settings › Version Control › GitHub with OAuth device-code banner", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -41,7 +41,8 @@ test("project switcher keeps names and metadata on separate lines and highlights
|
||||
|
||||
await page.getByRole("button", { name: "acme-api", exact: true }).click();
|
||||
const popup = page.getByRole("dialog", { name: "Projects" });
|
||||
await expect(popup.getByText("Release Tools")).toBeVisible();
|
||||
await expect(popup.getByText("Recent Projects")).toBeVisible();
|
||||
await expect(popup.getByText("Release Tools")).toHaveCount(0);
|
||||
const local = popup.getByRole("option", { name: new RegExp(NAME) });
|
||||
await expectBelow(local, NAME, PATH);
|
||||
await expectBelow(local, PATH, BRANCH);
|
||||
@@ -51,10 +52,8 @@ test("project switcher keeps names and metadata on separate lines and highlights
|
||||
|
||||
const remote = popup.getByRole("option", { name: /Payment Ledger/ });
|
||||
await expect(remote.locator("[data-remote-badge]")).toHaveCount(1);
|
||||
await expect(remote.locator('[data-remote-kind="ssh"]')).toBeVisible();
|
||||
await expect(local.locator("[data-remote-badge]")).toHaveCount(0);
|
||||
await expectBelow(remote, "Payment Ledger", HOST);
|
||||
await expectBelow(remote, HOST, REMOTE_PATH);
|
||||
await expectBelow(remote, "Payment Ledger", `${HOST}:${REMOTE_PATH}`);
|
||||
|
||||
await page.setViewportSize({ width: 960, height: 700 });
|
||||
await page.keyboard.type(HOST);
|
||||
@@ -66,7 +65,7 @@ test("project switcher keeps names and metadata on separate lines and highlights
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.type(`${HOST}:${REMOTE_PATH}`);
|
||||
await expect(remote.locator("mark")).toHaveText([HOST, REMOTE_PATH]);
|
||||
await expect(remote.locator("mark")).toHaveText(`${HOST}:${REMOTE_PATH}`);
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.type("acme-api");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("groups recent projects by Local and remote host across Welcome, Recent Projects, and Project Popup without row overlap", async ({
|
||||
test("keeps the project switcher flat while grouping Welcome and Recent Projects without row overlap", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 980, height: 740 });
|
||||
@@ -71,15 +71,43 @@ test("groups recent projects by Local and remote host across Welcome, Recent Pro
|
||||
}
|
||||
});
|
||||
|
||||
// 1. Project Widget dropdown keeps Open Projects flat and groups Recent Projects by host.
|
||||
// 1. The project widget uses the same row layout for local and remote projects.
|
||||
await page.getByRole("button", { name: "openidea_all" }).click();
|
||||
const projectPopup = page.getByRole("dialog", { name: "Projects" });
|
||||
await expect(projectPopup).toBeVisible();
|
||||
await expect(projectPopup).toContainText("Open Projects");
|
||||
await expect(projectPopup).toContainText("Recent Projects");
|
||||
await expect(projectPopup).toContainText("dev-mbp1.local");
|
||||
await expect(projectPopup).toContainText("Local");
|
||||
await expect(projectPopup.getByText("Local", { exact: true })).toHaveCount(0);
|
||||
await expect(projectPopup).toContainText("Ubuntu-24.04");
|
||||
// The two section headers and every project badge share the same left inset.
|
||||
const headers = [
|
||||
projectPopup.getByText("Open Projects", { exact: true }),
|
||||
projectPopup.getByText("Recent Projects", { exact: true }),
|
||||
];
|
||||
const headerMetrics = await Promise.all(
|
||||
headers.map((header) =>
|
||||
header.evaluate((el) => {
|
||||
const style = getComputedStyle(el);
|
||||
const rect = el.getBoundingClientRect();
|
||||
return { x: rect.x + parseFloat(style.paddingLeft), height: rect.height, fontSize: style.fontSize };
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(headerMetrics[1]).toEqual(headerMetrics[0]);
|
||||
const projectRows = projectPopup.getByRole("option").filter({ hasText: "/git/" });
|
||||
await expect(projectRows).toHaveCount(7);
|
||||
await expect(projectRows.locator("[data-remote-badge]")).toHaveCount(4);
|
||||
const rowMetrics = await projectRows.evaluateAll((rows) =>
|
||||
rows.map((el) => ({
|
||||
x: el.firstElementChild!.getBoundingClientRect().x,
|
||||
height: el.getBoundingClientRect().height,
|
||||
})),
|
||||
);
|
||||
for (const row of rowMetrics) expect(row.x).toBeCloseTo(headerMetrics[0]!.x, 0);
|
||||
// Both open projects have no branch metadata and must have identical heights.
|
||||
expect(rowMetrics[0]!.height).toBeCloseTo(rowMetrics[1]!.height, 0);
|
||||
await expect(projectPopup.getByRole("separator")).toHaveCount(2);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(projectPopup).toBeHidden();
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ async function selectPage(page: Page, id: string) {
|
||||
}, id);
|
||||
}
|
||||
|
||||
test("Git settings expose fetch tag modes and the check-only mode", async ({ workbench: page }) => {
|
||||
test("Git settings expose fetch tag modes and the check-only mode", async ({ workbench: page }, testInfo) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
@@ -20,6 +20,13 @@ test("Git settings expose fetch tag modes and the check-only mode", async ({ wor
|
||||
for (const label of ["Auto", "Sync", "Always", "Never"]) {
|
||||
await expect(choices.getByRole("option", { name: new RegExp(`^${label}`) })).toBeVisible();
|
||||
}
|
||||
const starts = await choices
|
||||
.getByRole("option")
|
||||
.evaluateAll((rows) =>
|
||||
rows.map((row) => row.querySelectorAll<HTMLElement>("[title]")[1]!.getBoundingClientRect().left),
|
||||
);
|
||||
for (const start of starts) expect(start).toBeCloseTo(starts[0]!);
|
||||
await choices.screenshot({ path: testInfo.outputPath("fetch-tags-descriptions.png") });
|
||||
const sync = choices.getByRole("option", { name: /^Sync/ });
|
||||
await expect(sync).toContainText("Delete local tags missing on remote");
|
||||
await sync.click();
|
||||
@@ -116,7 +123,7 @@ test("Git Log settings group display and column options with aligned checkboxes"
|
||||
const columns = dialog.getByRole("region", { name: "Visible columns" });
|
||||
const tagNames = view.getByRole("checkbox", { name: "Show tag names" });
|
||||
const hash = columns.getByRole("checkbox", { name: "Hash" });
|
||||
await expect(view.getByRole("checkbox")).toHaveCount(5);
|
||||
await expect(view.getByRole("checkbox")).toHaveCount(4);
|
||||
await expect(columns.getByRole("checkbox")).toHaveCount(4);
|
||||
|
||||
for (const width of [1000, 520]) {
|
||||
|
||||
@@ -128,6 +128,24 @@ test("Project Structure keeps every details pane usable in a compact window", as
|
||||
await expect(details).toBeAttached();
|
||||
expect((await details.boundingBox())!.width).toBeGreaterThan(200);
|
||||
}
|
||||
|
||||
const root = `/external/${"long-content-root/".repeat(12)}sources`;
|
||||
await page.evaluate(async (root) => {
|
||||
const path = "/src/features/settings/model/staging.ts";
|
||||
const { stage } = await import(/* @vite-ignore */ path);
|
||||
stage("projectStructure", "project", "projectStructure.contentRoots", [root]);
|
||||
}, root);
|
||||
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Add Content Root");
|
||||
await expect(dialog.getByRole("tab", { name: "Sources" })).toHaveAttribute("aria-selected", "true");
|
||||
const path = dialog.getByRole("region", { name: "Marked folders" }).getByText(root, { exact: true });
|
||||
await expect(path).toBeVisible();
|
||||
expect(
|
||||
await path.evaluate((element) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element);
|
||||
return range.getClientRects().length;
|
||||
}),
|
||||
).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
test("Project Structure starts with compact navigation and remembers the divider", async ({ workbench: page }) => {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import "../src/styles/tokens.css";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { syntaxHighlighting } from "@codemirror/language";
|
||||
import { openideaHighlightStyle } from "../src/editor/core/cm/highlight";
|
||||
import { vueLanguage } from "../src/editor/core/cm/vue";
|
||||
|
||||
document.documentElement.dataset.theme = new URLSearchParams(location.search).get("theme") ?? "dark";
|
||||
new EditorView({
|
||||
parent: document.body,
|
||||
doc: '<template>\n <div><Icon /><el-input v-model="x"></el-input></div>\n</template>\n',
|
||||
extensions: [vueLanguage(), syntaxHighlighting(openideaHighlightStyle)],
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="./vueHighlight.fixture.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,14 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
for (const [theme, custom, tag] of [
|
||||
["dark", "rgb(47, 186, 163)", "rgb(213, 183, 120)"],
|
||||
["light", "rgb(178, 29, 191)", "rgb(0, 51, 179)"],
|
||||
] as const) {
|
||||
test(`Vue component tags have the custom tag colour (${theme})`, async ({ page }) => {
|
||||
await page.goto(`/e2e/vueHighlight.html?theme=${theme}`);
|
||||
const line = page.locator(".cm-line").nth(1);
|
||||
await expect(line.getByText("Icon", { exact: true })).toHaveCSS("color", custom);
|
||||
await expect(line.getByText("el-input", { exact: true }).first()).toHaveCSS("color", custom);
|
||||
await expect(line.getByText("div", { exact: true }).first()).toHaveCSS("color", tag);
|
||||
});
|
||||
}
|
||||
@@ -15,6 +15,18 @@ int main(void) {
|
||||
}
|
||||
'''
|
||||
|
||||
[[language-servers]]
|
||||
# Xcode projects with a BSP config: plain clangd finds no compile flags there, while
|
||||
# sourcekit-lsp reads them through the build server and serves C-family files with its
|
||||
# own clangd. Only `buildServer.json` (xcode-build-server, sourcekit-xcode-bsp): a bare
|
||||
# `.bsp` directory also belongs to sbt, Mill and Bazel.
|
||||
name = "sourcekit-lsp"
|
||||
command = "sourcekit-lsp"
|
||||
root-markers = ["buildServer.json"]
|
||||
require-root-marker = true
|
||||
replaces = ["clangd"]
|
||||
install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); https://www.swift.org/install"
|
||||
|
||||
[[language-servers]]
|
||||
name = "clangd"
|
||||
command = "clangd"
|
||||
|
||||
@@ -19,6 +19,18 @@ int main() {
|
||||
[rainbow-brackets]
|
||||
angle = ["TemplateArgumentList", "TemplateParameterList"]
|
||||
|
||||
[[language-servers]]
|
||||
# Xcode projects with a BSP config: plain clangd finds no compile flags there, while
|
||||
# sourcekit-lsp reads them through the build server and serves C-family files with its
|
||||
# own clangd. Only `buildServer.json` (xcode-build-server, sourcekit-xcode-bsp): a bare
|
||||
# `.bsp` directory also belongs to sbt, Mill and Bazel.
|
||||
name = "sourcekit-lsp"
|
||||
command = "sourcekit-lsp"
|
||||
root-markers = ["buildServer.json"]
|
||||
require-root-marker = true
|
||||
replaces = ["clangd"]
|
||||
install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); https://www.swift.org/install"
|
||||
|
||||
[[language-servers]]
|
||||
name = "clangd"
|
||||
command = "clangd"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
id = "json"
|
||||
name = "JSON"
|
||||
formatter = { tool = "prettier", parser = "json", range = true }
|
||||
extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map", "uproject", "uplugin"]
|
||||
extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map", "uproject", "uplugin", "xcstrings"]
|
||||
filenames = [".prettierrc", ".watchmanconfig", "composer.lock", ".arcconfig"]
|
||||
indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "JSON"
|
||||
|
||||
@@ -5,6 +5,19 @@ line-comment = "//"
|
||||
block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
ui-mode = "Objective-C"
|
||||
tree-sitter = "objc"
|
||||
|
||||
[[language-servers]]
|
||||
# Xcode projects with a BSP config: plain clangd finds no compile flags there, while
|
||||
# sourcekit-lsp reads them through the build server and serves C-family files with its
|
||||
# own clangd. Only `buildServer.json` (xcode-build-server, sourcekit-xcode-bsp): a bare
|
||||
# `.bsp` directory also belongs to sbt, Mill and Bazel.
|
||||
name = "sourcekit-lsp"
|
||||
command = "sourcekit-lsp"
|
||||
root-markers = ["buildServer.json"]
|
||||
require-root-marker = true
|
||||
replaces = ["clangd"]
|
||||
install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); https://www.swift.org/install"
|
||||
|
||||
[[language-servers]]
|
||||
name = "clangd"
|
||||
|
||||
@@ -5,6 +5,19 @@ line-comment = "//"
|
||||
block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
ui-mode = "Objective-C++"
|
||||
tree-sitter = "objc"
|
||||
|
||||
[[language-servers]]
|
||||
# Xcode projects with a BSP config: plain clangd finds no compile flags there, while
|
||||
# sourcekit-lsp reads them through the build server and serves C-family files with its
|
||||
# own clangd. Only `buildServer.json` (xcode-build-server, sourcekit-xcode-bsp): a bare
|
||||
# `.bsp` directory also belongs to sbt, Mill and Bazel.
|
||||
name = "sourcekit-lsp"
|
||||
command = "sourcekit-lsp"
|
||||
root-markers = ["buildServer.json"]
|
||||
require-root-marker = true
|
||||
replaces = ["clangd"]
|
||||
install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); https://www.swift.org/install"
|
||||
|
||||
[[language-servers]]
|
||||
name = "clangd"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
id = "strings"
|
||||
name = "Strings"
|
||||
extensions = ["strings"]
|
||||
line-comment = "//"
|
||||
block-comment = ["/*", "*/"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
# Apple `.strings`: `"key" = "value";` with C comments, so the C mode colours it.
|
||||
ui-mode = "C"
|
||||
@@ -0,0 +1,7 @@
|
||||
id = "xcconfig"
|
||||
name = "Xcode Config"
|
||||
extensions = ["xcconfig"]
|
||||
line-comment = "//"
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
# C-like: `//` comments, `#include` directives and quoted values.
|
||||
ui-mode = "C"
|
||||
@@ -1,6 +1,6 @@
|
||||
id = "xml"
|
||||
name = "XML"
|
||||
extensions = ["xml", "xsd", "xsl", "xslt", "svg", "plist", "csproj", "fsproj", "vbproj", "props", "targets", "nuspec", "xaml", "resx", "wsdl", "fxml", "iml", "jnlp", "rss", "atom", "xliff", "xlf", "storyboard", "xib", "tld", "pom"]
|
||||
extensions = ["xml", "xsd", "xsl", "xslt", "svg", "plist", "entitlements", "xcprivacy", "csproj", "fsproj", "vbproj", "props", "targets", "nuspec", "xaml", "resx", "wsdl", "fxml", "iml", "jnlp", "rss", "atom", "xliff", "xlf", "storyboard", "xib", "tld", "pom"]
|
||||
filenames = ["NuGet.Config", "Directory.Build.targets", "web.config", "app.config"]
|
||||
first-line = "^<\\?xml\\b"
|
||||
block-comment = ["<!--", "-->"]
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
"--syn-escape": "#7fd1c4",
|
||||
"--syn-regexp": "#7fd1c4",
|
||||
"--syn-tag": "#e0a46e",
|
||||
"--syn-custom-tag": "#8fd4c9",
|
||||
"--syn-attribute": "#9fc0e8",
|
||||
"--syn-todo": "#7fd1c4",
|
||||
"--syn-link": "#6fc3df",
|
||||
|
||||
@@ -138,6 +138,8 @@
|
||||
"--bg-search-match": "#ba9752",
|
||||
"--bg-search-match-current": "#f2c55c",
|
||||
"--fg-search-match": "#14171c",
|
||||
"--bg-list-match": "#ba9752",
|
||||
"--fg-list-match": "#14171c",
|
||||
"--bg-dialog": "#14171c",
|
||||
"--bg-popup-inline": "#1f252e",
|
||||
"--bg-popup-advertiser": "#1f252e",
|
||||
|
||||
@@ -333,7 +333,7 @@ a token.
|
||||
|
||||
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
|
||||
|
||||
272 themeable tokens: 126 in the UI theme file, 146 in the editor colour scheme file.
|
||||
275 themeable tokens: 128 in the UI theme file, 147 in the editor colour scheme file.
|
||||
|
||||
### Surfaces (UI theme)
|
||||
|
||||
@@ -482,6 +482,7 @@ a token.
|
||||
| `--syn-escape` | `#cf8e6d` | `#0037a6` |
|
||||
| `--syn-regexp` | `#42c3d4` | `#264eff` |
|
||||
| `--syn-tag` | `#d5b778` | `#0033b3` |
|
||||
| `--syn-custom-tag` | `#2fbaa3` | `#b21dbf` |
|
||||
| `--syn-attribute` | `#bcbec4` | `#174ad4` |
|
||||
| `--syn-todo` | `#8bb33d` | `#008dde` |
|
||||
| `--syn-link` | `#548af7` | `#006dcc` |
|
||||
@@ -662,6 +663,8 @@ a token.
|
||||
| `--bg-search-match` | `#ba9752` | `#fee6b1` |
|
||||
| `--bg-search-match-current` | `#f2c55c` | `#fcd47e` |
|
||||
| `--fg-search-match` | `#191a1c` | `#000000` |
|
||||
| `--bg-list-match` | `#ba9752` | `#fee6b1` |
|
||||
| `--fg-list-match` | `#191a1c` | `#000000` |
|
||||
| `--bg-dialog` | `#191a1c` | `#f7f8f9` |
|
||||
| `--bg-popup-inline` | `#26282c` | `#f7f8f9` |
|
||||
| `--bg-popup-advertiser` | `#26282c` | `#f7f8f9` |
|
||||
|
||||
+29
-5
@@ -973,9 +973,9 @@ export const commands = {
|
||||
iosSimulatorOpenApp: () => typedError<null, IdeError>(__TAURI_INVOKE("ios_simulator_open_app")),
|
||||
iosSimulatorShutdown: (udid: string) => typedError<null, IdeError>(__TAURI_INVOKE("ios_simulator_shutdown", { udid })),
|
||||
/**
|
||||
* The available iOS simulators, booted first; `None` outside macOS or when the project has no
|
||||
* Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
|
||||
* no change feed, and one listing takes a fraction of a second.
|
||||
* The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside
|
||||
* macOS or when the project has no Xcode project or workspace at its root. Asked again whenever
|
||||
* the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second.
|
||||
*/
|
||||
iosSimulators: () => typedError<IosSimulator[] | null, IdeError>(__TAURI_INVOKE("ios_simulators")),
|
||||
/** Incremental build of the jdtls workspace serving `module` (e.g. before HotSwap). */
|
||||
@@ -5975,6 +5975,20 @@ export type CustomKeymap = {
|
||||
overrides?: { [key in string]: string[] },
|
||||
};
|
||||
|
||||
/** Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through. */
|
||||
export type CycleCaseSettings = {
|
||||
/** `snake_case` */
|
||||
snake?: boolean,
|
||||
/** `SCREAMING_SNAKE_CASE` */
|
||||
screaming?: boolean,
|
||||
/** `kebab-case` */
|
||||
kebab?: boolean,
|
||||
/** `camelCase` */
|
||||
camel?: boolean,
|
||||
/** `PascalCase` */
|
||||
pascal?: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* A field watchpoint (DAP data breakpoint) on a `dataId` from [`DebugManager::data_breakpoint_info`]
|
||||
* (java-debug ids, `Class#field`, stay valid across sessions).
|
||||
@@ -10044,14 +10058,22 @@ export type InvalidateCachesOptions = {
|
||||
buildCaches?: boolean,
|
||||
};
|
||||
|
||||
/** One simulator `simctl list devices available` reports. */
|
||||
/**
|
||||
* One simulator `simctl list devices available` reports, or one physical device
|
||||
* `devicectl list devices` knows.
|
||||
*/
|
||||
export type IosSimulator = {
|
||||
udid: string,
|
||||
name: string,
|
||||
/** The runtime, as Xcode shows it: `iOS 27.0`. */
|
||||
runtime: string,
|
||||
/** `Booted`, `Shutdown`, `Booting`, `Shutting Down`. */
|
||||
/**
|
||||
* `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`],
|
||||
* [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`].
|
||||
*/
|
||||
state: string,
|
||||
/** An iPhone or iPad rather than a simulator. */
|
||||
physical: boolean,
|
||||
};
|
||||
|
||||
/** A binary argument or result of an IPC command. */
|
||||
@@ -15065,6 +15087,8 @@ export type SmartKeysSettings = {
|
||||
insertDocStub?: boolean,
|
||||
/** Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`. */
|
||||
backspaceUnindent?: string,
|
||||
/** The styles Cycle Identifier Case goes through. */
|
||||
cycleCase?: CycleCaseSettings,
|
||||
};
|
||||
|
||||
export type SourceFolder = {
|
||||
|
||||
@@ -543,9 +543,10 @@ export type ContributedFormatter = (
|
||||
state: EditorState,
|
||||
range: { from: number; to: number } | null,
|
||||
) => Array<{ from: number; to: number; insert: string }>;
|
||||
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. */
|
||||
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. May be async when
|
||||
* the answer needs a lookup; `false` hands the position back to the language server. */
|
||||
export interface ContributedDefinition {
|
||||
(view: EditorView, pos: number): boolean;
|
||||
(view: EditorView, pos: number): boolean | Promise<boolean>;
|
||||
/** Cheap, side-effect-free eligibility for hover underline and navigation probing. */
|
||||
canHandle?(state: EditorState, pos: number): boolean;
|
||||
}
|
||||
|
||||
@@ -139,6 +139,7 @@ import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
|
||||
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import { toggleReadOnly } from "./fileAttributes";
|
||||
import { codeVisionShown, toggleCodeVision } from "./codeVision";
|
||||
import { breadcrumbsShown, toggleBreadcrumbs } from "./breadcrumbs";
|
||||
import { appearanceSwitches, localAppearanceSwitches, toggleAppearance, type AppearanceSwitch } from "./gutterMenu";
|
||||
import { openNavBarPopup } from "./view/NavBarPopup";
|
||||
import {
|
||||
@@ -779,6 +780,11 @@ export async function toggleSchemeSwitch(key: SchemeSwitch, on = !editorPrefs()[
|
||||
}
|
||||
}
|
||||
|
||||
function activeBreadcrumbsShown(): boolean {
|
||||
const slot = activeSlot();
|
||||
return !!slot && breadcrumbsShown(slot.tabId, editorPrefs().breadcrumbs, slot.model.info?.id);
|
||||
}
|
||||
|
||||
/** IDEA's StickyLinesDisableForLangAction: the active document's known base language, if enabled. */
|
||||
function activeStickyLinesLanguage(): string | null {
|
||||
// A notebook cell has no base document: never change the last text tab's language setting.
|
||||
@@ -964,6 +970,20 @@ export function registerEditorActions(): () => void {
|
||||
localAppearanceSwitch("editor.toggleLocalWhitespaces", "whitespaces"),
|
||||
localAppearanceSwitch("editor.toggleLocalGutterIcons", "gutterIcons"),
|
||||
localAppearanceSwitch("editor.toggleLocalIndentGuides", "indentGuides"),
|
||||
{
|
||||
id: "editor.toggleBreadcrumbs",
|
||||
title: "Show Breadcrumbs",
|
||||
description: "Toggle display of the Breadcrumbs bar in the current editor.",
|
||||
category: "View",
|
||||
keywords: ["breadcrumbs", "navigation bar", "hide breadcrumbs"],
|
||||
when: "textEditorActive",
|
||||
enabled: () => !focusedCellEditor() && !!activeSlot(),
|
||||
toggled: activeBreadcrumbsShown,
|
||||
run: () => {
|
||||
const slot = activeSlot();
|
||||
if (slot) toggleBreadcrumbs(slot.tabId, editorPrefs().breadcrumbs, slot.model.info?.id);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "editor.toggleCodeVision",
|
||||
title: "Code Vision",
|
||||
@@ -1120,6 +1140,30 @@ export function registerEditorActions(): () => void {
|
||||
activeSlot()?.model.toggleRenderedDocs();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "editor.toggleRenderedDocsForAll",
|
||||
title: "Render All Doc Comments",
|
||||
category: "View",
|
||||
keywords: ["render documentation comments", "javadoc", "rendered doc", "comments", "all editors"],
|
||||
toggled: () => editorPrefs().appearance.renderDocComments,
|
||||
run: async () => {
|
||||
const on = !editorPrefs().appearance.renderDocComments;
|
||||
try {
|
||||
useProject.setState({
|
||||
settings: await call(
|
||||
commands.settingsSet("global", "editor.appearance.renderDocComments", JSON.stringify(on)),
|
||||
),
|
||||
});
|
||||
editorController().manager.resetRenderedDocs();
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot change the setting",
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
text("editor.toggleRenderedView", "Toggle Rendered View", (v) => toggleRenderedViewAtCaret(v), {
|
||||
category: "View",
|
||||
keywords: ["reader mode", "render documentation comment", "javadoc", "edit comment"],
|
||||
@@ -1328,7 +1372,7 @@ export function registerEditorActions(): () => void {
|
||||
edit("code.joinLines", "Join Lines", (v) => joinLines(v)),
|
||||
edit("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
|
||||
edit("code.transpose", "Transpose", (v) => transpose(v), { category: "Editor Actions" }),
|
||||
edit("code.cycleCase", "Cycle Identifier Case", (v) => cycleCase(v), {
|
||||
edit("code.cycleCase", "Cycle Identifier Case", (v) => cycleCase(v, editorPrefs().smartKeys.cycleCase), {
|
||||
keywords: ["camel", "snake", "kebab", "pascal", "screaming"],
|
||||
}),
|
||||
caret("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
|
||||
|
||||
@@ -4,9 +4,10 @@ import type { EditorSlot as EditorSlotType } from "./model/slot";
|
||||
import type { DocModel } from "./model/document";
|
||||
|
||||
let activeSlot: Partial<EditorSlotType> | null = null;
|
||||
let activeManager: { resetRenderedDocs(): void } | null = null;
|
||||
vi.mock("./controller", async (importOriginal) => ({
|
||||
...(await importOriginal<object>()),
|
||||
editorController: () => ({ activeSlot }),
|
||||
editorController: () => ({ activeSlot, manager: activeManager }),
|
||||
}));
|
||||
|
||||
/** Writes the dotted key into the current settings, as the host does. */
|
||||
@@ -35,8 +36,10 @@ const { createMemoryBackend } = await import("./backend");
|
||||
const { DocumentManager } = await import("./model/document");
|
||||
const { EditorSlot } = await import("./model/slot");
|
||||
const { gutterIconsOn, localAppearanceField } = await import("./cm/prefs");
|
||||
const { renderDocComments } = await import("./cm/renderedDocs");
|
||||
const { DEFAULT_SETTINGS } = await import("@/features/settings/model/schema");
|
||||
const { resetDistractionFree } = await import("@/workbench/distractionFree");
|
||||
const { clearBreadcrumbOverrides, pruneBreadcrumbOverrides, useBreadcrumbOverrides } = await import("./breadcrumbs");
|
||||
|
||||
let dispose: () => void;
|
||||
beforeAll(() => {
|
||||
@@ -45,6 +48,8 @@ beforeAll(() => {
|
||||
afterAll(() => dispose());
|
||||
afterEach(() => {
|
||||
activeSlot = null;
|
||||
activeManager = null;
|
||||
clearBreadcrumbOverrides();
|
||||
useProject.setState({ settings: null });
|
||||
useContextKeys.setState({}, true);
|
||||
resetDistractionFree();
|
||||
@@ -170,6 +175,7 @@ describe("active editor appearance toggles", () => {
|
||||
settings: () => useProject.getState().settings,
|
||||
notify: vi.fn(),
|
||||
});
|
||||
activeManager = manager;
|
||||
const model = await manager.acquire(file);
|
||||
models.add(model);
|
||||
const slot = new EditorSlot(model, `${file}-${slots.size}`, {
|
||||
@@ -255,6 +261,36 @@ describe("active editor appearance toggles", () => {
|
||||
for (const control of controls) expect(actionToggled(getAction(control.id))).toBe(local[control.key]);
|
||||
});
|
||||
|
||||
it("toggles rendered doc comments globally and clears every open document's override", async () => {
|
||||
const first = await openSlot();
|
||||
const second = await openSlot(otherPath);
|
||||
activeSlot = first;
|
||||
first.model.toggleRenderedDocs();
|
||||
second.model.toggleRenderedDocs();
|
||||
second.model.toggleRenderedDocs();
|
||||
expect(first.model.renderedDocsOn()).toBe(true);
|
||||
expect(second.model.renderedDocsOn()).toBe(false);
|
||||
|
||||
const action = getAction("editor.toggleRenderedDocsForAll");
|
||||
expect(action).toMatchObject({ title: "Render All Doc Comments", category: "View" });
|
||||
expect(resolveActionId("ToggleRenderedDocPresentationForAll")).toBe("editor.toggleRenderedDocsForAll");
|
||||
expect(actionToggled(action)).toBe(false);
|
||||
|
||||
expect(await executeAction("editor.toggleRenderedDocsForAll")).toBe(true);
|
||||
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.appearance.renderDocComments", "true");
|
||||
expect(actionToggled(action)).toBe(true);
|
||||
expect(first.model.renderedDocsOverride).toBeNull();
|
||||
expect(second.model.renderedDocsOverride).toBeNull();
|
||||
expect(first.currentState().facet(renderDocComments)).toBe(true);
|
||||
expect(second.currentState().facet(renderDocComments)).toBe(true);
|
||||
|
||||
expect(await executeAction("editor.toggleRenderedDocsForAll")).toBe(true);
|
||||
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.appearance.renderDocComments", "false");
|
||||
expect(actionToggled(action)).toBe(false);
|
||||
expect(first.currentState().facet(renderDocComments)).toBe(false);
|
||||
expect(second.currentState().facet(renderDocComments)).toBe(false);
|
||||
});
|
||||
|
||||
it("lets a local Gutter Icons override enable providers while the global setting is off", async () => {
|
||||
setGlobalAppearance({ lineNumbers: true, whitespaces: false, gutterIcons: false, indentGuides: true });
|
||||
const first = await openSlot();
|
||||
@@ -280,6 +316,94 @@ describe("active editor appearance toggles", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Show Breadcrumbs action", () => {
|
||||
const id = "editor.toggleBreadcrumbs";
|
||||
const activate = (tabId: string, language = "typescript") => {
|
||||
activeSlot = { disposed: false, tabId, model: { info: { id: language } } } as never;
|
||||
};
|
||||
const setBreadcrumbs = (show: boolean, disabledLanguages: string[] = []) => {
|
||||
useProject.setState({
|
||||
settings: { editor: { breadcrumbs: { show, placement: "bottom", disabledLanguages } } } as never,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
setBreadcrumbs(true);
|
||||
useContextKeys.setState({ textEditorActive: true });
|
||||
});
|
||||
|
||||
it("is a View action mapped from IDEA", () => {
|
||||
expect(getAction(id)).toMatchObject({
|
||||
title: "Show Breadcrumbs",
|
||||
description: "Toggle display of the Breadcrumbs bar in the current editor.",
|
||||
category: "View",
|
||||
when: "textEditorActive",
|
||||
});
|
||||
expect(resolveActionId("EditorToggleShowBreadcrumbs")).toBe(id);
|
||||
});
|
||||
|
||||
it("changes only the active editor and leaves global settings untouched", async () => {
|
||||
activate("t1");
|
||||
const settings = structuredClone(useProject.getState().settings);
|
||||
const action = getAction(id);
|
||||
expect(actionToggled(action)).toBe(true);
|
||||
expect(await executeAction(id)).toBe(true);
|
||||
expect(actionToggled(action)).toBe(false);
|
||||
expect(useBreadcrumbOverrides.getState()).toEqual({ t1: false });
|
||||
expect(useProject.getState().settings).toEqual(settings);
|
||||
expect(ipc.settingsSet).not.toHaveBeenCalled();
|
||||
|
||||
activate("t2");
|
||||
expect(actionToggled(action)).toBe(true);
|
||||
expect(await executeAction(id)).toBe(true);
|
||||
expect(useBreadcrumbOverrides.getState()).toEqual({ t1: false, t2: false });
|
||||
activate("t1");
|
||||
expect(await executeAction(id)).toBe(true);
|
||||
expect(useBreadcrumbOverrides.getState()).toEqual({ t1: true, t2: false });
|
||||
});
|
||||
|
||||
it("lets a forced value override the global setting and disabled language", async () => {
|
||||
setBreadcrumbs(false, ["typescript"]);
|
||||
activate("t1");
|
||||
const action = getAction(id);
|
||||
expect(actionToggled(action)).toBe(false);
|
||||
expect(await executeAction(id)).toBe(true);
|
||||
expect(actionToggled(action)).toBe(true);
|
||||
activate("t2");
|
||||
expect(actionToggled(action)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the override while untouched editors follow global changes", async () => {
|
||||
setBreadcrumbs(false);
|
||||
activate("t1");
|
||||
expect(await executeAction(id)).toBe(true);
|
||||
setBreadcrumbs(true);
|
||||
expect(actionToggled(getAction(id))).toBe(true);
|
||||
activate("t2");
|
||||
expect(actionToggled(getAction(id))).toBe(true);
|
||||
setBreadcrumbs(false);
|
||||
expect(actionToggled(getAction(id))).toBe(false);
|
||||
activate("t1");
|
||||
expect(actionToggled(getAction(id))).toBe(true);
|
||||
});
|
||||
|
||||
it("does not run without an active text editor", async () => {
|
||||
expect(await executeAction(id)).toBe(false);
|
||||
activate("t1");
|
||||
useContextKeys.setState({ textEditorActive: false });
|
||||
expect(await executeAction(id)).toBe(false);
|
||||
expect(useBreadcrumbOverrides.getState()).toEqual({});
|
||||
});
|
||||
|
||||
it("drops overrides for closed editors and when the session stops", () => {
|
||||
useBreadcrumbOverrides.setState({ t1: false, t2: true }, true);
|
||||
pruneBreadcrumbOverrides(new Set(["t1"]));
|
||||
expect(useBreadcrumbOverrides.getState()).toEqual({ t1: false });
|
||||
clearBreadcrumbOverrides();
|
||||
expect(useBreadcrumbOverrides.getState()).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Disable Sticky Lines for Language", () => {
|
||||
const id = "editor.disableStickyLinesForLanguage";
|
||||
const key = "editor.codeEditing.stickyLinesDisabledLanguages";
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { create } from "zustand";
|
||||
import type { EditorExtras } from "@/platform/editorSettings";
|
||||
|
||||
export const useBreadcrumbOverrides = create<Record<string, boolean>>(() => ({}));
|
||||
|
||||
export function breadcrumbsShown(
|
||||
tabId: string,
|
||||
prefs: EditorExtras["breadcrumbs"],
|
||||
language: string | undefined,
|
||||
): boolean {
|
||||
const forced = useBreadcrumbOverrides.getState()[tabId];
|
||||
return forced ?? (prefs.show && (!language || !prefs.disabledLanguages.includes(language)));
|
||||
}
|
||||
|
||||
export function toggleBreadcrumbs(
|
||||
tabId: string,
|
||||
prefs: EditorExtras["breadcrumbs"],
|
||||
language: string | undefined,
|
||||
): void {
|
||||
const shown = !breadcrumbsShown(tabId, prefs, language);
|
||||
useBreadcrumbOverrides.setState((state) => ({ ...state, [tabId]: shown }));
|
||||
}
|
||||
|
||||
export function pruneBreadcrumbOverrides(live: ReadonlySet<string>): void {
|
||||
const state = useBreadcrumbOverrides.getState();
|
||||
const closed = Object.keys(state).filter((id) => !live.has(id));
|
||||
if (!closed.length) return;
|
||||
const next = { ...state };
|
||||
for (const id of closed) delete next[id];
|
||||
useBreadcrumbOverrides.setState(next, true);
|
||||
}
|
||||
|
||||
export function clearBreadcrumbOverrides(): void {
|
||||
useBreadcrumbOverrides.setState({}, true);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ensureSyntaxTree } from "@codemirror/language";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { isCustomTagName } from "./customTags";
|
||||
import { vueLanguage } from "./vue";
|
||||
|
||||
describe("Vue custom tag names", () => {
|
||||
it("are PascalCase or hyphenated names", () => {
|
||||
expect(["Icon", "el-input", "router-view", "MyButton"].map(isCustomTagName)).toEqual([true, true, true, true]);
|
||||
expect(["div", "template", "span", "slot"].map(isCustomTagName)).toEqual([false, false, false, false]);
|
||||
});
|
||||
|
||||
it("get their own colour in templates, opening and closing tags alike", () => {
|
||||
const doc = `<template>\n <div><Icon /><el-input v-model="x"></el-input></div>\n</template>\n<script setup>\nconst a = 1 < 2\n</script>\n`;
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: vueLanguage() }),
|
||||
parent: document.body,
|
||||
});
|
||||
ensureSyntaxTree(view.state, doc.length, 5000);
|
||||
view.dispatch({}); // let the plugin see the finished tree
|
||||
const marked = [...view.dom.querySelectorAll(".cm-customTagName")].map((el) => el.textContent);
|
||||
view.destroy();
|
||||
expect(marked).toEqual(["Icon", "el-input", "el-input"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* WebStorm's "Custom tag name" colour: component tags in Vue templates (`<Icon>`, `<el-input>`)
|
||||
* stand apart from HTML elements (`--syn-custom-tag`, the tag colour when a theme has none).
|
||||
*/
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import { RangeSetBuilder } from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
|
||||
const customTag = Decoration.mark({ class: "cm-customTagName" });
|
||||
|
||||
/** A component, not an HTML element: PascalCase (`Icon`), or a custom-element name with a hyphen. */
|
||||
export function isCustomTagName(name: string): boolean {
|
||||
return /^[A-Z]/.test(name) || name.includes("-");
|
||||
}
|
||||
|
||||
function decorations(view: EditorView): DecorationSet {
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
const tree = syntaxTree(view.state);
|
||||
for (const { from, to } of view.visibleRanges) {
|
||||
tree.iterate({
|
||||
from,
|
||||
to,
|
||||
enter: (node) => {
|
||||
if (node.name !== "TagName") return;
|
||||
if (isCustomTagName(view.state.sliceDoc(node.from, node.to))) builder.add(node.from, node.to, customTag);
|
||||
},
|
||||
});
|
||||
}
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
const plugin = ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet;
|
||||
constructor(view: EditorView) {
|
||||
this.decorations = decorations(view);
|
||||
}
|
||||
update(update: ViewUpdate) {
|
||||
if (update.docChanged || update.viewportChanged || syntaxTree(update.state) !== syntaxTree(update.startState))
|
||||
this.decorations = decorations(update.view);
|
||||
}
|
||||
},
|
||||
{ decorations: (p) => p.decorations },
|
||||
);
|
||||
|
||||
/** Colours component tag names in a template (the syntax highlighting's tag span inside included). */
|
||||
export const customTagNames = [
|
||||
plugin,
|
||||
EditorView.baseTheme({
|
||||
".cm-customTagName, .cm-customTagName *": { color: "var(--syn-custom-tag, var(--syn-tag))" },
|
||||
}),
|
||||
];
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
} from "@codemirror/commands";
|
||||
import { SearchCursor } from "@codemirror/search";
|
||||
import { humpLeft, humpRight, wordStartLeft } from "../model/camelHumps";
|
||||
import { cycleIdentifierCase, wordSpan } from "../model/identifierCase";
|
||||
import { cycleIdentifierCase, wordSpan, type IdentifierCase } from "../model/identifierCase";
|
||||
import { restartSticky } from "./stickySelection";
|
||||
|
||||
type Node = ReturnType<ReturnType<typeof syntaxTree>["resolveInner"]>;
|
||||
@@ -1087,7 +1087,10 @@ const NAME_CHAR = /[\p{L}\p{N}_$-]/u;
|
||||
* or of each selection, from the style it is written in: snake_case →
|
||||
* SCREAMING_SNAKE_CASE → kebab-case → camelCase → PascalCase.
|
||||
*/
|
||||
export const cycleCase: Command = (view) => {
|
||||
export const cycleCase = (
|
||||
view: EditorView,
|
||||
enabled: Readonly<Partial<Record<IdentifierCase, boolean>>> = {},
|
||||
): boolean => {
|
||||
const { state } = view;
|
||||
if (state.readOnly) return false;
|
||||
/** The `-`-joined name at or right before `pos`. */
|
||||
@@ -1107,7 +1110,7 @@ export const cycleCase: Command = (view) => {
|
||||
const span = wordSpan(state.sliceDoc(name.from, name.to));
|
||||
if (!span) return { range: r };
|
||||
const from = name.from + span.from;
|
||||
const insert = cycleIdentifierCase(state.sliceDoc(from, name.from + span.to));
|
||||
const insert = cycleIdentifierCase(state.sliceDoc(from, name.from + span.to), enabled);
|
||||
if (insert === null) return { range: r };
|
||||
changed = true;
|
||||
const set = state.changes({ from, to: name.from + span.to, insert });
|
||||
|
||||
@@ -9,6 +9,7 @@ import { html } from "@codemirror/lang-html";
|
||||
import { lessLanguage } from "@codemirror/lang-less";
|
||||
import { sassLanguage } from "@codemirror/lang-sass";
|
||||
import { vue } from "@codemirror/lang-vue";
|
||||
import { customTagNames } from "./customTags";
|
||||
import { VERSIONED_SCRIPT_TYPES } from "./htmlScripts";
|
||||
|
||||
/**
|
||||
@@ -41,5 +42,6 @@ export function vueLanguage(): LanguageSupport {
|
||||
],
|
||||
});
|
||||
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
|
||||
return vue({ base: new LanguageSupport(language, base.support) });
|
||||
const support = vue({ base: new LanguageSupport(language, base.support) });
|
||||
return new LanguageSupport(support.language, [support.support, customTagNames]);
|
||||
}
|
||||
@@ -130,6 +130,7 @@ import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
|
||||
import type { VirtualDocument } from "@/platform/ipc";
|
||||
import type { Scheduler } from "./sync/DocSync";
|
||||
import { selectedLineContext, selectedLines } from "./selectedLines";
|
||||
import { clearBreadcrumbOverrides, pruneBreadcrumbOverrides } from "./breadcrumbs";
|
||||
|
||||
export const fileKey = (path: string) => `file:${path}`;
|
||||
export const fileInput = (path: string): EditorInput => ({ kind: "file", key: fileKey(path), path });
|
||||
@@ -547,6 +548,7 @@ export class EditorController implements SlotHost {
|
||||
this.preparedDocuments.clear();
|
||||
for (const slot of this.slots.values()) slot.dispose();
|
||||
this.slots.clear();
|
||||
clearBreadcrumbOverrides();
|
||||
this.selectionRequests.clear();
|
||||
this.manager.stop();
|
||||
useTabs.setState(initialTabsState(), true);
|
||||
@@ -563,6 +565,7 @@ export class EditorController implements SlotHost {
|
||||
private onTabsChanged(prev: TabsState, next: TabsState) {
|
||||
const live = new Set<string>();
|
||||
for (const p of Object.values(next.panes)) for (const t of p.tabs) live.add(t.id);
|
||||
pruneBreadcrumbOverrides(live);
|
||||
for (const id of this.selectionRequests.keys()) if (!live.has(id)) this.selectionRequests.delete(id);
|
||||
|
||||
for (const [id, slot] of this.slots) {
|
||||
|
||||
@@ -1099,6 +1099,13 @@ export class DocumentManager {
|
||||
for (const m of this.byPath.values()) m.applySettings();
|
||||
}
|
||||
|
||||
resetRenderedDocs() {
|
||||
for (const model of this.byPath.values()) {
|
||||
model.renderedDocsOverride = null;
|
||||
model.applySettings();
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves dirty documents; failures are notified, and an explicit Save All also rejects with them. */
|
||||
async saveAll(reason: "explicit" | "auto", skipUntitled = false) {
|
||||
const errors: unknown[] = [];
|
||||
|
||||
@@ -39,6 +39,21 @@ describe("cycle identifier case", () => {
|
||||
expect(cycleIdentifierCase("MyVarName")).toBe("my_var_name");
|
||||
});
|
||||
|
||||
it("goes only through the styles turned on, starting from the one the name is written in", () => {
|
||||
const camelSnake = { screaming: false, kebab: false, pascal: false };
|
||||
expect(cycleIdentifierCase("myVarName", camelSnake)).toBe("my_var_name");
|
||||
expect(cycleIdentifierCase("my_var_name", camelSnake)).toBe("myVarName");
|
||||
// A name in a style that is turned off still moves on to the next one that is on.
|
||||
expect(cycleIdentifierCase("my-var-name", camelSnake)).toBe("myVarName");
|
||||
expect(cycleIdentifierCase("MyVarName", camelSnake)).toBe("my_var_name");
|
||||
// Only the name's own style on: nothing else to go to.
|
||||
expect(
|
||||
cycleIdentifierCase("myVarName", { snake: false, screaming: false, kebab: false, pascal: false }),
|
||||
).toBeNull();
|
||||
// One word in snake_case is written as in camelCase, so with Name and NAME off it stays.
|
||||
expect(cycleIdentifierCase("name", { pascal: false, screaming: false })).toBeNull();
|
||||
});
|
||||
|
||||
it("gives one word its three spellings: name → Name → NAME", () => {
|
||||
expect(cycleIdentifierCase("name")).toBe("Name");
|
||||
expect(cycleIdentifierCase("Name")).toBe("NAME");
|
||||
|
||||
@@ -81,14 +81,20 @@ export function toIdentifierCase(text: string, style: IdentifierCase): string {
|
||||
|
||||
/**
|
||||
* `text` in the next style of the cycle, skipping the styles that write it the
|
||||
* same way; null when none writes it differently.
|
||||
* same way and those `enabled` turns off (Settings › Editor › General › Smart
|
||||
* Keys); null when none writes it differently.
|
||||
*/
|
||||
export function cycleIdentifierCase(text: string): string | null {
|
||||
export function cycleIdentifierCase(
|
||||
text: string,
|
||||
enabled: Readonly<Partial<Record<IdentifierCase, boolean>>> = {},
|
||||
): string | null {
|
||||
const current = identifierCase(text);
|
||||
if (!current) return null;
|
||||
// One word has three spellings, not five: name → Name → NAME.
|
||||
const single = identifierWords(text).length === 1 && !SEPARATOR.test(text);
|
||||
const order: readonly IdentifierCase[] = single ? ["camel", "pascal", "screaming", "snake"] : identifierCases;
|
||||
const all: readonly IdentifierCase[] = single ? ["camel", "pascal", "screaming", "snake"] : identifierCases;
|
||||
// The style the name is written in stays the starting point even when it is turned off.
|
||||
const order = all.filter((style) => style === current || enabled[style] !== false);
|
||||
const start = Math.max(0, order.indexOf(current));
|
||||
for (let step = 1; step <= order.length; step++) {
|
||||
const next = toIdentifierCase(text, order[(start + step) % order.length]!);
|
||||
|
||||
@@ -530,7 +530,7 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
|
||||
const wrappers = useTextEditorWrappers((s) => s.wrappers);
|
||||
if (isTextInput(tab.input)) {
|
||||
const virtual = tab.input.kind === "virtual" ? virtualData(tab.input) : undefined;
|
||||
const wrapper = tab.input.kind === "file" ? textEditorWrapperFor(wrappers, tab.input.path) : undefined;
|
||||
const wrapper = wrapperForInput(wrappers, tab.input);
|
||||
const host = shown && <TextEditorHost key={tab.id} tabId={tab.id} />;
|
||||
return (
|
||||
<>
|
||||
@@ -593,12 +593,7 @@ function keptTabs(
|
||||
const recent = mru
|
||||
.map((id) => tabs.find((t) => t.id === id))
|
||||
.filter(
|
||||
(t): t is Tab =>
|
||||
!!t &&
|
||||
(!!kinds.get(t.input.kind)?.keepAlive ||
|
||||
(t.input.kind === "file" &&
|
||||
t.input.path !== undefined &&
|
||||
!!textEditorWrapperFor(wrappers, t.input.path)?.keepAlive)),
|
||||
(t): t is Tab => !!t && (!!kinds.get(t.input.kind)?.keepAlive || !!wrapperForInput(wrappers, t.input)?.keepAlive),
|
||||
)
|
||||
.slice(0, KEPT_TABS);
|
||||
// In tab order, so switching tabs doesn't move their DOM (which would lose scroll offsets).
|
||||
@@ -664,10 +659,7 @@ function KindEditor({ tab }: { tab: Tab }) {
|
||||
function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
|
||||
const ctrl = editorController();
|
||||
const wrappers = useTextEditorWrappers((s) => s.wrappers);
|
||||
const LayoutActions =
|
||||
tab.input.kind === "file" && tab.input.path
|
||||
? textEditorWrapperFor(wrappers, tab.input.path)?.tabActions
|
||||
: undefined;
|
||||
const LayoutActions = wrapperForInput(wrappers, tab.input)?.tabActions;
|
||||
const [open, setOpen] = useState(false);
|
||||
const moreRef = useRef<HTMLButtonElement>(null);
|
||||
return (
|
||||
@@ -704,3 +696,9 @@ function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function wrapperForInput(wrappers: ReadonlyMap<string, TextEditorWrapperContribution>, input: EditorInput) {
|
||||
if (input.path && (input.kind === "file" || input.kind === "virtual")) {
|
||||
return textEditorWrapperFor(wrappers, input.path, input.kind === "virtual");
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
untitledTitle,
|
||||
} from "@/platform/virtualDocs";
|
||||
import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs } from "../controller";
|
||||
import { useBreadcrumbOverrides } from "../breadcrumbs";
|
||||
import { languageInfo } from "../cm/languages";
|
||||
import { useDocMeta, useOutline, type DocMeta } from "../model/document";
|
||||
import { symbolChain } from "./outline";
|
||||
@@ -365,6 +366,7 @@ export function CodeBreadcrumbs({
|
||||
position: "top" | "bottom";
|
||||
}) {
|
||||
const { breadcrumbs: prefs, fallbackFont } = useEditorPrefs();
|
||||
const forced = useBreadcrumbOverrides((s) => s[tabId]);
|
||||
const editorSettings = useProject((s) => s.settings?.editor);
|
||||
const language = useDocMeta((s) => s[path]?.language);
|
||||
const outline = useOutline((s) => s[path]);
|
||||
@@ -375,13 +377,8 @@ export function CodeBreadcrumbs({
|
||||
const caret = editorController().slots.get(tabId)?.caret();
|
||||
chain = outline ? symbolChain(outline, caret?.line ?? 0, caret?.col ?? 0) : NO_SYMBOLS;
|
||||
}
|
||||
if (
|
||||
!prefs.show ||
|
||||
prefs.placement !== position ||
|
||||
(language && prefs.disabledLanguages.includes(language)) ||
|
||||
!chain.length
|
||||
)
|
||||
return null;
|
||||
const shown = forced ?? (prefs.show && (!language || !prefs.disabledLanguages.includes(language)));
|
||||
if (!shown || prefs.placement !== position || !chain.length) return null;
|
||||
const family = editorSettings?.fontFamily;
|
||||
const fontFamily =
|
||||
(family && family !== BUNDLED_MONO_FAMILY) || fallbackFont.trim()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Profiler } from "react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { OutlineItem, Settings } from "@/platform/ipc";
|
||||
import type { EditorStatus } from "../controller";
|
||||
@@ -24,6 +24,9 @@ const { clearProjectViewLead, setProjectViewLead } = await import("@/workbench/c
|
||||
const { Breadcrumbs, CodeBreadcrumbs } = await import("./StatusItems");
|
||||
const { NavBarPopup, openNavBarPopup, useNavBarPopup } = await import("./NavBarPopup");
|
||||
const { useContextMenuStore } = await import("@/ui");
|
||||
const { clearBreadcrumbOverrides, useBreadcrumbOverrides } = await import("../breadcrumbs");
|
||||
|
||||
afterEach(() => clearBreadcrumbOverrides());
|
||||
|
||||
const PATH = "/p/Orders.ts";
|
||||
const span = (from: number, to: number) => ({ start: { line: from, col: 0 }, end: { line: to, col: 0 } });
|
||||
@@ -92,6 +95,31 @@ describe("caret-driven status widgets", () => {
|
||||
expect(commits).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("renders the active editor's forced breadcrumb visibility", () => {
|
||||
useProject.setState({
|
||||
settings: {
|
||||
appearance: { navigationBar: "top" },
|
||||
editor: { breadcrumbs: { show: false, placement: "bottom", disabledLanguages: ["typescript"] } },
|
||||
} as never,
|
||||
});
|
||||
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10)])] });
|
||||
act(() => useEditorStatus.setState({ status: caret(3, 4) }));
|
||||
render(
|
||||
<>
|
||||
<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />
|
||||
<CodeBreadcrumbs path={PATH} tabId="t2" position="bottom" />
|
||||
</>,
|
||||
);
|
||||
expect(screen.queryByRole("navigation", { name: "Code breadcrumbs" })).toBeNull();
|
||||
|
||||
act(() => useBreadcrumbOverrides.setState({ t1: true }));
|
||||
expect(screen.getAllByRole("navigation", { name: "Code breadcrumbs" })).toHaveLength(1);
|
||||
expect(screen.getByRole("navigation", { name: "Code breadcrumbs" }).textContent).toContain("place");
|
||||
|
||||
act(() => useBreadcrumbOverrides.setState({ t1: false }));
|
||||
expect(screen.queryByRole("navigation", { name: "Code breadcrumbs" })).toBeNull();
|
||||
});
|
||||
|
||||
it("follows the caret into a Vue component's <script> declarations", () => {
|
||||
useOutline.setState({
|
||||
[PATH]: [item("template", 0, 4), { ...item("script", 5, 30), children: [item("size", 10, 20)] }],
|
||||
|
||||
@@ -514,7 +514,11 @@ async function gotoResolved(
|
||||
// positions they do not own, so try every one instead of letting the first false
|
||||
// result hide the real target.
|
||||
const own = contributedAtAll<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
|
||||
if (own.some((definition) => definition(view, offset))) return;
|
||||
const anyHandled = async (index: number): Promise<boolean> => {
|
||||
if (index >= own.length) return false;
|
||||
return (await own[index]!(view, offset)) || anyHandled(index + 1);
|
||||
};
|
||||
if (await anyHandled(0)) return;
|
||||
if (showPhpConstructDocumentation(view, offset)) return;
|
||||
const before = view.state.doc;
|
||||
const plugin = await contributedNavigation(view, offset).catch(() => null);
|
||||
|
||||
Loaded 100 of 220 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача