Порівняти коміти

..
134 змінених файлів з 572 додано та 4171 видалено

No files matched your search

+22 -100
Переглянути файл
@@ -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:?}");
}
}
-25
Переглянути файл
@@ -314,30 +314,6 @@ pub struct SmartKeysSettings {
pub insert_doc_stub: bool,
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
/// The styles Cycle Identifier Case goes through.
pub cycle_case: CycleCaseSettings,
}
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CycleCaseSettings {
/// `snake_case`
pub snake: bool,
/// `SCREAMING_SNAKE_CASE`
pub screaming: bool,
/// `kebab-case`
pub kebab: bool,
/// `camelCase`
pub camel: bool,
/// `PascalCase`
pub pascal: bool,
}
impl Default for CycleCaseSettings {
fn default() -> Self {
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
}
}
impl Default for SmartKeysSettings {
@@ -359,7 +335,6 @@ impl Default for SmartKeysSettings {
smart_indent: true,
insert_doc_stub: true,
backspace_unindent: "autoindent".into(),
cycle_case: CycleCaseSettings::default(),
}
}
}
-55
Переглянути файл
@@ -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();
}
}
-31
Переглянути файл
@@ -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")]
+8 -37
Переглянути файл
@@ -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();
-2
Переглянути файл
@@ -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();
})
}
+7 -7
Переглянути файл
@@ -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);
}
}
+13 -59
Переглянути файл
@@ -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"))
);
}
+3 -3
Переглянути файл
@@ -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"]);
}
+3 -8
Переглянути файл
@@ -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)?;
-1
Переглянути файл
@@ -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
+2 -24
Переглянути файл
@@ -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
+3 -11
Переглянути файл
@@ -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);
+11 -112
Переглянути файл
@@ -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}");
}
}
}
}
+8 -64
Переглянути файл
@@ -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();
+2 -65
Переглянути файл
@@ -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:?}");
}
}
+1 -1
Переглянути файл
@@ -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};
-47
Переглянути файл
@@ -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());
}
}
+1 -1
Переглянути файл
@@ -8859,7 +8859,7 @@ async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
h.wait_status("sourcekit-lsp", ServerStatus::Ready).await;
eventually(|| h.launcher.state("sourcekit-lsp").docs.lock().contains_key(&uri_of(&path))).await;
assert!(h.statuses("clangd").is_empty(), "{language}");
assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::<Vec<_>>(), std::slice::from_ref(&h.root));
assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::<Vec<_>>(), [h.root.clone()]);
h.mgr.shutdown_all().await;
// sourcekit-lsp not installed: clangd still serves.
+3 -4
Переглянути файл
@@ -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
+10 -32
Переглянути файл
@@ -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);
}
}
+10 -45
Переглянути файл
@@ -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}");
+8 -47
Переглянути файл
@@ -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, &[]));
}
}
+2 -37
Переглянути файл
@@ -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()
-16
Переглянути файл
@@ -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]
+2 -108
Переглянути файл
@@ -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);
-54
Переглянути файл
@@ -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:?}");
}
+5 -5
Переглянути файл
@@ -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 {
+1 -1
Переглянути файл
@@ -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.
+1 -1
Переглянути файл
@@ -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 转发程序从这里读取。
-65
Переглянути файл
@@ -1,65 +0,0 @@
import type { AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const task: AgentTask = {
id: "composer-icons",
title: "Composer icons",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
for (const theme of ["light", "dark"] as const) {
test(`${theme}: Skills uses the same icon colour and size as peer composer actions`, async ({
workbench: page,
}, testInfo) => {
await page.evaluate(
async ({ task, theme }) => {
const storePath = "/src/features/agents/store.ts";
const themePath = "/src/workbench/theme.ts";
const store = await import(storePath);
await (await import(themePath)).setTheme(theme);
store.useAgents.setState({
loaded: true,
error: null,
tasks: new Map([[task.id, task]]),
entries: new Map([[task.id, []]]),
sessionLocation: "editor",
});
store.openTask(task.id);
},
{ task, theme },
);
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
await page.getByRole("button", { name: "Add Context" }).click();
const menu = page.getByRole("menu", { name: "Add Context" });
const skills = menu.getByRole("menuitem", { name: "Skills…" });
const memory = menu.getByRole("menuitem", { name: "Memory…" });
const peerColour = await memory.locator("svg circle").evaluate((el) => getComputedStyle(el).stroke);
await expect(skills.locator("svg path")).toHaveCSS("stroke", peerColour);
const peerSize = await memory.locator("svg").evaluate((el) => {
const { width, height } = getComputedStyle(el);
return { width, height };
});
await expect(skills.locator("svg")).toHaveCSS("width", peerSize.width);
await expect(skills.locator("svg")).toHaveCSS("height", peerSize.height);
await skills.hover();
await expect(skills.locator("svg path")).toHaveCSS("stroke", peerColour);
await menu.screenshot({ path: testInfo.outputPath("add-context.png"), animations: "disabled" });
await page.keyboard.press("Escape");
await expect(menu).toBeHidden();
});
}
-167
Переглянути файл
@@ -1,167 +0,0 @@
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const base: AgentTask = {
id: "recovery-style",
title: "Recovery",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const question: AgentEntry = {
type: "question",
id: "question-style",
title: "Choose the implementation",
chosen: null,
questions: [
{
header: "Implementation",
question: "Which approach should I use?",
options: [
{
label: "Reuse existing controls (Recommended)",
description: "Keep the existing behavior and theme.",
preview: "Use shared Button and Input components.",
},
{
label: "Create a custom control",
description: "Requires additional maintenance.",
preview: "Introduce a new component.",
},
],
},
{
header: "Tests",
question: "Which tests should I run?",
multiSelect: true,
options: [
{ label: "Unit tests", description: "Run focused component tests." },
{ label: "Browser tests", description: "Verify the rendered workflow." },
],
},
],
};
for (const theme of ["light", "dark"] as const) {
test(`${theme}: agent recovery and question controls follow the workbench style`, async ({
workbench: page,
}, testInfo) => {
await page.evaluate(
async ({ base, question, theme }) => {
const storePath = "/src/features/agents/store.ts";
const themePath = "/src/workbench/theme.ts";
const store = await import(storePath);
await (await import(themePath)).setTheme(theme);
const recovery: AgentTask = { ...base, interrupted: { reason: "quit", atMs: Date.now() - 120_000 } };
const ask: AgentTask = { ...base, id: "ask-style", title: "Question" };
const entries: AgentEntry[] = [
{ type: "user", text: "Continue with the implementation.", attachments: [], recovery: "windowClose" },
{ type: "agent", text: "The implementation is ready to continue." },
];
store.useAgents.setState({
loaded: true,
error: null,
tasks: new Map([
[recovery.id, recovery],
[ask.id, ask],
]),
entries: new Map([
[recovery.id, entries],
[ask.id, [question]],
]),
sessionLocation: "editor",
});
store.openTask(recovery.id);
},
{ base, question, theme },
);
const resume = page.getByRole("button", { name: "Resume", exact: true });
await expect(resume).toBeVisible();
const resumeColor = await resume.evaluate((el) => getComputedStyle(el).color);
await expect(resume.locator("svg path")).toHaveCSS("stroke", resumeColor);
const record = page.getByRole("separator").filter({ hasText: "Resumed after window close" });
const recordColor = await record.evaluate((el) => getComputedStyle(el).color);
await expect(record.locator("svg path")).toHaveCSS("stroke", recordColor);
await page
.getByRole("tabpanel", { name: "Recovery" })
.screenshot({ path: testInfo.outputPath("recovery.png"), animations: "disabled" });
await page.evaluate(async () => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
const tasks = new Map(useAgents.getState().tasks);
const current = tasks.get("recovery-style") as AgentTask;
tasks.set(current.id, {
...current,
status: "running",
interrupted: null,
retry: {
attempt: 1,
maxRetries: null,
retryAtMs: Date.now() + 30_000,
deadlineMs: Date.now() + 3_600_000,
error: "Connection lost",
},
});
useAgents.setState({ tasks });
});
const resumeNow = page.getByRole("button", { name: "Resume Now", exact: true });
await expect(resumeNow).toBeVisible();
await expect(resumeNow.locator("svg path")).toHaveCSS("stroke", resumeColor);
await page.evaluate(async () => {
const storePath = "/src/features/agents/store.ts";
(await import(storePath)).openTask("ask-style");
});
const card = page.getByRole("form", { name: "Choose the implementation" });
await expect(card).toBeVisible();
await expect(card.getByRole("button", { name: "Submit" })).toBeDisabled();
const buttonHeight = await card
.getByRole("button", { name: "Submit" })
.evaluate((el) => getComputedStyle(el).height);
await expect(card.getByRole("button", { name: "Next" })).toHaveCSS("height", buttonHeight);
await expect(card.getByRole("button", { name: "Previous" })).toHaveCSS("height", buttonHeight);
await expect(card.getByText("Implementation", { exact: true })).toHaveCount(1);
const choice = card.getByRole("radio", { name: /^Reuse existing controls/ });
const row = choice.locator("xpath=ancestor::label");
await expect(row).toHaveCSS("border-top-width", "0px");
await card.screenshot({ path: testInfo.outputPath("question.png"), animations: "disabled" });
await row.click();
await expect(card.getByRole("tab", { name: "Tests" })).toHaveAttribute("aria-selected", "true");
const checkbox = card.getByRole("checkbox", { name: /^Unit tests/ });
const checkboxRow = checkbox.locator("xpath=ancestor::label");
await checkboxRow.click();
await expect(checkbox).toBeChecked();
const selectionColor = await page.evaluate(() => {
const probe = document.createElement("span");
probe.style.backgroundColor = "var(--bg-tree-selected)";
document.body.append(probe);
const color = getComputedStyle(probe).backgroundColor;
probe.remove();
return color;
});
await expect(checkboxRow).toHaveCSS("background-color", selectionColor);
await expect(card.getByRole("button", { name: "Submit" })).toBeEnabled();
await card.screenshot({ path: testInfo.outputPath("question-selected.png"), animations: "disabled" });
await page.setViewportSize({ width: 900, height: 800 });
const composer = card.locator("xpath=following-sibling::div[1]").locator("[data-owns-file-drop]:visible");
const cardBounds = await card.boundingBox();
const composerBounds = await composer.boundingBox();
expect(cardBounds).not.toBeNull();
expect(composerBounds).not.toBeNull();
expect(Math.abs(cardBounds!.x - composerBounds!.x)).toBeLessThan(2);
expect(Math.abs(cardBounds!.width - composerBounds!.width)).toBeLessThan(2);
await card.screenshot({ path: testInfo.outputPath("question-narrow.png"), animations: "disabled" });
});
}
-90
Переглянути файл
@@ -20,96 +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)",
...Array.from({ length: 30 }, (_, index) => `Paragraph ${index + 1}`),
"## Ref 1",
...Array.from({ length: 30 }, (_, index) => `More text ${index + 1}`),
'<a id="ref-1"></a>',
"Reference text",
...Array.from({ length: 30 }, (_, index) => `Further text ${index + 1}`),
"## Ref 1 heading",
].join("\n\n");
await page.evaluate(async (source) => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
const path = "/dev/acme-api/references.md";
docBackend().files.set(path, source);
await editorService().openFile(path);
}, source);
await page.getByRole("button", { name: "Preview Only", exact: true }).click();
const preview = page.getByRole("document", { name: "Markdown preview" });
const referenceText = preview.getByText("Reference text", { exact: true });
const heading = preview.getByRole("heading", { name: "Ref 1 heading", exact: true });
await expect(preview.locator('[id="ref-1"]')).toHaveCount(1);
await expect(referenceText).not.toBeInViewport();
await preview.getByRole("link", { name: "Reference", exact: true }).click();
await expect(referenceText).toBeInViewport();
await expect(heading).not.toBeInViewport();
await preview.getByRole("link", { name: "Heading", exact: true }).click();
await expect(heading).toBeInViewport();
});
test("copies fenced Markdown code with hover or keyboard in both preview layouts", async ({
workbench: page,
context,
-54
Переглянути файл
@@ -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,
}) => {
+5 -4
Переглянути файл
@@ -41,8 +41,7 @@ test("project switcher keeps names and metadata on separate lines and highlights
await page.getByRole("button", { name: "acme-api", exact: true }).click();
const popup = page.getByRole("dialog", { name: "Projects" });
await expect(popup.getByText("Recent Projects")).toBeVisible();
await expect(popup.getByText("Release Tools")).toHaveCount(0);
await expect(popup.getByText("Release Tools")).toBeVisible();
const local = popup.getByRole("option", { name: new RegExp(NAME) });
await expectBelow(local, NAME, PATH);
await expectBelow(local, PATH, BRANCH);
@@ -52,8 +51,10 @@ test("project switcher keeps names and metadata on separate lines and highlights
const remote = popup.getByRole("option", { name: /Payment Ledger/ });
await expect(remote.locator("[data-remote-badge]")).toHaveCount(1);
await expect(remote.locator('[data-remote-kind="ssh"]')).toBeVisible();
await expect(local.locator("[data-remote-badge]")).toHaveCount(0);
await expectBelow(remote, "Payment Ledger", `${HOST}:${REMOTE_PATH}`);
await expectBelow(remote, "Payment Ledger", HOST);
await expectBelow(remote, HOST, REMOTE_PATH);
await page.setViewportSize({ width: 960, height: 700 });
await page.keyboard.type(HOST);
@@ -65,7 +66,7 @@ test("project switcher keeps names and metadata on separate lines and highlights
await page.keyboard.press("Escape");
await page.keyboard.type(`${HOST}:${REMOTE_PATH}`);
await expect(remote.locator("mark")).toHaveText(`${HOST}:${REMOTE_PATH}`);
await expect(remote.locator("mark")).toHaveText([HOST, REMOTE_PATH]);
await page.keyboard.press("Escape");
await page.keyboard.type("acme-api");
+3 -31
Переглянути файл
@@ -1,6 +1,6 @@
import { expect, stubDesktop, test } from "./fixtures";
test("keeps the project switcher flat while grouping Welcome and Recent Projects without row overlap", async ({
test("groups recent projects by Local and remote host across Welcome, Recent Projects, and Project Popup without row overlap", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 980, height: 740 });
@@ -71,43 +71,15 @@ test("keeps the project switcher flat while grouping Welcome and Recent Projects
}
});
// 1. The project widget uses the same row layout for local and remote projects.
// 1. Project Widget dropdown keeps Open Projects flat and groups Recent Projects by host.
await page.getByRole("button", { name: "openidea_all" }).click();
const projectPopup = page.getByRole("dialog", { name: "Projects" });
await expect(projectPopup).toBeVisible();
await expect(projectPopup).toContainText("Open Projects");
await expect(projectPopup).toContainText("Recent Projects");
await expect(projectPopup).toContainText("dev-mbp1.local");
await expect(projectPopup.getByText("Local", { exact: true })).toHaveCount(0);
await expect(projectPopup).toContainText("Local");
await expect(projectPopup).toContainText("Ubuntu-24.04");
// The two section headers and every project badge share the same left inset.
const headers = [
projectPopup.getByText("Open Projects", { exact: true }),
projectPopup.getByText("Recent Projects", { exact: true }),
];
const headerMetrics = await Promise.all(
headers.map((header) =>
header.evaluate((el) => {
const style = getComputedStyle(el);
const rect = el.getBoundingClientRect();
return { x: rect.x + parseFloat(style.paddingLeft), height: rect.height, fontSize: style.fontSize };
}),
),
);
expect(headerMetrics[1]).toEqual(headerMetrics[0]);
const projectRows = projectPopup.getByRole("option").filter({ hasText: "/git/" });
await expect(projectRows).toHaveCount(7);
await expect(projectRows.locator("[data-remote-badge]")).toHaveCount(4);
const rowMetrics = await projectRows.evaluateAll((rows) =>
rows.map((el) => ({
x: el.firstElementChild!.getBoundingClientRect().x,
height: el.getBoundingClientRect().height,
})),
);
for (const row of rowMetrics) expect(row.x).toBeCloseTo(headerMetrics[0]!.x, 0);
// Both open projects have no branch metadata and must have identical heights.
expect(rowMetrics[0]!.height).toBeCloseTo(rowMetrics[1]!.height, 0);
await expect(projectPopup.getByRole("separator")).toHaveCount(2);
await page.keyboard.press("Escape");
await expect(projectPopup).toBeHidden();
+1 -1
Переглянути файл
@@ -123,7 +123,7 @@ test("Git Log settings group display and column options with aligned checkboxes"
const columns = dialog.getByRole("region", { name: "Visible columns" });
const tagNames = view.getByRole("checkbox", { name: "Show tag names" });
const hash = columns.getByRole("checkbox", { name: "Hash" });
await expect(view.getByRole("checkbox")).toHaveCount(4);
await expect(view.getByRole("checkbox")).toHaveCount(5);
await expect(columns.getByRole("checkbox")).toHaveCount(4);
for (const width of [1000, 520]) {
-18
Переглянути файл
@@ -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 }) => {
-16
Переглянути файл
@@ -5975,20 +5975,6 @@ export type CustomKeymap = {
overrides?: { [key in string]: string[] },
};
/** Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through. */
export type CycleCaseSettings = {
/** `snake_case` */
snake?: boolean,
/** `SCREAMING_SNAKE_CASE` */
screaming?: boolean,
/** `kebab-case` */
kebab?: boolean,
/** `camelCase` */
camel?: boolean,
/** `PascalCase` */
pascal?: boolean,
};
/**
* A field watchpoint (DAP data breakpoint) on a `dataId` from [`DebugManager::data_breakpoint_info`]
* (java-debug ids, `Class#field`, stay valid across sessions).
@@ -15087,8 +15073,6 @@ export type SmartKeysSettings = {
insertDocStub?: boolean,
/** Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`. */
backspaceUnindent?: string,
/** The styles Cycle Identifier Case goes through. */
cycleCase?: CycleCaseSettings,
};
export type SourceFolder = {
+1 -45
Переглянути файл
@@ -139,7 +139,6 @@ import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import { toggleReadOnly } from "./fileAttributes";
import { codeVisionShown, toggleCodeVision } from "./codeVision";
import { breadcrumbsShown, toggleBreadcrumbs } from "./breadcrumbs";
import { appearanceSwitches, localAppearanceSwitches, toggleAppearance, type AppearanceSwitch } from "./gutterMenu";
import { openNavBarPopup } from "./view/NavBarPopup";
import {
@@ -780,11 +779,6 @@ export async function toggleSchemeSwitch(key: SchemeSwitch, on = !editorPrefs()[
}
}
function activeBreadcrumbsShown(): boolean {
const slot = activeSlot();
return !!slot && breadcrumbsShown(slot.tabId, editorPrefs().breadcrumbs, slot.model.info?.id);
}
/** IDEA's StickyLinesDisableForLangAction: the active document's known base language, if enabled. */
function activeStickyLinesLanguage(): string | null {
// A notebook cell has no base document: never change the last text tab's language setting.
@@ -970,20 +964,6 @@ export function registerEditorActions(): () => void {
localAppearanceSwitch("editor.toggleLocalWhitespaces", "whitespaces"),
localAppearanceSwitch("editor.toggleLocalGutterIcons", "gutterIcons"),
localAppearanceSwitch("editor.toggleLocalIndentGuides", "indentGuides"),
{
id: "editor.toggleBreadcrumbs",
title: "Show Breadcrumbs",
description: "Toggle display of the Breadcrumbs bar in the current editor.",
category: "View",
keywords: ["breadcrumbs", "navigation bar", "hide breadcrumbs"],
when: "textEditorActive",
enabled: () => !focusedCellEditor() && !!activeSlot(),
toggled: activeBreadcrumbsShown,
run: () => {
const slot = activeSlot();
if (slot) toggleBreadcrumbs(slot.tabId, editorPrefs().breadcrumbs, slot.model.info?.id);
},
},
{
id: "editor.toggleCodeVision",
title: "Code Vision",
@@ -1140,30 +1120,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"],
@@ -1372,7 +1328,7 @@ export function registerEditorActions(): () => void {
edit("code.joinLines", "Join Lines", (v) => joinLines(v)),
edit("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
edit("code.transpose", "Transpose", (v) => transpose(v), { category: "Editor Actions" }),
edit("code.cycleCase", "Cycle Identifier Case", (v) => cycleCase(v, editorPrefs().smartKeys.cycleCase), {
edit("code.cycleCase", "Cycle Identifier Case", (v) => cycleCase(v), {
keywords: ["camel", "snake", "kebab", "pascal", "screaming"],
}),
caret("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
+1 -125
Переглянути файл
@@ -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,10 +35,8 @@ const { createMemoryBackend } = await import("./backend");
const { DocumentManager } = await import("./model/document");
const { EditorSlot } = await import("./model/slot");
const { gutterIconsOn, localAppearanceField } = await import("./cm/prefs");
const { renderDocComments } = await import("./cm/renderedDocs");
const { DEFAULT_SETTINGS } = await import("@/features/settings/model/schema");
const { resetDistractionFree } = await import("@/workbench/distractionFree");
const { clearBreadcrumbOverrides, pruneBreadcrumbOverrides, useBreadcrumbOverrides } = await import("./breadcrumbs");
let dispose: () => void;
beforeAll(() => {
@@ -48,8 +45,6 @@ beforeAll(() => {
afterAll(() => dispose());
afterEach(() => {
activeSlot = null;
activeManager = null;
clearBreadcrumbOverrides();
useProject.setState({ settings: null });
useContextKeys.setState({}, true);
resetDistractionFree();
@@ -175,7 +170,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 +255,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();
@@ -316,94 +280,6 @@ describe("active editor appearance toggles", () => {
});
});
describe("Show Breadcrumbs action", () => {
const id = "editor.toggleBreadcrumbs";
const activate = (tabId: string, language = "typescript") => {
activeSlot = { disposed: false, tabId, model: { info: { id: language } } } as never;
};
const setBreadcrumbs = (show: boolean, disabledLanguages: string[] = []) => {
useProject.setState({
settings: { editor: { breadcrumbs: { show, placement: "bottom", disabledLanguages } } } as never,
});
};
beforeEach(() => {
setBreadcrumbs(true);
useContextKeys.setState({ textEditorActive: true });
});
it("is a View action mapped from IDEA", () => {
expect(getAction(id)).toMatchObject({
title: "Show Breadcrumbs",
description: "Toggle display of the Breadcrumbs bar in the current editor.",
category: "View",
when: "textEditorActive",
});
expect(resolveActionId("EditorToggleShowBreadcrumbs")).toBe(id);
});
it("changes only the active editor and leaves global settings untouched", async () => {
activate("t1");
const settings = structuredClone(useProject.getState().settings);
const action = getAction(id);
expect(actionToggled(action)).toBe(true);
expect(await executeAction(id)).toBe(true);
expect(actionToggled(action)).toBe(false);
expect(useBreadcrumbOverrides.getState()).toEqual({ t1: false });
expect(useProject.getState().settings).toEqual(settings);
expect(ipc.settingsSet).not.toHaveBeenCalled();
activate("t2");
expect(actionToggled(action)).toBe(true);
expect(await executeAction(id)).toBe(true);
expect(useBreadcrumbOverrides.getState()).toEqual({ t1: false, t2: false });
activate("t1");
expect(await executeAction(id)).toBe(true);
expect(useBreadcrumbOverrides.getState()).toEqual({ t1: true, t2: false });
});
it("lets a forced value override the global setting and disabled language", async () => {
setBreadcrumbs(false, ["typescript"]);
activate("t1");
const action = getAction(id);
expect(actionToggled(action)).toBe(false);
expect(await executeAction(id)).toBe(true);
expect(actionToggled(action)).toBe(true);
activate("t2");
expect(actionToggled(action)).toBe(false);
});
it("keeps the override while untouched editors follow global changes", async () => {
setBreadcrumbs(false);
activate("t1");
expect(await executeAction(id)).toBe(true);
setBreadcrumbs(true);
expect(actionToggled(getAction(id))).toBe(true);
activate("t2");
expect(actionToggled(getAction(id))).toBe(true);
setBreadcrumbs(false);
expect(actionToggled(getAction(id))).toBe(false);
activate("t1");
expect(actionToggled(getAction(id))).toBe(true);
});
it("does not run without an active text editor", async () => {
expect(await executeAction(id)).toBe(false);
activate("t1");
useContextKeys.setState({ textEditorActive: false });
expect(await executeAction(id)).toBe(false);
expect(useBreadcrumbOverrides.getState()).toEqual({});
});
it("drops overrides for closed editors and when the session stops", () => {
useBreadcrumbOverrides.setState({ t1: false, t2: true }, true);
pruneBreadcrumbOverrides(new Set(["t1"]));
expect(useBreadcrumbOverrides.getState()).toEqual({ t1: false });
clearBreadcrumbOverrides();
expect(useBreadcrumbOverrides.getState()).toEqual({});
});
});
describe("Disable Sticky Lines for Language", () => {
const id = "editor.disableStickyLinesForLanguage";
const key = "editor.codeEditing.stickyLinesDisabledLanguages";
-35
Переглянути файл
@@ -1,35 +0,0 @@
import { create } from "zustand";
import type { EditorExtras } from "@/platform/editorSettings";
export const useBreadcrumbOverrides = create<Record<string, boolean>>(() => ({}));
export function breadcrumbsShown(
tabId: string,
prefs: EditorExtras["breadcrumbs"],
language: string | undefined,
): boolean {
const forced = useBreadcrumbOverrides.getState()[tabId];
return forced ?? (prefs.show && (!language || !prefs.disabledLanguages.includes(language)));
}
export function toggleBreadcrumbs(
tabId: string,
prefs: EditorExtras["breadcrumbs"],
language: string | undefined,
): void {
const shown = !breadcrumbsShown(tabId, prefs, language);
useBreadcrumbOverrides.setState((state) => ({ ...state, [tabId]: shown }));
}
export function pruneBreadcrumbOverrides(live: ReadonlySet<string>): void {
const state = useBreadcrumbOverrides.getState();
const closed = Object.keys(state).filter((id) => !live.has(id));
if (!closed.length) return;
const next = { ...state };
for (const id of closed) delete next[id];
useBreadcrumbOverrides.setState(next, true);
}
export function clearBreadcrumbOverrides(): void {
useBreadcrumbOverrides.setState({}, true);
}
+3 -6
Переглянути файл
@@ -36,7 +36,7 @@ import {
} from "@codemirror/commands";
import { SearchCursor } from "@codemirror/search";
import { humpLeft, humpRight, wordStartLeft } from "../model/camelHumps";
import { cycleIdentifierCase, wordSpan, type IdentifierCase } from "../model/identifierCase";
import { cycleIdentifierCase, wordSpan } from "../model/identifierCase";
import { restartSticky } from "./stickySelection";
type Node = ReturnType<ReturnType<typeof syntaxTree>["resolveInner"]>;
@@ -1087,10 +1087,7 @@ const NAME_CHAR = /[\p{L}\p{N}_$-]/u;
* or of each selection, from the style it is written in: snake_case →
* SCREAMING_SNAKE_CASE → kebab-case → camelCase → PascalCase.
*/
export const cycleCase = (
view: EditorView,
enabled: Readonly<Partial<Record<IdentifierCase, boolean>>> = {},
): boolean => {
export const cycleCase: Command = (view) => {
const { state } = view;
if (state.readOnly) return false;
/** The `-`-joined name at or right before `pos`. */
@@ -1110,7 +1107,7 @@ export const cycleCase = (
const span = wordSpan(state.sliceDoc(name.from, name.to));
if (!span) return { range: r };
const from = name.from + span.from;
const insert = cycleIdentifierCase(state.sliceDoc(from, name.from + span.to), enabled);
const insert = cycleIdentifierCase(state.sliceDoc(from, name.from + span.to));
if (insert === null) return { range: r };
changed = true;
const set = state.changes({ from, to: name.from + span.to, insert });
-3
Переглянути файл
@@ -130,7 +130,6 @@ import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
import type { VirtualDocument } from "@/platform/ipc";
import type { Scheduler } from "./sync/DocSync";
import { selectedLineContext, selectedLines } from "./selectedLines";
import { clearBreadcrumbOverrides, pruneBreadcrumbOverrides } from "./breadcrumbs";
export const fileKey = (path: string) => `file:${path}`;
export const fileInput = (path: string): EditorInput => ({ kind: "file", key: fileKey(path), path });
@@ -548,7 +547,6 @@ export class EditorController implements SlotHost {
this.preparedDocuments.clear();
for (const slot of this.slots.values()) slot.dispose();
this.slots.clear();
clearBreadcrumbOverrides();
this.selectionRequests.clear();
this.manager.stop();
useTabs.setState(initialTabsState(), true);
@@ -565,7 +563,6 @@ export class EditorController implements SlotHost {
private onTabsChanged(prev: TabsState, next: TabsState) {
const live = new Set<string>();
for (const p of Object.values(next.panes)) for (const t of p.tabs) live.add(t.id);
pruneBreadcrumbOverrides(live);
for (const id of this.selectionRequests.keys()) if (!live.has(id)) this.selectionRequests.delete(id);
for (const [id, slot] of this.slots) {
-7
Переглянути файл
@@ -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[] = [];
-15
Переглянути файл
@@ -39,21 +39,6 @@ describe("cycle identifier case", () => {
expect(cycleIdentifierCase("MyVarName")).toBe("my_var_name");
});
it("goes only through the styles turned on, starting from the one the name is written in", () => {
const camelSnake = { screaming: false, kebab: false, pascal: false };
expect(cycleIdentifierCase("myVarName", camelSnake)).toBe("my_var_name");
expect(cycleIdentifierCase("my_var_name", camelSnake)).toBe("myVarName");
// A name in a style that is turned off still moves on to the next one that is on.
expect(cycleIdentifierCase("my-var-name", camelSnake)).toBe("myVarName");
expect(cycleIdentifierCase("MyVarName", camelSnake)).toBe("my_var_name");
// Only the name's own style on: nothing else to go to.
expect(
cycleIdentifierCase("myVarName", { snake: false, screaming: false, kebab: false, pascal: false }),
).toBeNull();
// One word in snake_case is written as in camelCase, so with Name and NAME off it stays.
expect(cycleIdentifierCase("name", { pascal: false, screaming: false })).toBeNull();
});
it("gives one word its three spellings: name → Name → NAME", () => {
expect(cycleIdentifierCase("name")).toBe("Name");
expect(cycleIdentifierCase("Name")).toBe("NAME");
+3 -9
Переглянути файл
@@ -81,20 +81,14 @@ export function toIdentifierCase(text: string, style: IdentifierCase): string {
/**
* `text` in the next style of the cycle, skipping the styles that write it the
* same way and those `enabled` turns off (Settings › Editor › General › Smart
* Keys); null when none writes it differently.
* same way; null when none writes it differently.
*/
export function cycleIdentifierCase(
text: string,
enabled: Readonly<Partial<Record<IdentifierCase, boolean>>> = {},
): string | null {
export function cycleIdentifierCase(text: string): string | null {
const current = identifierCase(text);
if (!current) return null;
// One word has three spellings, not five: name → Name → NAME.
const single = identifierWords(text).length === 1 && !SEPARATOR.test(text);
const all: readonly IdentifierCase[] = single ? ["camel", "pascal", "screaming", "snake"] : identifierCases;
// The style the name is written in stays the starting point even when it is turned off.
const order = all.filter((style) => style === current || enabled[style] !== false);
const order: readonly IdentifierCase[] = single ? ["camel", "pascal", "screaming", "snake"] : identifierCases;
const start = Math.max(0, order.indexOf(current));
for (let step = 1; step <= order.length; step++) {
const next = toIdentifierCase(text, order[(start + step) % order.length]!);
+11 -9
Переглянути файл
@@ -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");
}
}
+7 -4
Переглянути файл
@@ -31,7 +31,6 @@ import {
untitledTitle,
} from "@/platform/virtualDocs";
import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs } from "../controller";
import { useBreadcrumbOverrides } from "../breadcrumbs";
import { languageInfo } from "../cm/languages";
import { useDocMeta, useOutline, type DocMeta } from "../model/document";
import { symbolChain } from "./outline";
@@ -366,7 +365,6 @@ export function CodeBreadcrumbs({
position: "top" | "bottom";
}) {
const { breadcrumbs: prefs, fallbackFont } = useEditorPrefs();
const forced = useBreadcrumbOverrides((s) => s[tabId]);
const editorSettings = useProject((s) => s.settings?.editor);
const language = useDocMeta((s) => s[path]?.language);
const outline = useOutline((s) => s[path]);
@@ -377,8 +375,13 @@ export function CodeBreadcrumbs({
const caret = editorController().slots.get(tabId)?.caret();
chain = outline ? symbolChain(outline, caret?.line ?? 0, caret?.col ?? 0) : NO_SYMBOLS;
}
const shown = forced ?? (prefs.show && (!language || !prefs.disabledLanguages.includes(language)));
if (!shown || prefs.placement !== position || !chain.length) return null;
if (
!prefs.show ||
prefs.placement !== position ||
(language && prefs.disabledLanguages.includes(language)) ||
!chain.length
)
return null;
const family = editorSettings?.fontFamily;
const fontFamily =
(family && family !== BUNDLED_MONO_FAMILY) || fallbackFont.trim()
+1 -29
Переглянути файл
@@ -1,5 +1,5 @@
import { Profiler } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { OutlineItem, Settings } from "@/platform/ipc";
import type { EditorStatus } from "../controller";
@@ -24,9 +24,6 @@ const { clearProjectViewLead, setProjectViewLead } = await import("@/workbench/c
const { Breadcrumbs, CodeBreadcrumbs } = await import("./StatusItems");
const { NavBarPopup, openNavBarPopup, useNavBarPopup } = await import("./NavBarPopup");
const { useContextMenuStore } = await import("@/ui");
const { clearBreadcrumbOverrides, useBreadcrumbOverrides } = await import("../breadcrumbs");
afterEach(() => clearBreadcrumbOverrides());
const PATH = "/p/Orders.ts";
const span = (from: number, to: number) => ({ start: { line: from, col: 0 }, end: { line: to, col: 0 } });
@@ -95,31 +92,6 @@ describe("caret-driven status widgets", () => {
expect(commits).toBeGreaterThan(0);
});
it("renders the active editor's forced breadcrumb visibility", () => {
useProject.setState({
settings: {
appearance: { navigationBar: "top" },
editor: { breadcrumbs: { show: false, placement: "bottom", disabledLanguages: ["typescript"] } },
} as never,
});
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10)])] });
act(() => useEditorStatus.setState({ status: caret(3, 4) }));
render(
<>
<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />
<CodeBreadcrumbs path={PATH} tabId="t2" position="bottom" />
</>,
);
expect(screen.queryByRole("navigation", { name: "Code breadcrumbs" })).toBeNull();
act(() => useBreadcrumbOverrides.setState({ t1: true }));
expect(screen.getAllByRole("navigation", { name: "Code breadcrumbs" })).toHaveLength(1);
expect(screen.getByRole("navigation", { name: "Code breadcrumbs" }).textContent).toContain("place");
act(() => useBreadcrumbOverrides.setState({ t1: false }));
expect(screen.queryByRole("navigation", { name: "Code breadcrumbs" })).toBeNull();
});
it("follows the caret into a Vue component's <script> declarations", () => {
useOutline.setState({
[PATH]: [item("template", 0, 4), { ...item("script", 5, 30), children: [item("size", 10, 20)] }],
+2 -2
Переглянути файл
@@ -458,7 +458,7 @@ export function AgentsView() {
}
return [];
};
const rowButton = (label: string, icon: "pin" | "archive" | "agent-resume", run: () => void) => (
const rowButton = (label: string, icon: "pin" | "archive" | "resume", run: () => void) => (
<button
type="button"
className={styles.rowAction}
@@ -645,7 +645,7 @@ export function AgentsView() {
)}
<span className={styles.rowActions}>
{(interrupted || isWaitingForNetwork(n.task)) &&
rowButton("Resume", "agent-resume", () => void executeAction("agents.resumeTasks", [n.task.id]))}
rowButton("Resume", "resume", () => void executeAction("agents.resumeTasks", [n.task.id]))}
{pinned.has(n.task.id)
? rowButton("Unpin", "pin", () => pinTasks([n.task.id], false))
: rowButton("Pin", "pin", () => pinTasks([n.task.id], true))}
+1 -1
Переглянути файл
@@ -224,7 +224,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
provider
? [
{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp },
{ id: "skills", label: "Skills…", icon: "skills", run: openSkills },
{ id: "skills", label: "Skills…", icon: "bulb", run: openSkills },
{ id: "memory", label: "Memory…", icon: "history", run: openMemory },
]
: undefined
+31 -38
Переглянути файл
@@ -155,24 +155,19 @@
color: var(--fg-subtle);
}
/* Inset session notices share the composer and permission card geometry. */
/* The archived / interrupted / waiting-for-network notice above the conversation. */
.banner {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
min-height: calc(var(--h-control) + var(--space-2) * 2);
padding: var(--space-1-5) var(--space-2);
min-height: 36px;
padding: 9px 12px;
background: var(--bg-feedback-warning);
border: 1px solid var(--border-feedback-warning);
border-radius: var(--radius-control);
border-bottom: 1px solid var(--border-feedback-warning);
color: var(--fg-strong);
}
.bannerNeutral {
background: var(--bg-elev);
border-color: var(--border-strong);
}
.bannerIcon {
flex: none;
color: var(--warning);
@@ -190,9 +185,7 @@
font-size: var(--fs-small);
}
.bannerActions {
flex: 0 1 auto;
min-width: 0;
max-width: 100%;
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
@@ -219,7 +212,9 @@
align-items: center;
gap: var(--space-1-5);
padding: 2px var(--space-2);
--icon-color: currentColor;
border: 1px solid var(--border);
border-radius: var(--radius-small);
background: var(--bg-elev);
}
/* The conversation with its find bar. */
@@ -1738,12 +1733,12 @@
text-overflow: ellipsis;
}
/* Questions and forms use the same inset selection rows as the workbench lists. */
/* An open AskUserQuestion: every question with its options, answered at once in the conversation. */
.questionCard {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-3);
padding: 12px;
border: 1px solid var(--border-strong);
border-radius: var(--radius-control);
background: var(--bg-elev);
@@ -1757,11 +1752,12 @@
min-height: 0;
max-height: 50vh;
overflow-y: auto;
width: calc(100% - var(--space-3) * 2);
width: 100%;
max-width: var(--session-content-width);
margin: 0 auto 8px;
}
.fitWidth .questionCardPinned {
width: calc(100% - var(--space-3) * 2);
max-width: none;
}
.questionTabCheck {
@@ -1796,43 +1792,43 @@
border: 0;
}
.questionText {
margin-bottom: var(--space-1-5);
margin-bottom: 6px;
padding: 0;
color: var(--fg-strong);
font-weight: 600;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.questionTag {
margin: 0 var(--space-2) 0 0;
padding: 1px var(--space-1-5);
margin: 0 8px 0 0;
padding: 1px 6px;
border-radius: var(--radius-small);
background: var(--bg-hover);
color: var(--fg-muted);
font-size: var(--agent-fs-small, var(--fs-small));
font-weight: 400;
}
.questionLabel .questionTag {
margin: 0 0 0 var(--space-2);
margin: 0 0 0 8px;
}
.question .questionOption {
display: flex;
align-items: flex-start;
min-height: var(--h-list-row);
padding: var(--space-1-5) var(--space-2);
border-radius: var(--radius-selection);
padding: 8px 10px;
border-radius: var(--radius-row);
}
.question .questionOption:not(:has(input:disabled)):hover {
background: var(--bg-tree-hover);
/* Each option is a card of its own: separate targets, not one list with hairlines. */
.question .questionChoices > * {
border: 1px solid var(--border);
border-radius: var(--radius-row);
}
.question .questionOption:has(input:checked) {
background: var(--bg-tree-selected);
.question .questionChoices > *:hover {
border-color: var(--border-strong);
}
.question .questionOption:has(input:checked):hover {
background: var(--bg-tree-selected);
.question .questionChoices > *:has(input:checked) {
border-color: var(--accent);
background: var(--bg-hover);
}
.question .questionOption:has(input:disabled) {
opacity: 0.6;
.question .questionOption:hover {
background: var(--bg-hover);
}
.questionOption > :first-child {
margin-top: 1px;
@@ -1868,11 +1864,8 @@
color: var(--fg-subtle);
font-size: var(--agent-fs-small, var(--fs-small));
}
.questionOption:has(input:checked) :is(.questionDescription, .questionKey) {
color: var(--fg);
}
.questionOther {
margin: var(--space-0-5) 0 0 calc(16px + var(--space-2) * 2);
margin: 2px 0 0 30px;
}
.questionBody {
display: flex;
@@ -1899,7 +1892,7 @@
.questionPreview {
display: grid;
min-width: 0;
margin: 0 0 0 calc(16px + var(--space-2) * 2);
margin: 0 0 0 30px;
}
.questionPreviewItem {
display: flex;
-1
Переглянути файл
@@ -52,7 +52,6 @@ describe("SkillsPicker", () => {
const trigger = screen.getByRole("button", { name: "Skills" });
expect(trigger).toHaveTextContent("Skills3/4");
expect(trigger.querySelector("svg path")).toHaveAttribute("stroke", "currentColor");
fireEvent.click(trigger);
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
+1 -1
Переглянути файл
@@ -78,7 +78,7 @@ export function SkillsPicker({
return (
<SessionPicker
icon="skills"
icon="bulb"
brand="Skills"
triggerTitles={{
plain: tx("Skills ({active}/{total} active)"),
-11
Переглянути файл
@@ -221,17 +221,6 @@ describe("New Task composer commands", () => {
expect(agentSkillsList).toHaveBeenCalledOnce();
});
it("uses a theme-coloured Skills icon in the Add Context menu", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Add Context" }));
const item = await screen.findByRole("menuitem", { name: "Skills…" });
expect(item.querySelector("svg path")).toHaveAttribute("stroke", "currentColor");
expect(item.querySelector("svg")!.innerHTML).not.toMatch(/#[0-9a-f]{6}/i);
fireEvent.click(item);
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
});
it("names the icon-only Start action and disables it while starting", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
let finish!: (value: unknown) => void;
+19 -21
Переглянути файл
@@ -286,7 +286,7 @@ export function QuestionForm({
);
const chooseByNumber = (number: number) => {
const answer = answers[position];
if (!answer?.question.options.length) return;
if (!answer) return;
const option = answer.question.options[number - 1];
if (option) choose(answer, option.label, !answer.picked.includes(option.label));
else if (number === answer.question.options.length + 1) chooseOther(answer, answer.other === null);
@@ -362,20 +362,16 @@ export function QuestionForm({
</span>
),
})),
...(item.question.options.length
? [
{
key: group,
checked: item.other !== null,
onChange: (checked: boolean) => chooseOther(item, checked),
label: (
<span className={styles.questionLabel}>
<T>Other</T>
</span>
),
},
]
: []),
{
key: group,
checked: item.other !== null,
onChange: (checked: boolean) => chooseOther(item, checked),
label: (
<span className={styles.questionLabel}>
<T>Other</T>
</span>
),
},
];
return (
<div
@@ -391,9 +387,7 @@ export function QuestionForm({
>
<fieldset className={styles.question} disabled={busy}>
<legend className={styles.questionText}>
{!multiple && item.question.header && (
<span className={styles.questionTag}>{item.question.header}</span>
)}
{item.question.header && <span className={styles.questionTag}>{item.question.header}</span>}
{item.question.question}
</legend>
<div className={clsx(styles.questionBody, hasPreviews && styles.questionBodyWithPreview)}>
@@ -433,7 +427,7 @@ export function QuestionForm({
{item.other !== null && (
<Input
autoFocus={entry.type === "permission" || item.question.options.length > 0}
className={clsx(item.question.options.length > 0 && styles.questionOther)}
className={styles.questionOther}
value={item.other}
placeholder="Type your answer"
onChange={(event) => update(item, { ...item, other: event.target.value })}
@@ -488,13 +482,17 @@ export function QuestionForm({
</Button>
{multiple && (
<div className={styles.questionPager}>
<Button disabled={busy || position === 0} onClick={() => goTo(position - 1, true)}>
<Button size="small" disabled={busy || position === 0} onClick={() => goTo(position - 1, true)}>
Previous
</Button>
<span className={styles.questionPage}>
{position + 1} / {answers.length}
</span>
<Button disabled={busy || position === answers.length - 1} onClick={() => goTo(position + 1, true)}>
<Button
size="small"
disabled={busy || position === answers.length - 1}
onClick={() => goTo(position + 1, true)}
>
Next
</Button>
</div>
+4 -4
Переглянути файл
@@ -95,7 +95,7 @@ function InterruptedBanner({ task }: { task: AgentTask }) {
<Button
size="small"
variant="primary"
icon="agent-resume"
icon="resume"
disabled={resuming}
onClick={() => {
setResuming(true);
@@ -142,7 +142,7 @@ function WaitingForNetworkBanner({ task }: { task: AgentTask }) {
<Button
size="small"
variant="primary"
icon="agent-resume"
icon="resume"
onClick={() =>
void resumeTask(task.id).catch((e: unknown) =>
notifications().notify({
@@ -387,7 +387,7 @@ export function SessionComposer({
return (
<div className={styles.composerArea}>
{task.status === "archived" && (
<div className={clsx(styles.banner, styles.bannerNeutral)}>
<div className={styles.banner}>
<span className={styles.bannerText}>
<T>This task is archived. Unarchive it to continue the conversation.</T>
</span>
@@ -433,7 +433,7 @@ export function SessionComposer({
disabled={task.status === "archived"}
addMenu={[
{ id: "mcp", label: "MCP Servers…", icon: "plugin", disabled: task.status === "archived", run: openMcp },
{ id: "skills", label: "Skills…", icon: "skills", disabled: task.status === "archived", run: openSkills },
{ id: "skills", label: "Skills…", icon: "bulb", disabled: task.status === "archived", run: openSkills },
{ id: "memory", label: "Memory…", icon: "history", disabled: task.status === "archived", run: openMemory },
]}
toolbar={
+1 -1
Переглянути файл
@@ -295,7 +295,7 @@ function UserMessage({
<div className={styles.recoveryDivider} role="separator">
<span className={styles.recoveryRule} aria-hidden="true" />
<span className={styles.recoveryPill}>
<Icon name="agent-resume" size={12} />
<Icon name="resume" size={12} />
<span>{tx(recoveryDividerLabel(entry.recovery))}</span>
<MessageTime sentMs={entry.sentMs ?? null} doneMs={null} />
</span>
-16
Переглянути файл
@@ -1348,7 +1348,6 @@ describe("an asynchronous Codex question", () => {
it("accepts a typed answer without suggested choices", async () => {
const answerKey = freeQuestion();
const card = await screen.findByRole("form", { name: "What deadline?" });
expect(within(card).queryByRole("radio")).toBeNull();
const submit = within(card).getByRole("button", { name: "Submit" });
expect(submit).toBeDisabled();
fireEvent.change(within(card).getByPlaceholderText("Type your answer"), { target: { value: "Tomorrow" } });
@@ -1374,21 +1373,6 @@ describe("an asynchronous Codex question", () => {
expect(await screen.findByRole("form", { name: "Blocking question" })).not.toHaveClass(styles.questionCardPinned!);
});
it("uses the same pinned container for ACP forms as asynchronous questions", async () => {
const entry: AgentEntry = {
type: "permission",
id: 101,
title: "Project details",
options: [],
chosen: null,
form: { fields: [{ name: "project", title: "Project name", kind: "text", required: true }] },
};
backend.entries.set("A", [entry]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
expect(await screen.findByRole("form", { name: "Project details" })).toHaveClass(styles.questionCardPinned!);
});
it("skips without submitting an answer", async () => {
freeQuestion();
const card = await screen.findByRole("form", { name: "What deadline?" });
+2 -2
Переглянути файл
@@ -353,7 +353,7 @@ export const taskActions: Action[] = [
id: "agents.resumeAllInterrupted",
title: "Resume All Interrupted Tasks",
category: "Agents",
icon: "agent-resume",
icon: "resume",
when: "projectOpen",
keywords: ["resume", "continue", "interrupted", "recover"],
run: async () => {
@@ -497,7 +497,7 @@ export function taskMenu(tasks: AgentTask[], below: AgentTask[] = []): MenuItem[
kind: "action",
action: "agents.resumeTasks",
label: multiple ? tx`Resume (${interrupted.length})` : "Resume",
icon: "agent-resume",
icon: "resume",
arg: interrupted.map((t) => t.id),
},
{
+2 -22
Переглянути файл
@@ -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);
});
-64
Переглянути файл
@@ -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);
}
-164
Переглянути файл
@@ -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} />;
}
+6 -14
Переглянути файл
@@ -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)),
);
}, []);
-14
Переглянути файл
@@ -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",
-309
Переглянути файл
@@ -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();
}
});
});
-335
Переглянути файл
@@ -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;
}
-40
Переглянути файл
@@ -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();
-10
Переглянути файл
@@ -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);
+1 -8
Переглянути файл
@@ -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()),
];
+1 -9
Переглянути файл
@@ -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);
}
+3 -153
Переглянути файл
@@ -21,14 +21,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
};
});
vi.mock("@/platform/clipboard", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/clipboard")>()),
writeClipboardText: vi.fn(async () => {}),
}));
import { getAction, registerAction, executeAction } from "@/platform/actions";
import { writeClipboardText } from "@/platform/clipboard";
import { setLocale } from "@/platform/i18n";
import { registerAction, executeAction } from "@/platform/actions";
import { usePlatform } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { useKeymap } from "@/platform/keymap";
@@ -41,16 +34,13 @@ import { ProjectStructureDialog } from "../languages/ProjectStructurePage";
import { SettingsWindow } from "../window/SettingsWindow";
import dialogStyles from "../dialog/SettingsDialog.module.css";
import { activate } from "..";
import { copySettingsPath } from "../actions";
import { MessagesHost } from "@/workbench/messages";
import { resolveActionId } from "@/features/vim/rc";
let current: Settings;
let dispose: () => void = () => {};
const HTTP_PROXY_CONTEXT = { pageId: "general.httpProxy", scope: "global" } as const;
beforeEach(() => {
vi.mocked(writeClipboardText).mockClear();
current = structuredClone(DEFAULT_SETTINGS) as Settings;
settingsSet.mockReset().mockImplementation(async (_scope: string, key: string, json: string) => {
current = setAt(current, key, JSON.parse(json));
@@ -63,10 +53,7 @@ beforeEach(() => {
});
afterEach(() => {
act(() => {
closeSettings();
useSettingsDialog.setState({ projectStructureOpen: false });
});
act(() => useSettingsDialog.setState({ open: false, projectStructureOpen: false }));
act(hideContextMenu);
dispose();
});
@@ -85,32 +72,6 @@ async function openDialog(page?: string) {
}
describe("Settings dialog", () => {
it("copies the current Settings page path through the IDEA action", async () => {
expect(getAction("settings.copyPath")).toMatchObject({
title: "Copy Settings Path",
description: "Copy the relative path to the selected configurable option",
category: "Settings",
when: "settingsOpen",
});
expect(resolveActionId("CopySettingsPath")).toBe("settings.copyPath");
expect(await executeAction("settings.copyPath")).toBe(false);
expect(writeClipboardText).not.toHaveBeenCalled();
await openDialog("editor.font");
await act(async () => expect(await executeAction("settings.copyPath")).toBe(true));
expect(writeClipboardText).toHaveBeenCalledWith("Settings | Editor | Font");
expect(await copySettingsPath("missing.page")).toBe(false);
expect(writeClipboardText).toHaveBeenCalledTimes(1);
});
it("offers Copy Settings Path in the page tree context menu", async () => {
const dialog = await openDialog("editor.font");
render(<ContextMenuHost />);
fireEvent.contextMenu(within(dialog).getByRole("treeitem", { name: "Font" }), { button: 2 });
fireEvent.click(await screen.findByRole("menuitem", { name: "Copy Settings Path" }));
await vi.waitFor(() => expect(writeClipboardText).toHaveBeenCalledWith("Settings | Editor | Font"));
});
it("offers new window, current window, a new tab and ask, but not attach", async () => {
current = setAt(current, "general.openProjectIn", "attach");
const dialog = await openDialog("general");
@@ -824,68 +785,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 +816,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 -42
Переглянути файл
@@ -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);
}
});
});
-27
Переглянути файл
@@ -1,24 +1,9 @@
import type { Action } from "@/platform/actions";
import { writeClipboardText } from "@/platform/clipboard";
import { tx } from "@/platform/i18n";
import { useSettingsPages } from "@/workbench/contributions";
import { breadcrumb, buildPageTree } from "./model/pages";
import { useSettingsDialog } from "./model/staging";
import { nativeToAsciiAction } from "./nativeToAscii";
/** Java's page first: JDK, Maven and the language server are what new projects most often need. */
export const NEW_PROJECTS_PAGE = "languages.java";
export async function copySettingsPath(pageId?: string): Promise<boolean> {
const state = useSettingsDialog.getState();
if (!state.open) return false;
const tree = buildPageTree(useSettingsPages.getState().pages.values());
const names = breadcrumb(tree, pageId ?? state.pageId);
if (!names.length) return false;
await writeClipboardText([tx("Settings"), ...names.map((name) => tx(name))].join(" | "));
return true;
}
export function settingsActions(open: (page?: string, newProjects?: boolean) => void | Promise<void>): Action[] {
return [
nativeToAsciiAction(),
@@ -30,18 +15,6 @@ export function settingsActions(open: (page?: string, newProjects?: boolean) =>
keywords: ["preferences", "options", "configure"],
run: ({ arg }) => open(typeof arg === "string" ? arg : undefined),
},
{
id: "settings.copyPath",
title: "Copy Settings Path",
description: "Copy the relative path to the selected configurable option",
category: "Settings",
keywords: ["copy option path", "settings path", "breadcrumb"],
when: "settingsOpen",
enabled: () => useSettingsDialog.getState().open,
run: async ({ arg }) => {
await copySettingsPath(typeof arg === "string" ? arg : undefined);
},
},
{
id: "file.newProjectsSettings",
title: "Settings for New Projects…",
+1 -3
Переглянути файл
@@ -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. */
-8
Переглянути файл
@@ -8,7 +8,6 @@
*/
import { useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
import {
SettingsFormContext,
@@ -24,7 +23,6 @@ import {
Icon,
IconButton,
SearchField,
showContextMenu,
Spinner,
SplitGroup,
SplitHandle,
@@ -359,12 +357,6 @@ export function SettingsLayout() {
indent={16}
selected={current ? new Set([current.key]) : new Set()}
onSelectionChange={(_sel, node) => node && selectPage(node.key)}
onContextMenu={(node, _selected, event) => {
if (!node) return;
showContextMenu(event, [
{ label: tx("Copy Settings Path"), run: () => void executeAction("settings.copyPath", node.key) },
]);
}}
multiSelect={false}
speedSearch={false}
empty={
+84 -239
Переглянути файл
@@ -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")} />
-8
Переглянути файл
@@ -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;
+1 -14
Переглянути файл
@@ -5,7 +5,6 @@
*/
import { create } from "zustand";
import { overrideActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { call, commands, isTauri, type Settings } from "@/platform/ipc";
import { loadSettings, useProject } from "@/platform/project";
import { lastSettingsPage, rememberSettingsPage } from "./lastPage";
@@ -58,7 +57,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 +99,6 @@ export const useSettingsDialog = create<SettingsDialogState>(() => ({
open: false,
projectStructureOpen: false,
projectStructureSection: "project",
projectStructureQuery: "",
projectStructureModule: null,
pageId: DEFAULT_PAGE,
focus: null,
@@ -151,19 +148,13 @@ export function openSettings(pageId?: string, opts: { newProjects?: boolean; glo
saving: false,
error: null,
});
setContext("settingsOpen", true);
if (!newProjects) rememberSettingsPage(target.pageId);
if (!opts.globalBase) void loadGlobalBase();
}
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 +163,6 @@ export function openProjectStructure(section?: string, module: string | null = n
open: false,
projectStructureOpen: true,
projectStructureSection: parseProjectStructureSection(section),
projectStructureQuery: "",
projectStructureModule: module,
base,
globalBase: base,
@@ -184,7 +174,6 @@ export function openProjectStructure(section?: string, module: string | null = n
saving: false,
error: null,
});
setContext("settingsOpen", false);
void loadGlobalBase();
}
@@ -207,7 +196,6 @@ export function openModuleSettings(path?: string) {
export function closeProjectStructure() {
useSettingsDialog.setState({
projectStructureOpen: false,
projectStructureQuery: "",
projectStructureModule: null,
staged: {},
stagedSecrets: {},
@@ -261,7 +249,6 @@ export function closeSettings() {
saving: false,
pagesLoading: false,
});
setContext("settingsOpen", false);
}
let disposePageHistoryActions: (() => void) | null = null;
+1 -5
Переглянути файл
@@ -12,16 +12,12 @@
align-items: center;
gap: var(--space-2);
}
/* The wrapper that turns the Folders list off is the row's flex item, so it fills the row for the list. */
.folders {
flex: 1;
min-width: 0;
}
/* Framed like the Folders list above it; rows as in the status bar's Background Projects popup. */
.projects {
display: flex;
flex-direction: column;
width: 100%;
max-width: 480px;
min-width: 0;
margin: 0;
padding: 0;
-13
Переглянути файл
@@ -819,9 +819,6 @@ const SMART_KEYS = editorPage({
"whitespace",
"indent",
"semicolon",
"case",
"snake case",
"camel case",
],
sections: [
{
@@ -916,16 +913,6 @@ const SMART_KEYS = editorPage({
},
],
},
{
title: "Cycle Identifier Case",
items: [
{ t: "check", key: `${P}.smartKeys.cycleCase.snake`, label: "snake_case" },
{ t: "check", key: `${P}.smartKeys.cycleCase.screaming`, label: "SCREAMING_SNAKE_CASE" },
{ t: "check", key: `${P}.smartKeys.cycleCase.kebab`, label: "kebab-case" },
{ t: "check", key: `${P}.smartKeys.cycleCase.camel`, label: "camelCase" },
{ t: "check", key: `${P}.smartKeys.cycleCase.pascal`, label: "PascalCase" },
],
},
],
});
+1 -3
Переглянути файл
@@ -1,5 +1,4 @@
/** Built-in MCP server status and client configurations. */
import clsx from "clsx";
import { useEffect, useState } from "react";
import { commands, call, isTauri, onIdeEvent, type McpServerStatus } from "@/platform/ipc";
import { backgroundProjectState, unloadBackgroundProject, useBackgroundProjects } from "@/platform/mcpBackground";
@@ -180,9 +179,8 @@ function BackgroundFolders() {
const off = useBackgroundOff();
return (
<Row label="Folders" stacked disabled={off} hint="Served without a window.">
<div inert={off} className={clsx(styles.folders, off && styles.off)}>
<div inert={off} className={off ? styles.off : undefined}>
<GlobListEditor
fullWidth
value={paths}
onChange={setPaths}
placeholder="/path/to/project"
+2 -6
Переглянути файл
@@ -1,7 +1,7 @@
import { useEffect, useMemo, type ReactNode } from "react";
import type { EditorInput } from "@/workbench/contributions";
import { LogIdContext, LogOptionsContext } from "./logContext";
import { applicationLogOptions, rootLogOptions } from "./logOptions";
import { rootLogOptions } from "./logOptions";
import { ensureEditorLog, focusLogView, parkedLogOptions, useRootGitLog } from "./logStore";
import { LogView } from "./GitLog";
import styles from "./GitLog.module.css";
@@ -9,11 +9,7 @@ import styles from "./GitLog.module.css";
export function LogScope({ id, children }: { id: string; children: ReactNode }) {
const active = useRootGitLog((s) => s.shownLog);
const options = rootLogOptions();
const value = useMemo(() => {
if (active === id) return options;
const parked = parkedLogOptions(id);
return parked ? { ...parked, ...applicationLogOptions(options) } : options;
}, [active, id, options]);
const value = useMemo(() => (active === id ? options : (parkedLogOptions(id) ?? options)), [active, id, options]);
const focus = () => {
if (useRootGitLog.getState().shownLog !== id) focusLogView(id);
};
+3 -4
Переглянути файл
@@ -1,18 +1,17 @@
/** Settings › Version Control › Log: how the Git Log shows references, dates and columns. */
import { useId, type ReactNode } from "react";
import { Checkbox, T } from "@/ui";
import { setLogOptions, useLogOptions, type ApplicationLogOptions } from "./logOptions";
import { setLogOptions, useLogOptions, type LogOptions } from "./logOptions";
import styles from "./LogSettingsPage.module.css";
type Flag = {
[K in keyof ApplicationLogOptions]: ApplicationLogOptions[K] extends boolean ? K : never;
}[keyof ApplicationLogOptions];
type Flag = { [K in keyof LogOptions]: LogOptions[K] extends boolean ? K : never }[keyof LogOptions];
const OPTIONS: { key: Flag; label: string }[] = [
{ key: "compactRefs", label: "Show only the first reference" },
{ key: "tagNames", label: "Show tag names" },
{ key: "commitTimestamp", label: "Show commit time rather than author time" },
{ key: "refsOnLeft", label: "Show references on the left" },
{ key: "showLineStats", label: "Show lines added and deleted" },
];
const COLUMNS: { key: Flag; label: string }[] = [
+3 -12
Переглянути файл
@@ -145,19 +145,10 @@ describe("log options", () => {
expect(setLogOptions({ diffPreview: false })).toBe(false);
});
it("reloads only for options that change the query and persists only application-level properties", () => {
it("reloads only for options that change the query", () => {
expect(setLogOptions({ compactRefs: false })).toBe(false);
expect(setLogOptions({ noMerges: true, showHash: true })).toBe(true);
const stored = JSON.parse(localStorage.getItem("openidea.vcs.logOptions")!);
expect(stored).toMatchObject({ compactRefs: false, showHash: true });
expect(stored).not.toHaveProperty("noMerges");
});
it("applies application settings from another window without replacing the active tab's options", () => {
setLogOptions({ noMerges: true });
localStorage.setItem("openidea.vcs.logOptions", JSON.stringify({ compactRefs: false }));
window.dispatchEvent(new StorageEvent("storage", { key: "openidea.vcs.logOptions" }));
expect(useLogOptions.getState()).toMatchObject({ noMerges: true, compactRefs: false });
expect(setLogOptions({ noMerges: true })).toBe(true);
expect(JSON.parse(localStorage.getItem("openidea.vcs.logOptions")!).noMerges).toBe(true);
});
it("sends the graph options and the date range to the backend", async () => {
+2
Переглянути файл
@@ -530,5 +530,7 @@ describe("Settings › Version Control › Log", () => {
expect(useLogOptions.getState().tagNames).toBe(!DEFAULT_LOG_OPTIONS.tagNames);
fireEvent.click(screen.getByLabelText("Hash"));
expect(useLogOptions.getState().showHash).toBe(!DEFAULT_LOG_OPTIONS.showHash);
fireEvent.click(screen.getByLabelText("Show lines added and deleted"));
expect(useLogOptions.getState().showLineStats).toBe(true);
});
});
-51
Переглянути файл
@@ -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([]);
});
});
+10 -15
Переглянути файл
@@ -58,12 +58,8 @@ afterEach(async () => {
function Probe({ name }: { name: string }) {
const text = useGitLog((s) => s.filters.text);
const longEdges = useLogOptions((s) => s.longEdges);
return (
<button
onClick={() => setLogFilters({ text: `${name} edited` })}
>{`${name}: ${text} / long edges ${longEdges}`}</button>
);
const hash = useLogOptions((s) => s.showHash);
return <button onClick={() => setLogFilters({ text: `${name} edited` })}>{`${name}: ${text} / hash ${hash}`}</button>;
}
describe("independent log views", () => {
@@ -71,7 +67,7 @@ describe("independent log views", () => {
setLogFilters({ text: "main" });
const other = openLogTab("log", "Other");
setLogFilters({ text: "other" });
updateLogOptions({ longEdges: true });
updateLogOptions({ showHash: true });
selectGitTab("log");
render(
<>
@@ -83,16 +79,16 @@ describe("independent log views", () => {
</LogScope>
</>,
);
expect(screen.getByText("main: main / long edges false")).toBeInTheDocument();
expect(screen.getByText("other: other / long edges true")).toBeInTheDocument();
const button = screen.getByText("other: other / long edges true");
expect(screen.getByText("main: main / hash false")).toBeInTheDocument();
expect(screen.getByText("other: other / hash true")).toBeInTheDocument();
const button = screen.getByText("other: other / hash true");
await act(async () => {
fireEvent.pointerDown(button);
fireEvent.click(button);
});
expect(useGitLog.getState().shownLog).toBe(other);
expect(screen.getByText("main: main / long edges false")).toBeInTheDocument();
expect(screen.getByText("other: other edited / long edges true")).toBeInTheDocument();
expect(screen.getByText("main: main / hash false")).toBeInTheDocument();
expect(screen.getByText("other: other edited / hash true")).toBeInTheDocument();
});
it("restores each tab's filters and options after leaving and reopening the project", async () => {
@@ -109,9 +105,8 @@ describe("independent log views", () => {
selected: "/repo\0expanded",
selection: ["/repo\0expanded"],
});
updateLogOptions({ longEdges: true, diffLocation: "bottom" });
updateLogOptions({ showHash: true, diffLocation: "bottom" });
selectGitTab("log");
expect(useLogOptions.getState()).toMatchObject({ longEdges: false, diffLocation: "bottom" });
await reloadLog();
useVcs.setState({ root: "/another", repo: "/another", roots: ["/another"] });
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
@@ -119,7 +114,7 @@ describe("independent log views", () => {
expect(useGitLog.getState().fragments.expanded.size).toBe(0);
selectGitTab(other);
expect(useGitLog.getState().filters).toMatchObject({ paths: ["/repo/src"], branches: ["feature/.*"] });
expect(useLogOptions.getState()).toMatchObject({ longEdges: true, diffLocation: "bottom" });
expect(useLogOptions.getState()).toMatchObject({ showHash: true, diffLocation: "bottom" });
expect([...useGitLog.getState().fragments.expanded]).toEqual(["/repo\0expanded"]);
expect([...useGitLog.getState().fragments.collapsed]).toEqual(["/repo\0collapsed"]);
expect([...useGitLog.getState().fragments.merges]).toEqual(["/repo\0merge"]);
+2 -108
Переглянути файл
@@ -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();
+1 -32
Переглянути файл
@@ -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 });
+4 -13
Переглянути файл
@@ -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);
-37
Переглянути файл
@@ -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");
},
},
};
}
+7 -11
Переглянути файл
@@ -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):",
});
-41
Переглянути файл
@@ -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();
}
+11 -46
Переглянути файл
@@ -86,24 +86,6 @@ export const DEFAULT_LOG_OPTIONS: LogOptions = {
/** Options that change which commits the backend returns (a reload is needed). */
export const QUERY_OPTIONS: ReadonlyArray<keyof LogOptions> = ["sort", "firstParent", "noMerges"];
const APPLICATION_LOG_OPTION_KEYS = [
"compactRefs",
"tagNames",
"commitTimestamp",
"refsOnLeft",
"showAuthor",
"showDate",
"showHash",
"showSignature",
"showGitHubChecks",
"diffPreview",
"changesFromParents",
"diffLocation",
"columnOrder",
] as const satisfies readonly (keyof LogOptions)[];
export type ApplicationLogOptions = Pick<LogOptions, (typeof APPLICATION_LOG_OPTION_KEYS)[number]>;
const KEY = "openidea.vcs.logOptions";
export function parseLogOptions(raw: unknown): LogOptions {
@@ -130,20 +112,16 @@ export function parseLogOptions(raw: unknown): LogOptions {
return out;
}
function pickApplicationOptions(options: LogOptions): ApplicationLogOptions {
return Object.fromEntries(APPLICATION_LOG_OPTION_KEYS.map((key) => [key, options[key]])) as ApplicationLogOptions;
}
function loadApplicationOptions(): ApplicationLogOptions {
function load(): LogOptions {
try {
const raw = localStorage.getItem(KEY);
return pickApplicationOptions(parseLogOptions(raw ? JSON.parse(raw) : null));
return parseLogOptions(raw ? JSON.parse(raw) : null);
} catch {
return pickApplicationOptions(DEFAULT_LOG_OPTIONS);
return { ...DEFAULT_LOG_OPTIONS };
}
}
export const rootLogOptions = create<LogOptions>(() => ({ ...DEFAULT_LOG_OPTIONS, ...loadApplicationOptions() }));
export const rootLogOptions = create<LogOptions>(() => load());
export const useLogOptions = Object.assign(function useScopedLogOptions<T = LogOptions>(
selector?: (state: LogOptions) => T,
): T {
@@ -151,25 +129,13 @@ export const useLogOptions = Object.assign(function useScopedLogOptions<T = LogO
return rootLogOptions((state) => (selector ? selector(scoped ?? state) : ((scoped ?? state) as T)));
}, rootLogOptions);
export function applicationLogOptions(options: LogOptions = rootLogOptions.getState()): ApplicationLogOptions {
return pickApplicationOptions(options);
}
export function withApplicationLogOptions(options: Partial<LogOptions>): LogOptions {
return { ...DEFAULT_LOG_OPTIONS, ...options, ...applicationLogOptions() };
}
export function setActiveLogOptions(options: Partial<LogOptions>): void {
rootLogOptions.setState(withApplicationLogOptions(options));
}
// Settings › Version Control › Log edits them from the Settings window too.
if (typeof window !== "undefined")
window.addEventListener("storage", (e) => {
if (e.key === KEY) rootLogOptions.setState((state) => ({ ...state, ...loadApplicationOptions() }));
if (e.key === KEY) useLogOptions.setState(load());
});
export const logOptions = () => rootLogOptions.getState();
export const logOptions = () => useLogOptions.getState();
export type RefKind = "head" | "local" | "remote" | "tag";
@@ -218,14 +184,13 @@ export function refLabels(
return out;
}
/** Updates options and persists application-level properties; returns whether the log has to be reloaded. */
/** Updates options and persists them; returns whether the log has to be reloaded. */
export function setLogOptions(patch: Partial<LogOptions>): boolean {
const before = rootLogOptions.getState();
const after = { ...before, ...patch };
rootLogOptions.setState(after);
const before = useLogOptions.getState();
useLogOptions.setState(patch);
const after = useLogOptions.getState();
try {
// Per-tab properties are saved in the log session, not in the application store.
localStorage.setItem(KEY, JSON.stringify(applicationLogOptions(after)));
localStorage.setItem(KEY, JSON.stringify(after));
} catch {
// Storage unavailable: the options last for this session.
}
+11 -27
Переглянути файл
@@ -9,15 +9,7 @@ import { tx } from "@/platform/i18n";
import type { Branch, BranchInfo, Commit, LogQuery } from "@/bindings";
import { call, commands, nextRequestId, type RequestId } from "@/platform/ipc";
import { workflowSettings } from "@/platform/workflowSettings";
import {
logOptions,
parseLogOptions,
setActiveLogOptions,
setLogOptions,
useLogOptions,
withApplicationLogOptions,
type LogOptions,
} from "./logOptions";
import { logOptions, parseLogOptions, setLogOptions, useLogOptions, type LogOptions } from "./logOptions";
import { clearConsole, errorMessage } from "./ops";
import { currentRepo, currentRepoRoot, repoName, repoOf, useVcs } from "./store";
import { chooseLogCommit } from "./CommitChooser";
@@ -390,7 +382,6 @@ function freshView(filters: LogFilters): LogView {
/** Views of the log tabs not shown now. */
const parked = new Map<string, LogView>();
let switchingLogView = false;
function currentView(): LogView {
const {
@@ -447,19 +438,12 @@ function setViewState(id: string, patch: Partial<LogState> | ((state: LogState)
function showLogView(id: string) {
const s = useGitLog.getState();
if (s.shownLog === id) return;
switchingLogView = true;
try {
parked.set(s.shownLog, currentView());
const view = parked.get(id) ?? freshView(emptyFilters());
parked.delete(id);
const { options, ...state } = view;
useGitLog.setState({ ...state, shownLog: id });
setActiveLogOptions(options);
} finally {
switchingLogView = false;
}
saveLogSession(useVcs.getState().root);
const view = logState(id);
parked.set(s.shownLog, currentView());
const view = parked.get(id) ?? freshView(emptyFilters());
parked.delete(id);
const { options, ...state } = view;
setLogOptions(options);
useGitLog.setState({ ...state, shownLog: id });
if (!view.commits.length && !view.done && !view.loading) void reloadLog();
}
@@ -642,7 +626,7 @@ export function installGitLog(): () => void {
const comparisons = new Set(logTabs.filter((tab) => tab.comparison).map((tab) => tab.id));
for (const [id, view] of parked) {
if (comparisons.has(id)) void reloadLog({ preserve: true }, id);
else parked.set(id, { ...freshView(view.filters), options: withApplicationLogOptions(view.options) });
else parked.set(id, { ...freshView(view.filters), options: view.options });
}
void reloadLog({ preserve: comparisons.has(shownLog) });
}
@@ -715,7 +699,7 @@ function parseFilters(value: unknown): LogFilters {
}
function saveLogSession(root: string | null) {
if (!root || restoring || switchingLogView) return;
if (!root || restoring) return;
const state = useGitLog.getState();
const views = new Map(parked).set(state.shownLog, currentView());
try {
@@ -773,7 +757,7 @@ function restoreLogSession(root: string | null) {
tabs.find((tab) => tab.id === view.id),
),
),
options: withApplicationLogOptions(parseLogOptions(view.options)),
options: parseLogOptions(view.options),
fragments: parseFragments(view.fragments),
selected: typeof view.selected === "string" ? view.selected : null,
selection: Array.isArray(view.selection)
@@ -788,7 +772,7 @@ function restoreLogSession(root: string | null) {
const view = parked.get(id) ?? freshView(emptyFilters());
parked.delete(id);
const { options, ...state } = view;
setActiveLogOptions(options);
setLogOptions(options);
const bookmarks =
value.bookmarks && typeof value.bookmarks === "object"
? Object.fromEntries(
+2 -10
Переглянути файл
@@ -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");
+4 -10
Переглянути файл
@@ -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;
}
-7
Переглянути файл
@@ -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();
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more