дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 22:54:14 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
113f47772e |
No files matched your search
@@ -4,8 +4,7 @@
|
||||
//! same way into the test output, which also sees the production classes.
|
||||
use super::*;
|
||||
use ide_core::settings::{
|
||||
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
|
||||
split_jar_glob,
|
||||
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
|
||||
};
|
||||
use std::fs;
|
||||
|
||||
@@ -105,17 +104,13 @@ 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 {
|
||||
for entry in class_entries(root, class) {
|
||||
add(entry);
|
||||
}
|
||||
add(class_entry(root, class));
|
||||
}
|
||||
}
|
||||
}
|
||||
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() {
|
||||
for entry in class_entries(root, &dep.target) {
|
||||
add(entry);
|
||||
}
|
||||
add(class_entry(root, &dep.target));
|
||||
}
|
||||
}
|
||||
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
|
||||
@@ -138,50 +133,29 @@ fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
|
||||
root.join(dir)
|
||||
}
|
||||
|
||||
/// 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());
|
||||
}
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// 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> {
|
||||
if let Some((base, recursive)) = split_jar_glob(value) {
|
||||
return jar_files(&root.join(base), recursive);
|
||||
}
|
||||
let path = root.join(value.trim());
|
||||
if path.is_dir() {
|
||||
let jars = jar_files(&path, true);
|
||||
if !jars.is_empty() {
|
||||
return jars;
|
||||
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
|
||||
}
|
||||
None => vec![PathBuf::from(entry)],
|
||||
}
|
||||
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() };
|
||||
}
|
||||
/// 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());
|
||||
if path.is_dir() {
|
||||
let dirs = jar_dirs(&path);
|
||||
if !dirs.is_empty() {
|
||||
return dirs.iter().map(|d| wildcard(d)).collect();
|
||||
}
|
||||
let text = path.to_string_lossy().into_owned();
|
||||
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
|
||||
return text[..text.len() - 4].to_owned();
|
||||
}
|
||||
vec![path.to_string_lossy().into_owned()]
|
||||
text
|
||||
}
|
||||
|
||||
fn classpath(entries: &[String]) -> String {
|
||||
@@ -466,10 +440,7 @@ 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` 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`).
|
||||
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn structure_war_plan(
|
||||
root: &Path,
|
||||
@@ -478,7 +449,7 @@ pub fn structure_war_plan(
|
||||
jdk: Option<&StructureJdk>,
|
||||
language_level: &str,
|
||||
artifact: &ArtifactConfig,
|
||||
war: Option<&Path>,
|
||||
war: &Path,
|
||||
cache: &Path,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
|
||||
@@ -488,7 +459,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, war, cache));
|
||||
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
|
||||
plan.title = artifact.name.clone();
|
||||
Ok(plan)
|
||||
}
|
||||
@@ -1173,53 +1144,4 @@ 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:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,5 @@
|
||||
//! 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.
|
||||
@@ -48,28 +18,3 @@ 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,37 +2054,6 @@ 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,39 +448,18 @@ pub async fn format(
|
||||
options: FormatOptions,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let project = host.project(window)?;
|
||||
// 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),
|
||||
},
|
||||
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,
|
||||
};
|
||||
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,
|
||||
@@ -1406,14 +1385,6 @@ 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();
|
||||
|
||||
@@ -551,8 +551,6 @@ 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();
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -172,15 +172,15 @@ impl Policy {
|
||||
})
|
||||
}
|
||||
|
||||
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)
|
||||
fn resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The root of the project that serves `path` in the background under the current
|
||||
/// 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)
|
||||
/// settings and trust decisions. Opens nothing.
|
||||
pub(crate) fn serving_root(host: &Host, path: &Path) -> Option<PathBuf> {
|
||||
Policy::current(host)?.resolve(path)
|
||||
}
|
||||
|
||||
/// 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, None).as_deref() != Some(root) {
|
||||
if serving_root(host, root).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, None)).as_deref() != Some(&root) {
|
||||
if policy.as_ref().and_then(|policy| policy.resolve(&root)).as_deref() != Some(&root) {
|
||||
self.mcp_background.detach(self, &root, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,7 @@ 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. 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.
|
||||
/// recent folders that are gone or not absolute paths are skipped.
|
||||
pub(crate) fn resolve(
|
||||
mode: McpBackgroundProjects,
|
||||
listed: &[PathBuf],
|
||||
@@ -20,7 +18,6 @@ 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,
|
||||
@@ -31,37 +28,23 @@ 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() && inside(entry, false)).then(|| dunce::canonicalize(entry).ok()).flatten()
|
||||
};
|
||||
let existing = |entry: &PathBuf| entry.is_absolute().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 {
|
||||
let projects = decisions.projects.iter().filter(|p| inside(p, true));
|
||||
candidates.extend(projects.filter(|p| trusted_here(decisions, p)).cloned());
|
||||
candidates.extend(decisions.projects.iter().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, open).filter(|a| {
|
||||
.extend(marker_root(&path).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()
|
||||
}
|
||||
|
||||
@@ -81,10 +64,9 @@ 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).
|
||||
/// The search stops short of `within`.
|
||||
fn marker_root(path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
fn marker_root(path: &Path) -> Option<PathBuf> {
|
||||
let marked = |dir: &&Path| dir.join(".openidea").is_dir() || dir.join(".git").exists() || dir.join(".jj").exists();
|
||||
path.ancestors().take_while(|dir| Some(*dir) != within).find(marked).map(Path::to_path_buf)
|
||||
path.ancestors().find(marked).map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -177,35 +159,7 @@ mod tests {
|
||||
restricted: paths(restricted),
|
||||
};
|
||||
let home = base.join("home");
|
||||
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));
|
||||
let found = resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path));
|
||||
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
|
||||
}
|
||||
}
|
||||
@@ -216,7 +170,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), None, "{path}");
|
||||
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path)), None, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,7 +188,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, None).as_ref(), expected, "{what}");
|
||||
assert_eq!(resolve(mode, listed, decisions, recents, None, &here).as_ref(), expected, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,13 +200,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), None);
|
||||
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path));
|
||||
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"), None),
|
||||
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src")),
|
||||
Some(base.join("code/plain"))
|
||||
);
|
||||
}
|
||||
@@ -265,10 +219,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), None);
|
||||
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src")), None);
|
||||
let local = [base.join("ssh:/box/app")];
|
||||
assert_eq!(
|
||||
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src"), None),
|
||||
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src")),
|
||||
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), None);
|
||||
assert_eq!(registry.resolve(&root.join("parts")), 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), None, "no folder is served with the server off");
|
||||
assert_eq!(registry.resolve(&root.join("parts")), 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"), None), Some(root));
|
||||
assert_eq!(registry.resolve(&root.join("parts")), 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, None).as_deref() == Some(root) {
|
||||
if background::serving_root(&self.0, root).as_deref() == Some(root) {
|
||||
return Ok(self.0.trust.window_trusted(root).unwrap_or(false));
|
||||
}
|
||||
Err("project is no longer open".into())
|
||||
@@ -138,13 +138,8 @@ 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, 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 resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
background::serving_root(&self.0, path)
|
||||
}
|
||||
fn tools(&self, root: &Path) -> Result<Vec<ide_mcp::Tool>, String> {
|
||||
let trusted = self.lists_as_trusted(root)?;
|
||||
|
||||
@@ -26,7 +26,6 @@ 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
|
||||
|
||||
@@ -695,10 +695,8 @@ fn apply_library_classpath(
|
||||
DependencyScope::Compile | DependencyScope::Runtime => true,
|
||||
DependencyScope::Test | DependencyScope::Provided => test,
|
||||
};
|
||||
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))
|
||||
lib.classes.iter().filter_map(move |entry| {
|
||||
ide_sdk::apply::setting_path(root, entry).map(|path| (path.to_string_lossy().into_owned(), allowed))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -1494,26 +1492,6 @@ 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,19 +521,11 @@ pub async fn nav_python_library_imports(
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
// 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" {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.language.as_str() != "python" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&path)) else {
|
||||
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let roots = interpreter_site_packages(&python);
|
||||
|
||||
@@ -253,10 +253,8 @@ fn project_web_artifacts(ps: &ide_core::settings::ProjectStructureSettings) -> V
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Compiles the project and packs the Project Structure artifact `name` as the WAR Tomcat
|
||||
/// deploys, recorded in `base` like a build tool's archive.
|
||||
fn build_project_war(
|
||||
root: &std::path::Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
@@ -272,7 +270,10 @@ 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 target = compile::artifact_file(root, artifact);
|
||||
let war = base.join("artifact").join(format!(
|
||||
"{}.war",
|
||||
name.split(':').next().unwrap_or(name).replace(|c: char| !c.is_alphanumeric() && c != '-', "_")
|
||||
));
|
||||
let plan = compile::structure_war_plan(
|
||||
root,
|
||||
&ps,
|
||||
@@ -280,7 +281,7 @@ fn build_project_war(
|
||||
jdk.as_ref(),
|
||||
&settings.languages.java.language_level,
|
||||
artifact,
|
||||
None,
|
||||
&war,
|
||||
cache,
|
||||
)?;
|
||||
let result = compile::run(root, &plan, &ide_core::CancellationToken::new(), &|_| {})?;
|
||||
@@ -299,7 +300,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"), target.to_string_lossy().as_bytes())?;
|
||||
std::fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -331,14 +332,8 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
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 model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
|
||||
let artifacts = ide_build::web::artifacts(&project.root, &model);
|
||||
let id = config
|
||||
.extras
|
||||
.params
|
||||
@@ -350,6 +345,7 @@ 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);
|
||||
@@ -471,100 +467,3 @@ 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1603,15 +1603,14 @@ async fn post(server: &ide_mcp::McpServer, body: &Value) -> Value {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_open_in_a_window_answers_for_its_folders_that_no_nested_project_holds() {
|
||||
async fn a_project_open_in_a_window_answers_before_any_background_project() {
|
||||
let h = Harness::new();
|
||||
let inventory = h.serve_inventory();
|
||||
// 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]));
|
||||
// A listed folder inside the open project: the window's project answers for it.
|
||||
h.set("backgroundProjectPaths", json!([inventory, h.root.join("src")]));
|
||||
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}));
|
||||
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside.clone()}));
|
||||
let replies = bridged(&discovery, &inventory, &[read]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
|
||||
assert!(h.background().is_empty());
|
||||
@@ -1622,13 +1621,13 @@ async fn a_project_open_in_a_window_answers_for_its_folders_that_no_nested_proje
|
||||
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}");
|
||||
// A folder listed inside the window's project is a project of its own (#7040).
|
||||
// Nor does a background project loaded inside the window's project take its folder over.
|
||||
let nested = h.root.join("src");
|
||||
h.set("backgroundProjectPaths", json!([inventory, around, nested]));
|
||||
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"projectPath":nested,"file_path":"b.txt"}}));
|
||||
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}));
|
||||
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();
|
||||
@@ -1639,61 +1638,6 @@ async fn a_project_open_in_a_window_answers_for_its_folders_that_no_nested_proje
|
||||
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();
|
||||
|
||||
@@ -122,24 +122,10 @@ 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_class(c)).collect();
|
||||
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize(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) {
|
||||
@@ -147,9 +133,7 @@ pub fn configure_project_structure(
|
||||
}
|
||||
}
|
||||
for (class, source) in class_entries.iter().zip(&source_entries) {
|
||||
if !class.contains('*') {
|
||||
sources.insert(class.clone(), json!(source));
|
||||
}
|
||||
sources.insert(class.clone(), json!(source));
|
||||
}
|
||||
}
|
||||
for facet in &structure.facets {
|
||||
@@ -1969,51 +1953,4 @@ 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, NotebookCellText, cell_uri};
|
||||
pub use notebook::{NotebookCell, NotebookCellDoc, 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,14 +40,6 @@ 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,
|
||||
@@ -162,22 +154,6 @@ 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();
|
||||
@@ -408,27 +384,4 @@ 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());
|
||||
}
|
||||
}
|
||||
@@ -67,10 +67,9 @@ 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). `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> {
|
||||
/// 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> {
|
||||
None
|
||||
}
|
||||
/// The tools callable for `project` (one of [`Self::projects`] or a root
|
||||
|
||||
@@ -223,7 +223,9 @@ impl Session<'_> {
|
||||
roots.sort();
|
||||
roots.dedup();
|
||||
if let Some(requested) = requested.filter(|p| !p.trim().is_empty()) {
|
||||
return self.serving_root(&roots, Path::new(requested)).ok_or_else(|| {
|
||||
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(|| {
|
||||
RpcError::new(
|
||||
NOT_OPEN,
|
||||
format!(
|
||||
@@ -245,30 +247,10 @@ 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<OpenRoot> {
|
||||
fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
|
||||
if !path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
@@ -292,7 +274,7 @@ fn resolve(roots: &[PathBuf], path: &Path) -> Option<OpenRoot> {
|
||||
path.starts_with(&canonical).then(|| (canonical.components().count(), root))
|
||||
})
|
||||
.max_by_key(|(depth, _)| *depth)
|
||||
.map(|(depth, root)| OpenRoot { root: root.clone(), below: path.components().count() > depth })
|
||||
.map(|(_, root)| root.clone())
|
||||
}
|
||||
|
||||
fn tool_json(tool: &Tool) -> Value {
|
||||
@@ -317,15 +299,11 @@ mod tests {
|
||||
let inner = outer.join("inner");
|
||||
std::fs::create_dir_all(inner.join("src")).unwrap();
|
||||
let roots = [outer.clone(), inner.clone()];
|
||||
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);
|
||||
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);
|
||||
// Siblings sharing a prefix are not inside.
|
||||
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 }));
|
||||
assert_eq!(resolve(&roots[1..], &outer.join("inner-two")), None);
|
||||
}
|
||||
}
|
||||
@@ -225,22 +225,18 @@ 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 the folders served without a window.
|
||||
/// One project open in a window and, optionally, one folder served without a window.
|
||||
struct WithBackground {
|
||||
open: PathBuf,
|
||||
background: Vec<PathBuf>,
|
||||
background: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl ToolRegistry for WithBackground {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
}
|
||||
/// 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 resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
self.background.clone().filter(|root| path.starts_with(root))
|
||||
}
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(vec![Tool {
|
||||
@@ -257,16 +253,13 @@ impl ToolRegistry for WithBackground {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
/// The server over [`WithBackground`]; the folder `inventory` next to the open project.
|
||||
fn setup_with_background(served: bool) -> (Setup, PathBuf) {
|
||||
let mut s = setup();
|
||||
s.server.take().unwrap().stop();
|
||||
let base = s.project.parent().unwrap().to_path_buf();
|
||||
let inventory = base.join("inventory");
|
||||
let inventory = s.project.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir_all(inventory.join("src")).unwrap();
|
||||
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
|
||||
let registry = WithBackground { open: s.project.clone(), background };
|
||||
let registry = WithBackground { open: s.project.clone(), background: served.then(|| inventory.clone()) };
|
||||
s.server = Some(
|
||||
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
|
||||
.unwrap(),
|
||||
@@ -284,7 +277,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(&["inventory"]);
|
||||
let (s, inventory) = setup_with_background(true);
|
||||
let inside = inventory.join("src");
|
||||
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
@@ -303,37 +296,9 @@ 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(&[]);
|
||||
let (s, inventory) = setup_with_background(false);
|
||||
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}");
|
||||
|
||||
@@ -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.is_dir() => war,
|
||||
Some(war) if war.is_file() && is_war(&war) => war,
|
||||
_ => match find_built_war(root, Some(&module)) {
|
||||
Some(war) => war,
|
||||
None => return false,
|
||||
},
|
||||
};
|
||||
let Some(war_time) = newest_mtime_under(&war) else { return false };
|
||||
let Ok(war_time) = fs::metadata(&war).and_then(|m| m.modified()) 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,10 +1077,12 @@ 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(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())));
|
||||
Some(war) => {
|
||||
if war.is_file() && is_war(&war) {
|
||||
war
|
||||
} else {
|
||||
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.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")
|
||||
@@ -2415,45 +2417,4 @@ 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, &[]));
|
||||
}
|
||||
}
|
||||
@@ -506,8 +506,7 @@ 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.libraries.is_empty();
|
||||
|| !s.project_structure.source_roots.is_empty();
|
||||
if !java {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -522,45 +521,11 @@ 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 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 {
|
||||
for entry in lib.classes.iter().chain(&lib.sources) {
|
||||
let Some(path) = crate::apply::setting_path(root, entry) else { continue };
|
||||
let label = path
|
||||
.file_name()
|
||||
|
||||
@@ -3655,22 +3655,6 @@ 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]
|
||||
|
||||
@@ -920,7 +920,6 @@ fn log_indexed_rows(
|
||||
text,
|
||||
matches: HashMap::new(),
|
||||
projected: HashMap::new(),
|
||||
pruned: HashMap::new(),
|
||||
cancel,
|
||||
index,
|
||||
table: table.as_ref(),
|
||||
@@ -1011,7 +1010,6 @@ 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());
|
||||
@@ -1073,27 +1071,11 @@ 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 pruned.remove(&curr).unwrap_or(ancestors) {
|
||||
for a in ancestors {
|
||||
for &p in projected.get(&a).into_iter().flatten() {
|
||||
if !combined.contains(&p) {
|
||||
combined.push(p);
|
||||
@@ -1195,70 +1177,6 @@ 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,
|
||||
@@ -1268,8 +1186,6 @@ 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]>>,
|
||||
@@ -1356,26 +1272,6 @@ 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();
|
||||
@@ -1405,13 +1301,11 @@ 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 self.pruned.remove(&id).unwrap_or(ancestors) {
|
||||
for p in ancestors {
|
||||
for ancestor in self.projected.get(&p).into_iter().flatten() {
|
||||
if !nearest.contains(ancestor) {
|
||||
nearest.push(*ancestor);
|
||||
|
||||
@@ -267,57 +267,3 @@ 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() };
|
||||
// `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()),
|
||||
}
|
||||
let path = match base {
|
||||
Some(base) => base.join(rest.trim_start_matches(['/', '\\'])),
|
||||
None => PathBuf::from(rest),
|
||||
};
|
||||
path.is_absolute().then_some(path)
|
||||
}
|
||||
|
||||
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, 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
请以 **复制 Stdio 配置** 得到的可执行文件路径为准,上面的 macOS 路径只是示例。在 Windows 上,它是安装目录(或便携版目录)中的 `openidea.exe`。
|
||||
|
||||
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的最内层项目,无论该项目在窗口中打开还是作为后台项目提供服务。位于窗口项目之内的后台项目负责它自己的目录,调用中的相对路径以它的根目录为准。例如在 **受信任的项目** 模式下,受信任位置中的仓库(包括 Git 子模块)在调用指定它的目录时会作为单独的后台项目加载,即使外层项目已在窗口中打开。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
|
||||
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的那个项目。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
|
||||
|
||||
服务器运行期间,OpenIDEA 会把端口和令牌写入应用数据目录下的 `mcp/server.json`(只有你自己可读),stdio 转发程序从这里读取。
|
||||
|
||||
|
||||
@@ -20,62 +20,6 @@ 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)",
|
||||
|
||||
@@ -51,60 +51,6 @@ 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,
|
||||
}) => {
|
||||
|
||||
@@ -128,24 +128,6 @@ 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 }) => {
|
||||
|
||||
@@ -1140,30 +1140,6 @@ 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"],
|
||||
|
||||
@@ -4,10 +4,9 @@ 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, manager: activeManager }),
|
||||
editorController: () => ({ activeSlot }),
|
||||
}));
|
||||
|
||||
/** Writes the dotted key into the current settings, as the host does. */
|
||||
@@ -36,7 +35,6 @@ 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");
|
||||
@@ -48,7 +46,6 @@ beforeAll(() => {
|
||||
afterAll(() => dispose());
|
||||
afterEach(() => {
|
||||
activeSlot = null;
|
||||
activeManager = null;
|
||||
clearBreadcrumbOverrides();
|
||||
useProject.setState({ settings: null });
|
||||
useContextKeys.setState({}, true);
|
||||
@@ -175,7 +172,6 @@ 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}`, {
|
||||
@@ -261,36 +257,6 @@ 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();
|
||||
|
||||
@@ -1099,13 +1099,6 @@ 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[] = [];
|
||||
|
||||
@@ -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 = wrapperForInput(wrappers, tab.input);
|
||||
const wrapper = tab.input.kind === "file" ? textEditorWrapperFor(wrappers, tab.input.path) : undefined;
|
||||
const host = shown && <TextEditorHost key={tab.id} tabId={tab.id} />;
|
||||
return (
|
||||
<>
|
||||
@@ -593,7 +593,12 @@ 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 || !!wrapperForInput(wrappers, t.input)?.keepAlive),
|
||||
(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)),
|
||||
)
|
||||
.slice(0, KEPT_TABS);
|
||||
// In tab order, so switching tabs doesn't move their DOM (which would lose scroll offsets).
|
||||
@@ -659,7 +664,10 @@ function KindEditor({ tab }: { tab: Tab }) {
|
||||
function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
|
||||
const ctrl = editorController();
|
||||
const wrappers = useTextEditorWrappers((s) => s.wrappers);
|
||||
const LayoutActions = wrapperForInput(wrappers, tab.input)?.tabActions;
|
||||
const LayoutActions =
|
||||
tab.input.kind === "file" && tab.input.path
|
||||
? textEditorWrapperFor(wrappers, tab.input.path)?.tabActions
|
||||
: undefined;
|
||||
const [open, setOpen] = useState(false);
|
||||
const moreRef = useRef<HTMLButtonElement>(null);
|
||||
return (
|
||||
@@ -696,9 +704,3 @@ 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");
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,7 @@ import {
|
||||
useEditorRegistry,
|
||||
} from "@/editor/api";
|
||||
import { call, isCancelled, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc";
|
||||
import { libraryClassEntry, normalizeFolder, validateProjectStructure } from "@/platform/languageSettings";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { libraryArchiveRoot } from "@/platform/virtualDocs";
|
||||
import { registerProjectViewRoot, type ProjectViewRootContribution } from "@/workbench/contributions";
|
||||
import { goModNavigationExtension } from "./goModNavigation";
|
||||
@@ -111,24 +110,6 @@ const MANIFESTS = new Set([
|
||||
"mise.toml",
|
||||
]);
|
||||
|
||||
/** Whether an `fsChanged` event adds or removes a `.jar` inside a configured Project Structure library. */
|
||||
export function touchesConfiguredLibrary(paths: readonly string[]): boolean {
|
||||
const { project, settings } = useProject.getState();
|
||||
if (!project || !paths.length) return false;
|
||||
const libraries = validateProjectStructure(settings?.projectStructure).libraries;
|
||||
if (!libraries.length) return false;
|
||||
const jarPaths = paths.filter((p) => /\.jar$/i.test(p));
|
||||
if (!jarPaths.length) return false;
|
||||
const bases = libraries.flatMap((lib) =>
|
||||
lib.classes.map((raw) => libraryClassEntry(raw, project.root)?.path ?? "").filter(Boolean),
|
||||
);
|
||||
if (!bases.length) return false;
|
||||
return jarPaths.some((p) => {
|
||||
const rel = normalizeFolder(relativePath(project.root, p));
|
||||
return bases.some((b) => rel === b || rel.startsWith(`${b}/`));
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether an `fsChanged` event touches a library manifest. */
|
||||
export function touchesManifest(paths: readonly string[]): boolean {
|
||||
return paths.some(
|
||||
@@ -325,8 +306,7 @@ export function activate(): () => void {
|
||||
showOpenedLibrary(useEditorRegistry.getState().active?.ctx.path ?? null);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const unsubFs = onIdeEvent("fsChanged", (e) => {
|
||||
const changed = [...e.created, ...e.modified, ...e.removed];
|
||||
if (!touchesManifest(changed) && !touchesConfiguredLibrary([...e.created, ...e.removed])) return;
|
||||
if (!touchesManifest([...e.created, ...e.modified, ...e.removed])) return;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(refresh, MANIFEST_REFRESH_DELAY);
|
||||
});
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: grid;
|
||||
grid-template-columns: fit-content(36%) minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: var(--h-field);
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.control {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pathList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
max-height: 120px;
|
||||
overflow: auto;
|
||||
padding: var(--space-1-5) var(--space-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-field);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.pathItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pathItem > svg {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.pathText {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--danger);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
/**
|
||||
* "Create Library" dialog opened from Project view › Add as Library…:
|
||||
* mirrors IDEA's dialog for turning a `.jar` or JAR directory (such as `WEB-INF/lib`)
|
||||
* into a project library in `projectStructure.libraries`.
|
||||
*/
|
||||
import { useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
import { Dialog, Icon, Input, Select, T, type SelectOption } from "@/ui";
|
||||
import {
|
||||
DEPENDENCY_SCOPES,
|
||||
normalizeFolder,
|
||||
validateProjectStructure,
|
||||
type DependencyScopeValid,
|
||||
} from "@/platform/languageSettings";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import {
|
||||
addProjectLibrary,
|
||||
closeAddAsLibraryDialog,
|
||||
isJarPath,
|
||||
libraryClassPaths,
|
||||
suggestLibraryName,
|
||||
useAddLibraryRequest,
|
||||
type AddLibraryRequest,
|
||||
} from "./addLibrary";
|
||||
import styles from "./AddLibraryDialog.module.css";
|
||||
|
||||
const SCOPE_OPTIONS: SelectOption[] = DEPENDENCY_SCOPES.map((s) => ({
|
||||
value: s,
|
||||
label: s === "compile" ? "Compile" : s === "test" ? "Test" : s === "runtime" ? "Runtime" : "Provided",
|
||||
}));
|
||||
|
||||
function AddLibraryDialog({ request }: { request: AddLibraryRequest }) {
|
||||
const root = useProject((s) => s.project?.root ?? null);
|
||||
const settings = useProject((s) => s.settings);
|
||||
const existing = useMemo(() => validateProjectStructure(settings?.projectStructure).libraries, [settings]);
|
||||
const classPaths = useMemo(() => {
|
||||
if (!root) return [];
|
||||
const filtered = libraryClassPaths(request.paths, root, existing);
|
||||
return filtered.length > 0
|
||||
? filtered
|
||||
: [...new Set(request.paths.map((p) => normalizeFolder(relativePath(root, p))).filter(Boolean))];
|
||||
}, [request.paths, root, existing]);
|
||||
|
||||
const [name, setName] = useState(() => suggestLibraryName(request.paths, root ?? "", existing));
|
||||
const [scope, setScope] = useState<DependencyScopeValid>("compile");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const nameId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
const el = inputRef.current;
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
el.select();
|
||||
}, []);
|
||||
|
||||
const trimmed = name.trim();
|
||||
const duplicate = trimmed.length > 0 && existing.some((l) => l.name.trim() === trimmed);
|
||||
const validationError = !trimmed
|
||||
? tx("Library name cannot be empty.")
|
||||
: duplicate
|
||||
? tx("A library with this name already exists.")
|
||||
: null;
|
||||
|
||||
const submit = async () => {
|
||||
if (saving || validationError) return;
|
||||
setSaving(true);
|
||||
setSubmitError(null);
|
||||
try {
|
||||
const saved = await addProjectLibrary({ name: trimmed, paths: request.paths, scope });
|
||||
if (saved) closeAddAsLibraryDialog();
|
||||
} catch (e) {
|
||||
setSubmitError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title="Create Library"
|
||||
onClose={() => !saving && closeAddAsLibraryDialog()}
|
||||
width={460}
|
||||
buttons={[
|
||||
{ label: "OK", role: "default", disabled: saving || !!validationError, onClick: () => void submit() },
|
||||
{ label: "Cancel", role: "cancel", disabled: saving, onClick: closeAddAsLibraryDialog },
|
||||
]}
|
||||
>
|
||||
<form
|
||||
className={styles.form}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
<div className={styles.fields}>
|
||||
<label className={styles.label} htmlFor={nameId}>
|
||||
<T>Name</T>
|
||||
</label>
|
||||
<div className={styles.control}>
|
||||
<Input
|
||||
id={nameId}
|
||||
ref={inputRef}
|
||||
value={name}
|
||||
disabled={saving}
|
||||
invalid={!!validationError}
|
||||
aria-label="Library name"
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setSubmitError(null);
|
||||
}}
|
||||
/>
|
||||
{validationError && (
|
||||
<div className={styles.error} role="alert">
|
||||
{validationError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<span className={styles.label}>
|
||||
<T>Scope</T>
|
||||
</span>
|
||||
<div className={styles.control}>
|
||||
<Select
|
||||
value={scope}
|
||||
disabled={saving}
|
||||
options={SCOPE_OPTIONS}
|
||||
onChange={(v) => setScope(v as DependencyScopeValid)}
|
||||
aria-label="Library scope"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span className={styles.label}>
|
||||
<T>Classes</T>
|
||||
</span>
|
||||
<div className={styles.control}>
|
||||
<div className={styles.pathList} role="list" aria-label={tx("Library Roots")}>
|
||||
{classPaths.map((p) => (
|
||||
<div key={p} className={styles.pathItem} role="listitem">
|
||||
<Icon name={isJarPath(p) ? "file-archive" : "folder-library"} size={14} />
|
||||
<span className={styles.pathText}>{p}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{submitError && (
|
||||
<div className={styles.error} role="alert">
|
||||
{submitError}
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddLibraryDialogHost() {
|
||||
const request = useAddLibraryRequest();
|
||||
if (!request) return null;
|
||||
return <AddLibraryDialog key={request.seq} request={request} />;
|
||||
}
|
||||
@@ -28,7 +28,7 @@ import { tx, useTxTemplate } from "@/platform/i18n";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { canDragOut, dragOut, isDraggingOut } from "@/platform/dragOut";
|
||||
import { nativeDropPoint } from "@/platform/nativeDrop";
|
||||
import { validateProjectStructure, type RootFolder } from "@/platform/languageSettings";
|
||||
import type { RootFolder } from "@/platform/languageSettings";
|
||||
import { useDetectedRoots, useEffectiveRoots } from "@/platform/projectRoots";
|
||||
import { macStroke, strokeOf } from "@/platform/keymap";
|
||||
import {
|
||||
@@ -64,7 +64,6 @@ import {
|
||||
type TreeRowState,
|
||||
} from "@/ui";
|
||||
import { badgeKind } from "@/ui/symbolKind";
|
||||
import { isConfiguredLibraryDirectory, prepareLibraryTargets } from "./addLibrary";
|
||||
import { contextMenuItems, menuGroupContext, newMenuItems } from "./contextMenu";
|
||||
import { openNewPopup } from "./newPopupModel";
|
||||
import { presentationIcon, useJvmPresentation } from "@/ui/filePresentation";
|
||||
@@ -74,7 +73,7 @@ import {
|
||||
useProjectPresentation,
|
||||
type BuildPresentation,
|
||||
} from "@/platform/projectPresentation";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import { relativePath } from "@/platform/project";
|
||||
import { folderKind } from "./folderKind";
|
||||
import { PROJECT_TYPES } from "@/ui/projectType";
|
||||
import { useHomeDir } from "./home";
|
||||
@@ -172,7 +171,6 @@ function iconFor(
|
||||
detected: readonly RootFolder[],
|
||||
expanded: boolean,
|
||||
holdsOpen: boolean,
|
||||
libraryDir: boolean,
|
||||
): string {
|
||||
if (node.placeholder) return node.placeholder === "dir" ? "folder" : "file";
|
||||
if (node.icon) return node.icon;
|
||||
@@ -184,7 +182,6 @@ function iconFor(
|
||||
const key = rel !== null && build.modules.has(rel) ? rel : node.path;
|
||||
const module = root ? moduleFolderIcon(key, node.root, build.modules) : null;
|
||||
if (module) return module;
|
||||
if (libraryDir) return "folder-library";
|
||||
return node.root ? "module" : (themedFolderIconName(node.label, expanded, holdsOpen, node.path) ?? "folder");
|
||||
}
|
||||
return fileIconName(node.label, node.path);
|
||||
@@ -356,17 +353,12 @@ const Row = memo(function Row({
|
||||
const file = useJvmPresentation(node.dir || node.placeholder ? "" : node.path, node.entry?.mtimeMs);
|
||||
const expanded = useProjectTree((s) => node.dir && s.expanded.has(node.key));
|
||||
const holdsOpen = useProjectTree((s) => node.dir && holdsOpenFile(node.path, s.openFiles));
|
||||
const libraryDir = useProject((s) =>
|
||||
node.dir && !node.placeholder && !node.root && !node.icon && root
|
||||
? isConfiguredLibraryDirectory(node.path, root, validateProjectStructure(s.settings?.projectStructure).libraries)
|
||||
: false,
|
||||
);
|
||||
const icon =
|
||||
deco.icon ??
|
||||
(projectType
|
||||
? PROJECT_TYPES[projectType].icon
|
||||
: node.dir || node.placeholder || node.icon
|
||||
? iconFor(node, roots, root, build, detected, expanded, holdsOpen, libraryDir)
|
||||
? iconFor(node, roots, root, build, detected, expanded, holdsOpen)
|
||||
: presentationIcon(node.path, file, roots, root, build.spring));
|
||||
const moduleFolder =
|
||||
node.dir && !node.placeholder && !!root && isModuleFolder(relativePath(root, node.path), node.root, build.modules);
|
||||
@@ -705,10 +697,10 @@ export function ProjectView() {
|
||||
const nodes = [...sel].map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.placeholder);
|
||||
const target = nodes.length ? nodes : [node];
|
||||
if (target.every((n) => n.group) || target.some((n) => n.member)) return;
|
||||
// Contributed groups and collapsed library folders may read the filesystem first (bounded wait).
|
||||
// Contributed groups may read the file first (bounded wait).
|
||||
const at = { x: e.clientX, y: e.clientY };
|
||||
void Promise.all([prepareMenuGroups("projectView", menuGroupContext(target)), prepareLibraryTargets(target)]).then(
|
||||
() => showContextMenu(at, contextMenuItems(target, at)),
|
||||
void prepareMenuGroups("projectView", menuGroupContext(target)).then(() =>
|
||||
showContextMenu(at, contextMenuItems(target, at)),
|
||||
);
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import { isUntitledUri } from "@/platform/virtualDocs";
|
||||
import { showContextMenu, type MenuItem } from "@/ui";
|
||||
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
|
||||
import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions";
|
||||
import { canAddAsLibrary, openAddAsLibraryDialog } from "./addLibrary";
|
||||
import { compareTarget, isModuleNode, newMenuItems, revealLabel } from "./contextMenu";
|
||||
import { LABELS, setFileColor } from "./fileColor";
|
||||
import { openNewPopup } from "./newPopupModel";
|
||||
@@ -592,19 +591,6 @@ export function registerProjectActions(): () => void {
|
||||
if (target) delegate(target.action, target.arg);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "project.addAsLibrary",
|
||||
title: "Add as Library…",
|
||||
category: "Project View",
|
||||
icon: "library",
|
||||
when: OPEN,
|
||||
keywords: ["jar", "dependency", "classpath", "project structure", "lib"],
|
||||
enabled: ({ arg }) => canAddAsLibrary(nodesFrom(arg)),
|
||||
run: ({ arg }) => {
|
||||
const nodes = nodesFrom(arg);
|
||||
if (canAddAsLibrary(nodes)) openAddAsLibraryDialog(nodes);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "project.reloadFromDisk",
|
||||
title: "Reload from Disk",
|
||||
|
||||
@@ -1,309 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { FileEntry, Settings } from "@/platform/ipc";
|
||||
import { DEFAULT_PROJECT_STRUCTURE, validateProjectStructure } from "@/platform/languageSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { touchesConfiguredLibrary } from "@/features/libraries";
|
||||
import { registerProjectViewRoot } from "@/workbench/contributions";
|
||||
import {
|
||||
canAddAsLibrary,
|
||||
clearLibraryProbeCache,
|
||||
closeAddAsLibraryDialog,
|
||||
isConfiguredLibraryDirectory,
|
||||
isLibraryNode,
|
||||
openAddAsLibraryDialog,
|
||||
pendingAddLibraryDialog,
|
||||
prepareLibraryTargets,
|
||||
suggestLibraryName,
|
||||
} from "./addLibrary";
|
||||
import { AddLibraryDialogHost } from "./AddLibraryDialog";
|
||||
import type { ProjectNode } from "./model";
|
||||
import { selectModel, useProjectTree } from "./store";
|
||||
|
||||
const ipcMocks = vi.hoisted(() => ({
|
||||
fsReadDir: vi.fn(),
|
||||
settingsSet: vi.fn(),
|
||||
settingsGet: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
fsReadDir: (...args: unknown[]) => ipcMocks.fsReadDir(...args),
|
||||
settingsSet: (...args: unknown[]) => ipcMocks.settingsSet(...args),
|
||||
settingsGet: (...args: unknown[]) => ipcMocks.settingsGet(...args),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const ROOT = "/app";
|
||||
|
||||
const node = (path: string, dir = false, extra: Partial<ProjectNode> = {}): ProjectNode => ({
|
||||
key: path,
|
||||
path,
|
||||
chain: [path],
|
||||
label: path.slice(path.lastIndexOf("/") + 1),
|
||||
dir,
|
||||
root: false,
|
||||
entry: null,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
symlink: false,
|
||||
...extra,
|
||||
});
|
||||
|
||||
const fileEntry = (path: string, kind: "file" | "dir" = "file"): FileEntry => ({
|
||||
name: path.slice(path.lastIndexOf("/") + 1),
|
||||
path,
|
||||
kind,
|
||||
size: kind === "dir" ? 0 : 128,
|
||||
mtimeMs: 0,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
});
|
||||
|
||||
function setLibraries(
|
||||
libraries: Array<{ name: string; classes: string[]; sources?: string[]; javadocs?: string[]; scope?: string }>,
|
||||
) {
|
||||
const settings = {
|
||||
projectStructure: {
|
||||
...structuredClone(DEFAULT_PROJECT_STRUCTURE),
|
||||
libraries: libraries.map((l) => ({
|
||||
name: l.name,
|
||||
classes: l.classes,
|
||||
sources: l.sources ?? [],
|
||||
javadocs: l.javadocs ?? [],
|
||||
scope: (l.scope ?? "compile") as "compile" | "test" | "runtime" | "provided",
|
||||
})),
|
||||
},
|
||||
} as unknown as Settings;
|
||||
useProject.setState({
|
||||
project: { name: "app", root: ROOT, trusted: true, isGit: false, settings } as never,
|
||||
settings,
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
ipcMocks.fsReadDir.mockReset();
|
||||
ipcMocks.settingsSet.mockReset();
|
||||
ipcMocks.settingsGet.mockReset();
|
||||
clearLibraryProbeCache();
|
||||
closeAddAsLibraryDialog();
|
||||
setLibraries([]);
|
||||
useProjectTree.setState({ root: ROOT, name: "app", listings: new Map() });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
clearLibraryProbeCache();
|
||||
closeAddAsLibraryDialog();
|
||||
useProject.setState({ project: null, settings: null });
|
||||
useProjectTree.setState({ root: null, name: "", listings: new Map() });
|
||||
});
|
||||
|
||||
describe("addLibrary candidate detection", () => {
|
||||
it("recognizes WEB-INF/lib even before its listing is loaded or when empty", () => {
|
||||
expect(canAddAsLibrary([node(`${ROOT}/WebContent/WEB-INF/lib`, true)])).toBe(true);
|
||||
expect(canAddAsLibrary([node(`${ROOT}/WebRoot/WEB-INF/lib`, true)])).toBe(true);
|
||||
expect(canAddAsLibrary([node(`${ROOT}/WEB-INF/lib`, true)])).toBe(true);
|
||||
});
|
||||
|
||||
it("recognizes single and multiple .jar files and rejects mixed non-library selections", () => {
|
||||
expect(canAddAsLibrary([node(`${ROOT}/lib/spring-core.jar`)])).toBe(true);
|
||||
expect(canAddAsLibrary([node(`${ROOT}/lib/spring-core.jar`), node(`${ROOT}/lib/mybatis.jar`)])).toBe(true);
|
||||
expect(canAddAsLibrary([node(`${ROOT}/lib/spring-core.jar`), node(`${ROOT}/README.md`)])).toBe(false);
|
||||
expect(canAddAsLibrary([node(`${ROOT}/src/Main.java`)])).toBe(false);
|
||||
expect(canAddAsLibrary([node(ROOT, true, { root: true })])).toBe(false);
|
||||
expect(canAddAsLibrary([node("/outside/other.jar")])).toBe(false);
|
||||
});
|
||||
|
||||
it("probes collapsed directories via fsReadDir without false positives on WEB-INF or source folders", async () => {
|
||||
ipcMocks.fsReadDir.mockImplementation(async (dir: string) => {
|
||||
if (dir === `${ROOT}/vendor/jars`) {
|
||||
return { status: "ok", data: [{ name: "gson.jar", path: `${dir}/gson.jar`, kind: "file", targetKind: null }] };
|
||||
}
|
||||
if (dir === `${ROOT}/nested-lib`) {
|
||||
return { status: "ok", data: [{ name: "spring", path: `${dir}/spring`, kind: "dir", targetKind: null }] };
|
||||
}
|
||||
if (dir === `${ROOT}/nested-lib/spring`) {
|
||||
return {
|
||||
status: "ok",
|
||||
data: [{ name: "spring-core.jar", path: `${dir}/spring-core.jar`, kind: "file", targetKind: null }],
|
||||
};
|
||||
}
|
||||
if (dir === `${ROOT}/WebContent/WEB-INF`) {
|
||||
return {
|
||||
status: "ok",
|
||||
data: [
|
||||
{ name: "web.xml", path: `${dir}/web.xml`, kind: "file", targetKind: null },
|
||||
{ name: "lib", path: `${dir}/lib`, kind: "dir", targetKind: null },
|
||||
],
|
||||
};
|
||||
}
|
||||
if (dir === `${ROOT}/ts-lib`) {
|
||||
return { status: "ok", data: [{ name: "index.ts", path: `${dir}/index.ts`, kind: "file", targetKind: null }] };
|
||||
}
|
||||
return { status: "ok", data: [] };
|
||||
});
|
||||
|
||||
const jarsDir = node(`${ROOT}/vendor/jars`, true);
|
||||
expect(canAddAsLibrary([jarsDir])).toBe(false);
|
||||
await prepareLibraryTargets([jarsDir]);
|
||||
expect(canAddAsLibrary([jarsDir])).toBe(true);
|
||||
|
||||
const nestedLib = node(`${ROOT}/nested-lib`, true);
|
||||
await prepareLibraryTargets([nestedLib]);
|
||||
expect(canAddAsLibrary([nestedLib])).toBe(true);
|
||||
|
||||
// Parent WEB-INF holds web.xml directly, so it must not be treated as a JAR folder.
|
||||
const webInf = node(`${ROOT}/WebContent/WEB-INF`, true);
|
||||
await prepareLibraryTargets([webInf]);
|
||||
expect(canAddAsLibrary([webInf])).toBe(false);
|
||||
|
||||
const tsLib = node(`${ROOT}/ts-lib`, true);
|
||||
await prepareLibraryTargets([tsLib]);
|
||||
expect(canAddAsLibrary([tsLib])).toBe(false);
|
||||
});
|
||||
|
||||
it("recognizes already-loaded tree listings holding .jar or .class files synchronously", () => {
|
||||
useProjectTree.setState({
|
||||
listings: new Map([
|
||||
[`${ROOT}/ext`, [fileEntry(`${ROOT}/ext/servlet-api.jar`)]],
|
||||
[`${ROOT}/classes`, [fileEntry(`${ROOT}/classes/App.class`)]],
|
||||
]),
|
||||
});
|
||||
expect(canAddAsLibrary([node(`${ROOT}/ext`, true)])).toBe(true);
|
||||
expect(canAddAsLibrary([node(`${ROOT}/classes`, true)])).toBe(true);
|
||||
});
|
||||
|
||||
it("hides Add as Library once a folder or JAR is already configured, and flags it as a library node", () => {
|
||||
setLibraries([{ name: "lib", classes: ["WebContent/WEB-INF/lib"] }]);
|
||||
const dir = node(`${ROOT}/WebContent/WEB-INF/lib`, true);
|
||||
const jarInside = node(`${ROOT}/WebContent/WEB-INF/lib/spring-core.jar`);
|
||||
const readmeInside = node(`${ROOT}/WebContent/WEB-INF/lib/README.txt`);
|
||||
const otherJar = node(`${ROOT}/extra/other.jar`);
|
||||
|
||||
expect(canAddAsLibrary([dir])).toBe(false);
|
||||
expect(canAddAsLibrary([jarInside])).toBe(false);
|
||||
expect(isLibraryNode(dir)).toBe(true);
|
||||
expect(isLibraryNode(jarInside)).toBe(true);
|
||||
expect(isLibraryNode(readmeInside)).toBe(false);
|
||||
expect(
|
||||
isConfiguredLibraryDirectory(
|
||||
dir.path,
|
||||
ROOT,
|
||||
validateProjectStructure(useProject.getState().settings?.projectStructure).libraries,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(canAddAsLibrary([otherJar])).toBe(true);
|
||||
expect(isLibraryNode(otherJar)).toBe(false);
|
||||
});
|
||||
|
||||
it("suggests unique default library names", () => {
|
||||
expect(suggestLibraryName([`${ROOT}/WebContent/WEB-INF/lib`], ROOT, [])).toBe("lib");
|
||||
expect(
|
||||
suggestLibraryName([`${ROOT}/WebContent/WEB-INF/lib`], ROOT, [
|
||||
{ name: "lib", classes: ["lib"], sources: [], javadocs: [], scope: "compile" },
|
||||
]),
|
||||
).toBe("lib (2)");
|
||||
expect(suggestLibraryName([`${ROOT}/lib/spring-core-5.3.jar`], ROOT, [])).toBe("spring-core-5.3");
|
||||
expect(suggestLibraryName([`${ROOT}/deps/a.jar`, `${ROOT}/deps/b.jar`], ROOT, [])).toBe("deps");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AddLibraryDialogHost", () => {
|
||||
it("validates the name, saves the new project library, and reloads settings", async () => {
|
||||
setLibraries([{ name: "existing", classes: ["other/a.jar"] }]);
|
||||
ipcMocks.settingsSet.mockResolvedValue({ status: "ok", data: useProject.getState().settings });
|
||||
ipcMocks.settingsGet.mockResolvedValue(useProject.getState().settings);
|
||||
|
||||
render(<AddLibraryDialogHost />);
|
||||
act(() => openAddAsLibraryDialog([node(`${ROOT}/WebContent/WEB-INF/lib`, true)]));
|
||||
|
||||
const dialog = screen.getByRole("dialog", { name: "Create Library" });
|
||||
expect(dialog).toBeInTheDocument();
|
||||
const input = screen.getByRole("textbox", { name: "Library name" }) as HTMLInputElement;
|
||||
expect(input.value).toBe("lib");
|
||||
expect(screen.getByText("WebContent/WEB-INF/lib")).toBeInTheDocument();
|
||||
|
||||
const okBtn = screen.getByRole("button", { name: "OK" });
|
||||
expect(okBtn).not.toBeDisabled();
|
||||
|
||||
// Empty name disables OK.
|
||||
fireEvent.change(input, { target: { value: " " } });
|
||||
expect(okBtn).toBeDisabled();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Library name cannot be empty.");
|
||||
|
||||
// Duplicate name disables OK.
|
||||
fireEvent.change(input, { target: { value: "existing" } });
|
||||
expect(okBtn).toBeDisabled();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("A library with this name already exists.");
|
||||
|
||||
// Valid name submits to settingsSet and closes.
|
||||
fireEvent.change(input, { target: { value: "web-lib" } });
|
||||
expect(okBtn).not.toBeDisabled();
|
||||
fireEvent.click(okBtn);
|
||||
|
||||
await waitFor(() => expect(ipcMocks.settingsSet).toHaveBeenCalledTimes(1));
|
||||
expect(ipcMocks.settingsSet).toHaveBeenCalledWith(
|
||||
"project",
|
||||
"projectStructure.libraries",
|
||||
JSON.stringify([
|
||||
{ name: "existing", classes: ["other/a.jar"], sources: [], javadocs: [], scope: "compile" },
|
||||
{ name: "web-lib", classes: ["WebContent/WEB-INF/lib"], sources: [], javadocs: [], scope: "compile" },
|
||||
]),
|
||||
);
|
||||
await waitFor(() => expect(pendingAddLibraryDialog()).toBeNull());
|
||||
});
|
||||
});
|
||||
|
||||
describe("External Libraries live refresh and project tree writability", () => {
|
||||
it("refreshes External Libraries when a JAR is added or removed inside a configured library directory", () => {
|
||||
setLibraries([{ name: "web-lib", classes: ["WebContent/WEB-INF/lib"] }]);
|
||||
expect(touchesConfiguredLibrary([`${ROOT}/WebContent/WEB-INF/lib/spring-mvc.jar`])).toBe(true);
|
||||
expect(touchesConfiguredLibrary([`${ROOT}/WebContent/WEB-INF/lib/sub/extra.jar`])).toBe(true);
|
||||
expect(touchesConfiguredLibrary([`${ROOT}/WebContent/WEB-INF/lib/notes.txt`])).toBe(false);
|
||||
expect(touchesConfiguredLibrary([`${ROOT}/other/foo.jar`])).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a configured project library folder writable in the Project tree even when empty", () => {
|
||||
setLibraries([{ name: "lib", classes: ["WebContent/WEB-INF/lib"] }]);
|
||||
const dispose = registerProjectViewRoot({
|
||||
id: "externalLibraries",
|
||||
label: "External Libraries",
|
||||
icon: "library",
|
||||
order: 5,
|
||||
readOnly: true,
|
||||
children: [
|
||||
{
|
||||
label: "lib",
|
||||
icon: "library",
|
||||
children: [{ label: "lib", icon: "folder-library", path: `${ROOT}/WebContent/WEB-INF/lib` }],
|
||||
},
|
||||
],
|
||||
});
|
||||
try {
|
||||
useProjectTree.setState({
|
||||
root: ROOT,
|
||||
name: "app",
|
||||
listings: new Map([
|
||||
[ROOT, [fileEntry(`${ROOT}/WebContent`, "dir")]],
|
||||
[`${ROOT}/WebContent`, [fileEntry(`${ROOT}/WebContent/WEB-INF`, "dir")]],
|
||||
[`${ROOT}/WebContent/WEB-INF`, [fileEntry(`${ROOT}/WebContent/WEB-INF/lib`, "dir")]],
|
||||
[`${ROOT}/WebContent/WEB-INF/lib`, []],
|
||||
]),
|
||||
});
|
||||
const model = selectModel(useProjectTree.getState());
|
||||
const key = model.keyOfPath.get(`${ROOT}/WebContent/WEB-INF/lib`);
|
||||
expect(key).toBeTruthy();
|
||||
expect(model.byKey.get(key!)?.readOnly).toBeFalsy();
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,335 +0,0 @@
|
||||
/**
|
||||
* "Add as Library…" (Project view context menu): adds a `.jar` file, multiple
|
||||
* `.jar` files, or a directory holding `.jar` / `.class` files (such as a
|
||||
* legacy Java web app's `WEB-INF/lib`) to `projectStructure.libraries`.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import {
|
||||
libraryClassEntry,
|
||||
normalizeFolder,
|
||||
validateProjectStructure,
|
||||
type DependencyScopeValid,
|
||||
type ProjectLibraryValid,
|
||||
} from "@/platform/languageSettings";
|
||||
import { loadSettings, relativePath, useProject } from "@/platform/project";
|
||||
import { isDirEntry, type ProjectNode } from "./model";
|
||||
import { isSameOrInside, nameOf, parentOf } from "./paths";
|
||||
import { useProjectTree } from "./store";
|
||||
|
||||
const JAR_EXT = /\.jar$/i;
|
||||
const CLASS_EXT = /\.class$/i;
|
||||
/** Conventional Java web library folder (`WEB-INF/lib` / `WEB-INF/libs`), offered even while empty. */
|
||||
const WEB_INF_LIB = /(^|\/)WEB-INF\/libs?$/i;
|
||||
const SKIP_SUBDIRS = new Set([".git", ".hg", ".svn", ".idea", ".openidea", "node_modules", "target", "build", "out"]);
|
||||
const MAX_SUBDIRS_TO_PROBE = 16;
|
||||
const PREPARE_TIMEOUT_MS = 200;
|
||||
|
||||
export interface AddLibraryRequest {
|
||||
/** Absolute paths selected in the Project view. */
|
||||
paths: string[];
|
||||
seq: number;
|
||||
}
|
||||
|
||||
const useAddLibraryDialog = create<{ request: AddLibraryRequest | null }>(() => ({ request: null }));
|
||||
let requestSeq = 0;
|
||||
|
||||
export function openAddAsLibraryDialog(nodes: readonly ProjectNode[]) {
|
||||
const paths = nodes.map((n) => n.path);
|
||||
if (!paths.length) return;
|
||||
useAddLibraryDialog.setState({ request: { paths, seq: ++requestSeq } });
|
||||
}
|
||||
|
||||
export function closeAddAsLibraryDialog() {
|
||||
useAddLibraryDialog.setState({ request: null });
|
||||
}
|
||||
|
||||
export function useAddLibraryRequest(): AddLibraryRequest | null {
|
||||
return useAddLibraryDialog((s) => s.request);
|
||||
}
|
||||
|
||||
/** Test hook: the currently open Create Library dialog request. */
|
||||
export function pendingAddLibraryDialog(): AddLibraryRequest | null {
|
||||
return useAddLibraryDialog.getState().request;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Directory probing (cached for collapsed folders inspected before context menu)
|
||||
|
||||
const dirProbeCache = new Map<string, boolean>();
|
||||
|
||||
export function clearLibraryProbeCache(paths?: readonly string[]) {
|
||||
if (!paths) {
|
||||
dirProbeCache.clear();
|
||||
return;
|
||||
}
|
||||
for (const dir of [...dirProbeCache.keys()]) {
|
||||
if (paths.some((p) => p === dir || isSameOrInside(p, dir) || isSameOrInside(dir, p))) {
|
||||
dirProbeCache.delete(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function isJarPath(path: string): boolean {
|
||||
return JAR_EXT.test(path);
|
||||
}
|
||||
|
||||
export function isWebInfLibPath(rel: string): boolean {
|
||||
return WEB_INF_LIB.test(normalizeFolder(rel));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `absPath` is already covered by an entry in `libraries`.
|
||||
* A JAR directory entry covers itself and any `.jar` file inside it.
|
||||
*/
|
||||
export function isAlreadyInLibraries(
|
||||
absPath: string,
|
||||
isDir: boolean,
|
||||
root: string,
|
||||
libraries: readonly ProjectLibraryValid[],
|
||||
): boolean {
|
||||
const target = normalizeFolder(relativePath(root, absPath));
|
||||
if (!target) return false;
|
||||
for (const lib of libraries) {
|
||||
for (const raw of lib.classes) {
|
||||
const entry = libraryClassEntry(raw, root);
|
||||
if (!entry || !entry.path) continue;
|
||||
if (entry.path === target) return true;
|
||||
if (entry.glob === "recursive" && target.startsWith(`${entry.path}/`)) return true;
|
||||
if (entry.glob === "shallow" && !isDir && isJarPath(target) && parentOf(target) === entry.path) return true;
|
||||
if (entry.glob === "none" && !isDir && isJarPath(target) && !isJarPath(entry.path)) {
|
||||
if (target.startsWith(`${entry.path}/`)) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `absPath` is directly registered as a directory entry in `projectStructure.libraries`
|
||||
* (for the `folder-library` icon in the Project tree and "Open Library Settings").
|
||||
*/
|
||||
export function isConfiguredLibraryDirectory(
|
||||
absPath: string,
|
||||
root: string,
|
||||
libraries: readonly ProjectLibraryValid[],
|
||||
): boolean {
|
||||
const target = normalizeFolder(relativePath(root, absPath));
|
||||
if (!target) return false;
|
||||
for (const lib of libraries) {
|
||||
for (const raw of lib.classes) {
|
||||
const entry = libraryClassEntry(raw, root);
|
||||
if (entry && entry.path === target) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function listingHasLibraryFiles(
|
||||
entries: readonly { name: string; kind: string; targetKind?: string | null }[],
|
||||
): boolean {
|
||||
return entries.some((e) => {
|
||||
const kind = e.kind === "symlink" ? (e.targetKind ?? "file") : e.kind;
|
||||
return kind !== "dir" && (JAR_EXT.test(e.name) || CLASS_EXT.test(e.name));
|
||||
});
|
||||
}
|
||||
|
||||
function isDirCandidateSync(node: ProjectNode, root: string): boolean {
|
||||
const rel = normalizeFolder(relativePath(root, node.path));
|
||||
if (isWebInfLibPath(rel)) return true;
|
||||
const cached = dirProbeCache.get(node.path);
|
||||
if (cached !== undefined) return cached;
|
||||
const listing = useProjectTree.getState().listings.get(node.path);
|
||||
if (listing && listingHasLibraryFiles(listing)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
async function probeDirectory(dir: string): Promise<boolean> {
|
||||
const cached = dirProbeCache.get(dir);
|
||||
if (cached !== undefined) return cached;
|
||||
const loaded = useProjectTree.getState().listings.get(dir);
|
||||
const entries = loaded
|
||||
? loaded.map((e) => ({
|
||||
name: e.name,
|
||||
path: e.path,
|
||||
kind: isDirEntry(e) ? "dir" : "file",
|
||||
targetKind: null as string | null,
|
||||
}))
|
||||
: await call(commands.fsReadDir(dir)).catch(() => null);
|
||||
if (!entries) return false;
|
||||
if (listingHasLibraryFiles(entries)) {
|
||||
dirProbeCache.set(dir, true);
|
||||
return true;
|
||||
}
|
||||
// Only look one level deeper when the directory holds subdirectories and no regular files of
|
||||
// its own (e.g. `lib/spring/*.jar`), so parents like `WEB-INF/` (which holds `web.xml`) stay out.
|
||||
let hasRegularFile = false;
|
||||
const subdirs: string[] = [];
|
||||
for (const e of entries) {
|
||||
const kind = e.kind === "symlink" ? (e.targetKind ?? "file") : e.kind;
|
||||
if (kind === "dir") {
|
||||
if (!SKIP_SUBDIRS.has(e.name) && !e.name.startsWith(".")) subdirs.push(e.path);
|
||||
} else if (!e.name.startsWith(".")) {
|
||||
hasRegularFile = true;
|
||||
}
|
||||
}
|
||||
if (!hasRegularFile && subdirs.length > 0) {
|
||||
for (const sub of subdirs.slice(0, MAX_SUBDIRS_TO_PROBE)) {
|
||||
const subLoaded = useProjectTree.getState().listings.get(sub);
|
||||
const subEntries = subLoaded
|
||||
? subLoaded.map((e) => ({
|
||||
name: e.name,
|
||||
kind: isDirEntry(e) ? "dir" : "file",
|
||||
targetKind: null as string | null,
|
||||
}))
|
||||
: // oxlint-disable-next-line no-await-in-loop -- bounded small directory probe before menu open
|
||||
await call(commands.fsReadDir(sub)).catch(() => null);
|
||||
if (
|
||||
subEntries &&
|
||||
subEntries.some((e) => {
|
||||
const kind = e.kind === "symlink" ? (e.targetKind ?? "file") : e.kind;
|
||||
return kind !== "dir" && JAR_EXT.test(e.name);
|
||||
})
|
||||
) {
|
||||
dirProbeCache.set(dir, true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
dirProbeCache.set(dir, false);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspects collapsed directory nodes in `nodes` before the Project view context menu opens so
|
||||
* "Add as Library…" appears on the first right-click of a folder holding `.jar` / `.class` files.
|
||||
*/
|
||||
export async function prepareLibraryTargets(nodes: readonly ProjectNode[]): Promise<void> {
|
||||
if (!isTauri() || !nodes.length) return;
|
||||
const root = useProject.getState().project?.root;
|
||||
if (!root) return;
|
||||
const eligible = nodes.every(
|
||||
(n) => !n.root && !n.placeholder && !n.group && !n.readOnly && isSameOrInside(n.path, root),
|
||||
);
|
||||
if (!eligible) return;
|
||||
const dirsToProbe = nodes
|
||||
.filter((n) => n.dir && !isWebInfLibPath(relativePath(root, n.path)) && !dirProbeCache.has(n.path))
|
||||
.filter((n) => {
|
||||
const listing = useProjectTree.getState().listings.get(n.path);
|
||||
return !(listing && listingHasLibraryFiles(listing));
|
||||
});
|
||||
if (!dirsToProbe.length) return;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
await Promise.race([
|
||||
Promise.all(dirsToProbe.map((n) => probeDirectory(n.path))),
|
||||
new Promise<void>((r) => {
|
||||
timer = setTimeout(r, PREPARE_TIMEOUT_MS);
|
||||
}),
|
||||
]);
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the Project view context menu should offer "Add as Library…" for `nodes`.
|
||||
* True when every node is an in-project `.jar` file or a library directory (e.g. `WEB-INF/lib`,
|
||||
* or a folder containing `.jar` / `.class` files) and at least one is not already a library.
|
||||
*/
|
||||
export function canAddAsLibrary(nodes: readonly ProjectNode[]): boolean {
|
||||
if (!nodes.length) return false;
|
||||
const { project, settings } = useProject.getState();
|
||||
if (!project) return false;
|
||||
const root = project.root;
|
||||
for (const n of nodes) {
|
||||
if (n.root || n.placeholder || n.group || n.readOnly) return false;
|
||||
if (!isSameOrInside(n.path, root)) return false;
|
||||
if (n.dir) {
|
||||
if (!isDirCandidateSync(n, root)) return false;
|
||||
} else if (!isJarPath(n.path)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const libraries = validateProjectStructure(settings?.projectStructure).libraries;
|
||||
return nodes.some((n) => !isAlreadyInLibraries(n.path, n.dir, root, libraries));
|
||||
}
|
||||
|
||||
/** Whether a single node is already registered in `projectStructure.libraries`. */
|
||||
export function isLibraryNode(node: ProjectNode): boolean {
|
||||
if (node.root || node.placeholder || node.group || node.readOnly) return false;
|
||||
const { project, settings } = useProject.getState();
|
||||
if (!project || !isSameOrInside(node.path, project.root)) return false;
|
||||
const libraries = validateProjectStructure(settings?.projectStructure).libraries;
|
||||
return isAlreadyInLibraries(node.path, node.dir, project.root, libraries);
|
||||
}
|
||||
|
||||
/** Project-relative normalized class paths for `paths`, omitting entries already in `libraries`. */
|
||||
export function libraryClassPaths(
|
||||
paths: readonly string[],
|
||||
root: string,
|
||||
libraries: readonly ProjectLibraryValid[] = [],
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
for (const p of paths) {
|
||||
const rel = normalizeFolder(relativePath(root, p));
|
||||
if (!rel || out.includes(rel)) continue;
|
||||
if (isAlreadyInLibraries(p, !isJarPath(p), root, libraries)) continue;
|
||||
out.push(rel);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Suggests a unique default library name for `paths`. */
|
||||
export function suggestLibraryName(
|
||||
paths: readonly string[],
|
||||
root: string,
|
||||
existing: readonly ProjectLibraryValid[],
|
||||
): string {
|
||||
const stem = (p: string) => nameOf(p).replace(JAR_EXT, "").trim();
|
||||
let base = "";
|
||||
if (paths.length === 1) {
|
||||
base = stem(paths[0]!);
|
||||
} else if (paths.length > 1) {
|
||||
const parents = new Set(paths.map((p) => parentOf(p)));
|
||||
const sharedParent = parents.size === 1 ? [...parents][0]! : null;
|
||||
if (sharedParent && sharedParent !== root && isSameOrInside(sharedParent, root)) {
|
||||
base = nameOf(sharedParent).trim();
|
||||
} else {
|
||||
base = stem(paths[0]!);
|
||||
}
|
||||
}
|
||||
if (!base) base = "Library";
|
||||
const taken = new Set(existing.map((l) => l.name.trim()));
|
||||
if (!taken.has(base)) return base;
|
||||
let n = 2;
|
||||
while (taken.has(`${base} (${n})`)) n++;
|
||||
return `${base} (${n})`;
|
||||
}
|
||||
|
||||
/** Appends a new library to `projectStructure.libraries` and reloads project settings. */
|
||||
export async function addProjectLibrary(input: {
|
||||
name: string;
|
||||
paths: readonly string[];
|
||||
scope: DependencyScopeValid;
|
||||
}): Promise<boolean> {
|
||||
const { project, settings } = useProject.getState();
|
||||
if (!project || !isTauri()) return false;
|
||||
const name = input.name.trim();
|
||||
if (!name) return false;
|
||||
const ps = validateProjectStructure(settings?.projectStructure);
|
||||
const classes = libraryClassPaths(input.paths, project.root, ps.libraries);
|
||||
const fallbackClasses =
|
||||
classes.length > 0
|
||||
? classes
|
||||
: [...new Set(input.paths.map((p) => normalizeFolder(relativePath(project.root, p))).filter(Boolean))];
|
||||
if (!fallbackClasses.length) return false;
|
||||
const created: ProjectLibraryValid = {
|
||||
name,
|
||||
classes: fallbackClasses,
|
||||
sources: [],
|
||||
javadocs: [],
|
||||
scope: input.scope,
|
||||
};
|
||||
const next = [...ps.libraries, created];
|
||||
await call(commands.settingsSet("project", "projectStructure.libraries", JSON.stringify(next)));
|
||||
await loadSettings();
|
||||
return true;
|
||||
}
|
||||
@@ -164,46 +164,6 @@ describe("project view context menu", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("offers Add as Library… on WEB-INF/lib and JAR files, and Open Library Settings once added", () => {
|
||||
const opened: unknown[] = [];
|
||||
const dispose = registerActions([
|
||||
{ id: "file.projectStructure", title: "Project Structure…", run: ({ arg }) => void opened.push(arg) },
|
||||
]);
|
||||
try {
|
||||
const webLib = node(`${ROOT}/WebContent/WEB-INF/lib`, true);
|
||||
const libItems = labels(contextMenuItems([webLib]));
|
||||
expect(libItems).toContain("Add as Library…");
|
||||
expect(libItems.indexOf("Add as Library…")).toBeGreaterThan(libItems.indexOf("Mark Directory as"));
|
||||
expect(libItems.indexOf("Add as Library…")).toBeLessThan(libItems.indexOf("File Color"));
|
||||
|
||||
const jar = node(`${ROOT}/ext/spring-core.jar`);
|
||||
expect(labels(contextMenuItems([jar]))).toContain("Add as Library…");
|
||||
|
||||
// Plain non-library folder does not offer Add as Library….
|
||||
expect(labels(contextMenuItems([node(`${ROOT}/docs`, true)]))).not.toContain("Add as Library…");
|
||||
|
||||
// Once configured in projectStructure.libraries, Add as Library… disappears and Open Library Settings is offered.
|
||||
useProject.setState({
|
||||
project: { name: "p", root: ROOT, trusted: true, isGit: true, settings: {} } as never,
|
||||
settings: {
|
||||
projectStructure: {
|
||||
libraries: [
|
||||
{ name: "lib", classes: ["WebContent/WEB-INF/lib"], sources: [], javadocs: [], scope: "compile" },
|
||||
],
|
||||
},
|
||||
} as never,
|
||||
});
|
||||
const configured = contextMenuItems([webLib]);
|
||||
expect(labels(configured)).not.toContain("Add as Library…");
|
||||
const openSettings = resolveMenuItems(configured).find((r) => r.label === "Open Library Settings");
|
||||
expect(openSettings).toBeDefined();
|
||||
openSettings!.run!();
|
||||
expect(opened).toEqual(["libraries"]);
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("offers Git for repositories found below a non-Git project root", () => {
|
||||
useProject.setState({ project: { name: "p", root: ROOT, trusted: true, isGit: false, settings: {} } as never });
|
||||
expect(sub(contextMenuItems([node("/p/a.py")]), "Git")).toBeUndefined();
|
||||
|
||||
@@ -12,7 +12,6 @@ import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { menuGroupItems, gitMenuItems, toolWindowService, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import type { FolderRole } from "@/platform/languageSettings";
|
||||
import { canAddAsLibrary, isLibraryNode, openAddAsLibraryDialog } from "./addLibrary";
|
||||
import { directoryRole, markDirectory } from "./markDirectory";
|
||||
import { fileColorMenu } from "./fileColor";
|
||||
import type { ProjectNode } from "./model";
|
||||
@@ -448,8 +447,6 @@ export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center")
|
||||
shortcut: isModuleNode(single) ? keyLabel("project.open") : undefined,
|
||||
}),
|
||||
);
|
||||
if (inProject && single && isLibraryNode(single))
|
||||
push(delegated("file.projectStructure", "libraries", "Open Library Settings", { icon: "project-structure" }));
|
||||
|
||||
push({ kind: "separator" });
|
||||
|
||||
@@ -488,13 +485,6 @@ export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center")
|
||||
],
|
||||
});
|
||||
}
|
||||
if (inProject && canAddAsLibrary(nodes))
|
||||
push({
|
||||
id: "addAsLibrary",
|
||||
label: "Add as Library…",
|
||||
icon: "library",
|
||||
run: () => openAddAsLibraryDialog(nodes),
|
||||
});
|
||||
if (inProject && single && !single.root && !single.placeholder && !single.group) {
|
||||
const color = fileColorMenu(single.path, single.dir);
|
||||
if (color) push(color);
|
||||
|
||||
@@ -26,8 +26,6 @@ import {
|
||||
useProjectViewRoots,
|
||||
} from "@/workbench/contributions";
|
||||
import { registerProjectActions } from "./actions";
|
||||
import { clearLibraryProbeCache } from "./addLibrary";
|
||||
import { AddLibraryDialogHost } from "./AddLibraryDialog";
|
||||
import { mavenExternalRoots } from "./mavenRoots";
|
||||
import { gradleModuleGroups } from "./moduleGroups";
|
||||
import { FileRefactorDialogHost } from "./FileRefactorDialogs";
|
||||
@@ -84,7 +82,6 @@ export function activate(): () => void {
|
||||
if (s.project?.root !== prev.project?.root) {
|
||||
unityGeneration++;
|
||||
clearTimeout(unityTimer);
|
||||
clearLibraryProbeCache();
|
||||
}
|
||||
if (s.project !== prev.project) sync();
|
||||
});
|
||||
@@ -315,7 +312,6 @@ export function activate(): () => void {
|
||||
titleMenu: useProjectTitleMenu,
|
||||
}),
|
||||
registerOverlay({ id: "project.fileRefactor", component: FileRefactorDialogHost }),
|
||||
registerOverlay({ id: "project.addLibrary", component: AddLibraryDialogHost }),
|
||||
registerOverlay({ id: "project.refactoringPreview", component: RefactoringPreviewHost }),
|
||||
registerOverlay({ id: "project.newPopup", component: NewPopupHost }),
|
||||
registerProjectActions(),
|
||||
@@ -333,10 +329,7 @@ export function activate(): () => void {
|
||||
.map((n) => n.path),
|
||||
),
|
||||
initProjectTypes(),
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
clearLibraryProbeCache([...e.created, ...e.removed]);
|
||||
void applyFsChange(e);
|
||||
}),
|
||||
onIdeEvent("fsChanged", (e) => void applyFsChange(e)),
|
||||
onIdeEvent("excludedDirsChanged", (e) => void reloadLoadedDirs(e.dirs)),
|
||||
onIdeEvent("projectRootsChanged", () => void reloadArchiveDirs()),
|
||||
];
|
||||
|
||||
@@ -14,9 +14,7 @@ import { isIgnoredName } from "@/platform/ignoredNames";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { validateProjectStructure } from "@/platform/languageSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { isConfiguredLibraryDirectory } from "./addLibrary";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { projectLocation } from "@/platform/remote";
|
||||
import {
|
||||
@@ -333,14 +331,8 @@ export function selectModel(s: ProjectTreeState): TreeModel {
|
||||
model.roots[0].detail = s.unity.editorVersion ? `Unity ${s.unity.editorVersion}` : "Unity";
|
||||
if (s.unreal && s.mode === "unreal" && model.roots[0])
|
||||
model.roots[0].detail = s.unreal.engine ? `Unreal ${s.unreal.engine.id}` : "Unreal · engine not found";
|
||||
const configured = validateProjectStructure(useProject.getState().settings?.projectStructure).libraries;
|
||||
const libraries = extraFolders(contributed).flatMap((r) =>
|
||||
r.readOnly &&
|
||||
r.path !== undefined &&
|
||||
isSameOrInside(r.path, s.root!) &&
|
||||
!isConfiguredLibraryDirectory(r.path, s.root!, configured)
|
||||
? [r.path]
|
||||
: [],
|
||||
r.readOnly && r.path !== undefined && isSameOrInside(r.path, s.root!) ? [r.path] : [],
|
||||
);
|
||||
model = withReadOnlyFolders(model, libraries);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ vi.mock("@/platform/clipboard", async (importOriginal) => ({
|
||||
|
||||
import { getAction, registerAction, executeAction } from "@/platform/actions";
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { setLocale } from "@/platform/i18n";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useKeymap } from "@/platform/keymap";
|
||||
@@ -824,68 +823,12 @@ describe("Settings dialog", () => {
|
||||
expect(settingsSet).toHaveBeenCalledWith("project", "projectStructure.compilerOutput", '"out/classes"');
|
||||
});
|
||||
|
||||
it("searches Project Structure settings, opens the matching module tab and keeps a draft", async () => {
|
||||
useProject.setState({ project: { name: "demo", root: "/project" } as never });
|
||||
render(<ProjectStructureDialog />);
|
||||
await act(async () => executeAction("file.projectStructure"));
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Compiler output"), { target: { value: "out/classes" } });
|
||||
const nav = screen.getByRole("navigation", { name: "Project Structure sections" });
|
||||
const search = within(nav).getByRole("textbox", { name: "Search settings" });
|
||||
fireEvent.change(search, { target: { value: "test output path" } });
|
||||
expect(within(nav).getByRole("button", { name: "Modules" })).toHaveAttribute("aria-current", "page");
|
||||
expect(screen.getByRole("tab", { name: "Paths" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(screen.getByLabelText("Test output path").closest("[data-search-match]")).toBeInTheDocument();
|
||||
expect(within(nav).queryByRole("button", { name: "Project" })).toBeNull();
|
||||
|
||||
fireEvent.keyDown(search, { key: "Enter" });
|
||||
expect(settingsSet).not.toHaveBeenCalled();
|
||||
await act(async () => search.focus());
|
||||
fireEvent.change(search, { target: { value: "jdk" } });
|
||||
expect(within(nav).getByRole("button", { name: "Project" })).toHaveAttribute("aria-current", "page");
|
||||
fireEvent.keyDown(search, { key: "ArrowDown" });
|
||||
expect(within(nav).getByRole("button", { name: "SDKs" })).toHaveAttribute("aria-current", "page");
|
||||
expect(search).toHaveFocus();
|
||||
|
||||
fireEvent.change(search, { target: { value: "missing setting" } });
|
||||
expect(within(nav).getByText("No matches")).toBeInTheDocument();
|
||||
fireEvent.keyDown(search, { key: "Escape" });
|
||||
expect(search).toHaveValue("");
|
||||
|
||||
fireEvent.click(within(nav).getByRole("button", { name: "Project" }));
|
||||
expect(screen.getByLabelText("Compiler output")).toHaveValue("out/classes");
|
||||
});
|
||||
|
||||
it("matches translated Project Structure labels and clears the filter for a direct navigation", async () => {
|
||||
try {
|
||||
await act(async () => setLocale("zh"));
|
||||
useProject.setState({ project: { name: "demo", root: "/project" } as never });
|
||||
render(<ProjectStructureDialog />);
|
||||
await act(async () => executeAction("file.projectStructure"));
|
||||
|
||||
const nav = screen.getByRole("navigation", { name: "项目结构分区" });
|
||||
const search = within(nav).getByRole("textbox", { name: "搜索设置" });
|
||||
fireEvent.change(search, { target: { value: "测试输出路径" } });
|
||||
expect(within(nav).getByRole("button", { name: "模块" })).toHaveAttribute("aria-current", "page");
|
||||
expect(screen.getByRole("tab", { name: "路径" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(screen.getByLabelText("测试输出路径").closest("[data-search-match]")).toBeInTheDocument();
|
||||
|
||||
await act(async () => executeAction("file.projectStructure", "project"));
|
||||
expect(search).toHaveValue("");
|
||||
expect(within(nav).getByRole("button", { name: "项目" })).toHaveAttribute("aria-current", "page");
|
||||
} finally {
|
||||
await act(async () => setLocale("en"));
|
||||
}
|
||||
});
|
||||
|
||||
it("disables Project Structure controls whose settings have no execution support", async () => {
|
||||
useProject.setState({ project: { name: "demo", root: "/project" } as never });
|
||||
render(<ProjectStructureDialog />);
|
||||
await act(async () => executeAction("file.projectStructure", "modules"));
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Paths" }));
|
||||
// Without Maven or Gradle, the IDE compiles against the module's custom output and test output paths.
|
||||
expect(screen.getByLabelText("Output path")).toBeEnabled();
|
||||
expect(screen.getByLabelText("Test output path")).toBeEnabled();
|
||||
expect(screen.getByLabelText("Test output path")).toBeDisabled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Dependencies" }));
|
||||
// Project dependencies are supported: the checklist is live, no disabled placeholder.
|
||||
expect(screen.getByRole("group", { name: "The project depends on these projects" })).toBeInTheDocument();
|
||||
@@ -911,61 +854,6 @@ describe("Settings dialog", () => {
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Paths" }));
|
||||
expect(screen.getByLabelText("Module language level")).toBeDisabled();
|
||||
expect(screen.getByLabelText("Output path")).toBeDisabled();
|
||||
expect(screen.getByLabelText("Test output path")).toBeDisabled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ os: "windows", modifier: { ctrlKey: true } },
|
||||
{ os: "macos", modifier: { metaKey: true } },
|
||||
] as const)("marks and unmarks multiple selected module folders on $os", async ({ os, modifier }) => {
|
||||
current = setAt(current, "projectStructure.sourceRoots", ["alpha", "beta"]);
|
||||
useProject.setState({ settings: current, project: { name: "demo", root: "/project" } as never });
|
||||
const platform = usePlatform.getState();
|
||||
usePlatform.setState({ os });
|
||||
const readDir = vi.spyOn(commands, "fsReadDir").mockResolvedValue({
|
||||
status: "ok",
|
||||
data: ["alpha", "beta", "gamma"].map((name) => ({
|
||||
name,
|
||||
path: `/project/${name}`,
|
||||
kind: "dir",
|
||||
size: 0,
|
||||
mtimeMs: null,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
})),
|
||||
});
|
||||
try {
|
||||
render(<ProjectStructureDialog />);
|
||||
await act(async () => executeAction("file.projectStructure", "modules"));
|
||||
const tree = within(screen.getByRole("tree", { name: "Content root" }));
|
||||
const alpha = await tree.findByRole("treeitem", { name: "alpha" });
|
||||
const beta = tree.getByRole("treeitem", { name: "beta" });
|
||||
const gamma = tree.getByRole("treeitem", { name: "gamma" });
|
||||
fireEvent.mouseDown(alpha);
|
||||
fireEvent.mouseDown(gamma, { shiftKey: true });
|
||||
expect(beta).toHaveAttribute("aria-selected", "true");
|
||||
fireEvent.mouseDown(beta, modifier);
|
||||
expect(beta).toHaveAttribute("aria-selected", "false");
|
||||
|
||||
const mark = within(screen.getByRole("toolbar", { name: "Mark as" })).getByRole("button", { name: "Sources" });
|
||||
const marked = within(screen.getByRole("region", { name: "Marked folders" }));
|
||||
expect(mark).toHaveAttribute("aria-pressed", "false");
|
||||
fireEvent.click(mark);
|
||||
expect(mark).toHaveAttribute("aria-pressed", "true");
|
||||
expect(marked.getByText("gamma")).toBeInTheDocument();
|
||||
fireEvent.click(mark);
|
||||
expect(marked.queryByText("alpha")).toBeNull();
|
||||
expect(marked.queryByText("gamma")).toBeNull();
|
||||
expect(marked.getByText("beta")).toBeInTheDocument();
|
||||
expect(settingsSet).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
|
||||
expect(settingsSet).toHaveBeenCalledWith("project", "projectStructure.sourceRoots", '["beta"]');
|
||||
} finally {
|
||||
readDir.mockRestore();
|
||||
act(() => usePlatform.setState(platform));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { commands, type Settings } from "@/platform/ipc";
|
||||
|
||||
const open = vi.fn();
|
||||
@@ -140,45 +140,4 @@ describe("Project Structure module overrides", () => {
|
||||
vi.mocked(commands.buildModel).mockResolvedValue({ status: "error", error: "no build model" } as never);
|
||||
}
|
||||
});
|
||||
it("uses custom verbatim tooltips for content roots and enables custom module test output paths", async () => {
|
||||
act(() => useSettingsDialog.setState({ projectStructureOpen: false }));
|
||||
const longRoot = "/Users/dream-mini/Main/xlrj/ejsh/EJSH-very-long-project-directory";
|
||||
useProject.setState({
|
||||
settings: structuredClone(DEFAULT_SETTINGS) as Settings,
|
||||
project: { name: "EJSH", root: longRoot } as never,
|
||||
});
|
||||
await act(async () => openProjectStructure("modules"));
|
||||
|
||||
const marked = screen.getByRole("region", { name: "Marked folders" });
|
||||
const rootPathEl = within(marked).getByText(longRoot);
|
||||
expect(rootPathEl).toHaveAttribute("data-tooltip", longRoot);
|
||||
expect(rootPathEl).toHaveAttribute("data-tooltip-verbatim", "");
|
||||
expect(rootPathEl).not.toHaveAttribute("title");
|
||||
|
||||
// In Paths tab, a custom (non-Maven/Gradle) root module can edit both Output path and Test output path.
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Paths" }));
|
||||
const outputInput = screen.getByLabelText("Output path");
|
||||
const testOutputInput = screen.getByLabelText("Test output path");
|
||||
expect(outputInput).toBeEnabled();
|
||||
expect(testOutputInput).toBeEnabled();
|
||||
fireEvent.change(outputInput, { target: { value: "WebRoot/WEB-INF/classes" } });
|
||||
fireEvent.change(testOutputInput, { target: { value: "out/test-classes" } });
|
||||
expect(outputInput).toHaveValue("WebRoot/WEB-INF/classes");
|
||||
expect(testOutputInput).toHaveValue("out/test-classes");
|
||||
|
||||
// When Maven owns the build, Test output path stays disabled.
|
||||
act(() => useSettingsDialog.setState({ projectStructureOpen: false }));
|
||||
vi.mocked(commands.buildModel).mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { maven: { projects: [] }, gradle: [] },
|
||||
} as never);
|
||||
try {
|
||||
await act(async () => openProjectStructure("modules"));
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Paths" }));
|
||||
expect(await screen.findByText(/Maven and Gradle manage their own test output/)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Test output path")).toBeDisabled();
|
||||
} finally {
|
||||
vi.mocked(commands.buildModel).mockResolvedValue({ status: "error", error: "no build model" } as never);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,6 @@ import { labelMatches } from "../model/pages";
|
||||
export interface PageContextValue {
|
||||
pageId: string;
|
||||
scope: Scope;
|
||||
searchQuery?: string;
|
||||
}
|
||||
|
||||
export const PageContext = createContext<PageContextValue>({ pageId: "", scope: "global" });
|
||||
@@ -80,8 +79,7 @@ function useExternalValue<T>(page: string, key: string, base: T, apply: (value:
|
||||
}
|
||||
|
||||
export function useSearchQuery(): string {
|
||||
const { searchQuery } = usePageContext();
|
||||
return useSettingsDialog((s) => searchQuery ?? s.query);
|
||||
return useSettingsDialog((s) => s.query);
|
||||
}
|
||||
|
||||
/** Whether `label` should be highlighted for the current search. */
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
SearchField,
|
||||
Select,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
@@ -22,7 +21,6 @@ import {
|
||||
Tree,
|
||||
folderIconName,
|
||||
showContextMenu,
|
||||
tooltipAttrs,
|
||||
type DialogButton,
|
||||
type FolderKind,
|
||||
type IconName,
|
||||
@@ -34,7 +32,7 @@ import { call, commands, isTauri, nextRequestId, type FileEntry } from "@/platfo
|
||||
import { mergeLibraryGroups } from "@/platform/libraries";
|
||||
import type { BuildModel, LibraryGroup, WebArtifact } from "@/bindings";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import { PageContext, useSearchQuery, useSetting, useSettingsFormFor } from "../components/context";
|
||||
import { PageContext, useSetting, useSettingsFormFor } from "../components/context";
|
||||
import {
|
||||
applySettings,
|
||||
closeProjectStructure,
|
||||
@@ -42,9 +40,7 @@ import {
|
||||
resetPage,
|
||||
selectProjectStructureSection,
|
||||
useSettingsDialog,
|
||||
type ProjectStructureSection,
|
||||
} from "../model/staging";
|
||||
import { matchesTerms, queryTerms } from "../model/pages";
|
||||
import {
|
||||
ARTIFACT_KINDS,
|
||||
DEPENDENCY_SCOPES,
|
||||
@@ -68,7 +64,7 @@ import {
|
||||
type ProjectStructureValid,
|
||||
} from "@/platform/languageSettings";
|
||||
import { initProjectRoots, useDetectedRoots } from "@/platform/projectRoots";
|
||||
import { Row, SearchLabel, Section } from "../components/Form";
|
||||
import { Row, Section } from "../components/Form";
|
||||
import { detectSdks, forgetSdk, rememberSdk, useSdks, type SdkKind } from "./api";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { DownloadJdkDialog } from "./DownloadJdkDialog";
|
||||
@@ -77,6 +73,15 @@ import styles from "./Sdk.module.css";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
export type ProjectStructureSectionId =
|
||||
| "project"
|
||||
| "modules"
|
||||
| "dependencies"
|
||||
| "libraries"
|
||||
| "facets"
|
||||
| "artifacts"
|
||||
| "sdks";
|
||||
|
||||
interface DirNode {
|
||||
path: string;
|
||||
name: string;
|
||||
@@ -88,15 +93,6 @@ interface DirNode {
|
||||
|
||||
const inside = (root: string, path: string) => path === root || path.startsWith(root + "/");
|
||||
|
||||
const isAbsolutePath = (path: string) => /^(?:[A-Za-z]:[\\/]|\/)/.test(path);
|
||||
|
||||
const browseDefault = (root: string | null, value: string | undefined): string | undefined => {
|
||||
const trimmed = value?.trim();
|
||||
if (!trimmed) return root || undefined;
|
||||
if (isAbsolutePath(trimmed)) return trimmed;
|
||||
return root ? `${root}/${trimmed}` : trimmed;
|
||||
};
|
||||
|
||||
const ROLES: Array<{ role: FolderRole; label: string; title: string; kind: FolderKind; cls: string }> = [
|
||||
{ role: "source", label: "Sources", title: "Source Folders", kind: "source", cls: styles.sourceTitle! },
|
||||
{ role: "test", label: "Tests", title: "Test Source Folders", kind: "test", cls: styles.testTitle! },
|
||||
@@ -111,19 +107,6 @@ const ROLES: Array<{ role: FolderRole; label: string; title: string; kind: Folde
|
||||
{ role: "excluded", label: "Excluded", title: "Excluded Folders", kind: "excluded", cls: styles.excludedTitle! },
|
||||
];
|
||||
|
||||
type ModuleTab = "sources" | "paths";
|
||||
|
||||
const MODULE_SEARCH_LABELS = {
|
||||
sources: [
|
||||
"Sources",
|
||||
"Add Content Root",
|
||||
"Exclude files:",
|
||||
"Restore detected roots",
|
||||
...ROLES.flatMap(({ label, title }) => [label, title]),
|
||||
],
|
||||
paths: ["Paths", "Module SDK & Compiler Output", "Module SDK", "Language level", "Output path", "Test output path"],
|
||||
};
|
||||
|
||||
const PROJECT_JAVA_LEVEL_OPTIONS: SelectOption[] = JAVA_LANGUAGE_LEVELS.map((level) =>
|
||||
level ? { value: level, label: level } : { value: "", label: "SDK default", detail: "from build / JDK" },
|
||||
);
|
||||
@@ -277,7 +260,7 @@ function ContentRoots({ root, children }: { root: string; children: ReactNode })
|
||||
</div>
|
||||
<div className={clsx(styles.rootItem, styles.contentRoot)}>
|
||||
<Icon name="module" size={14} />
|
||||
<span className={styles.rootPath} {...tooltipAttrs(root, undefined, true)}>
|
||||
<span className={styles.rootPath} title={root}>
|
||||
{root}
|
||||
</span>
|
||||
</div>
|
||||
@@ -285,7 +268,7 @@ function ContentRoots({ root, children }: { root: string; children: ReactNode })
|
||||
{list.map((r) => (
|
||||
<div key={r} className={clsx(styles.rootItem, styles.contentRoot)}>
|
||||
<Icon name="module" size={14} />
|
||||
<span className={styles.rootPath} {...tooltipAttrs(r, undefined, true)}>
|
||||
<span className={styles.rootPath} title={r}>
|
||||
{r}
|
||||
</span>
|
||||
<IconButton
|
||||
@@ -393,7 +376,7 @@ function ProjectSection() {
|
||||
const picked = await choosePath({
|
||||
directory: true,
|
||||
title: "Select Compiler Output Directory",
|
||||
defaultPath: browseDefault(root, compilerOutput),
|
||||
defaultPath: compilerOutput || root || undefined,
|
||||
});
|
||||
if (picked) setCompilerOutput(root && inside(root, picked) ? relativePath(root, picked) : picked);
|
||||
}}
|
||||
@@ -433,7 +416,7 @@ function ModuleSourcesTab({ moduleKey }: { moduleKey: string }) {
|
||||
const [children, setChildren] = useState<Map<string, DirNode[]>>(new Map());
|
||||
const moduleRoot = root ? (moduleKey === "." ? root : `${root}/${moduleKey}`) : null;
|
||||
const [expanded, setExpanded] = useState<Set<string>>(() => new Set(moduleRoot ? [moduleRoot] : []));
|
||||
const [selected, setSelected] = useState<Set<string>>(() => new Set());
|
||||
const [selected, setSelected] = useState<DirNode | null>(null);
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
|
||||
@@ -495,16 +478,19 @@ function ModuleSourcesTab({ moduleKey }: { moduleKey: string }) {
|
||||
};
|
||||
}, [root, ps.contentRoots, moduleRoot, moduleKey]);
|
||||
|
||||
if (!root || !rootNode)
|
||||
if (!rootNode)
|
||||
return (
|
||||
<div className={styles.note}>
|
||||
<T>Open a project to configure its folders.</T>
|
||||
</div>
|
||||
);
|
||||
|
||||
const markable = [...selected]
|
||||
.filter((path) => inside(rootNode.path, path))
|
||||
.map((path) => (path === root ? "" : relativePath(root, path)));
|
||||
const markable = selected?.rel ?? null;
|
||||
const role = markable !== null ? rootRole(roots, markable) : null;
|
||||
const mark = (r: FolderRole) => {
|
||||
if (markable === null) return;
|
||||
setPs(markFolder(ps, markable, role === r ? null : r, detected));
|
||||
};
|
||||
const moduleDetected =
|
||||
moduleKey === "."
|
||||
? detected
|
||||
@@ -527,7 +513,7 @@ function ModuleSourcesTab({ moduleKey }: { moduleKey: string }) {
|
||||
const shown = x.path || name || ".";
|
||||
return (
|
||||
<div key={x.path} className={styles.rootItem}>
|
||||
<span className={styles.rootPath} {...tooltipAttrs(x.path || root || undefined, undefined, true)}>
|
||||
<span className={styles.rootPath} title={x.path || root || undefined}>
|
||||
{shown}
|
||||
{x.detectedFrom && <span className={styles.rootHint}> {tx`detected from ${x.detectedFrom}`}</span>}
|
||||
</span>
|
||||
@@ -558,25 +544,19 @@ function ModuleSourcesTab({ moduleKey }: { moduleKey: string }) {
|
||||
<span>
|
||||
<T>Mark as:</T>
|
||||
</span>
|
||||
{ROLES.map((r) => {
|
||||
const folders = r.role === "excluded" ? markable.filter(Boolean) : markable;
|
||||
const marked = folders.length > 0 && folders.every((path) => rootRole(roots, path) === r.role);
|
||||
return (
|
||||
<button
|
||||
key={r.role}
|
||||
type="button"
|
||||
className={styles.markButton}
|
||||
aria-pressed={marked}
|
||||
disabled={folders.length === 0}
|
||||
onClick={() =>
|
||||
setPs(folders.reduce((next, path) => markFolder(next, path, marked ? null : r.role, detected), ps))
|
||||
}
|
||||
>
|
||||
<Icon name={folderIconName(r.kind)} size={14} />
|
||||
{tx(r.label)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{ROLES.map((r) => (
|
||||
<button
|
||||
key={r.role}
|
||||
type="button"
|
||||
className={styles.markButton}
|
||||
aria-pressed={role === r.role}
|
||||
disabled={markable === null || (!markable && r.role === "excluded")}
|
||||
onClick={() => mark(r.role)}
|
||||
>
|
||||
<Icon name={folderIconName(r.kind)} size={14} />
|
||||
{tx(r.label)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.treeScroll}>
|
||||
<Tree<DirNode>
|
||||
@@ -589,9 +569,9 @@ function ModuleSourcesTab({ moduleKey }: { moduleKey: string }) {
|
||||
loadChildren={load}
|
||||
expanded={expanded}
|
||||
onExpandedChange={(set) => setExpanded(set)}
|
||||
horizontalScroll
|
||||
selected={selected}
|
||||
onSelectionChange={setSelected}
|
||||
multiSelect={false}
|
||||
selected={selected ? new Set([selected.path]) : new Set()}
|
||||
onSelectionChange={(_s, lead) => setSelected(lead)}
|
||||
getIcon={(n) => {
|
||||
if (n.rel === null) return n.contentRoot ? "module" : folderIconName("plain");
|
||||
const r = rootRole(roots, n.rel);
|
||||
@@ -723,7 +703,7 @@ function ProjectDependencies() {
|
||||
onChange={(checked) => toggle(c.path, checked)}
|
||||
aria-label={tx`The project depends on ${c.name}`}
|
||||
/>
|
||||
<span className={styles.rootPath} {...tooltipAttrs(c.path, undefined, true)}>
|
||||
<span className={styles.rootPath} title={c.path}>
|
||||
{tildify(c.path)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -815,7 +795,7 @@ function MemberDependencies({ members }: { members: readonly string[] }) {
|
||||
onChange={(checked) => toggle(c.path, checked)}
|
||||
aria-label={tx`The root depends on ${c.name}`}
|
||||
/>
|
||||
<span className={styles.rootPath} {...tooltipAttrs(c.path, undefined, true)}>
|
||||
<span className={styles.rootPath} title={c.path}>
|
||||
{tildify(c.path)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -841,14 +821,7 @@ function ModulesSection() {
|
||||
"projectStructure.modules",
|
||||
);
|
||||
const [selectedModule, setSelectedModule] = useState<string>(".");
|
||||
const [tabChoice, setTabChoice] = useState<{ tab: ModuleTab; query: string }>({ tab: "sources", query: "" });
|
||||
const query = useSearchQuery();
|
||||
const terms = queryTerms(query);
|
||||
const matchingTabs = (["sources", "paths"] as const).filter((tab) =>
|
||||
matchesTerms(["Modules", ...MODULE_SEARCH_LABELS[tab]], terms),
|
||||
);
|
||||
const [matchingTab, otherTab] = matchingTabs;
|
||||
const subTab = matchingTab && !otherTab && tabChoice.query !== query ? matchingTab : tabChoice.tab;
|
||||
const [subTab, setSubTab] = useState<"sources" | "paths">("sources");
|
||||
const [moduleError, setModuleError] = useState(false);
|
||||
const outId = useId();
|
||||
const testOutId = useId();
|
||||
@@ -935,7 +908,6 @@ function ModulesSection() {
|
||||
};
|
||||
|
||||
const activeMod = modules.find((m) => m.key === activeKey) ?? modules[0];
|
||||
const customTestOutputSupported = activeKey === "." && activeMod?.buildTool === "custom";
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
@@ -1003,7 +975,7 @@ function ModulesSection() {
|
||||
role="tab"
|
||||
className={styles.sectionTab}
|
||||
aria-selected={subTab === "sources"}
|
||||
onClick={() => setTabChoice({ tab: "sources", query })}
|
||||
onClick={() => setSubTab("sources")}
|
||||
>
|
||||
<T>Sources</T>
|
||||
</button>
|
||||
@@ -1012,7 +984,7 @@ function ModulesSection() {
|
||||
role="tab"
|
||||
className={styles.sectionTab}
|
||||
aria-selected={subTab === "paths"}
|
||||
onClick={() => setTabChoice({ tab: "paths", query })}
|
||||
onClick={() => setSubTab("paths")}
|
||||
>
|
||||
<T>Paths</T>
|
||||
</button>
|
||||
@@ -1078,7 +1050,7 @@ function ModulesSection() {
|
||||
const picked = await choosePath({
|
||||
directory: true,
|
||||
title: "Select Compiler Output Directory",
|
||||
defaultPath: browseDefault(root, currentModuleCfg.compilerOutput),
|
||||
defaultPath: currentModuleCfg.compilerOutput || root || undefined,
|
||||
});
|
||||
if (picked)
|
||||
updateModuleCfg({
|
||||
@@ -1091,24 +1063,20 @@ function ModulesSection() {
|
||||
<Row
|
||||
label="Test output path"
|
||||
htmlFor={testOutId}
|
||||
hint={
|
||||
customTestOutputSupported
|
||||
? "Directory for test classes when not managed by Maven or Gradle."
|
||||
: "Custom test output paths are not supported yet. Maven and Gradle manage their own test output."
|
||||
}
|
||||
hint="Custom test output paths are not supported yet. Maven and Gradle manage their own test output."
|
||||
>
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={testOutId}
|
||||
mono
|
||||
className={styles.pathInput}
|
||||
disabled={!customTestOutputSupported}
|
||||
disabled
|
||||
value={currentModuleCfg.testCompilerOutput}
|
||||
placeholder="target/test-classes"
|
||||
onChange={(e) => updateModuleCfg({ testCompilerOutput: e.target.value })}
|
||||
/>
|
||||
<IconButton
|
||||
disabled={!customTestOutputSupported}
|
||||
disabled
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
@@ -1116,7 +1084,7 @@ function ModulesSection() {
|
||||
const picked = await choosePath({
|
||||
directory: true,
|
||||
title: "Select Test Output Directory",
|
||||
defaultPath: browseDefault(root, currentModuleCfg.testCompilerOutput),
|
||||
defaultPath: currentModuleCfg.testCompilerOutput || root || undefined,
|
||||
});
|
||||
if (picked)
|
||||
updateModuleCfg({
|
||||
@@ -2101,108 +2069,29 @@ function SdksSection() {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Exported Pages
|
||||
|
||||
interface StructureNavItem {
|
||||
id: ProjectStructureSection;
|
||||
label: string;
|
||||
icon: IconName;
|
||||
searchLabels: readonly string[];
|
||||
}
|
||||
|
||||
const NAV_GROUPS: Array<{
|
||||
title: string;
|
||||
items: StructureNavItem[];
|
||||
items: Array<{ id: ProjectStructureSectionId; label: string; icon: IconName }>;
|
||||
}> = [
|
||||
{
|
||||
title: "Project Settings",
|
||||
items: [
|
||||
{
|
||||
id: "project",
|
||||
label: "Project",
|
||||
icon: "folder",
|
||||
searchLabels: [
|
||||
"Project name",
|
||||
"Project SDK",
|
||||
"SDK",
|
||||
"Language level",
|
||||
"Compiler output",
|
||||
"Language Server",
|
||||
"JDK",
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "modules",
|
||||
label: "Modules",
|
||||
icon: "module",
|
||||
searchLabels: [
|
||||
...MODULE_SEARCH_LABELS.sources,
|
||||
...MODULE_SEARCH_LABELS.paths,
|
||||
"Import Module from Existing Sources…",
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "dependencies",
|
||||
label: "Dependencies",
|
||||
icon: "build-dependencies",
|
||||
searchLabels: ["Project Dependencies", "Add Project…"],
|
||||
},
|
||||
{
|
||||
id: "libraries",
|
||||
label: "Libraries",
|
||||
icon: "folder-library",
|
||||
searchLabels: ["Library Details", "Resolved Build & SDK Libraries", "Classes", "Sources", "Scope", "JAR"],
|
||||
},
|
||||
{
|
||||
id: "facets",
|
||||
label: "Facets",
|
||||
icon: "file-config",
|
||||
searchLabels: [
|
||||
"Framework Facets",
|
||||
"Framework",
|
||||
"Web",
|
||||
"Spring",
|
||||
"JPA",
|
||||
"Deployment descriptor",
|
||||
"Web resource directory",
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "artifacts",
|
||||
label: "Artifacts",
|
||||
icon: "file-archive",
|
||||
searchLabels: [
|
||||
"Packaging Artifacts",
|
||||
"JAR",
|
||||
"WAR",
|
||||
"WAR Exploded",
|
||||
"Output directory",
|
||||
"Main class",
|
||||
"Included libraries",
|
||||
],
|
||||
},
|
||||
{ id: "project", label: "Project", icon: "folder" },
|
||||
{ id: "modules", label: "Modules", icon: "module" },
|
||||
{ id: "dependencies", label: "Dependencies", icon: "build-dependencies" },
|
||||
{ id: "libraries", label: "Libraries", icon: "folder-library" },
|
||||
{ id: "facets", label: "Facets", icon: "file-config" },
|
||||
{ id: "artifacts", label: "Artifacts", icon: "file-archive" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Platform Settings",
|
||||
items: [
|
||||
{
|
||||
id: "sdks",
|
||||
label: "SDKs",
|
||||
icon: "settings",
|
||||
searchLabels: ["JDK", "SDK home path", "Use as Project SDK", "Download JDK…", "Detect again"],
|
||||
},
|
||||
],
|
||||
items: [{ id: "sdks", label: "SDKs", icon: "settings" }],
|
||||
},
|
||||
];
|
||||
|
||||
const NAV_ITEMS = NAV_GROUPS.flatMap((g) => g.items);
|
||||
|
||||
function matchingStructureSections(query: string): StructureNavItem[] {
|
||||
const terms = queryTerms(query);
|
||||
return terms.length
|
||||
? NAV_ITEMS.filter(({ label, searchLabels }) => matchesTerms([label, ...searchLabels], terms))
|
||||
: NAV_ITEMS;
|
||||
}
|
||||
|
||||
export function ProjectStructureDialog() {
|
||||
const open = useSettingsDialog((s) => s.projectStructureOpen);
|
||||
if (!open) return null;
|
||||
@@ -2223,33 +2112,17 @@ function ProjectStructureStatus() {
|
||||
}
|
||||
|
||||
function ProjectStructureDialogInner() {
|
||||
const {
|
||||
projectStructureSection: section,
|
||||
projectStructureQuery: query,
|
||||
staged,
|
||||
base,
|
||||
globalBase,
|
||||
saving,
|
||||
} = useSettingsDialog();
|
||||
const section = useSettingsDialog((s) => s.projectStructureSection);
|
||||
const { staged, base, globalBase, saving } = useSettingsDialog();
|
||||
const hasProject = useProject((s) => !!s.project);
|
||||
const scope = hasProject ? "project" : "global";
|
||||
const pageId = "projectStructure";
|
||||
const ctx = useMemo(() => ({ pageId, scope, searchQuery: query }) as const, [scope, query]);
|
||||
const ctx = useMemo(() => ({ pageId, scope }) as const, [scope]);
|
||||
const form = useSettingsFormFor(pageId, scope);
|
||||
const pending = useMemo(() => pendingChanges({ base, globalBase, staged }).length > 0, [base, globalBase, staged]);
|
||||
|
||||
const activeGroup = NAV_GROUPS.find((g) => g.items.some((i) => i.id === section)) ?? NAV_GROUPS[0]!;
|
||||
const activeItem = activeGroup.items.find((i) => i.id === section) ?? activeGroup.items[0]!;
|
||||
const visible = matchingStructureSections(query);
|
||||
const visibleIds = new Set(visible.map((item) => item.id));
|
||||
|
||||
const onQuery = (value: string) => {
|
||||
const next = matchingStructureSections(value);
|
||||
const title = value.trim().toLowerCase();
|
||||
const named = next.find((item) => [item.label, tx(item.label)].some((label) => label.toLowerCase() === title));
|
||||
const selected = named ?? next.find((item) => item.id === section) ?? next[0];
|
||||
useSettingsDialog.setState({ projectStructureQuery: value, projectStructureSection: selected?.id ?? section });
|
||||
};
|
||||
|
||||
const ok = async () => {
|
||||
if (await applySettings()) closeProjectStructure();
|
||||
@@ -2262,22 +2135,12 @@ function ProjectStructureDialogInner() {
|
||||
];
|
||||
|
||||
const onNavKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Escape" && query) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onQuery("");
|
||||
return;
|
||||
}
|
||||
if ((e.key !== "ArrowDown" && e.key !== "ArrowUp") || e.altKey || e.metaKey || e.ctrlKey) return;
|
||||
if (!visible.length) return;
|
||||
e.preventDefault();
|
||||
const idx = visible.findIndex((item) => item.id === section);
|
||||
const nextIdx = e.key === "ArrowDown" ? Math.min(visible.length - 1, idx + 1) : Math.max(0, idx - 1);
|
||||
const next = visible[nextIdx]!;
|
||||
selectProjectStructureSection(next.id);
|
||||
if (e.target instanceof HTMLElement && e.target.closest("[data-section]")) {
|
||||
e.currentTarget.querySelector<HTMLButtonElement>("button[data-section='" + next.id + "']")?.focus();
|
||||
}
|
||||
const idx = NAV_ITEMS.findIndex((t) => t.id === section);
|
||||
const nextIdx = e.key === "ArrowDown" ? Math.min(NAV_ITEMS.length - 1, idx + 1) : Math.max(0, idx - 1);
|
||||
const next = NAV_ITEMS[nextIdx];
|
||||
if (next) selectProjectStructureSection(next.id);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -2307,45 +2170,27 @@ function ProjectStructureDialogInner() {
|
||||
aria-label={tx("Project Structure sections")}
|
||||
onKeyDown={onNavKeyDown}
|
||||
>
|
||||
<SearchField
|
||||
data-autofocus
|
||||
className={styles.psNavSearch}
|
||||
aria-label="Search settings"
|
||||
value={query}
|
||||
onChange={onQuery}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.ctrlKey && !e.metaKey) e.preventDefault();
|
||||
}}
|
||||
/>
|
||||
{visible.length === 0 && (
|
||||
<div className={styles.empty} role="status">
|
||||
<T>No matches</T>
|
||||
</div>
|
||||
)}
|
||||
{NAV_GROUPS.map((group) => {
|
||||
const items = group.items.filter((item) => visibleIds.has(item.id));
|
||||
if (!items.length) return null;
|
||||
return (
|
||||
<div key={group.title} className={styles.psNavGroup}>
|
||||
<div className={styles.psNavGroupHeader}>
|
||||
<T>{group.title}</T>
|
||||
</div>
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={clsx(styles.psNavItem, section === item.id && styles.psNavItemActive)}
|
||||
data-section={item.id}
|
||||
aria-current={section === item.id ? "page" : undefined}
|
||||
onClick={() => selectProjectStructureSection(item.id)}
|
||||
>
|
||||
<Icon name={item.icon} size={14} />
|
||||
<SearchLabel text={item.label} />
|
||||
</button>
|
||||
))}
|
||||
{NAV_GROUPS.map((group) => (
|
||||
<div key={group.title} className={styles.psNavGroup}>
|
||||
<div className={styles.psNavGroupHeader}>
|
||||
<T>{group.title}</T>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{group.items.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={clsx(styles.psNavItem, section === item.id && styles.psNavItemActive)}
|
||||
aria-current={section === item.id ? "page" : undefined}
|
||||
onClick={() => selectProjectStructureSection(item.id)}
|
||||
>
|
||||
<Icon name={item.icon} size={14} />
|
||||
<span>
|
||||
<T>{item.label}</T>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Project Structure sections")} />
|
||||
|
||||
@@ -430,10 +430,6 @@
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.roots .rootPath {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.note {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
@@ -762,10 +758,6 @@
|
||||
padding: 8px 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.psNavSearch {
|
||||
flex: none;
|
||||
margin: 0 var(--space-2) var(--space-2);
|
||||
}
|
||||
.psNavGroup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -58,7 +58,6 @@ export interface SettingsDialogState {
|
||||
open: boolean;
|
||||
projectStructureOpen: boolean;
|
||||
projectStructureSection: ProjectStructureSection;
|
||||
projectStructureQuery: string;
|
||||
/**
|
||||
* Project-relative path (`/`-separated, `""` for the project folder) Modules should select
|
||||
* the module of, set by Open Module Settings; null keeps the page's own selection.
|
||||
@@ -101,7 +100,6 @@ export const useSettingsDialog = create<SettingsDialogState>(() => ({
|
||||
open: false,
|
||||
projectStructureOpen: false,
|
||||
projectStructureSection: "project",
|
||||
projectStructureQuery: "",
|
||||
projectStructureModule: null,
|
||||
pageId: DEFAULT_PAGE,
|
||||
focus: null,
|
||||
@@ -158,12 +156,7 @@ export function openSettings(pageId?: string, opts: { newProjects?: boolean; glo
|
||||
|
||||
export function openProjectStructure(section?: string, module: string | null = null) {
|
||||
if (useSettingsDialog.getState().projectStructureOpen) {
|
||||
if (section) {
|
||||
useSettingsDialog.setState({
|
||||
projectStructureSection: parseProjectStructureSection(section),
|
||||
projectStructureQuery: "",
|
||||
});
|
||||
}
|
||||
if (section) selectProjectStructureSection(parseProjectStructureSection(section));
|
||||
if (module !== null) useSettingsDialog.setState({ projectStructureModule: module });
|
||||
return;
|
||||
}
|
||||
@@ -172,7 +165,6 @@ export function openProjectStructure(section?: string, module: string | null = n
|
||||
open: false,
|
||||
projectStructureOpen: true,
|
||||
projectStructureSection: parseProjectStructureSection(section),
|
||||
projectStructureQuery: "",
|
||||
projectStructureModule: module,
|
||||
base,
|
||||
globalBase: base,
|
||||
@@ -207,7 +199,6 @@ export function openModuleSettings(path?: string) {
|
||||
export function closeProjectStructure() {
|
||||
useSettingsDialog.setState({
|
||||
projectStructureOpen: false,
|
||||
projectStructureQuery: "",
|
||||
projectStructureModule: null,
|
||||
staged: {},
|
||||
stagedSecrets: {},
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
call: vi.fn(async (r: Promise<unknown>) => r),
|
||||
commands: { ...actual.commands, vcsLogUsers: vi.fn() },
|
||||
};
|
||||
});
|
||||
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { fetchLogUsers, knownLogUsers, resetLogUsers } from "../log/logUsers";
|
||||
|
||||
const users = vi.mocked(commands.vcsLogUsers);
|
||||
|
||||
afterEach(() => {
|
||||
resetLogUsers();
|
||||
users.mockReset();
|
||||
});
|
||||
|
||||
describe("Log User filter authors", () => {
|
||||
it("knows nothing before the first list and reuses a running fetch", async () => {
|
||||
let resolve!: (v: string[]) => void;
|
||||
users.mockReturnValue(new Promise((r) => (resolve = r)) as never);
|
||||
expect(knownLogUsers("/repo")).toEqual([]);
|
||||
const a = fetchLogUsers("/repo");
|
||||
const b = fetchLogUsers("/repo");
|
||||
expect(users).toHaveBeenCalledTimes(1);
|
||||
resolve(["Ann <a@x>"]);
|
||||
expect(await a).toEqual(["Ann <a@x>"]);
|
||||
expect(await b).toEqual(["Ann <a@x>"]);
|
||||
expect(knownLogUsers("/repo")).toEqual(["Ann <a@x>"]);
|
||||
});
|
||||
|
||||
it("answers from the known list while it is recent and fetches again later", async () => {
|
||||
users.mockResolvedValueOnce(["Ann <a@x>"] as never).mockResolvedValueOnce(["Ann <a@x>", "Bob <b@x>"] as never);
|
||||
await fetchLogUsers("/repo");
|
||||
expect(await fetchLogUsers("/repo", Date.now() + 60_000)).toEqual(["Ann <a@x>"]);
|
||||
expect(users).toHaveBeenCalledTimes(1);
|
||||
expect(await fetchLogUsers("/repo", Date.now() + 10 * 60_000)).toEqual(["Ann <a@x>", "Bob <b@x>"]);
|
||||
expect(users).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("keeps the known list when a fetch fails", async () => {
|
||||
users.mockResolvedValueOnce(["Ann <a@x>"] as never).mockRejectedValueOnce(new Error("git failed") as never);
|
||||
await fetchLogUsers("/repo");
|
||||
expect(await fetchLogUsers("/repo", Date.now() + 10 * 60_000)).toEqual(["Ann <a@x>"]);
|
||||
expect(knownLogUsers("/other")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { BranchInfo, FetchReport, GhProjectAccountStatus, PushReport, RemoteOp } from "@/bindings";
|
||||
import type { BranchInfo, FetchReport, PushReport, RemoteOp } from "@/bindings";
|
||||
|
||||
let branch: Partial<BranchInfo> = {};
|
||||
/** What a pull brings in: the head moves to `c2`, with these changed files and commits. */
|
||||
@@ -10,7 +10,6 @@ let reports: Record<string, PushReport | FetchReport> = {};
|
||||
let partialReport: PushReport | null = null;
|
||||
let remoteGate: Promise<void> | null = null;
|
||||
let remoteRepos: Array<string | null> = [];
|
||||
const ghAccountStatus = vi.fn();
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
|
||||
@@ -52,7 +51,6 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
vcsDiffRevisions: async () => ({ status: "ok", data: Array.from({ length: pulled.files }, (_, i) => ({ i })) }),
|
||||
vcsLog: async () => ({ status: "ok", data: Array.from({ length: pulled.commits }, (_, i) => ({ i })) }),
|
||||
vcsFinishShelfBatch: async () => ({ status: "ok", data: null }),
|
||||
ghProjectAccountStatus: () => ghAccountStatus(),
|
||||
cancelRequest: async () => ({ status: "ok", data: null }),
|
||||
},
|
||||
};
|
||||
@@ -75,13 +73,11 @@ import {
|
||||
import { pushTargets } from "../remoteUi";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
type Note = { title: string; level: string; body?: string; actions?: Array<{ label: string; run: () => void }> };
|
||||
type Note = { title: string; level: string; body?: string };
|
||||
let notes: Note[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
notes = [];
|
||||
ghAccountStatus.mockReset();
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: null });
|
||||
provideNotificationService({ notify: (n) => void notes.push(n as Note), expire: () => {} });
|
||||
});
|
||||
|
||||
@@ -105,108 +101,6 @@ const pushTitle = async () => {
|
||||
return notes.at(-1)!.title;
|
||||
};
|
||||
|
||||
describe("GitHub HTTPS authentication failure", () => {
|
||||
const message =
|
||||
"remote: Repository not found.\nfatal: repository 'https://github.com/example/private.git/' not found";
|
||||
const multiAccount: GhProjectAccountStatus = {
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "personal", active: true },
|
||||
{ login: "work", active: false },
|
||||
],
|
||||
configuredAccount: "",
|
||||
effectiveAccount: "personal",
|
||||
suggestedAccount: "work",
|
||||
};
|
||||
|
||||
it("preserves the Git error and opens project GitHub settings without changing accounts", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
const settings = vi.fn();
|
||||
const unregister = registerActions([{ id: "file.settings", title: "Settings", run: settings }]);
|
||||
try {
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
const note = notes.at(-1)!;
|
||||
expect(note.title).toBe("Update failed");
|
||||
expect(note.body).toContain(message);
|
||||
expect(note.body).toContain("personal may not have access");
|
||||
expect(ghAccountStatus).toHaveBeenCalledTimes(1);
|
||||
expect(settings).not.toHaveBeenCalled();
|
||||
expect(remoteRepos).toEqual(["/p"]);
|
||||
note.actions?.find((action) => action.label === "GitHub Settings")?.run();
|
||||
await vi.waitFor(() => expect(settings).toHaveBeenCalledWith(expect.objectContaining({ arg: "vcs.github" })));
|
||||
} finally {
|
||||
unregister();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
"fatal: repository 'https://gitlab.com/example/private.git/' not found",
|
||||
"fatal: repository 'https://github.com.evil.example/private.git/' not found",
|
||||
"fatal: repository '[email protected]:example/private.git' not found",
|
||||
"remote: Repository not found.",
|
||||
"fatal: unable to access 'https://github.com/example/private.git/': Could not resolve host: github.com",
|
||||
])("does not check gh for unrelated errors: %s", async (message) => {
|
||||
failure = { kind: "invalid", message };
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(ghAccountStatus).not.toHaveBeenCalled();
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message });
|
||||
});
|
||||
|
||||
it("keeps the original failure when only one account is signed in", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { ...multiAccount, accounts: multiAccount.accounts.slice(0, 1) },
|
||||
});
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined });
|
||||
});
|
||||
|
||||
it("keeps the original failure when account detection is unavailable", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockRejectedValue(new Error("gh unavailable"));
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined });
|
||||
});
|
||||
|
||||
it("offers the same guidance for push failures without retrying", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
expect(
|
||||
await pushTargets([
|
||||
{
|
||||
repo: "/p",
|
||||
op: {
|
||||
op: "pushSelected",
|
||||
selection: { branch: "main", revision: null, remote: "origin", target: "main" },
|
||||
force_with_lease: false,
|
||||
set_upstream: false,
|
||||
tags: null,
|
||||
no_verify: false,
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({
|
||||
title: "Push failed",
|
||||
body: expect.stringContaining("personal may not have access"),
|
||||
actions: [expect.objectContaining({ label: "GitHub Settings" })],
|
||||
});
|
||||
expect(remoteRepos).toEqual(["/p"]);
|
||||
});
|
||||
|
||||
it("offers the same guidance for fetch authentication failures", async () => {
|
||||
failure = {
|
||||
kind: "invalid",
|
||||
message: "fatal: Authentication failed for 'https://github.com/example/private.git/'",
|
||||
};
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
expect(await runRemote({ op: "fetch" }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)?.actions?.map(({ label }) => label)).toEqual(["Show Git Console", "GitHub Settings"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetch result notification", () => {
|
||||
it("keeps successful remotes and pruned refs visible when other remotes fail", async () => {
|
||||
const showConsole = vi.fn();
|
||||
|
||||
@@ -9,7 +9,6 @@ const mocks = vi.hoisted(() => ({
|
||||
checkout: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
openWorktree: vi.fn(),
|
||||
ghAccountStatus: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/actions", async (original) => ({
|
||||
...(await original<typeof import("@/platform/actions")>()),
|
||||
@@ -24,15 +23,7 @@ vi.mock("../ops", async (original) => ({
|
||||
vi.mock("../openWorktree", () => ({ openWorktree: mocks.openWorktree }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsBranchInfo: mocks.head,
|
||||
vcsCheckout: mocks.checkout,
|
||||
ghProjectAccountStatus: mocks.ghAccountStatus,
|
||||
},
|
||||
};
|
||||
return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head, vcsCheckout: mocks.checkout } };
|
||||
});
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
@@ -132,28 +123,6 @@ describe("Update Selected", () => {
|
||||
expect(mocks.openWorktree).toHaveBeenCalledWith("/worktrees/topic", true);
|
||||
});
|
||||
|
||||
it("offers GitHub account settings for an unchecked branch's HTTPS failure", async () => {
|
||||
mocks.update.mockResolvedValue([
|
||||
result("topic", "failed", "/p", "fatal: repository 'https://github.com/acme/private.git/' not found"),
|
||||
]);
|
||||
mocks.ghAccountStatus.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "personal", active: true },
|
||||
{ login: "work", active: false },
|
||||
],
|
||||
effectiveAccount: "personal",
|
||||
},
|
||||
});
|
||||
await updateBranches([target("topic", "/p")]);
|
||||
const [action] = mocks.notify.mock.lastCall![0].actions;
|
||||
expect(action.label).toBe("GitHub Settings");
|
||||
action.run();
|
||||
expect(mocks.execute).toHaveBeenCalledWith("file.settings", "vcs.github");
|
||||
});
|
||||
|
||||
it("offers Update Selected in the context menu of a multi-selection", () => {
|
||||
const selected = [target("a", "/p"), target("b", "/p")];
|
||||
const items = branchMenu(selected[0]!.branch, "main", () => {}, { selected });
|
||||
|
||||
@@ -17,7 +17,6 @@ import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { openWorktree } from "./openWorktree";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import { activeRepository } from "./activeRepository";
|
||||
import { ask, confirmChecked } from "@/workbench/messages";
|
||||
import { branchNamePrefixes, isFavoriteBranch, isProtectedBranch, pushRecent, shortRemoteName } from "./branches";
|
||||
@@ -1447,11 +1446,6 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) {
|
||||
const results = await runBranchUpdates(new Map([...byRepo].map(([repo, names]) => [repo, [...names]])));
|
||||
if (!results || useProject.getState().project !== project) return;
|
||||
const { lines, ...summary } = branchUpdateSummary(results, heads.length > 1);
|
||||
const help = await githubHttpsFailureHelp(
|
||||
results.flatMap((r) => (r.status === "failed" && r.message ? [r.message] : [])),
|
||||
);
|
||||
if (useProject.getState().project !== project) return;
|
||||
if (help) lines.push(help.message);
|
||||
const body = createElement(Fragment, null, ...lines.map((line) => createElement("div", { key: line }, line)));
|
||||
const worktrees = [...new Set(results.flatMap((r) => (r.status === "failed" && r.worktree ? [r.worktree] : [])))];
|
||||
notifications().notify({
|
||||
@@ -1460,13 +1454,10 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) {
|
||||
userInitiated: true,
|
||||
...summary,
|
||||
body,
|
||||
actions: [
|
||||
...worktrees.map((path) => {
|
||||
const name = repoName(path);
|
||||
return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) };
|
||||
}),
|
||||
...(help ? [help.action] : []),
|
||||
],
|
||||
actions: worktrees.map((path) => {
|
||||
const name = repoName(path);
|
||||
return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) };
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (current.length && useProject.getState().project === project) await runRemoteRound(current);
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
/** GitHub deliberately uses "Repository not found" for inaccessible private repositories.
|
||||
* Require Git's actual failing HTTPS URL: the same error from another host or SSH is unrelated
|
||||
* to gh's HTTPS credential helper. Never infer a credential mismatch from the error alone.
|
||||
*/
|
||||
function isGithubHttpsFailure(message: string): boolean {
|
||||
return /^fatal: (?:repository 'https:\/\/github\.com\/[^'\r\n]+' not found|Authentication failed for 'https:\/\/github\.com\/[^'\r\n]+')\.?(?:\r?$)/im.test(
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
/** Diagnose only explicit failed remote operations. The existing project account settings
|
||||
* handle selection; do not switch gh's global account, edit remotes, or retry a Git write.
|
||||
*/
|
||||
export async function githubHttpsFailureHelp(messages: readonly string[]) {
|
||||
if (!messages.some(isGithubHttpsFailure)) return null;
|
||||
const project = useProject.getState().project;
|
||||
const status = await call(commands.ghProjectAccountStatus()).catch(() => null);
|
||||
if (!status?.ghInstalled || status.accounts.length < 2 || useProject.getState().project !== project) return null;
|
||||
return {
|
||||
message: status.effectiveAccount
|
||||
? tx`GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, ${status.effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.`
|
||||
: tx(
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.",
|
||||
),
|
||||
action: {
|
||||
label: "GitHub Settings",
|
||||
run: () => {
|
||||
if (useProject.getState().project === project) void executeAction("file.settings", "vcs.github");
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { getAction, isActionEnabled } from "@/platform/actions";
|
||||
import { useContextKeys } from "@/platform/context";
|
||||
import { isMacHost } from "@/platform/keymap";
|
||||
@@ -31,7 +32,6 @@ import { LogPathsEditor, chooseLogPaths } from "../PathFilterDialog";
|
||||
import { openExternalLog } from "../RevisionBrowser";
|
||||
import { currentRepo, repoName, useVcs } from "../store";
|
||||
import { useDropdownMenu, useLogRepositories, useReadOnlyLog } from "./logHooks";
|
||||
import { fetchLogUsers, knownLogUsers } from "./logUsers";
|
||||
import { toggle } from "./shared";
|
||||
|
||||
// --- filters ----------------------------------------------------------------
|
||||
@@ -198,20 +198,16 @@ export function FilterBar({ fileHistory = false }: { fileHistory?: boolean }) {
|
||||
if (r) setLogBranches(r);
|
||||
};
|
||||
|
||||
const openUser = (anchor: HTMLElement) => {
|
||||
const openUser = async (anchor: HTMLElement) => {
|
||||
const roots = filters.repositories?.length
|
||||
? filters.repositories
|
||||
: repositories.length
|
||||
? repositories
|
||||
: [currentRepo()];
|
||||
// Listing every author of a large history takes seconds: open with the authors known so far
|
||||
// (loaded commits and earlier lists) and let only Select… wait for the full list.
|
||||
const fetching = Promise.all(roots.map((repo) => fetchLogUsers(repo)));
|
||||
const authorsOf = (users: readonly (readonly string[])[]) =>
|
||||
[...new Set(users.flat().concat(commits.map((c) => `${c.author} <${c.email}>`)))].sort((a, b) =>
|
||||
a.localeCompare(b),
|
||||
);
|
||||
const authors = authorsOf(roots.map((repo) => knownLogUsers(repo)));
|
||||
const users = await Promise.all(roots.map((repo) => call(commands.vcsLogUsers(repo)).catch(() => [] as string[])));
|
||||
const authors = [...new Set(users.flat().concat(commits.map((c) => `${c.author} <${c.email}>`)))].sort((a, b) =>
|
||||
a.localeCompare(b),
|
||||
);
|
||||
menuBelow(anchor, [
|
||||
...recentFilterValues("authors").map((authors) => ({
|
||||
verbatim: true,
|
||||
@@ -232,7 +228,7 @@ export function FilterBar({ fileHistory = false }: { fileHistory?: boolean }) {
|
||||
run: async () => {
|
||||
const r = await chooseMany({
|
||||
title: "Filter by User",
|
||||
options: [ME, ...authorsOf(await fetching)],
|
||||
options: [ME, ...authors],
|
||||
initial: filters.authors,
|
||||
customLabel: "Other names or emails (comma-separated):",
|
||||
});
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* Every author of a repository's history (`git log --all`) for the Log's User filter. On a large
|
||||
* history listing them takes seconds, so the filter opens with what is already known and the list
|
||||
* is fetched in the background, at most once per {@link REFRESH_MS} for each repository.
|
||||
*/
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
|
||||
const REFRESH_MS = 5 * 60_000;
|
||||
|
||||
const known = new Map<string, { users: readonly string[]; at: number }>();
|
||||
const pending = new Map<string, Promise<readonly string[]>>();
|
||||
const key = (repo: string | null) => repo ?? "";
|
||||
|
||||
/** The authors of `repo`: the running fetch, else a new one unless the known list is recent. */
|
||||
export function fetchLogUsers(repo: string | null, now = Date.now()): Promise<readonly string[]> {
|
||||
const k = key(repo);
|
||||
const running = pending.get(k);
|
||||
if (running) return running;
|
||||
const cached = known.get(k);
|
||||
if (cached && now - cached.at < REFRESH_MS) return Promise.resolve(cached.users);
|
||||
const fetch = call(commands.vcsLogUsers(repo))
|
||||
.then((users) => {
|
||||
known.set(k, { users, at: Date.now() });
|
||||
return users as readonly string[];
|
||||
})
|
||||
.catch(() => known.get(k)?.users ?? [])
|
||||
.finally(() => pending.delete(k));
|
||||
pending.set(k, fetch);
|
||||
return fetch;
|
||||
}
|
||||
|
||||
/** The authors of `repo` fetched so far, without waiting. */
|
||||
export function knownLogUsers(repo: string | null): readonly string[] {
|
||||
return known.get(key(repo))?.users ?? [];
|
||||
}
|
||||
|
||||
/** Test hook: forgets every fetched list. */
|
||||
export function resetLogUsers() {
|
||||
known.clear();
|
||||
pending.clear();
|
||||
}
|
||||
@@ -24,7 +24,6 @@ import { flushChangelists } from "./changelists";
|
||||
import { pushHistoryRepo, rememberPushTarget } from "./pushHistory";
|
||||
import { describePush, formatPushOutcomes, partialPushReport, pushedCommits, type RepoPushOutcome } from "./pushReport";
|
||||
import { cancelIncomingCheck } from "./incomingRequest";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import { beginGitWork, conflictedFiles, currentRepo, refreshNow, repoName, repoOf, useVcs } from "./store";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -552,13 +551,6 @@ export async function runRemoteRound<Op extends RemoteOp>(
|
||||
: first.op === "unshallow"
|
||||
? tx("Could not fetch full Git history")
|
||||
: `${doneTitle} failed`;
|
||||
const help = await githubHttpsFailureHelp(remaining.map(({ error }) => errorMessage(error)));
|
||||
if (cancelRequested || useProject.getState().project !== project)
|
||||
throw new IpcError({ kind: "cancelled", message: "cancelled" });
|
||||
const actions = [
|
||||
...(partial || isFetch ? [gitConsoleNotificationAction()] : []),
|
||||
...(help ? [help.action] : []),
|
||||
];
|
||||
notify({
|
||||
level: "error",
|
||||
key: "vcs.remote",
|
||||
@@ -569,9 +561,9 @@ export async function runRemoteRound<Op extends RemoteOp>(
|
||||
? tx(message)
|
||||
: message,
|
||||
)
|
||||
.concat(pruned, help ? [help.message] : [])
|
||||
.concat(pruned)
|
||||
.join("\n"),
|
||||
actions: actions.length ? actions : undefined,
|
||||
actions: partial || isFetch ? [gitConsoleNotificationAction()] : undefined,
|
||||
});
|
||||
}
|
||||
if (!reported && isUpdate(first) && updated.length) await notifyUpdated(updated, "vcs.remote.updated");
|
||||
|
||||
@@ -26,7 +26,6 @@ import { openDialog } from "./dialogs";
|
||||
import { useBranches } from "./gitMenuDialogs";
|
||||
import { saveVcsSetting } from "./settingsUi";
|
||||
import { formatTime } from "./model";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import {
|
||||
allRepos,
|
||||
errorMessage,
|
||||
@@ -1494,13 +1493,12 @@ function pushReviewActions(review: readonly PushReviewTarget[]) {
|
||||
];
|
||||
}
|
||||
|
||||
async function pushFailed(
|
||||
function pushFailed(
|
||||
failures: RemoteFailure<PushOp>[],
|
||||
total: number,
|
||||
rejected: boolean,
|
||||
pushed: readonly RepoPushOutcome[],
|
||||
): Promise<false> {
|
||||
const project = useProject.getState().project;
|
||||
): false {
|
||||
const isPartial = ({ error }: RemoteFailure<PushOp>) => !!partialPushReport(error);
|
||||
const names = (items: RemoteFailure<PushOp>[]) =>
|
||||
items.flatMap(({ target }) => (target.repo ? [repoName(target.repo)] : [])).join(", ");
|
||||
@@ -1523,11 +1521,7 @@ async function pushFailed(
|
||||
: tx(errorMessage(failures[0]!.error)),
|
||||
);
|
||||
}
|
||||
const help = await githubHttpsFailureHelp(failures.map(({ error }) => errorMessage(error)));
|
||||
if (useProject.getState().project !== project) return false;
|
||||
if (help) lines.push(help.message);
|
||||
const actions = [...(pushReviewActions(review) ?? []), ...(help ? [help.action] : [])];
|
||||
if (partiallyApplied.length) actions.push(gitConsoleNotificationAction());
|
||||
const actions = pushReviewActions(review);
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
@@ -1540,7 +1534,7 @@ async function pushFailed(
|
||||
? "Push rejected"
|
||||
: "Push failed",
|
||||
body: lines.join("\n"),
|
||||
actions: actions.length ? actions : undefined,
|
||||
actions: partiallyApplied.length ? [...(actions ?? []), gitConsoleNotificationAction()] : actions,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -4,8 +4,6 @@ import { hasFileType, wildcardMatch } from "@/platform/fileTypes";
|
||||
import type { FileProbe } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { gitRevisionOf } from "@/platform/virtualDocs";
|
||||
import { repositoryPath } from "@/features/vcs/repositoryPaths";
|
||||
|
||||
export const IMAGE_KIND = "image";
|
||||
export const BINARY_KIND = "binary";
|
||||
@@ -34,11 +32,6 @@ export function isMarkdownPath(path: string, mode: "preview" | "source" = "previ
|
||||
return hasFileType(path, ["markdown"], extensions, settings?.files, project?.root ?? null);
|
||||
}
|
||||
|
||||
export function isMarkdownRevision(uri: string): boolean {
|
||||
const revision = gitRevisionOf(uri);
|
||||
return !!revision && isMarkdownPath(repositoryPath(revision.repo, revision.path));
|
||||
}
|
||||
|
||||
/** Whether `path` gets the reStructuredText preview under Settings › File Types. */
|
||||
export function isRstPath(path: string): boolean {
|
||||
const { settings, project } = useProject.getState();
|
||||
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
imageInput,
|
||||
isImagePath,
|
||||
isMarkdownPath,
|
||||
isMarkdownRevision,
|
||||
isRstPath,
|
||||
isSvgPath,
|
||||
wantsHexView,
|
||||
@@ -166,7 +165,6 @@ export function activate(): () => void {
|
||||
id: "viewers.markdown",
|
||||
keepAlive: true,
|
||||
matches: isMarkdownPath,
|
||||
matchesVirtual: isMarkdownRevision,
|
||||
component: lazyComponent(() => import("./markdown/MarkdownEditor").then((m) => m.MarkdownEditor), {
|
||||
prefetch: true,
|
||||
}),
|
||||
|
||||
@@ -12,7 +12,6 @@ import { MAX_COUNT, findExcluded, findOpen, findScope } from "@/editor/core/cm/f
|
||||
import { fontZoom, resetConfiguredEditorsFontZoom, stepConfiguredEditorsFontZoom } from "@/editor/core/cm/prefs";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { isMarkdownRevision } from "../fileKinds";
|
||||
|
||||
export interface LiveMarkdownFind {
|
||||
search: string;
|
||||
@@ -360,8 +359,6 @@ export function registerMarkdownLiveSource(): () => void {
|
||||
id: "viewers.markdownLive",
|
||||
// The document's language: contributions are rebuilt when File Types change it.
|
||||
extensions: (ctx) =>
|
||||
(ctx.virtual ? isMarkdownRevision(ctx.path) : ctx.language === "markdown" || ctx.language === "mdx")
|
||||
? [livePlugin(ctx.path)]
|
||||
: [],
|
||||
!ctx.virtual && (ctx.language === "markdown" || ctx.language === "mdx") ? [livePlugin(ctx.path)] : [],
|
||||
});
|
||||
}
|
||||
@@ -166,7 +166,6 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
|
||||
EditorToggleShowLineNumbers: "editor.toggleLocalLineNumbers",
|
||||
EditorToggleShowGutterIcons: "editor.toggleLocalGutterIcons",
|
||||
EditorToggleShowIndentLines: "editor.toggleLocalIndentGuides",
|
||||
ToggleRenderedDocPresentationForAll: "editor.toggleRenderedDocsForAll",
|
||||
EditorToggleShowBreadcrumbs: "editor.toggleBreadcrumbs",
|
||||
EditorStickyLinesDisableForLang: "editor.disableStickyLinesForLanguage",
|
||||
ActivateProjectToolWindow: "toolwindow.project",
|
||||
|
||||
@@ -103,8 +103,7 @@ describe("IDEA keymap parity", () => {
|
||||
["editor.toggleStickySelection", [], []],
|
||||
// EditorSelectLine has no shortcut.
|
||||
["editor.selectLine", [], []],
|
||||
// ToggleRenderedDocPresentationForAll and EditorToggleShow* actions have no shortcut.
|
||||
["editor.toggleRenderedDocsForAll", [], []],
|
||||
// EditorToggleShow* actions have no shortcut.
|
||||
["editor.toggleLocalLineNumbers", [], []],
|
||||
["editor.toggleLocalWhitespaces", [], []],
|
||||
["editor.toggleLocalGutterIcons", [], []],
|
||||
|
||||
@@ -321,7 +321,6 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
// ToggleZenMode has no default.
|
||||
"view.toggleZenMode": [],
|
||||
"editor.toggleLineNumbers": [],
|
||||
"editor.toggleRenderedDocsForAll": [],
|
||||
"editor.toggleIndentGuides": [],
|
||||
"editor.toggleStickyLines": [],
|
||||
"editor.toggleWhitespaces": [],
|
||||
|
||||
@@ -315,7 +315,6 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
// ToggleZenMode has no default.
|
||||
"view.toggleZenMode": [],
|
||||
"editor.toggleLineNumbers": [],
|
||||
"editor.toggleRenderedDocsForAll": [],
|
||||
"editor.toggleIndentGuides": [],
|
||||
"editor.toggleStickyLines": [],
|
||||
"editor.toggleWhitespaces": [],
|
||||
|
||||
@@ -258,7 +258,6 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"editor.toggleLocalWhitespaces": [],
|
||||
"editor.toggleLocalGutterIcons": [],
|
||||
"editor.toggleLocalIndentGuides": [],
|
||||
"editor.toggleRenderedDocsForAll": [],
|
||||
"editor.toggleBreadcrumbs": [],
|
||||
"window.toggleFullScreen": ["Meta+Ctrl+F"],
|
||||
// Project window groups are an IntelliJ concept; VS Code has no counterpart.
|
||||
|
||||
@@ -423,24 +423,6 @@ export function normalizeFolder(path: string): string {
|
||||
.replace(/^\/+|\/+$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* A Project Structure library class entry (a jar, a folder, or a folder with a `*.jar` or recursive
|
||||
* jar glob; absolute or relative) as a `/` path relative to `root` when inside it, plus its glob.
|
||||
*/
|
||||
export function libraryClassEntry(
|
||||
entry: string,
|
||||
root: string,
|
||||
): { path: string; glob: "none" | "shallow" | "recursive" } | null {
|
||||
let s = entry.trim().replace(/\\/g, "/");
|
||||
if (!s) return null;
|
||||
let glob: "none" | "shallow" | "recursive" = "none";
|
||||
if (s.endsWith("/**/*.jar")) [s, glob] = [s.slice(0, -"/**/*.jar".length), "recursive"];
|
||||
else if (s.endsWith("/*.jar")) [s, glob] = [s.slice(0, -"/*.jar".length), "shallow"];
|
||||
const base = root.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
const path = s === base ? "" : s.startsWith(`${base}/`) ? s.slice(base.length + 1) : s;
|
||||
return { path: normalizeFolder(path), glob };
|
||||
}
|
||||
|
||||
/** A stored preview font size within IDEA's 8..72, or `null` (follow the editor font). */
|
||||
const previewSize = (v: unknown): number | null =>
|
||||
typeof v === "number" && Number.isFinite(v) ? Math.min(72, Math.max(8, Math.round(v))) : null;
|
||||
|
||||
@@ -1435,7 +1435,6 @@
|
||||
"Platform Settings": "Platform Settings",
|
||||
"Project Structure sections": "Project Structure sections",
|
||||
"Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.",
|
||||
"Directory for test classes when not managed by Maven or Gradle.": "Directory for test classes when not managed by Maven or Gradle.",
|
||||
"This project is built by Maven or Gradle: build and deploy the artifacts they define.": "This project is built by Maven or Gradle: build and deploy the artifacts they define.",
|
||||
"Add Module Overrides…": "Add Module Overrides…",
|
||||
"Import Module from Existing Sources": "Import Module from Existing Sources",
|
||||
@@ -4824,14 +4823,5 @@
|
||||
"Recent projects": "Recent projects",
|
||||
"Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.": "Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.",
|
||||
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "{imported} new, {groups} new project groups, {missing} skipped (folder missing)",
|
||||
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it",
|
||||
"Add as Library…": "Add as Library…",
|
||||
"Open Library Settings": "Open Library Settings",
|
||||
"Create Library": "Create Library",
|
||||
"Library name": "Library name",
|
||||
"Library name cannot be empty.": "Library name cannot be empty.",
|
||||
"A library with this name already exists.": "A library with this name already exists.",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.",
|
||||
"GitHub Settings": "GitHub Settings"
|
||||
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it"
|
||||
}
|
||||
@@ -6226,11 +6226,5 @@
|
||||
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "La asistencia de código entre archivos para {container} necesita una configuración de Build Server Protocol. Instala xcode-build-server (brew install xcode-build-server) para generarla.",
|
||||
"Check Again": "Comprobar de nuevo",
|
||||
"Running {tool}…": "Ejecutando {tool}…",
|
||||
"Open Module Settings": "Abrir configuración del módulo",
|
||||
"Add as Library…": "Añadir como biblioteca…",
|
||||
"Open Library Settings": "Abrir configuración de biblioteca",
|
||||
"Create Library": "Crear biblioteca",
|
||||
"Library name": "Nombre de biblioteca",
|
||||
"Library name cannot be empty.": "El nombre de la biblioteca no puede estar vacío.",
|
||||
"A library with this name already exists.": "Ya existe una biblioteca con este nombre."
|
||||
"Open Module Settings": "Abrir configuración del módulo"
|
||||
}
|
||||
@@ -5871,11 +5871,5 @@
|
||||
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "L’assistance au code entre fichiers pour {container} nécessite une configuration Build Server Protocol. Installez xcode-build-server (brew install xcode-build-server) pour en générer une.",
|
||||
"Check Again": "Vérifier à nouveau",
|
||||
"Running {tool}…": "Exécution de {tool}…",
|
||||
"Open Module Settings": "Ouvrir les paramètres du module",
|
||||
"Add as Library…": "Ajouter en tant que bibliothèque…",
|
||||
"Open Library Settings": "Ouvrir les paramètres de la bibliothèque",
|
||||
"Create Library": "Créer une bibliothèque",
|
||||
"Library name": "Nom de la bibliothèque",
|
||||
"Library name cannot be empty.": "Le nom de la bibliothèque ne peut pas être vide.",
|
||||
"A library with this name already exists.": "Une bibliothèque portant ce nom existe déjà."
|
||||
"Open Module Settings": "Ouvrir les paramètres du module"
|
||||
}
|
||||
@@ -6336,11 +6336,5 @@
|
||||
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container}의 파일 간 코드 인사이트에는 Build Server Protocol 설정이 필요합니다. xcode-build-server(brew install xcode-build-server)를 설치하면 생성할 수 있습니다.",
|
||||
"Check Again": "다시 확인",
|
||||
"Running {tool}…": "{tool} 실행 중…",
|
||||
"Open Module Settings": "모듈 설정 열기",
|
||||
"Add as Library…": "라이브러리로 추가…",
|
||||
"Open Library Settings": "라이브러리 설정 열기",
|
||||
"Create Library": "라이브러리 만들기",
|
||||
"Library name": "라이브러리 이름",
|
||||
"Library name cannot be empty.": "라이브러리 이름은 비워 둘 수 없습니다.",
|
||||
"A library with this name already exists.": "이 이름의 라이브러리가 이미 존재합니다."
|
||||
"Open Module Settings": "모듈 설정 열기"
|
||||
}
|
||||
@@ -6034,11 +6034,5 @@
|
||||
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "Analiza kodu między plikami dla {container} wymaga konfiguracji Build Server Protocol. Zainstaluj xcode-build-server (brew install xcode-build-server), aby ją wygenerować.",
|
||||
"Check Again": "Sprawdź ponownie",
|
||||
"Running {tool}…": "Uruchamianie {tool}…",
|
||||
"Open Module Settings": "Otwórz ustawienia modułu",
|
||||
"Add as Library…": "Dodaj jako bibliotekę…",
|
||||
"Open Library Settings": "Otwórz ustawienia biblioteki",
|
||||
"Create Library": "Utwórz bibliotekę",
|
||||
"Library name": "Nazwa biblioteki",
|
||||
"Library name cannot be empty.": "Nazwa biblioteki nie może być pusta.",
|
||||
"A library with this name already exists.": "Biblioteka o tej nazwie już istnieje."
|
||||
"Open Module Settings": "Otwórz ustawienia modułu"
|
||||
}
|
||||
@@ -6049,11 +6049,5 @@
|
||||
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "A inteligência de código entre arquivos para {container} precisa de uma configuração do Build Server Protocol. Instale o xcode-build-server (brew install xcode-build-server) para gerá-la.",
|
||||
"Check Again": "Verificar novamente",
|
||||
"Running {tool}…": "Executando {tool}…",
|
||||
"Open Module Settings": "Abrir configurações do módulo",
|
||||
"Add as Library…": "Adicionar como biblioteca…",
|
||||
"Open Library Settings": "Abrir configurações da biblioteca",
|
||||
"Create Library": "Criar biblioteca",
|
||||
"Library name": "Nome da biblioteca",
|
||||
"Library name cannot be empty.": "O nome da biblioteca não pode estar vazio.",
|
||||
"A library with this name already exists.": "Já existe uma biblioteca com este nome."
|
||||
"Open Module Settings": "Abrir configurações do módulo"
|
||||
}
|
||||
@@ -10270,11 +10270,5 @@
|
||||
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "Для межфайловой поддержки кода в {container} нужна конфигурация Build Server Protocol. Установите xcode-build-server (brew install xcode-build-server), чтобы создать её.",
|
||||
"Check Again": "Проверить снова",
|
||||
"Running {tool}…": "Выполняется {tool}…",
|
||||
"Open Module Settings": "Открыть настройки модуля",
|
||||
"Add as Library…": "Добавить как библиотеку…",
|
||||
"Open Library Settings": "Открыть настройки библиотеки",
|
||||
"Create Library": "Создать библиотеку",
|
||||
"Library name": "Имя библиотеки",
|
||||
"Library name cannot be empty.": "Имя библиотеки не может быть пустым.",
|
||||
"A library with this name already exists.": "Библиотека с таким именем уже существует."
|
||||
"Open Module Settings": "Открыть настройки модуля"
|
||||
}
|
||||
@@ -8891,11 +8891,5 @@
|
||||
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container} için dosyalar arası kod zekâsı bir Build Server Protocol yapılandırması gerektirir. Oluşturmak için xcode-build-server'ı yükleyin (brew install xcode-build-server).",
|
||||
"Check Again": "Yeniden Denetle",
|
||||
"Running {tool}…": "{tool} çalıştırılıyor…",
|
||||
"Open Module Settings": "Modül Ayarlarını Aç",
|
||||
"Add as Library…": "Kitaplık Olarak Ekle…",
|
||||
"Open Library Settings": "Kitaplık Ayarlarını Aç",
|
||||
"Create Library": "Kitaplık Oluştur",
|
||||
"Library name": "Kitaplık adı",
|
||||
"Library name cannot be empty.": "Kitaplık adı boş olamaz.",
|
||||
"A library with this name already exists.": "Bu ada sahip bir kitaplık zaten var."
|
||||
"Open Module Settings": "Modül Ayarlarını Aç"
|
||||
}
|
||||
@@ -7385,7 +7385,6 @@
|
||||
"Cannot copy the value": "無法複製該值",
|
||||
"The check could not run: {reason}": "檢查無法執行:{reason}",
|
||||
"Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "暫不支援自訂測試輸出路徑。測試輸出由 Maven 和 Gradle 管理。",
|
||||
"Directory for test classes when not managed by Maven or Gradle.": "非 Maven 或 Gradle 管理時存放測試類別檔案的目錄。",
|
||||
"This project is built by Maven or Gradle: build and deploy the artifacts they define.": "此專案由 Maven 或 Gradle 建置:請建置和部署它們定義的構件。",
|
||||
"Add Module Overrides…": "新增模組覆蓋設定…",
|
||||
"Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "模組覆蓋設定只適用於目前開啟專案內的目錄。要從外部匯入已有模組,請使用「匯入已有模組」。",
|
||||
@@ -8234,7 +8233,6 @@
|
||||
"The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only.": "Java 語言伺服器匯入專案時下載所有相依性的原始碼。關閉時,庫中的類別以反編譯形式開啟,可在其「下載原始碼」橫幅中只下載該庫的原始碼。",
|
||||
"Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server.": "執行和偵錯時用 Maven(專案的 javac)建置 Maven 模組,而不是用 Java 語言伺服器。編輯器中的問題仍來自語言伺服器。",
|
||||
"Render Documentation Comments": "渲染文件註解",
|
||||
"Render All Doc Comments": "渲染所有文件註解",
|
||||
"Render documentation comments": "渲染文件註解",
|
||||
"Toggle Rendered View": "切換渲染檢視",
|
||||
"Type params": "型別引數",
|
||||
@@ -9533,14 +9531,5 @@
|
||||
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container} 的跨檔案程式碼智慧需要 Build Server Protocol 設定。安裝 xcode-build-server(brew install xcode-build-server)即可產生。",
|
||||
"Check Again": "重新檢查",
|
||||
"Running {tool}…": "正在執行 {tool}…",
|
||||
"Open Module Settings": "開啟模組設定",
|
||||
"Add as Library…": "新增為庫…",
|
||||
"Open Library Settings": "開啟庫設定",
|
||||
"Create Library": "建立庫",
|
||||
"Library name": "庫名稱",
|
||||
"Library name cannot be empty.": "庫名稱不可為空。",
|
||||
"A library with this name already exists.": "已存在同名的庫。",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,{effectiveAccount} 可能沒有存取權限。請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。",
|
||||
"GitHub Settings": "GitHub 設定"
|
||||
"Open Module Settings": "開啟模組設定"
|
||||
}
|
||||
@@ -8308,7 +8308,6 @@
|
||||
"Cannot copy the value": "无法复制该值",
|
||||
"The check could not run: {reason}": "检查无法运行:{reason}",
|
||||
"Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "暂不支持自定义测试输出路径。测试输出由 Maven 和 Gradle 管理。",
|
||||
"Directory for test classes when not managed by Maven or Gradle.": "非 Maven 或 Gradle 管理时存放测试类文件的目录。",
|
||||
"This project is built by Maven or Gradle: build and deploy the artifacts they define.": "此项目由 Maven 或 Gradle 构建:请构建和部署它们定义的构件。",
|
||||
"Add Module Overrides…": "添加模块覆盖设置…",
|
||||
"Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "模块覆盖设置只适用于当前打开项目内的目录。要从外部导入已有模块,请使用「导入已有模块」。",
|
||||
@@ -9216,7 +9215,6 @@
|
||||
"The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only.": "Java 语言服务器导入项目时下载所有依赖的源代码。关闭时,库中的类以反编译形式打开,可在其“下载源代码”横幅中只下载该库的源代码。",
|
||||
"Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server.": "运行和调试时用 Maven(项目的 javac)构建 Maven 模块,而不是用 Java 语言服务器。编辑器中的问题仍来自语言服务器。",
|
||||
"Render Documentation Comments": "渲染文档注释",
|
||||
"Render All Doc Comments": "渲染所有文档注释",
|
||||
"Render documentation comments": "渲染文档注释",
|
||||
"Toggle Rendered View": "切换渲染视图",
|
||||
"Type params": "类型参数",
|
||||
@@ -11521,14 +11519,5 @@
|
||||
"No new recent projects to import": "没有可导入的新最近项目",
|
||||
"Cannot import recent projects": "无法导入最近项目",
|
||||
"Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.": "已导入 {imported} 个最近项目和 {groups} 个项目分组,跳过 {missing} 个文件夹已不存在的项目。",
|
||||
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "新增 {imported} 个,新增 {groups} 个项目分组,跳过 {missing} 个(文件夹已不存在)",
|
||||
"Add as Library…": "添加为库…",
|
||||
"Open Library Settings": "打开库设置",
|
||||
"Create Library": "创建库",
|
||||
"Library name": "库名称",
|
||||
"Library name cannot be empty.": "库名称不能为空。",
|
||||
"A library with this name already exists.": "已存在同名的库。",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,{effectiveAccount} 可能没有访问权限。请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。",
|
||||
"GitHub Settings": "GitHub 设置"
|
||||
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "新增 {imported} 个,新增 {groups} 个项目分组,跳过 {missing} 个(文件夹已不存在)"
|
||||
}
|
||||
@@ -726,7 +726,6 @@ export interface TextEditorWrapperContribution {
|
||||
/** Yields to any other wrapper matching the file (a plugin's editor for `*.diagram.svg`). */
|
||||
fallback?: boolean;
|
||||
matches(path: string): boolean;
|
||||
matchesVirtual?(uri: string): boolean;
|
||||
component: ComponentType<{ path: string; tabId: string; children: ReactNode; actionsInTabs?: boolean }>;
|
||||
/** Layout controls in the tab strip; the wrapper supplies a floating fallback when tabs are hidden. */
|
||||
tabActions?: ComponentType<{ path: string; tabId: string }>;
|
||||
@@ -752,11 +751,10 @@ export function registerTextEditorWrapper(w: TextEditorWrapperContribution): ()
|
||||
export function textEditorWrapperFor(
|
||||
wrappers: ReadonlyMap<string, TextEditorWrapperContribution>,
|
||||
path: string,
|
||||
virtual = false,
|
||||
): TextEditorWrapperContribution | undefined {
|
||||
let fallback: TextEditorWrapperContribution | undefined;
|
||||
for (const w of wrappers.values()) {
|
||||
if (!(virtual ? w.matchesVirtual?.(path) : w.matches(path))) continue;
|
||||
if (!w.matches(path)) continue;
|
||||
if (!w.fallback) return w;
|
||||
fallback ??= w;
|
||||
}
|
||||
|
||||
Reference in new issue
Заблокувати користувача