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

..
Автор SHA1 Повідомлення Дата
l0ng-ai c9fbe5a808 feat(terminal): activate the project's conda environment in new terminals
Tools › Terminal › Activate virtualenv only knew venvs (pyvenv.cfg and
their activate scripts). A conda interpreter has neither, so the terminal
stayed in the shell's own (base) environment. New terminals now run
conda activate <prefix> through the installation's shell hook for cmd,
PowerShell, bash, zsh, POSIX shells and fish, finding the installation
from the env itself (base), the parent of envs/, CONDA_EXE or PATH.

Fixes #2697
2026-11-11 21:10:31 +08:00
66 змінених файлів з 430 додано та 1744 видалено

No files matched your search

-3
Переглянути файл
@@ -261,9 +261,6 @@ pub enum WhileRunning {
pub struct McpServerSettings {
/// Serve the tools on 127.0.0.1 while the IDE runs.
pub enabled: bool,
/// Run the tools that change the project or start processes without asking first
/// (IDEA's brave mode). Read from the IDE's own settings only, never a project's.
pub run_without_confirmation: bool,
}
/// Absent profiles retain automatic discovery for existing projects.
-12
Переглянути файл
@@ -342,16 +342,4 @@ mod tests {
assert_eq!(error_message(&msg), "cannot find a.py");
assert_eq!(error_message(&json!({"message": "nope"})), "nope");
}
#[test]
fn a_failed_launch_response_keeps_delves_too_old_error_verbatim() {
// The UI's repair offer keys off this exact wording (`missingAdapter`), so the
// conversion to the IPC error must not fold it into a generic message.
let message = "Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 \
(maximum supported version 1.26, suppress this error with --check-go-version=false)";
let e = ide_core::IdeError::from(DapError::Failed { command: "launch".into(), message: message.into() });
assert_eq!(e.kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(e.message, format!("launch failed: {message}"));
assert!(e.message.contains("Version of Delve is too old for Go version go1.27.0"));
}
}
+17 -44
Переглянути файл
@@ -136,19 +136,24 @@ pub struct DockerRegistry {
pub username: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerSettings {
#[serde(default)]
#[serde(default = "default_connections")]
pub connections: Vec<DockerConnection>,
#[serde(default)]
pub registries: Vec<DockerRegistry>,
}
/// Whether `c` is the connection older versions injected when nothing was configured:
/// Services lists only connections the user added, so this one is dropped on load.
fn is_injected_default(c: &DockerConnection) -> bool {
c.id == "default" && c.name == "Docker" && c.endpoint == DockerEndpoint::Default
impl Default for DockerSettings {
fn default() -> Self {
Self { connections: default_connections(), registries: Vec::new() }
}
}
/// Before anything is configured the CLI's own daemon is shown, as before connections existed.
fn default_connections() -> Vec<DockerConnection> {
vec![DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default }]
}
const SETTINGS_FILE: &str = "docker.json";
@@ -156,17 +161,10 @@ const PASSWORDS_FILE: &str = "docker-passwords.json";
pub fn load_settings(data_dir: &Path) -> DockerSettings {
match std::fs::read(data_dir.join(SETTINGS_FILE)) {
// A file written before the opt-in Services rework carries the injected default
// (saved along with a registry or another connection); drop it unless edited.
Ok(bytes) => serde_json::from_slice(&bytes)
.map(|mut s: DockerSettings| {
s.connections.retain(|c| !is_injected_default(c));
s
})
.unwrap_or_else(|e| {
tracing::warn!("{SETTINGS_FILE}: {e}");
DockerSettings::default()
}),
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
tracing::warn!("{SETTINGS_FILE}: {e}");
DockerSettings::default()
}),
Err(_) => DockerSettings::default(),
}
}
@@ -375,8 +373,7 @@ mod tests {
fn settings_round_trip_and_passwords() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
// Nothing configured: no connection is invented.
assert!(load_settings(dir).connections.is_empty());
assert_eq!(load_settings(dir).connections[0].endpoint, DockerEndpoint::Default);
let settings = DockerSettings {
connections: vec![DockerConnection {
id: "c1".into(),
@@ -398,32 +395,8 @@ mod tests {
assert!(auth_for(dir, "postgres").is_none());
save_settings(dir, &DockerSettings { registries: Vec::new(), ..settings }).unwrap();
assert_eq!(registry_password(dir, "r1"), None);
// An empty list stays empty.
// An empty list stays empty (the default connection is only for a missing file).
save_settings(dir, &DockerSettings { connections: Vec::new(), registries: Vec::new() }).unwrap();
assert!(load_settings(dir).connections.is_empty());
}
#[test]
fn load_drops_the_injected_default_connection() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let injected =
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
let registry =
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
save_settings(dir, &DockerSettings { connections: vec![injected()], registries: vec![registry.clone()] })
.unwrap();
let loaded = load_settings(dir);
assert!(loaded.connections.is_empty());
assert_eq!(loaded.registries, vec![registry]);
// A connection the user renamed or re-pointed stays theirs.
let renamed = DockerConnection { name: "Local engine".into(), ..injected() };
save_settings(dir, &DockerSettings { connections: vec![renamed.clone()], registries: Vec::new() }).unwrap();
assert_eq!(load_settings(dir).connections, vec![renamed]);
let repointed =
DockerConnection { endpoint: DockerEndpoint::Socket { path: "/var/run/docker.sock".into() }, ..injected() };
save_settings(dir, &DockerSettings { connections: vec![repointed.clone()], registries: Vec::new() }).unwrap();
assert_eq!(load_settings(dir).connections, vec![repointed]);
}
}
-5
Переглянути файл
@@ -51,12 +51,7 @@ impl Call {
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
self.host.mcp_requests.ask(self, request).await
}
/// Asks the user before a tool changes the project or starts a process, unless brave mode
/// is on — read from the IDE's own settings only, which a project's settings can't set.
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
if self.host.global_settings.effective().mcp_server.run_without_confirmation {
return self.project.require_trust();
}
self.ask(ide_core::event::McpUiRequest::Confirm {
client: self.client.clone(),
tool: self.tool.clone(),
+34 -139
Переглянути файл
@@ -71,12 +71,6 @@ pub trait PluginWorkspace: Send + Sync {
/// Roots of the open projects.
fn projects(&self) -> Vec<PathBuf>;
/// Roots of the workspace members attached to the project at `root` (a
/// project window group's folders, as the editor and LSP resolve them).
/// Empty for a plain project.
fn member_roots(&self, _root: &Path) -> Vec<PathBuf> {
Vec::new()
}
/// Unsaved text of the open document at `path`.
fn buffer_text(&self, path: &Path) -> Option<String>;
/// A window's unsaved text, with the normal project overlay as fallback.
@@ -2025,10 +2019,6 @@ impl HostApi for PluginApi {
self.shared.workspace().map(|w| w.projects()).unwrap_or_default()
}
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
self.shared.workspace().map(|w| w.member_roots(root)).unwrap_or_default()
}
fn buffer_text(&self, path: &Path) -> Option<String> {
self.shared.workspace()?.buffer_text(path)
}
@@ -2169,29 +2159,23 @@ impl HostApi for PluginApi {
out.sort();
return Ok(out);
}
// A project window group's members are project scope too (their files
// are in the group's index, and a group root holds none of them).
let mut roots = vec![root.to_path_buf()];
roots.extend(self.member_roots(root));
let mut out = Vec::new();
'walk: for root in &roots {
for (n, entry) in ignore::WalkBuilder::new(root)
.hidden(false)
.filter_entry(|e| e.file_name() != ".git")
.build()
.flatten()
.enumerate()
{
if n >= MAX_WALK || out.len() >= limit {
break 'walk;
}
if !entry.file_type().is_some_and(|t| t.is_file()) {
continue;
}
let Ok(rel) = entry.path().strip_prefix(root) else { continue };
if matcher.is_match(rel) {
out.push(to_ipc(entry.path()));
}
for (n, entry) in ignore::WalkBuilder::new(root)
.hidden(false)
.filter_entry(|e| e.file_name() != ".git")
.build()
.flatten()
.enumerate()
{
if n >= MAX_WALK || out.len() >= limit {
break;
}
if !entry.file_type().is_some_and(|t| t.is_file()) {
continue;
}
let Ok(rel) = entry.path().strip_prefix(root) else { continue };
if matcher.is_match(rel) {
out.push(to_ipc(entry.path()));
}
}
out.sort();
@@ -2908,26 +2892,11 @@ impl HostWorkspace {
.and_then(|w| host.project(w).ok())
.filter(|p| p.root == root)
.or_else(|| host.windows_for_root(root).first().and_then(|w| host.project(w).ok()))
// A project window group's member root: its files belong to the
// group's project, like everywhere else in the editor.
.or_else(|| {
host.projects()
.into_iter()
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| m.as_path() == root))
})
}
fn projects(&self) -> Vec<Arc<crate::project::Project>> {
self.0.upgrade().map(|h| h.projects()).unwrap_or_default()
}
/// The open project whose workspace group contains `root` (the group root
/// itself matches `p.root == root` and needs no member lookup).
fn project_covering(&self, root: &Path) -> Option<Arc<crate::project::Project>> {
self.projects().into_iter().find(|p| {
p.root == root || crate::project::workspace_member_roots(&p.root).iter().any(|m| m.as_path() == root)
})
}
/// The project holding an open document at `path`, and its id.
fn open_document(&self, path: &Path) -> Option<(Arc<crate::project::Project>, ide_core::DocId)> {
self.projects().into_iter().find_map(|p| p.documents.by_path(path).map(|doc| (p, doc)))
@@ -3017,10 +2986,6 @@ impl PluginWorkspace for HostWorkspace {
) -> Result<ide_plugin::TextSearch, HostError> {
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
let project = self.project_for(client, root).ok_or_else(|| HostError::NotFound("project closed".into()))?;
// Matches must land in the project root or, for a project window group,
// in any of its members.
let mut roots = vec![root.to_path_buf()];
roots.extend(crate::project::workspace_member_roots(root));
if limit == 0 {
return Ok(ide_plugin::TextSearch::default());
}
@@ -3050,9 +3015,8 @@ impl PluginWorkspace for HostWorkspace {
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
// Restrict project.read to the project root and its workspace
// members, including symlink targets.
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &to_ipc(&file.path.0)) else {
// Restrict project.read to the project root, including symlink targets.
let Ok(path) = ide_plugin::resolve_in_root(root, &to_ipc(&file.path.0)) else {
continue;
};
let text = project.documents.text_of(&path).or_else(|| {
@@ -3118,19 +3082,12 @@ impl PluginWorkspace for HostWorkspace {
}
fn projects(&self) -> Vec<PathBuf> {
let mut roots: Vec<PathBuf> = HostWorkspace::projects(self)
.iter()
.flat_map(|p| std::iter::once(p.root.clone()).chain(crate::project::workspace_member_roots(&p.root)))
.collect();
let mut roots: Vec<PathBuf> = HostWorkspace::projects(self).iter().map(|p| p.root.clone()).collect();
roots.sort();
roots.dedup();
roots
}
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
crate::project::workspace_member_roots(root)
}
fn buffer_text(&self, path: &Path) -> Option<String> {
HostWorkspace::projects(self).iter().find_map(|p| p.documents.text_of(path))
}
@@ -3141,9 +3098,9 @@ impl PluginWorkspace for HostWorkspace {
}
fn indexed_files(&self, root: &Path, matches: &dyn Fn(&Path) -> bool, limit: usize) -> Option<Vec<PathBuf>> {
// The index covering `root`: the project rooted there, or the workspace
// group project whose member it is (a member's files are in the group's).
HostWorkspace::project_covering(self, root)?.index.files_matching(root, matches, limit)
// The index of the project rooted at `root` (a workspace member's files are in its own).
let project = HostWorkspace::projects(self).into_iter().find(|p| p.root == root)?;
project.index.files_matching(root, matches, limit)
}
fn symbols(
@@ -3154,7 +3111,9 @@ impl PluginWorkspace for HostWorkspace {
cancel: &CancellationToken,
deadline: Instant,
) -> Result<Vec<ide_plugin::SymbolInfo>, HostError> {
let project = HostWorkspace::project_covering(self, root)
let project = HostWorkspace::projects(self)
.into_iter()
.find(|p| p.root == root)
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?;
let stopped = || cancel.is_cancelled() || Instant::now() >= deadline;
let interrupted = || {
@@ -3164,13 +3123,15 @@ impl PluginWorkspace for HostWorkspace {
HostError::Failed("symbol search timed out".into())
}
};
// The symbols of the requested root and, for a project window group, of
// its members (a member's symbols are in the group's index).
let members = crate::project::workspace_member_roots(root);
let in_scope = |path: &Path| path.starts_with(root) || members.iter().any(|m| path.starts_with(m));
let symbols = project
.index
.find_symbols_until(query, ide_index::SymbolFilter::All, limit.min(1000), &in_scope, &stopped)
.find_symbols_until(
query,
ide_index::SymbolFilter::All,
limit.min(1000),
&|path| path.starts_with(root),
&stopped,
)
.ok_or_else(interrupted)?;
let mut out = Vec::new();
for s in symbols {
@@ -3212,8 +3173,7 @@ impl PluginWorkspace for HostWorkspace {
}
fn trusted(&self, root: &Path) -> bool {
// A workspace member is as trusted as the group's project it was opened with.
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
HostWorkspace::projects(self).iter().any(|p| p.root == root && p.is_trusted())
}
fn project_of(&self, window: &str) -> Option<PathBuf> {
@@ -3238,12 +3198,6 @@ impl PluginWorkspace for HostWorkspace {
.iter()
.filter(|p| path.starts_with(&p.root))
.max_by_key(|p| p.root.as_os_str().len())
// A project window group's member files report through the group's project.
.or_else(|| {
projects
.iter()
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| path.starts_with(m)))
})
.ok_or_else(|| HostError::Invalid(format!("{} is not in an open project", path.display())))?;
project.sink.emit(ide_core::IdeEvent::Diagnostics {
path: path.to_path_buf().into(),
@@ -3258,25 +3212,15 @@ impl PluginWorkspace for HostWorkspace {
.into_iter()
.filter(|p| path.starts_with(&p.root))
.max_by_key(|p| p.root.as_os_str().len())
.or_else(|| {
HostWorkspace::projects(self)
.into_iter()
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| path.starts_with(m)))
})
.and_then(|p| p.vcs_encoding(path, None).ok())
.unwrap_or_else(|| encoding_rs::UTF_8.into())
}
fn plugin_settings(&self, plugin: &str, root: Option<&Path>) -> serde_json::Map<String, serde_json::Value> {
let Some(host) = self.0.upgrade() else { return serde_json::Map::new() };
// A member root reads the settings of the group's project, like the
// group's own root does.
let settings = match root.and_then(|r| host.projects().into_iter().find(|p| p.root == r)) {
Some(p) => p.settings.effective(),
None => match root.map(|r| HostWorkspace::project_covering(self, r)) {
Some(Some(p)) => p.settings.effective(),
_ => host.global_settings.effective(),
},
None => host.global_settings.effective(),
};
settings.plugins.get(plugin).cloned().unwrap_or_default()
}
@@ -3582,55 +3526,6 @@ mod tests {
);
}
/// A workspace whose container root has no files: the member holds them.
struct Members(PathBuf, Vec<PathBuf>);
impl PluginWorkspace for Members {
fn projects(&self) -> Vec<PathBuf> {
vec![self.0.clone()]
}
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
if root == self.0 { self.1.clone() } else { Vec::new() }
}
fn buffer_text(&self, _: &Path) -> Option<String> {
None
}
fn document(&self, _: &Path) -> Option<(u64, String)> {
None
}
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit]) -> Result<u64, HostError> {
Err(HostError::Stale)
}
fn trusted(&self, _: &Path) -> bool {
true
}
fn project_of(&self, _: &str) -> Option<PathBuf> {
None
}
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
Ok(())
}
}
#[test]
fn find_files_cover_workspace_members() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let (root, member) = (base.join("workspace"), base.join("member"));
std::fs::create_dir_all(root.join(".openidea")).unwrap();
std::fs::create_dir_all(member.join("src")).unwrap();
std::fs::write(root.join(".openidea/workspace.json"), "{}").unwrap();
std::fs::write(member.join("src/UserMapper.xml"), "<mapper/>").unwrap();
let api = api(&root, Arc::default());
*api.shared.workspace.write() = Some(Arc::new(Members(root.clone(), vec![member.clone()])));
// The container holds no sources: the member's files are project scope.
assert_eq!(api.find_files(&root, "**/*Mapper.xml", 10).unwrap(), [to_ipc(&member.join("src/UserMapper.xml"))]);
// A member root lists its own files, like any project root.
assert_eq!(api.find_files(&member, "src/*.xml", 10).unwrap(), [to_ipc(&member.join("src/UserMapper.xml"))]);
// And a path outside the group is never listed.
std::fs::write(base.join("OutsideMapper.xml"), "<mapper/>").unwrap();
assert!(api.find_files(&root, "**/*Mapper.xml", 10).unwrap().len() == 1);
}
#[test]
fn process_environment_only_adds_variables() {
let tmp = tempfile::tempdir().unwrap();
+2 -9
Переглянути файл
@@ -27,12 +27,8 @@ pub async fn plugin_navigation_files(
if files.len() > 20_000 {
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
}
// A project window group's members are project scope: their files are
// in the group's index (the group root holds none of them).
let members = crate::project::workspace_member_roots(&project.root);
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
Ok(NavigationFiles {
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
paths: files.into_iter().filter(|p| p.starts_with(&project.root)).map(Into::into).collect(),
indexing,
extensions,
})
@@ -68,14 +64,11 @@ pub async fn plugin_navigation_index(
if !project.is_trusted() {
return Err(IdeError::unavailable("project is not trusted"));
}
// A project window group's members are project scope.
let mut roots = vec![project.root.clone()];
roots.extend(crate::project::workspace_member_roots(&project.root));
for path in paths {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) else {
let Ok(path) = ide_plugin::resolve_in_root(&project.root, &path.to_string_lossy()) else {
continue;
};
let extensions = plugins.navigation_extensions(&project.root);
+1 -5
Переглянути файл
@@ -204,11 +204,7 @@ impl PluginHost {
if text.len() > MAX_DOCUMENT_BYTES {
return Err(IdeError::invalid("navigation document is too large"));
}
// A project window group's members are project scope: a member's file
// is indexed into the group's graph like any file of the group root.
let mut roots = vec![root.to_path_buf()];
roots.extend(crate::project::workspace_member_roots(root));
let real = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()).map_err(IdeError::invalid)?;
let real = ide_plugin::resolve_in_root(root, &path.to_string_lossy()).map_err(IdeError::invalid)?;
if real != path {
return Err(IdeError::invalid("navigation requires a canonical project path"));
}
-13
Переглянути файл
@@ -1188,19 +1188,6 @@ fn index_roots(root: &Path, folders: Vec<PathBuf>) -> ide_index::IndexRoots {
ide_index::IndexRoots { include_root: !container, folders: folders.into_iter().filter(|p| p != root).collect() }
}
/// The member roots of an explicit workspace container (empty for a plain
/// project): how the editor and the language servers resolve a file's own
/// project in a project window group. Also the roots the plugin surface may
/// reach into — see `plugins::api`.
pub(crate) fn workspace_member_roots(root: &Path) -> Vec<PathBuf> {
ide_workspace::workspace::Workspace::load(root)
.ok()
.flatten()
.filter(|w| w.is_container(root))
.map(|w| w.projects)
.unwrap_or_default()
}
/// Workspace members in manifest order, or extra Project Structure directories and the
/// Gradle project folders outside the project as of the last sync (`build_cache`).
fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cache: &Path) -> Vec<PathBuf> {
-37
Переглянути файл
@@ -416,40 +416,3 @@ async fn rust_references_and_rename_through_mcp() {
assert!(project.documents.text_snapshot(doc.id).unwrap().text.contains("format_amount"));
assert!(std::fs::read_to_string(h.root.join("src/main.rs")).unwrap().contains("format_amount"));
}
#[tokio::test(flavor = "multi_thread")]
async fn brave_mode_runs_tools_without_asking_only_from_the_global_settings() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let p = h.host.project("main").unwrap();
// A project's own settings can't turn the confirmations off.
let project_layer =
p.settings.set(ide_workspace::SettingsScope::Project, "mcpServer.runWithoutConfirmation", json!(true));
assert!(project_layer.is_err());
let denied = h.error("build_project", json!({}));
let answer = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, answer);
assert!(error.contains("denied by the user"), "{error}");
h.events.lock().unwrap().clear();
h.host
.global_settings
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
.unwrap();
let (host, root) = (h.host.clone(), h.root.clone());
let result = tokio::time::timeout(
std::time::Duration::from_secs(60),
tokio::task::spawn_blocking(move || {
Registry::new(host).call(&root, "build_project", "{}", CancellationToken::new())
}),
)
.await
.expect("ran without waiting for an answer")
.unwrap();
assert!(!format!("{result:?}").contains("denied"), "{result:?}");
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
-239
Переглянути файл
@@ -8,7 +8,6 @@
use ide_core::error::ErrorKind;
use ide_core::ipc_path::to_ipc;
use ide_host::plugins::*;
use ide_host::{Host, HostConfig};
use ide_plugin::{EditorContext, HostError, Invocation, Limits};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
@@ -6336,241 +6335,3 @@ fn api14_stage3_terminal_calls_are_denied_without_process_grants() {
f.host.set_capability("execution", "process:execution-tool", false).unwrap();
assert!(f.run("execution", "terminal", None).unwrap_err().contains("not granted"));
}
// ─── Project window groups ────────────────────────────────────────────────────
// A group's container root holds only `.openidea` metadata; the files live in
// the member projects. The plugin surface reaches them like the editor and the
// language servers do.
/// A real host over a project window group with the members `alpha` (holding a
/// nested `inner` member, for deepest resolution) and `beta`.
struct GroupFixture {
base: PathBuf,
host: Arc<Host>,
plugins: Arc<PluginHost>,
root: PathBuf,
alpha: PathBuf,
inner: PathBuf,
beta: PathBuf,
_runtime: tokio::runtime::Runtime,
_tmp: tempfile::TempDir,
}
impl GroupFixture {
fn new() -> Self {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let (root, alpha, beta) = (base.join("workspace"), base.join("alpha"), base.join("beta"));
let inner = alpha.join("inner");
for dir in [alpha.join("src"), inner.join("mappers"), beta.join("src")] {
std::fs::create_dir_all(dir).unwrap();
}
ide_workspace::workspace::Workspace::save(
&root,
"Group",
vec![alpha.clone(), inner.clone(), beta.clone()],
true,
)
.unwrap();
std::fs::write(alpha.join("src/needle.php"), "alpha needle\n").unwrap();
std::fs::write(inner.join("mappers/route.idx"), "def route:item\nref route:item\n").unwrap();
std::fs::write(beta.join("src/Notes.txt"), "beta needle\n").unwrap();
std::fs::write(base.join("secret.txt"), "top secret").unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: runtime.handle().clone(),
project_environment: false,
}));
for dir in [&root, &alpha, &beta] {
host.trust.decide(dir, true, false).unwrap();
}
{
let _guard = runtime.enter();
let project = host.open_project("main", &root).unwrap();
assert!(project.index.wait_idle(Duration::from_secs(30)));
}
let plugins = Arc::new(
PluginHost::new(base.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
);
plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
plugins.set_project_policy(Arc::new(|_| true));
Self { base, host, plugins, root, alpha, inner, beta, _runtime: runtime, _tmp: tmp }
}
/// Runs an installed plugin's `command` with `root` (default: the group
/// container) as the invoking project.
fn run(&self, id: &str, command: &str, arg: Option<&str>, root: Option<&Path>) -> Result<Option<String>, String> {
let inv = Invocation {
client: Some("main".into()),
workspace_root: Some(dunce::canonicalize(root.unwrap_or(&self.root)).unwrap()),
..Default::default()
};
self.plugins.run_command(id, command, arg, inv).map_err(|e| e.message)
}
/// Installs `dir` with everything granted.
fn install(&self, dir: &Path) {
self.plugins.install_from_dir(dir, &Consent::all()).unwrap();
}
/// The roots the plugin surface lists, sorted and deduplicated.
fn listed_roots(&self) -> Vec<PathBuf> {
HostWorkspace(Arc::downgrade(&self.host)).projects()
}
}
impl Drop for GroupFixture {
fn drop(&mut self) {
self.host.close_project("main");
}
}
/// `projects()` lists the members with their own roots, and the member roots of
/// the container are exactly the workspace manifest's.
#[test]
fn projects_list_the_workspace_members() {
let f = GroupFixture::new();
assert_eq!(
f.listed_roots(),
[f.alpha.clone(), f.inner.clone(), f.beta.clone(), f.root.clone()]
.iter()
.map(|p| dunce::canonicalize(p).unwrap())
.collect::<Vec<_>>()
);
assert_eq!(
HostWorkspace(Arc::downgrade(&f.host)).member_roots(&f.root),
[f.alpha.clone(), f.inner.clone(), f.beta.clone()]
.iter()
.map(|p| dunce::canonicalize(p).unwrap())
.collect::<Vec<_>>()
);
// A member has no members of its own.
assert!(HostWorkspace(Arc::downgrade(&f.host)).member_roots(&f.alpha).is_empty());
}
/// `project-of(path)` resolves to the deepest member project containing the
/// path, where the container and every member appear.
#[test]
fn project_of_resolves_to_the_deepest_workspace_member() {
let f = GroupFixture::new();
f.install(&sample("path-events"));
let project =
|path: &Path| f.run("test.path-events", "project", Some(path.to_str().unwrap()), None).unwrap().unwrap();
assert_eq!(project(&f.alpha.join("src/needle.php")), to_ipc(&f.alpha));
// The nested member, not its containing member.
assert_eq!(project(&f.inner.join("mappers/route.idx")), to_ipc(&f.inner));
assert_eq!(project(&f.beta.join("src/Notes.txt")), to_ipc(&f.beta));
// The container itself is still a project.
assert_eq!(project(&f.root), to_ipc(&f.root));
// And a path in no project resolves to none.
assert!(
f.run("test.path-events", "project", Some(f.base.join("secret.txt").to_str().unwrap()), None)
.unwrap()
.is_none()
);
}
/// `project.read` and `project.write` reach the member files through the
/// group's project, and never leave the group's roots.
#[test]
fn project_reads_and_writes_reach_workspace_members() {
let f = GroupFixture::new();
f.install(&misbehave_with(f._tmp.path(), "misbehave-group-writer", "project.write"));
let notes = f.beta.join("src/Notes.txt");
assert_eq!(f.run("misbehave", "read", Some(notes.to_str().unwrap()), None).unwrap().unwrap(), "beta needle\n");
// Writing into a member creates its missing parent directories.
let fresh = f.beta.join("src/generated/mapper.xml");
f.run("misbehave", "projwrite", Some(fresh.to_str().unwrap()), None).unwrap();
assert_eq!(std::fs::read_to_string(&fresh).unwrap(), "written inside the project\n");
// `ctx.project()` is still the group's project.
assert_eq!(f.run("misbehave", "root", None, None).unwrap().unwrap(), to_ipc(&f.root));
// What is outside every root of the group stays refused, unwritten.
let outside = f.base.join("secret.txt");
let err = f.run("misbehave", "read", Some(outside.to_str().unwrap()), None).unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
let err = f.run("misbehave", "projwrite", Some(outside.to_str().unwrap()), None).unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
assert_eq!(std::fs::read_to_string(outside).unwrap(), "top secret");
// A member-scoped project reads its own files only: its root is the member.
assert_eq!(f.run("misbehave", "read", Some("src/Notes.txt"), Some(&f.beta)).unwrap().unwrap(), "beta needle\n");
}
/// Find in Files covers the members: search from the container finds member
/// matches, a member-scoped project sees only its own.
#[test]
fn project_search_reaches_workspace_members() {
let f = GroupFixture::new();
f.install(&sample("api14"));
let search = |root: &Path, needle: &str| f.run("api14", "search-text", Some(needle), Some(root)).unwrap().unwrap();
// From the container: matches in the members come through.
let all = search(&f.root, "needle");
assert!(all.contains("needle.php"), "{all}");
assert!(all.contains("Notes.txt"), "{all}");
// The container holds no sources: `.openidea` metadata never matches.
assert!(!all.contains("workspace.json"), "{all}");
// From a member: only that member's matches.
let own = search(&f.beta, "needle");
assert!(own.contains("Notes.txt"), "{own}");
assert!(!own.contains("needle.php"), "{own}");
// What is outside every root is never found.
assert!(!search(&f.root, "top secret").contains("secret.txt"));
}
/// The document-indexer covers member files: discovery offers them, indexing
/// one publishes its navigation, and files outside the group stay out.
#[test]
fn document_indexer_covers_workspace_members() {
let f = GroupFixture::new();
f.install(&sample("indexer"));
let mapping = f.inner.join("mappers/route.idx");
// Discovery: the member file is in the window's project scope.
let files = f
._runtime
.block_on(ide_host::plugins::index_ops::plugin_navigation_files(&f.host, f.plugins.clone(), "main"))
.unwrap();
assert!(files.paths.iter().any(|p| p.0 == mapping), "{:?}", files.paths);
// Indexing the member file through the window's project publishes it: the
// open document is indexed at its version, like an editor click resolves.
let project = f.host.project("main").unwrap();
let doc = project.documents.open(&mapping).unwrap();
f._runtime
.block_on(ide_host::plugins::index_ops::plugin_navigation_index(
&f.host,
f.plugins.clone(),
"main",
vec![mapping.clone()],
ide_core::RequestId::next(),
))
.unwrap();
let result = f
.plugins
.navigation_at(&f.root, &mapping, doc.version, ide_core::Pos::new(1, 5), Some("main"), |_| None)
.unwrap();
assert_eq!(result.targets[0].path.0, mapping);
// A file outside the group is never offered, and indexing skips it.
let outside = f.base.join("escape.idx");
std::fs::write(&outside, "def outside:item\n").unwrap();
let files = f
._runtime
.block_on(ide_host::plugins::index_ops::plugin_navigation_files(&f.host, f.plugins.clone(), "main"))
.unwrap();
assert!(!files.paths.iter().any(|p| p.0 == outside), "{:?}", files.paths);
f._runtime
.block_on(ide_host::plugins::index_ops::plugin_navigation_index(
&f.host,
f.plugins.clone(),
"main",
vec![outside.clone()],
ide_core::RequestId::next(),
))
.unwrap();
assert!(f.plugins.navigation_at(&f.root, &outside, 1, ide_core::Pos::new(0, 4), Some("main"), |_| None).is_none());
}
-5
Переглянути файл
@@ -33,7 +33,6 @@ mod tsserver_bridge;
pub mod types;
mod uri;
mod virtual_doc;
mod vue_navigation;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{FileInspection, InspectHost, InspectOptions};
@@ -844,7 +843,6 @@ impl LspManager {
self.schedule_pull(doc, Some(&server), Duration::ZERO);
}
self.check_clang_tidy(&server).await;
self.check_vue_navigation(&server).await;
server.refresh_busy_status(&self.sink);
server.announce_ready(generation);
self.spawn_supervisor(server, generation, peer);
@@ -1062,11 +1060,8 @@ impl LspManager {
if s.name == compose::SERVER && compose_added {
me.reconfigure_soon();
}
let hint = me.clone();
let server = s.clone();
self.runtime.spawn(async move { me.check_clang_tidy(&server).await });
let server = s.clone();
self.runtime.spawn(async move { hint.check_vue_navigation(&server).await });
}
}
}
-182
Переглянути файл
@@ -1,182 +0,0 @@
//! Vue 2 (Options API) template navigation: without `strictFunctionTypes`, the Vue 2.7
//! types infer `methods` / `computed` on `this` as `any`, so `textDocument/definition`
//! and hover in templates resolve to nothing (vuejs/language-tools#5257). The bundled
//! server can serve Vue 2.7 fine once the option is on (see #1164).
use crate::{LspManager, Server};
use ide_core::IdeEvent;
use std::path::Path;
pub(crate) const SERVER: &str = "vue-language-server";
pub(crate) const MESSAGE: &str = "Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.";
impl LspManager {
pub(crate) async fn check_vue_navigation(&self, server: &Server) {
if server.name != SERVER || self.shown_messages.lock().contains(&(SERVER.into(), MESSAGE.into())) {
return;
}
let Some(file) = self
.docs
.lock()
.values()
.find(|doc| {
doc.language.as_str() == "vue" && doc.servers.iter().any(|attached| attached.server.id == server.id)
})
.map(|doc| doc.path.clone())
else {
return;
};
let root = self.project_root_for(&file);
let Some(me) = self.me.upgrade() else { return };
let _ = tokio::task::spawn_blocking(move || {
if vue2_project(&root)
&& missing_strict_function_types(&root)
&& !me.shutting_down.load(std::sync::atomic::Ordering::Acquire)
&& me.first_message(SERVER, MESSAGE)
{
me.sink.emit(IdeEvent::LanguageServerWarning {
name: SERVER.into(),
message: MESSAGE.into(),
// No managed tool fixes this (the server itself is fine), so none is
// offered: the UI falls back to the settings shortcut only.
install_tool: String::new(),
});
}
})
.await;
}
}
/// The project's `package.json` depends on Vue 2 (2.7 is the version the Vue Language
/// Tools serve; older 2.x ranges resolve to it).
fn vue2_project(root: &Path) -> bool {
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else { return false };
let Ok(json) = serde_json::from_str::<serde_json::Value>(&manifest) else { return false };
["dependencies", "devDependencies"]
.iter()
.any(|section| json.get(section).and_then(|s| s.get("vue")).and_then(|v| v.as_str()).is_some_and(is_vue_2))
}
/// A `vue` version range whose major version is 2: `^2.7.16`, `~2.7`, `2.x`, `2`, `v2`.
fn is_vue_2(spec: &str) -> bool {
let rest = spec.trim().trim_start_matches(|c: char| !(c.is_ascii_digit() || c == 'v'));
let rest = rest.trim_start_matches('v');
let mut parts = rest.split('.');
parts.next().and_then(|major| major.parse::<u32>().ok()) == Some(2)
}
/// `jsconfig.json` / `tsconfig.json` at the root all lack the option: `strict` or
/// `strictFunctionTypes` is not `true` in their own `compilerOptions`. A config that
/// `extends` a base (which could set it) or can't be parsed stays quiet: a wrong hint
/// is worse than a missed one.
fn missing_strict_function_types(root: &Path) -> bool {
["jsconfig.json", "tsconfig.json"].iter().all(|name| match std::fs::read_to_string(root.join(name)) {
// No config there: nothing contradicts the hint (the option defaults to off).
Err(_) => true,
Ok(src) => strict_function_types(&src) == Some(false),
})
}
/// `strictFunctionTypes: true` or `strict: true` in `compilerOptions` of a JSONC config;
/// `None` when the config `extends` another or can't be parsed (the effective options
/// are unknown).
fn strict_function_types(src: &str) -> Option<bool> {
let json = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(src)).ok()?;
if json.get("extends").and_then(|e| e.as_str()).is_some_and(|e| !e.trim().is_empty()) {
return None;
}
Some(
["strictFunctionTypes", "strict"]
.iter()
.any(|key| json.get("compilerOptions").and_then(|o| o.get(key)).and_then(|v| v.as_bool()) == Some(true)),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vue_2_version_ranges() {
for spec in ["^2.7.16", "~2.7.0", "2.7", "2.x", "2.*", "2", "v2.7.16", ">=2.6.0 <3"] {
assert!(is_vue_2(spec), "{spec}");
}
for spec in ["^3.5.13", "3", "~3.0.0", "latest", "workspace:*", "*"] {
assert!(!is_vue_2(spec), "{spec}");
}
}
#[test]
fn vue_2_dependency_in_either_section() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(
root.join("package.json"),
r#"{"dependencies": {"vue": "^2.7.16", "vue-template-compiler": "^2.7.16"}}"#,
)
.unwrap();
assert!(vue2_project(root));
std::fs::write(root.join("package.json"), r#"{"devDependencies": {"vue": "~2.7"}}"#).unwrap();
assert!(vue2_project(root));
std::fs::write(root.join("package.json"), r#"{"dependencies": {"vue": "^3.5.13"}}"#).unwrap();
assert!(!vue2_project(root));
std::fs::write(root.join("package.json"), r#"{"dependencies": {}}"#).unwrap();
assert!(!vue2_project(root));
}
#[test]
fn strict_function_types_in_jsonc() {
// Comments and trailing commas survive a real jsconfig.json.
let src = r#"{
// Generated by @vue/cli.
"compilerOptions": {
"target": "ES6",
"module": "commonjs", /* kept */
"allowJs": true,
},
"include": ["src/**/*"],
}"#;
assert_eq!(strict_function_types(src), Some(false));
assert_eq!(
strict_function_types(&src.replace("\"allowJs\": true", "\"strictFunctionTypes\": true")),
Some(true)
);
assert_eq!(strict_function_types(&src.replace("\"allowJs\": true", "\"strict\": true")), Some(true));
assert_eq!(strict_function_types(&src.replace("\"allowJs\": true", "\"strict\": false")), Some(false));
assert_eq!(
strict_function_types(&src.replace(
"\"include\": [\"src/**/*\"],",
"\"extends\": \"@vue/tsconfig\", \"include\": [\"src/**/*\"],"
)),
None
);
assert_eq!(strict_function_types("no json here"), None);
}
#[test]
fn missing_option_needs_a_quiet_config() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
// No config at all: the option defaults to off.
assert!(missing_strict_function_types(root));
let jsconfig = root.join("jsconfig.json");
std::fs::write(&jsconfig, r#"{"compilerOptions": {"module": "commonjs"}}"#).unwrap();
assert!(missing_strict_function_types(root));
// The option on in either config: navigation works there.
std::fs::write(&jsconfig, r#"{"compilerOptions": {"strictFunctionTypes": true}}"#).unwrap();
assert!(!missing_strict_function_types(root));
std::fs::write(&jsconfig, r#"{"compilerOptions": {"strict": true}}"#).unwrap();
assert!(!missing_strict_function_types(root));
// A base config could set it: stay quiet.
std::fs::write(&jsconfig, r#"{"extends": "./tsconfig.base.json", "compilerOptions": {}}"#).unwrap();
assert!(!missing_strict_function_types(root));
// An unparsable config: stay quiet.
std::fs::write(&jsconfig, "not json").unwrap();
assert!(!missing_strict_function_types(root));
// tsconfig.json carries the option for a jsconfig-less project.
std::fs::remove_file(&jsconfig).unwrap();
std::fs::write(root.join("tsconfig.json"), r#"{"compilerOptions": {"strict": true}}"#).unwrap();
assert!(!missing_strict_function_types(root));
}
}
+2 -2
Переглянути файл
@@ -21,8 +21,8 @@ pub use runtime::{
component_api, host_api,
};
pub use sandbox::{
MAX_READ_BYTES, inside_root, inside_roots, read_text, resolve_in_root, resolve_in_roots, resolve_new_in_root,
resolve_real, resolve_writable_in_root, resolve_writable_in_roots,
MAX_READ_BYTES, inside_root, read_text, resolve_in_root, resolve_new_in_root, resolve_real,
resolve_writable_in_root,
};
pub use types::*;
pub use wasmtime::component::Component;
-7
Переглянути файл
@@ -356,13 +356,6 @@ pub trait HostApi: Send + Sync {
}
/// Roots of the open projects.
fn projects(&self) -> Vec<std::path::PathBuf>;
/// Roots of the workspace members attached to the project at `root` (a
/// project window group's folders, as the editor and LSP resolve them).
/// Empty for a plain project.
fn member_roots(&self, root: &Path) -> Vec<std::path::PathBuf> {
let _ = root;
Vec::new()
}
/// The most specific open project containing a document (including a new file).
fn project_of(&self, path: &Path) -> Option<std::path::PathBuf> {
if !path.is_absolute() {
-133
Переглянути файл
@@ -65,29 +65,6 @@ pub fn resolve_in_root(root: &Path, path: &str) -> Result<PathBuf, String> {
Ok(real)
}
/// [`resolve_in_root`] over several roots: the project root and, for a project
/// window group, its member roots. `roots` is tried in order (the project root
/// first), and the first root that contains `path` wins; a relative path may
/// name a file of any member. When no root contains it, the project root's
/// refusal is the error, as if there had been no members at all.
pub fn resolve_in_roots(roots: &[PathBuf], path: &str) -> Result<PathBuf, String> {
let (project_root, members) = match roots.split_first() {
Some((project_root, members)) => (project_root, members),
None => return Err(format!("{path}: no such file")),
};
match resolve_in_root(project_root, path) {
Ok(real) => Ok(real),
Err(project_root_error) => {
for root in members {
if let Ok(real) = resolve_in_root(root, path) {
return Ok(real);
}
}
Err(project_root_error)
}
}
}
/// Whether `path` (absolute, or relative to `root`) lands inside `root`,
/// without requiring it to exist: `Ok(true)` also for a missing path, so
/// callers distinguish "outside" from "absent". Existing symlinks are
@@ -97,23 +74,6 @@ pub fn inside_root(root: &Path, path: &str) -> Result<bool, String> {
Ok(resolve_real(&joined).starts_with(&root))
}
/// [`inside_root`] over several roots, as [`resolve_in_roots`] does: a path is
/// inside when any of them contains it.
pub fn inside_roots(roots: &[PathBuf], path: &str) -> Result<bool, String> {
let Some((project_root, members)) = roots.split_first() else {
return Ok(false);
};
if inside_root(project_root, path)? {
return Ok(true);
}
for root in members {
if inside_root(root, path)? {
return Ok(true);
}
}
Ok(false)
}
/// Like [`resolve_in_root`] for a path that may not exist yet (a file about to
/// be created) or that names a symlink itself (to delete or rename it): the
/// directory part is resolved through symlinks, the final name is kept as is,
@@ -168,25 +128,6 @@ pub fn resolve_writable_in_root(root: &Path, path: &str) -> Result<PathBuf, Stri
Ok(real)
}
/// [`resolve_writable_in_root`] over several roots, as [`resolve_in_roots`] does.
pub fn resolve_writable_in_roots(roots: &[PathBuf], path: &str) -> Result<PathBuf, String> {
let (project_root, members) = match roots.split_first() {
Some((project_root, members)) => (project_root, members),
None => return Err(format!("{path}: access outside the project root is not allowed")),
};
match resolve_writable_in_root(project_root, path) {
Ok(real) => Ok(real),
Err(project_root_error) => {
for root in members {
if let Ok(real) = resolve_writable_in_root(root, path) {
return Ok(real);
}
}
Err(project_root_error)
}
}
}
fn resolve_write_target(path: &Path, links_left: usize) -> Result<PathBuf, std::io::Error> {
match dunce::canonicalize(path) {
Ok(real) => return Ok(real),
@@ -470,80 +411,6 @@ mod tests {
assert!(inside_root(&root, "").is_err());
}
/// A project window group: the container root and its member roots.
fn group(tmp: &tempfile::TempDir) -> (PathBuf, PathBuf, Vec<PathBuf>) {
let container = tmp.path().join("workspace");
let alpha = tmp.path().join("alpha");
let beta = tmp.path().join("beta");
for dir in [&container, &alpha, &beta] {
std::fs::create_dir_all(dir).unwrap();
}
let container = dunce::canonicalize(container).unwrap();
let alpha = dunce::canonicalize(alpha).unwrap();
let beta = dunce::canonicalize(beta).unwrap();
(container, alpha.clone(), vec![alpha, beta])
}
#[test]
fn member_roots_accept_their_files_and_the_container_still_confines() {
let tmp = tempfile::tempdir().unwrap();
let (container, alpha, members) = group(&tmp);
std::fs::create_dir_all(container.join("src")).unwrap();
std::fs::write(container.join("src/notes.txt"), "hi").unwrap();
std::fs::create_dir_all(alpha.join("src")).unwrap();
let member_file = alpha.join("src/mapper.xml");
std::fs::write(&member_file, "hi").unwrap();
std::fs::write(tmp.path().join("secret.txt"), "s").unwrap();
let roots = [container.clone()].iter().cloned().chain(members.clone()).collect::<Vec<_>>();
// A member's absolute file resolves through its member root.
assert_eq!(resolve_in_roots(&roots, member_file.to_str().unwrap()).unwrap(), member_file);
// The container's own files still resolve as before.
let container_file = container.join("src/notes.txt");
assert_eq!(resolve_in_roots(&roots, "src/notes.txt").unwrap(), container_file);
// A missing path is `no such file`, wherever it would land.
let gone = container_file.with_file_name("gone.txt");
assert_eq!(
resolve_in_roots(&roots, gone.to_str().unwrap()).unwrap_err(),
format!("{}: no such file", gone.display())
);
// Outside every root is refused with the container's refusal.
let outside = tmp.path().join("secret.txt");
let err = resolve_in_roots(&roots, outside.to_str().unwrap()).unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
let err = resolve_in_roots(&roots, "../secret.txt").unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
// `inside_roots` accepts member paths, including missing ones, and
// refuses what no root contains.
assert!(inside_roots(&roots, member_file.to_str().unwrap()).unwrap());
assert!(inside_roots(&roots, "missing/one.txt").unwrap());
assert!(inside_roots(&roots, alpha.join("src/new.xml").to_str().unwrap()).unwrap());
assert!(!inside_roots(&roots, outside.to_str().unwrap()).unwrap());
// No members: exactly the single-root behaviour.
let single = [container.clone()];
assert_eq!(resolve_in_roots(&single, "src/notes.txt").unwrap(), container_file);
assert!(!inside_roots(&single, member_file.to_str().unwrap()).unwrap());
}
#[test]
fn new_and_writable_paths_accept_members() {
let tmp = tempfile::tempdir().unwrap();
let (container, alpha, members) = group(&tmp);
std::fs::create_dir_all(container.join("src")).unwrap();
std::fs::create_dir_all(alpha.join("src")).unwrap();
let roots = [container.clone()].iter().cloned().chain(members.iter().cloned()).collect::<Vec<_>>();
let member_new = alpha.join("src/new.xml");
assert_eq!(resolve_writable_in_roots(&roots, member_new.to_str().unwrap()).unwrap(), member_new);
let container_new = container.join("src/new.txt");
assert_eq!(resolve_writable_in_roots(&roots, "src/new.txt").unwrap(), container_new);
let outside = tmp.path().join("escape.txt");
let err = resolve_writable_in_roots(&roots, outside.to_str().unwrap()).unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
let err = resolve_writable_in_roots(&roots, "../../escape.txt").unwrap_err();
assert!(err.contains("outside the project root"), "{err}");
}
#[test]
fn new_paths_are_confined_to_root() {
let tmp = tempfile::tempdir().unwrap();
+7 -33
Переглянути файл
@@ -686,7 +686,7 @@ impl workspace::HostProject for StoreData {
return Ok(Err(e));
}
let root = self.table.get(&this)?.root.clone();
let real = match self.resolve_in_project(&root, &path) {
let real = match sandbox::resolve_in_root(&root, &path) {
Ok(real) => real,
Err(e) => {
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
@@ -704,7 +704,7 @@ impl workspace::HostProject for StoreData {
return Ok(Err(e));
}
let root = self.table.get(&this)?.root.clone();
let real = match self.resolve_in_project(&root, &path) {
let real = match sandbox::resolve_in_root(&root, &path) {
Ok(real) => real,
Err(e) => {
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
@@ -720,20 +720,15 @@ impl workspace::HostProject for StoreData {
return Ok(Err(e));
}
let root = self.table.get(&this)?.root.clone();
match self.inside_project(&root, &path) {
match sandbox::inside_root(&root, &path) {
Err(e) => Ok(Err(wit::Error::Invalid(e))),
Ok(false) => {
Ok(Err(wit::Error::Invalid(format!("{path}: access outside the project root is not allowed"))))
}
Ok(true) => {
let requested = Path::new(&path);
let joined =
|root: &Path| if requested.is_absolute() { requested.to_path_buf() } else { root.join(requested) };
let mut exists = joined(&root).exists();
if !exists && !requested.is_absolute() {
exists = self.host.member_roots(&root).iter().any(|root| joined(root).exists());
}
Ok(Ok(exists))
let joined = if requested.is_absolute() { requested.to_path_buf() } else { root.join(requested) };
Ok(Ok(joined.exists()))
}
}
}
@@ -743,7 +738,7 @@ impl workspace::HostProject for StoreData {
return Ok(Err(e));
}
let root = self.table.get(&this)?.root.clone();
let real = match self.resolve_in_project(&root, &path) {
let real = match sandbox::resolve_in_root(&root, &path) {
Ok(real) => real,
Err(e) => {
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
@@ -802,7 +797,7 @@ impl workspace::HostProject for StoreData {
return Ok(Err(too_much_to_write(&path)));
}
let root = self.table.get(&this)?.root.clone();
let real = match self.resolve_writable_in_project(&root, &path) {
let real = match sandbox::resolve_writable_in_root(&root, &path) {
Ok(real) => real,
Err(e) => return Ok(Err(wit::Error::Invalid(e))),
};
@@ -858,27 +853,6 @@ fn core_range(r: wit::Range) -> ide_core::Range {
ide_core::Range::new(pos(r.start), pos(r.end))
}
impl StoreData {
/// A `project` resource's path: inside the resource's root, or — for a
/// project window group — inside any of its member roots (as the editor and
/// LSP resolve them). When no root accepts the path, the resource root's own
/// refusal is the error, as if there were no members.
fn resolve_in_project(&self, root: &Path, path: &str) -> Result<PathBuf, String> {
sandbox::resolve_in_root(root, path).or_else(|root_error| {
sandbox::resolve_in_roots(&self.host.member_roots(root), path).map_err(|_| root_error)
})
}
/// [`Self::resolve_in_project`] for a content write's destination.
fn resolve_writable_in_project(&self, root: &Path, path: &str) -> Result<PathBuf, String> {
sandbox::resolve_writable_in_root(root, path).or_else(|root_error| {
sandbox::resolve_writable_in_roots(&self.host.member_roots(root), path).map_err(|_| root_error)
})
}
/// Whether a `project` resource's path lands inside the resource's root or
/// any member of its workspace group, without requiring it to exist.
fn inside_project(&self, root: &Path, path: &str) -> Result<bool, String> {
sandbox::inside_root(root, path)
.or_else(|root_error| sandbox::inside_roots(&self.host.member_roots(root), path).map_err(|_| root_error))
}
fn decoration_path(&self, path: &str) -> Result<PathBuf, wit::Error> {
if Path::new(path).is_absolute() {
return Ok(PathBuf::from(path));
+2 -2
Переглянути файл
@@ -17,7 +17,7 @@ The left side is a tree; the right side shows details of the selected item (a co
### Run configurations
Only types you add appear here: choose **Add Service › Run Configuration Type**; each type is a group, kept until you remove it with **Remove from Services**. Removing a type or a single configuration takes effect at once, even while it runs: the run moves to the Run tool window, so its console stays reachable. Running a configuration of a type you have not added keeps its output in the Run or Debug tool window too.
Spring Boot configurations appear by default. Other types appear when you add them with **Add Service › Run Configuration Type**, or once a configuration of that type has run. Each type is a group.
- Group actions: **Run All**, **Restart All**, **Stop All**, **Open in Browser**.
- Configuration actions: **Run** (or **Rerun**), **Debug**, **Stop**, **Open in Browser**, **Update Application** (for configurations that support it).
@@ -31,7 +31,7 @@ OpenIDEA drives Docker through the `docker` CLI, so anything that provides a wor
### Connections
With nothing configured, Services lists no Docker connection. To add one (the first one usually connects to the Docker CLI default: `DOCKER_HOST` or the current context), choose **Add Service › Docker Connection…**:
With nothing configured, Services shows one connection named **Docker** that uses the Docker CLI default (`DOCKER_HOST` or the current context). To add another, choose **Add Service › Docker Connection…**:
| Field | Options |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+2 -2
Переглянути файл
@@ -17,7 +17,7 @@ description: "在服务工具窗口中管理运行配置、Docker 容器、镜
### 运行配置
只有你添加的类型才会出现:选择 **添加服务 › 运行配置类型**(类型会一直保留,直到用 **从服务中移除** 删掉;每种类型一个分组)。移除类型或单个配置立即生效——即使它正在运行,运行也会转到运行工具窗口,控制台始终可达。运行未添加类型的配置时,输出同样留在运行或调试工具窗口。
Spring Boot 配置默认就会显示。其他类型在通过 **添加服务 › 运行配置类型** 添加后,或者该类型的配置运行过一次后出现。每种类型一个分组。
- 分组操作:**全部运行**、**全部重启**、**全部停止**、**在浏览器中打开**。
- 配置操作:**运行**(或 **重新运行**)、**调试**、**停止**、**在浏览器中打开**、**更新应用**(仅支持的配置)。
@@ -31,7 +31,7 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
### 连接
什么都不配置时,服务中不列出任何 Docker 连接。要添加一个连接(第一个通常连接 Docker CLI 默认设置:`DOCKER_HOST` 或当前上下文),选择 **添加服务 › Docker 连接…**:
什么都不配置时,服务中会有一个名为 **Docker** 的连接,使用 Docker CLI 默认设置(`DOCKER_HOST` 或当前上下文)。要添加其他连接,选择 **添加服务 › Docker 连接…**:
| 字段 | 说明 |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-43
Переглянути файл
@@ -153,46 +153,3 @@ test("Docker Compose editor completes service references and navigates to declar
await page.keyboard.press("Meta+b");
await expect(editor.locator(".cm-activeLine")).toHaveText(" backend:");
});
test("the Services detail pane adds no second scrollbar over a console", async ({ workbench: page }) => {
// A short window: the run toolbar is taller than the detail pane, which used to make
// the split panel scroll too (the console had its own scrollbar right beside it).
await page.setViewportSize({ width: 1200, height: 640 });
await page.evaluate(async () => {
const store = await import(/* @vite-ignore */ "/src/features/run/store.ts" as string);
await store.startSampleOutput(200, 50);
const id = store.useRun.getState().activeSession as string;
store.useRun.setState((s: { sessions: { id: string }[]; versions: Record<string, number> }) => ({
sessions: s.sessions.map((x) => (x.id === id ? { ...x, status: "running" } : x)),
versions: { ...s.versions, [id]: (s.versions[id] ?? 0) + 1 },
}));
const svc = await import(/* @vite-ignore */ "/src/features/run/services.tsx" as string);
const tree = await import(/* @vite-ignore */ "/src/features/services/tree.ts" as string);
const session = store.useRun.getState().sessions.find((s: { id: string }) => s.id === id);
svc.addType(session.config.kind);
tree.useServicesTree.setState({
selectedKey: `run:config:${session.config.id}`,
selectedKeys: new Set([`run:config:${session.config.id}`]),
});
});
await page.keyboard.press("Meta+8");
await expect(page.getByRole("log").first()).toBeVisible();
const result = await page.evaluate(() => {
const log = document.querySelector('[data-toolwindow="services"] [role="log"]');
let panel: Element | null = log;
while (panel && !panel.hasAttribute("data-panel")) panel = panel.parentElement;
const inner = panel?.firstElementChild as HTMLElement | null;
const scrollers: string[] = [];
for (const el of document.querySelectorAll<HTMLElement>('[data-toolwindow="services"] *')) {
const cs = getComputedStyle(el);
if ((cs.overflowY === "auto" || cs.overflowY === "scroll") && el.scrollHeight - el.clientHeight > 2)
scrollers.push(String(el.className));
}
return { overflowY: inner ? getComputedStyle(inner).overflowY : "missing", scrollers };
});
// The panel's inner div carries the library's inline `overflow: auto`; the detail pane
// overrides it, so the console is the only scroller.
expect(result.overflowY).toBe("hidden");
expect(result.scrollers.filter((c) => c.includes("detailPane") || c.includes("_panel_"))).toEqual([]);
expect(result.scrollers.length).toBeGreaterThan(0);
});
-5
Переглянути файл
@@ -6665,11 +6665,6 @@ export type McpServerInput = {
export type McpServerSettings = {
/** Serve the tools on 127.0.0.1 while the IDE runs. */
enabled?: boolean,
/**
* Run the tools that change the project or start processes without asking first
* (IDEA's brave mode). Read from the IDE's own settings only, never a project's.
*/
runWithoutConfirmation?: boolean,
};
/** What Settings › Agents › MCP Server shows. */
+18 -18
Переглянути файл
@@ -32,7 +32,6 @@ import {
nodeLabel,
profileChecked,
withGradleOptions,
gradleHasTestTask,
type BuildNode,
} from "./model";
import {
@@ -65,9 +64,7 @@ export function nodeConfig(
const first = nodes[0];
if (!first) return null;
if (first.kind === "runConfig")
return first.config.kind === "gradle"
? withGradleOptions(first.config, settings.gradle, gradleHasTestTask(model.gradle ?? []))
: first.config;
return first.config.kind === "gradle" ? withGradleOptions(first.config, settings.gradle) : first.config;
if ((first.kind === "phase" || first.kind === "goal") && model.maven) {
const same = nodes.filter(
(n): n is Extract<BuildNode, { kind: "phase" | "goal" }> =>
@@ -171,13 +168,15 @@ function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[]
iconSize={16}
action={maven ? "maven.analyzeDependencies" : "gradle.analyzeDependencies"}
/>
<IconButton
icon="skip-tests"
size="small"
iconSize={16}
action={`${tool}.toggleSkipTests`}
pressed={maven ? settings.maven.skipTests : settings.gradle.skipTests}
/>
{maven && (
<IconButton
icon="skip-tests"
size="small"
iconSize={16}
action="maven.toggleSkipTests"
pressed={settings.maven.skipTests}
/>
)}
<span className={styles.sep} />
<IconButton icon="expand-all" size="small" iconSize={16} action={`${tool}.expandAll`} />
<IconButton icon="collapse-all" size="small" iconSize={16} action={`${tool}.collapseAll`} />
@@ -235,9 +234,7 @@ function BuildBanner({ info, tool }: { info: MavenModel | GradleModel; tool: Bui
function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
const choices = useBuild((s) => s.settings.maven.profiles);
// Each toggle strikes through only its own tool's tree: the Maven `test` phase, or the Gradle `test` task.
const mavenSkipTests = useBuild((s) => s.settings.maven.skipTests);
const gradleSkipTests = useBuild((s) => s.settings.gradle.skipTests);
const skipTests = useBuild((s) => s.settings.maven.skipTests);
if (node.kind === "profile") {
return (
<span className={styles.row} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
@@ -260,13 +257,16 @@ function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
: node.kind === "task"
? node.task.description
: null;
const skipped =
(mavenSkipTests && node.kind === "phase" && node.phase === "test") ||
(gradleSkipTests && node.kind === "task" && node.task.name === "test");
return (
<span className={styles.row} title={node.kind === "task" ? (node.task.description ?? undefined) : undefined}>
<Icon name={nodeIcon(node)} size={16} className={styles.icon} />
<span className={clsx(styles.label, state.selected && styles.selectedLabel, skipped && styles.skippedGoal)}>
<span
className={clsx(
styles.label,
state.selected && styles.selectedLabel,
skipTests && node.kind === "phase" && node.phase === "test" && styles.skippedGoal,
)}
>
{nodeLabel(node)}
</span>
{detail && <span className={styles.detail}>{detail}</span>}
-60
Переглянути файл
@@ -174,64 +174,4 @@ describe("build tools feature", () => {
render(<GradleView />);
expect(screen.getByText("test")).not.toHaveClass(styles.skippedGoal!);
});
it("toggles Gradle Skip Tests and runs tasks with -x test", async () => {
const started: unknown[] = [];
const off = registerAction({
id: "run.runConfig",
title: "Run",
hidden: true,
run: ({ arg }) => void started.push(arg),
});
const build = {
dir: "",
projects: [
{
path: ":",
name: "demo",
dir: "",
buildFile: "build.gradle.kts",
tasks: [{ name: "test", group: "verification", description: null }],
},
],
command: "/p/gradlew",
env: {},
javaVersion: null,
syncedAt: null,
stale: false,
syncError: null,
};
const key = gradleProjectKey(build, build.projects[0]!);
act(() =>
useBuild.setState({
root: "/p",
model: { maven: mavenModel.maven, gradle: [build] },
expanded: { maven: new Set(), gradle: new Set([key, `${key}:tasks`, `${key}:tasks:verification`]) },
}),
);
await executeAction("gradle.toggleSkipTests");
expect(useBuild.getState().settings.gradle).toMatchObject({ skipTests: true });
expect(JSON.parse(localStorage.getItem("openidea.buildTools:/p")!).gradle.skipTests).toBe(true);
expect(
allActions()
.find((a) => a.id === "gradle.toggleSkipTests")!
.toggled?.(),
).toBe(true);
render(<GradleView />);
const task = screen.getByText("test");
expect(task).toHaveClass(styles.skippedGoal!);
await act(async () => {
task.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
});
off();
expect(started).toHaveLength(1);
const { config } = started[0] as { config: RunConfig };
expect(config).toMatchObject({
name: "demo [test]",
command: "/p/gradlew",
args: ["test", "-x", "test"],
kind: "gradle",
isTest: false,
});
});
});
-12
Переглянути файл
@@ -51,7 +51,6 @@ import {
generateSources,
syncTool,
toggleGradleOffline,
toggleGradleSkipTests,
toggleMavenOffline,
toggleSkipTests,
useBuild,
@@ -452,17 +451,6 @@ export function activate(): () => void {
toggled: () => useBuild.getState().settings.gradle.offline,
run: () => toggleGradleOffline(),
},
{
id: "gradle.toggleSkipTests",
title: "Toggle 'Skip Tests' Mode",
description: "Runs Gradle with -x test",
category: "Gradle",
icon: "skip-tests",
when: GRADLE_WHEN,
keywords: ["gradle", "skip tests"],
toggled: () => useBuild.getState().settings.gradle.skipTests,
run: () => toggleGradleSkipTests(),
},
{
id: "gradle.expandAll",
title: "Expand All",
+1 -1
Переглянути файл
@@ -378,7 +378,7 @@ it("runs duplicate task paths with the selected build's wrapper, cwd and offline
model,
expanded: { maven: new Set(), gradle: expanded },
current: { gradle: gradleProjectKey(builds[1]!, builds[1]!.projects[1]!) },
settings: { ...useBuild.getState().settings, gradle: { offline: true, skipTests: false } },
settings: { ...useBuild.getState().settings, gradle: { offline: true } },
}),
);
const started: RunConfig[] = [];
+4 -54
Переглянути файл
@@ -20,8 +20,6 @@ import {
profilesArg,
splitArgs,
taskCompletions,
withGradleOptions,
gradleHasTestTask,
type BuildNode,
} from "./model";
@@ -326,7 +324,7 @@ describe("Gradle tree and runs", () => {
it("runs tasks by path from the build directory", () => {
const app = gradle.projects[1]!;
const config = gradleTaskConfig(gradle, app, ["test"], { offline: true, skipTests: false });
const config = gradleTaskConfig(gradle, app, ["test"], { offline: true });
expect(config).toMatchObject({
name: "app [test]",
kind: "gradle",
@@ -337,61 +335,13 @@ describe("Gradle tree and runs", () => {
env: {},
isTest: true,
});
expect(
gradleTaskConfig(gradle, gradle.projects[0]!, ["wrapper"], { offline: false, skipTests: false }).args,
).toEqual(["wrapper"]);
expect(gradleTaskConfig(gradle, app, [":lib:jar", "--info"], { offline: false, skipTests: false }).args).toEqual([
expect(gradleTaskConfig(gradle, gradle.projects[0]!, ["wrapper"], { offline: false }).args).toEqual(["wrapper"]);
expect(gradleTaskConfig(gradle, app, [":lib:jar", "--info"], { offline: false }).args).toEqual([
":lib:jar",
"--info",
]);
});
it("appends -x test to task runs when Skip Tests is on", () => {
const app = gradle.projects[1]!;
const skipped = gradleTaskConfig(gradle, app, ["build"], { offline: false, skipTests: true });
expect(skipped.args).toEqual([":app:build", "-x", "test"]);
// Running `test` with Skip Tests on is not a test run for the Run window.
const test = gradleTaskConfig(gradle, app, ["test"], { offline: false, skipTests: true });
expect(test.args).toEqual([":app:test", "-x", "test"]);
expect(test.isTest).toBe(false);
// A command line that already excludes tests is not changed again (typed task names keep
// the pre-existing project-path prefix).
const explicit = gradleTaskConfig(gradle, app, ["build", "-x", "test"], { offline: false, skipTests: true });
expect(explicit.args).toEqual([":app:build", "-x", ":app:test"]);
const verbose = gradleTaskConfig(gradle, app, ["build", "--exclude-task", "test"], {
offline: false,
skipTests: true,
});
expect(verbose.args).toEqual([":app:build", "--exclude-task", ":app:test"]);
// A build without a `test` task would fail on `-x test`.
const noTests = {
...gradle,
projects: gradle.projects.map((p) => ({ ...p, tasks: p.tasks.filter((t) => t.name !== "test") })),
};
expect(gradleHasTestTask([noTests])).toBe(false);
expect(
gradleTaskConfig(noTests, noTests.projects[1]!, ["build"], { offline: false, skipTests: true }).args,
).toEqual([":app:build"]);
});
it("applies the toolbar toggles to saved configurations started from the tree", () => {
const saved = runConfig({ id: "g", name: "app [build]", kind: "gradle", args: ["build"] });
expect(withGradleOptions(saved, { offline: false, skipTests: false }).args).toEqual(["build"]);
expect(withGradleOptions(saved, { offline: true, skipTests: false }).args).toEqual(["build", "--offline"]);
expect(withGradleOptions(saved, { offline: true, skipTests: true }).args).toEqual([
"build",
"--offline",
"-x",
"test",
]);
const excluding = withGradleOptions(runConfig({ ...saved, args: ["build", "-x", "test"] }), {
offline: false,
skipTests: true,
});
expect(excluding.args).toEqual(["build", "-x", "test"]);
expect(withGradleOptions(saved, { offline: false, skipTests: true }, false).args).toEqual(["build"]);
});
it("keeps identical project paths and tasks of independent builds distinct", () => {
const builds = ["first", "second"].map((dir) => ({
...gradle,
@@ -411,7 +361,7 @@ describe("Gradle tree and runs", () => {
return gradleChildren(group, builds, [])![0]!;
});
expect(tasks[0]!.key).not.toBe(tasks[1]!.key);
const runs = builds.map((b) => gradleTaskConfig(b, b.projects[1]!, ["test"], { offline: true, skipTests: false }));
const runs = builds.map((b) => gradleTaskConfig(b, b.projects[1]!, ["test"], { offline: true }));
expect(runs[0]!.id).not.toBe(runs[1]!.id);
expect(runs[1]).toMatchObject({
command: "/p/second/gradlew",
+5 -34
Переглянути файл
@@ -83,8 +83,6 @@ export interface MavenRunOptions {
export interface GradleRunOptions {
offline: boolean;
/** Skip Tests toolbar toggle: task runs get `-x test` (no Maven-style toggle exists in IDEA's Gradle window). */
skipTests: boolean;
}
// ---------------------------------------------------------------------------
@@ -516,29 +514,6 @@ export function gradleTaskPath(project: GradleProject, task: string): string {
return project.path === ":" ? task : `${project.path}:${task}`;
}
/**
* Whether one of the builds has a task named `test`: `-x test` fails the whole run with
* "Task 'test' not found" in a build without one (Kotlin Multiplatform, non-JVM builds).
*/
export function gradleHasTestTask(models: readonly GradleModel[]): boolean {
return models.some((m) => m.projects.some((p) => p.tasks.some((t) => t.name === "test")));
}
/** Whether the command line already excludes the `test` task (`-x test`, `-xtest`, `--exclude-task test`). */
function excludesTest(args: readonly string[]): boolean {
return args.some((a, i) => {
const value =
a === "-x" || a === "--exclude-task"
? args[i + 1]
: a.startsWith("--exclude-task=")
? a.slice("--exclude-task=".length)
: a.startsWith("-x")
? a.slice(2)
: undefined;
return value === "test";
});
}
export function gradleTaskConfig(
model: GradleModel,
project: GradleProject,
@@ -547,8 +522,6 @@ export function gradleTaskConfig(
): RunConfig {
const args = tasks.map((t) => (t.startsWith("-") || t.startsWith(":") ? t : gradleTaskPath(project, t)));
if (options.offline && !args.includes("--offline")) args.push("--offline");
// Typed task names are project-path prefixed above, so the typed line is the one to inspect.
if (options.skipTests && gradleHasTestTask([model]) && !excludesTest(tasks)) args.push("-x", "test");
const names = tasks.filter((t) => !t.startsWith("-"));
return {
id: `gradle:task:${JSON.stringify([model.dir, project.path])}:${tasks.join(" ")}`,
@@ -560,17 +533,15 @@ export function gradleTaskConfig(
// As for Maven: the Gradle JVM / `JAVA_HOME` is derived from Settings at launch, not frozen here.
env: {},
detected: false,
isTest: !options.skipTests && names.some((t) => /(^|:)(test|check|build|integrationTest)$/.test(t)),
isTest: names.some((t) => /(^|:)(test|check|build|integrationTest)$/.test(t)),
debugAdapter: null,
};
}
/** Applies the current toggles to a saved configuration started from the tree (`hasTestTask`: see {@link gradleHasTestTask}). */
export function withGradleOptions(config: RunConfig, options: GradleRunOptions, hasTestTask = true): RunConfig {
let args = config.args;
if (options.offline && !args.includes("--offline")) args = [...args, "--offline"];
if (options.skipTests && hasTestTask && !excludesTest(args)) args = [...args, "-x", "test"];
return args === config.args ? config : { ...config, args };
/** Applies the current toggles to a saved configuration started from the tree. */
export function withGradleOptions(config: RunConfig, options: GradleRunOptions): RunConfig {
if (!options.offline || config.args.includes("--offline")) return config;
return { ...config, args: [...config.args, "--offline"] };
}
// ---------------------------------------------------------------------------
+1 -3
Переглянути файл
@@ -45,7 +45,7 @@ export interface BuildSettings {
export const DEFAULT_SETTINGS: BuildSettings = {
maven: { offline: false, skipTests: false, profiles: {} },
gradle: { offline: false, skipTests: false },
gradle: { offline: false },
};
interface SyncState {
@@ -131,8 +131,6 @@ export const toggleSkipTests = () =>
updateSettings((s) => ({ ...s, maven: { ...s.maven, skipTests: !s.maven.skipTests } }));
export const toggleGradleOffline = () =>
updateSettings((s) => ({ ...s, gradle: { ...s.gradle, offline: !s.gradle.offline } }));
export const toggleGradleSkipTests = () =>
updateSettings((s) => ({ ...s, gradle: { ...s.gradle, skipTests: !s.gradle.skipTests } }));
/** Delay before reloading Maven after a profile toggle, so a few toggles in a row reload once. */
export const PROFILE_RELOAD_DELAY_MS = 800;
-28
Переглянути файл
@@ -3,7 +3,6 @@ import { IpcError } from "@/platform/ipc";
import { missingAdapter } from "../missingAdapter";
const unavailable = (message: string) => new IpcError({ kind: "unavailable", message });
const invalid = (message: string) => new IpcError({ kind: "invalidInput", message });
describe("missing debug adapters", () => {
it("offers OpenIDEA's debugpy when the interpreter has none", () => {
@@ -42,33 +41,6 @@ describe("missing debug adapters", () => {
});
});
it("offers to reinstall Delve when it is too old for the Go toolchain", () => {
const message =
"launch failed: Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 " +
"(maximum supported version 1.26, suppress this error with --check-go-version=false)";
// The failed `launch` response arrives as `invalidInput` (a DAP error, not a missing binary).
expect(missingAdapter("delve", invalid(message))).toMatchObject({
tool: "delve",
title: "Delve is too old for Go 1.27.0",
action: "Reinstall and Debug",
body: `${message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
});
});
it("offers the reinstall even when delve exited during startup", () => {
const e = unavailable(
"debug adapter `delve` exited during startup:\nVersion of Delve is too old for Go version go1.27.0",
);
expect(missingAdapter("delve", e)).toMatchObject({ tool: "delve", action: "Reinstall and Debug" });
});
it("keeps a Go launch that failed for another reason as a plain error", () => {
expect(missingAdapter("delve", invalid("launch failed: could not find project directory"))).toBeNull();
expect(
missingAdapter("delve", unavailable("debug adapter `delve` exited during startup:\nexit status 1")),
).toBeNull();
});
it("leaves other failures and adapters without an installer alone", () => {
expect(missingAdapter("js-debug", unavailable("connection refused"))).toBeNull();
expect(missingAdapter("js-debug", new Error("debug adapter `js-debug` not found"))).toBeNull();
-28
Переглянути файл
@@ -65,32 +65,4 @@ describe("debug start failures", () => {
expect.objectContaining({ title: "Cannot start debugger for Listen for Xdebug", body: PORT_IN_USE }),
);
});
it("offers to reinstall a Delve that is too old for the Go toolchain", async () => {
const notify = vi.fn();
provideNotificationService({ notify });
useDebug.setState({ sessions: {}, active: null, console: {} });
const message =
"launch failed: Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 " +
"(maximum supported version 1.26, suppress this error with --check-go-version=false)";
ipc.debugStart.mockResolvedValueOnce({ status: "error", error: { kind: "invalidInput", message, data: null } });
const go: LaunchConfig = {
name: "api: go run .",
adapter: "delve",
request: "launch",
program: "/p/api",
args: [],
cwd: "/p/api",
env: {},
extraJson: JSON.stringify({ mode: "debug" }),
};
expect(await startSession(go)).toBeNull();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
title: "Delve is too old for Go 1.27.0",
body: `${message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
actions: [expect.objectContaining({ label: "Reinstall and Debug" })],
}),
);
});
});
+3 -26
Переглянути файл
@@ -1,10 +1,8 @@
/**
* A debug adapter that is not installed, or an installed one that refuses the Go
* toolchain: name it and offer the one-click install / reinstall (ide-tools) followed
* by the same launch again, instead of a bare error.
* A debug adapter that is not installed: name it and offer the one-click install
* (ide-tools) followed by the same launch again, instead of a bare error.
*/
import { IpcError } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
/** Adapters the tools installer can provide (adapter id → tool name). */
const INSTALLABLE: Record<string, { tool: string; title: string }> = {
@@ -18,37 +16,16 @@ const INSTALLABLE: Record<string, { tool: string; title: string }> = {
"bash-debug": { tool: "bash-debug", title: "Bash Debug is not installed" },
};
/**
* Delve refuses a Go toolchain newer than it supports: the adapter starts, but its
* `launch` request fails with "Version of Delve is too old for Go version go1.27.0
* (maximum supported version 1.26, …)". The managed install is
* `go install github.com/go-delve/delve/cmd/dlv@latest`, so reinstalling updates it.
*/
const DELVE_TOO_OLD = /Version of Delve is too old for Go version go([\d.]+)/;
export interface MissingAdapter {
tool: string;
title: string;
body: string;
/** The action's label when "Install and Debug" doesn't fit (a stale adapter's reinstall). */
action?: string;
}
/** The install offer for a failed start, or null when the failure is something else. */
export function missingAdapter(adapter: string, e: unknown): MissingAdapter | null {
if (!(e instanceof IpcError)) return null;
if (adapter === "delve") {
const go = DELVE_TOO_OLD.exec(e.message)?.[1];
if (go)
return {
tool: "delve",
title: tx`Delve is too old for Go ${go}`,
body: `${e.message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
action: "Reinstall and Debug",
};
}
const entry = INSTALLABLE[adapter];
if (!entry || e.kind !== "unavailable") return null;
if (!entry || !(e instanceof IpcError) || e.kind !== "unavailable") return null;
if (adapter === "debugpy" && e.message.startsWith("debugpy is not installed")) {
return {
tool: entry.tool,
+1 -1
Переглянути файл
@@ -677,7 +677,7 @@ export async function startSession(
sticky: true,
actions: [
{
label: missing.action ?? "Install and Debug",
label: "Install and Debug",
run: () => void executeAction("tools.install", missing.tool).then(() => startSession(launch, options)),
},
],
+1 -4
Переглянути файл
@@ -34,9 +34,6 @@ const GROUP_ICONS: Record<string, string> = {
gems: "file-ruby",
};
/** SDK groups, which IDEA writes in angle brackets (`< 21 >`); library groups (`Maven: g:a:v`) go without. */
const SDK_KINDS = new Set(["jdk", "python", "ruby", "go", "rust"]);
/** An archive's root (`/jdk/lib/src.zip!`): its entries live below `<archive>!/`. */
const isArchiveRoot = (path: string) => path.endsWith("!");
@@ -94,7 +91,7 @@ export function librariesRoot(groups: readonly LibraryGroup[]): ProjectViewRootC
order: 5,
readOnly: true,
children: groups.map((g) => ({
label: SDK_KINDS.has(g.kind) ? `< ${g.name} >` : g.name,
label: `< ${g.name} >`,
icon: GROUP_ICONS[g.kind] ?? "library",
children: g.roots.map((r) => ({
label: r.name,
+1 -3
Переглянути файл
@@ -64,9 +64,7 @@ describe("External Libraries", () => {
{ name: "Maven: g:a:1", kind: "maven", roots: [{ name: "a-1-sources.jar", path: "/m2/g/a/1/a-1-sources.jar!" }] },
])!;
expect(root.children?.[0]?.children?.map((c) => c.icon)).toEqual(["folder-library", "file-archive"]);
// As in IDEA: SDKs in angle brackets, dependencies without.
expect(root.children?.[0]).toMatchObject({ label: "< temurin-21 >" });
expect(root.children?.[1]).toMatchObject({ label: "Maven: g:a:1", icon: "maven-project" });
expect(root.children?.[1]).toMatchObject({ label: "< Maven: g:a:1 >", icon: "maven-project" });
dispose = setLibraryRoots("test", ["/jdk/lib/src.zip!"]);
expect(isLibraryPath("/jdk/lib/src.zip!/java.base/java/lang/String.java")).toBe(true);
});
-8
Переглянути файл
@@ -34,14 +34,6 @@
gap: 2px;
padding: 4px 0;
border-right: 1px solid var(--border);
min-height: 0;
/* A pane shorter than the buttons (the Services detail) scrolls them with the wheel
instead of growing the pane and adding a second scrollbar. */
overflow-y: auto;
scrollbar-width: none;
}
.toolbar::-webkit-scrollbar {
display: none;
}
.toolbarSep {
width: 16px;
+48 -46
Переглянути файл
@@ -59,11 +59,15 @@ export function sessionIcon(s: RunSession): string {
export function SessionPanel({
session,
showLifecycle = true,
onRerun,
onDebug,
onStop,
}: {
session: RunSession;
/** False in the Services detail: the window's own toolbar already offers Run/Debug/Stop for the selection. */
showLifecycle?: boolean;
onRerun?: (() => void) | null;
/** Override the Debug button (Services: rerun the attached debugger's launch); null disables it. */
onDebug?: (() => void) | null;
onStop?: () => void;
}) {
const updating = useApplicationUpdates((s) => s.ids.has(session.id));
const version = useRun((s) => s.versions[session.id] ?? 0);
@@ -165,50 +169,48 @@ export function SessionPanel({
return (
<div className={styles.session}>
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Run actions")}>
{showLifecycle && (
<>
<IconButton
icon="rerun"
title="Rerun"
shortcut={shortcutLabel("run.rerun")}
onClick={() => rerunSession(session.id)}
/>
{/* Switch the launch mode: the same configuration started under the debugger. */}
<IconButton
icon="debug"
title="Debug"
shortcut={shortcutLabel("run.debug")}
onClick={() => void debugSession(session.id)}
/>
{rt.tests && (
<IconButton
icon="rerun"
tone="danger"
title="Rerun Failed Tests"
shortcut={shortcutLabel("run.rerunFailed")}
disabled={!canRerunFailed}
onClick={() => void rerunFailed(session.id)}
/>
)}
<IconButton
icon="stop"
title={session.status === "stopping" ? tx`Stopping… (click to kill)` : "Stop"}
tone={running ? "danger" : "default"}
disabled={!running}
onClick={() => void stopSession(session.id)}
/>
{isUpdatable(session.config) && (
<IconButton
icon="refresh"
title="Update Application"
shortcut={shortcutLabel("run.updateApplication")}
disabled={session.status !== "running" || updating}
onClick={() => showApplicationUpdate(session.id)}
/>
)}
<div className={styles.toolbarSep} />
</>
<IconButton
icon="rerun"
title="Rerun"
shortcut={shortcutLabel("run.rerun")}
disabled={onRerun === null}
onClick={onRerun ?? (() => rerunSession(session.id))}
/>
{/* Switch the launch mode: the same configuration started under the debugger. */}
<IconButton
icon="debug"
title="Debug"
shortcut={shortcutLabel("run.debug")}
disabled={onDebug === null}
onClick={onDebug ?? (() => void debugSession(session.id))}
/>
{rt.tests && (
<IconButton
icon="rerun"
tone="danger"
title="Rerun Failed Tests"
shortcut={shortcutLabel("run.rerunFailed")}
disabled={!canRerunFailed}
onClick={() => void rerunFailed(session.id)}
/>
)}
<IconButton
icon="stop"
title={session.status === "stopping" ? tx`Stopping… (click to kill)` : "Stop"}
tone={running || onStop ? "danger" : "default"}
disabled={!running && !onStop}
onClick={onStop ?? (() => void stopSession(session.id))}
/>
{isUpdatable(session.config) && (
<IconButton
icon="refresh"
title="Update Application"
shortcut={shortcutLabel("run.updateApplication")}
disabled={session.status !== "running" || updating}
onClick={() => showApplicationUpdate(session.id)}
/>
)}
<div className={styles.toolbarSep} />
{!rt.terminal && (
<>
<IconButton
+2 -1
Переглянути файл
@@ -44,7 +44,7 @@ import { invalidateGoModules } from "./goModules";
import { invalidatePythonPackages } from "./pythonPackages";
import { RunWidget } from "./RunWidget";
import { runConfigsRunAnything } from "./runAnything";
import { cleanupRemovedProject, registerRunServiceActions, runServiceProvider } from "./services";
import { cleanupRemovedProject, recordRun, registerRunServiceActions, runServiceProvider } from "./services";
import { liveServiceSession, serviceSessions } from "./serviceSessions";
import { ServiceImportHost } from "./serviceImport";
import { cmakeBuildId } from "./cmake";
@@ -158,6 +158,7 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho
}
if (remoteDebugBlocked(config)) return;
if (!(await prepareLaunch(config, chain, show))) return;
recordRun(config.id);
// Python on a Docker / Compose target: debugpy in the container, the debugger attaches.
if (containerDebuggable(config) && getAction("debug.attach")) {
await debugInContainer(config);
+9
Переглянути файл
@@ -63,6 +63,7 @@ import {
} from "./remote";
import { onRunExited, resetRuns, saveUserConfigs, startRun, useRun } from "./store";
import { newConfigOfType } from "./types";
import { readRan } from "./services";
const cfg = (id: string, extra: Partial<RunConfig> = {}): RunConfig => ({
id,
@@ -356,6 +357,14 @@ describe("remote debugging", () => {
await executeAction("run.debugConfig", local.id);
expect(startConfig).toHaveBeenCalledWith(local);
});
it("remembers a non-Spring-Boot configuration accepted for debugging", async () => {
useProject.setState({ project: { root: "/remember-debug" } as never });
const local = cfg("python:debug", { debugAdapter: "debugpy" });
useRun.setState({ configs: [local], loaded: true });
await executeAction("run.debugConfig", local.id);
expect(readRan("/remember-debug")).toContain(local.id);
});
});
describe("coverage and profiling", () => {
+77 -39
Переглянути файл
@@ -18,7 +18,9 @@ import {
categorizedTypes,
runServiceProvider,
registerRunServiceActions,
DEFAULT_TYPES,
readHidden,
readRan,
readTypes,
runServiceItems,
sessionDetail,
@@ -105,7 +107,7 @@ describe("run configurations in Services", () => {
rerun: null,
show: () => {},
};
const build = (status: DebugServiceSession["status"]) => runServiceItems([c], [], [kind], {}, [{ ...d, status }]);
const build = (status: DebugServiceSession["status"]) => runServiceItems([c], [], [], [], {}, [{ ...d, status }]);
expect(build("running")[0]?.children?.[0]).toMatchObject({
key: "run:config:debug-app",
detail: "Debugging",
@@ -130,10 +132,12 @@ describe("run configurations in Services", () => {
rerun: null,
show: () => {},
};
const direct = runServiceItems([c], [r], ["spring-boot"], {}, [d]);
const direct = runServiceItems([c], [r], DEFAULT_TYPES, [], {}, [d]);
expect(direct[0]?.detail).toBe("1 running");
expect(direct[0]?.children?.[0]?.detail).toBe("Debugging");
const attached = runServiceItems([c], [{ ...r, status: "running" }], ["spring-boot"], {}, [{ ...d, processId: 7 }]);
const attached = runServiceItems([c], [{ ...r, status: "running" }], DEFAULT_TYPES, [], {}, [
{ ...d, processId: 7 },
]);
expect(attached[0]?.detail).toBe("1 running");
expect(attached[0]?.children).toHaveLength(1);
expect(attached[0]?.children?.[0]?.detail).toBe(":8080");
@@ -152,15 +156,15 @@ describe("run configurations in Services", () => {
rerun: null,
show: () => {},
};
expect(runServiceItems([c], [], ["spring-boot"], {}, [d])[0]?.children?.[0]).toMatchObject({
expect(runServiceItems([c], [], DEFAULT_TYPES, [], {}, [d])[0]?.children?.[0]).toMatchObject({
detail: ":8080",
icon: "debug",
dim: false,
});
// A paused debugger still wins over the announced port.
expect(runServiceItems([c], [], ["spring-boot"], {}, [{ ...d, status: "paused" }])[0]?.children?.[0]?.detail).toBe(
"Suspended",
);
expect(
runServiceItems([c], [], DEFAULT_TYPES, [], {}, [{ ...d, status: "paused" }])[0]?.children?.[0]?.detail,
).toBe("Suspended");
});
it("applies display order to detected and saved configurations of every language", () => {
@@ -172,7 +176,7 @@ describe("run configurations in Services", () => {
config("py-a", "python"),
config("py-b", "python"),
];
const items = runServiceItems(configs, [], ["spring-boot", "npm", "python"], {
const items = runServiceItems(configs, [], ["spring-boot", "npm", "python"], [], {
"spring-boot": ["java-b", "java-a"],
npm: ["node-b", "node-a"],
python: ["py-b", "py-a"],
@@ -190,17 +194,23 @@ describe("run configurations in Services", () => {
const second = { ...config("workspace:two:app", kind), cwd: "/workspace/two", module: "two" };
const fresh = config("workspace:two:new", kind);
const configs = [first, second, fresh];
const items = runServiceItems(configs, [], [kind], { [kind]: [second.id, first.id] });
const items = runServiceItems(configs, [], [kind], [], { [kind]: [second.id, first.id] });
expect(items[0]!.children!.map((c) => c.key)).toEqual([second, first, fresh].map((c) => `run:config:${c.id}`));
expect(configs).toEqual([first, second, fresh]);
});
it("orders remembered configurations when their type was not explicitly added", () => {
const items = runServiceItems([build, test], [], [], ["build", "test"], { cargo: ["test", "build"] });
expect(items[0]!.children!.map((c) => c.key)).toEqual(["run:config:test", "run:config:build"]);
});
it("keeps stable service identity and session details after refresh and rename", () => {
const renamed = { ...build, name: "Renamed build" };
const items = runServiceItems(
[renamed, test],
[session("s1", renamed, "running", 1, { httpPort: 8080 })],
["cargo"],
[],
{ cargo: ["test", "build"] },
);
expect(items[0]!.children!.map((c) => [c.key, c.label, c.detail])).toEqual([
@@ -209,23 +219,27 @@ describe("run configurations in Services", () => {
]);
});
it("lists added types fully and keeps other types out", () => {
it("lists added types fully and other types only with their runs", () => {
const sessions = [
session("s1", dev, "finished", 1),
session("s2", dev, "running", 2),
session("s3", scratch, "failed", 3, { exitCode: 2 }),
];
const items = runServiceItems([build, test, dev], sessions, ["cargo"]);
expect(items.map((i) => [i.key, i.label, i.detail])).toEqual([["run:type:cargo", "Cargo", undefined]]);
expect(items.map((i) => [i.key, i.label, i.detail])).toEqual([
["run:type:cargo", "Cargo", undefined],
["run:type:npm", "npm", "1 running"],
["run:type:python", "Python", undefined],
]);
expect(items[0]!.children!.map((c) => [c.key, c.detail, c.dim])).toEqual([
["run:config:build", undefined, true],
["run:config:test", undefined, true],
]);
// The newest session of a configuration decides its state once its type is added.
const npm = runServiceItems([dev], sessions, ["npm"]);
expect(npm[0]!.children!.map((c) => [c.label, c.detail, c.dim, c.icon])).toEqual([
// The newest session of a configuration decides its state.
expect(items[1]!.children!.map((c) => [c.label, c.detail, c.dim, c.icon])).toEqual([
["dev", "Running", false, "run"],
]);
expect(items[2]!.children!.map((c) => [c.key, c.detail])).toEqual([["run:config:context:file", "Failed (exit 2)"]]);
});
it("has no groups without added types or sessions", () => {
@@ -239,14 +253,12 @@ describe("run configurations in Services", () => {
expect(sessionStatus(session("a", build, "finished", 0))).toBe("Finished");
});
it("shows nothing for a type that was never added", () => {
it("shows Spring Boot by default, hidden while the project has none", () => {
const app = config("spring:app", "spring-boot");
expect(runServiceItems([build, app], [], [])).toEqual([]);
const items = runServiceItems([build, app], [], ["spring-boot"]);
expect(runServiceItems([build], [], DEFAULT_TYPES)).toEqual([]);
const items = runServiceItems([build, app], [], DEFAULT_TYPES);
expect(items.map((i) => [i.key, i.label, i.expanded])).toEqual([["run:type:spring-boot", "Spring Boot", true]]);
expect(items[0]!.children!.map((c) => [c.label, c.detail, c.dim])).toEqual([["spring:app", undefined, true]]);
// An added type stays listed without configurations until it is removed again.
expect(runServiceItems([build], [], ["spring-boot"])[0]!.children).toEqual([]);
});
it("shows the HTTP port of a running application instead of its state", () => {
@@ -255,39 +267,62 @@ describe("run configurations in Services", () => {
expect(sessionDetail(running)).toBe(":8080");
expect(sessionDetail(session("s1", app, "running", 1))).toBe("Running");
expect(sessionDetail(session("s1", app, "finished", 1, { httpPort: 8080, stopped: true }))).toBe("Stopped");
expect(runServiceItems([app], [running], ["spring-boot"])[0]!.children![0]!.detail).toBe(":8080");
expect(runServiceItems([app], [running], DEFAULT_TYPES)[0]!.children![0]!.detail).toBe(":8080");
});
});
describe("types added to Services", () => {
beforeEach(() => localStorage.clear());
it("starts empty and persists the user's list per project", () => {
expect(readTypes("/p")).toEqual([]);
it("defaults to Spring Boot and persists the user's list per project", () => {
expect(readTypes("/p")).toEqual(["spring-boot"]);
localStorage.setItem("openidea.services.runTypes:/p", JSON.stringify(["npm"]));
expect(readTypes("/p")).toEqual(["npm"]);
localStorage.setItem("openidea.services.runTypes:/p", "[]");
expect(readTypes("/p")).toEqual([]);
expect(readTypes("/q")).toEqual([]);
expect(readTypes("/q")).toEqual(["spring-boot"]);
});
});
describe("sessions of types not added", () => {
describe("configurations that ran", () => {
const dev = config("dev", "npm");
const scratch = config("context:file", "python");
beforeEach(() => localStorage.clear());
it("keeps the type out of Services", () => {
expect(runServiceItems([dev], [session("s1", dev, "running", 1)], [])).toEqual([]);
it("persists the ran configuration ids per project", () => {
expect(readRan("/p")).toEqual([]);
localStorage.setItem("openidea.services.ran:/p", JSON.stringify(["dev"]));
expect(readRan("/p")).toEqual(["dev"]);
expect(readRan("/q")).toEqual([]);
});
it("lists previously run configurations without a session", () => {
const items = runServiceItems([dev, scratch], [], [], ["dev", "context:file"]);
expect(items.map((i) => [i.key, i.label])).toEqual([
["run:type:npm", "npm"],
["run:type:python", "Python"],
]);
expect(items[0]!.children!.map((c) => [c.label, c.dim])).toEqual([["dev", true]]);
expect(items[1]!.children!.map((c) => c.key)).toEqual(["run:config:context:file"]);
});
it("ignores ran ids whose configuration is gone and merges sessions", () => {
const gone = runServiceItems([dev], [], [], ["missing"]);
expect(gone).toEqual([]);
const running = session("s1", dev, "running", 1);
const items = runServiceItems([dev], [running], [], ["dev"]);
expect(items).toHaveLength(1);
expect(items[0]!.children!.map((c) => [c.label, c.detail])).toEqual([["dev", "Running"]]);
});
it("drops a deleted configuration once its run has ended (#1497)", () => {
const removed = (id: string) => id === "dev";
const ended = runServiceItems([], [session("s1", dev, "finished", 1)], ["npm"], {}, [], removed);
expect(ended[0]!.children).toEqual([]);
const live = runServiceItems([], [session("s1", dev, "running", 1)], ["npm"], {}, [], removed);
const ended = runServiceItems([], [session("s1", dev, "finished", 1)], [], ["dev"], {}, [], removed);
expect(ended).toEqual([]);
const live = runServiceItems([], [session("s1", dev, "running", 1)], [], ["dev"], {}, [], removed);
expect(live[0]!.children!.map((c) => [c.label, c.detail])).toEqual([["dev", "Running"]]);
// Never a saved configuration (a build task, an external tool): its finished run stays.
const adHoc = runServiceItems([], [session("s2", scratch, "finished", 1)], ["python"], {}, [], removed);
const adHoc = runServiceItems([], [session("s2", scratch, "finished", 1)], [], [], {}, [], removed);
expect(adHoc[0]!.children!.map((c) => c.key)).toEqual(["run:config:context:file"]);
});
});
@@ -310,24 +345,25 @@ describe("hidden configurations", () => {
const a = config("a", "spring-boot");
const b = config("b", "spring-boot");
it("hides a configuration even while it runs", () => {
it("hides a configuration unless it runs", () => {
const hidden = { "spring-boot": ["a"] };
const stopped = runServiceItems([a, b], [], ["spring-boot"], {}, [], () => false, hidden);
const stopped = runServiceItems([a, b], [], DEFAULT_TYPES, [], {}, [], () => false, hidden);
expect(stopped[0]!.children!.map((c) => c.key)).toEqual(["run:config:b"]);
const running = runServiceItems(
[a, b],
[session("s1", a, "running", 1)],
["spring-boot"],
DEFAULT_TYPES,
[],
{},
[],
() => false,
hidden,
);
expect(running[0]!.children!.map((c) => c.key)).toEqual(["run:config:b"]);
expect(running[0]!.children!.map((c) => c.key)).toEqual(["run:config:a", "run:config:b"]);
});
it("keeps an added type's group whose configurations are all hidden", () => {
const items = runServiceItems([a], [], ["spring-boot"], {}, [], () => false, { "spring-boot": ["a"] });
it("keeps an empty default group whose configurations are all hidden", () => {
const items = runServiceItems([a], [], DEFAULT_TYPES, [], {}, [], () => false, { "spring-boot": ["a"] });
expect(items).toHaveLength(1);
expect(items[0]!.children).toEqual([]);
});
@@ -348,7 +384,8 @@ describe("hidden configurations", () => {
const items = runServiceItems(
[compose, dockerfile, image],
[session("s1", compose, "running", 1), session("s2", dockerfile, "finished", 2)],
["docker-compose", "docker-dockerfile", "docker-image"],
[...DEFAULT_TYPES, "docker-compose", "docker-dockerfile", "docker-image"],
[compose.id, dockerfile.id, image.id],
);
expect(items).toEqual([]);
});
@@ -547,7 +584,6 @@ describe("group batch actions", () => {
it("uses the saved display order and leaves other types alone", async () => {
useProject.setState({ project: { root: "/group-order" } as never });
localStorage.setItem("openidea.services.runTypes:/group-order", JSON.stringify(["spring-boot"]));
localStorage.setItem("openidea.services.runOrder:/group-order", JSON.stringify({ "spring-boot": ["c", "a", "b"] }));
const configs = [
config("a", "spring-boot"),
@@ -635,6 +671,7 @@ describe("removing a workspace member from Services", () => {
sessions: [session("s1", main, "finished", 1), session("s2", vue, "running", 2, { runId: 7 })],
});
localStorage.setItem("openidea.services.runTypes:/w/main", JSON.stringify(["spring-boot", "npm"]));
localStorage.setItem("openidea.services.ran:/w/main", JSON.stringify(["app", "dev"]));
await cleanupRemovedProject("/w/vue");
@@ -643,6 +680,7 @@ describe("removing a workspace member from Services", () => {
expect(s.configs.map((c) => c.id)).toEqual(["app"]);
expect(s.temporary).toEqual([]);
expect(readTypes("/w/main")).toEqual(["spring-boot"]);
expect(readRan("/w/main")).toEqual(["app"]);
expect(ipc.runConfigs).toHaveBeenCalled();
});
@@ -720,6 +758,6 @@ describe("service selection", () => {
await pending;
await Promise.resolve();
expect(readHidden("/other-selection")).toEqual({});
expect(readTypes("/other-selection")).toEqual([]);
expect(readTypes("/other-selection")).toEqual(DEFAULT_TYPES);
});
});
+106 -22
Переглянути файл
@@ -1,10 +1,10 @@
/**
* Run configurations in the Services tool window (IDEA's Run Dashboard): the
* configuration types added there ("Add Service › Run Configuration Type"), one
* group each, with run / debug / stop / rerun per configuration. Nothing else is
* listed, and what is removed leaves at once; a run it started keeps its console
* in the Run tool window. A configuration that ran shows its console in the
* detail pane, a running web application its HTTP port.
* Run configurations in the Services tool window (IDEA's Run Dashboard): Spring
* Boot by default, the configuration types added there ("Add Service › Run
* Configuration Type"), the types of this window's run sessions and the
* configurations that ran before (kept per project across restarts), one group
* each, with run / debug / stop / rerun per configuration. A configuration that
* ran shows its console in the detail pane, a running web application its HTTP port.
*/
import { useEffect, useMemo } from "react";
import { create } from "zustand";
@@ -33,6 +33,7 @@ import { showApplicationUpdate } from "./applicationUpdate";
import { isUpdatable } from "./updatePolicies";
import {
configRemoved,
debugSession,
loadConfigs,
persistTemporary,
rerunConfig,
@@ -67,6 +68,9 @@ export const RUN_PROVIDER = "runConfigurations";
const TYPE_PREFIX = "run:type:";
const CONFIG_PREFIX = "run:config:";
const STORAGE_KEY = "openidea.services.runTypes:";
const RAN_KEY = "openidea.services.ran:";
/** Types shown in Services until the user changes the list. */
export const DEFAULT_TYPES: readonly string[] = ["spring-boot"];
/** Docker run kinds whose containers/deployments are already shown under the Docker provider in Services. */
const DOCKER_PROVIDER_KINDS: ReadonlySet<string> = new Set(["docker-compose", "docker-dockerfile", "docker-image"]);
@@ -75,15 +79,15 @@ const DOCKER_PROVIDER_KINDS: ReadonlySet<string> = new Set(["docker-compose", "d
const useAddedTypes = create<{ root: string | null; types: string[] }>(() => ({ root: null, types: [] }));
/** The project's types; empty until the user adds one with "Add Service". */
/** The project's types; Spring Boot until the user changes the list. */
export function readTypes(root: string): string[] {
try {
const raw = localStorage.getItem(STORAGE_KEY + root);
if (raw === null) return [];
if (raw === null) return [...DEFAULT_TYPES];
const v: unknown = JSON.parse(raw);
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
} catch {
return [];
return [...DEFAULT_TYPES];
}
}
@@ -114,6 +118,41 @@ export function removeType(kind: string) {
setAddedTypes(currentTypes().filter((t) => t !== kind));
}
// ---------------------------------------------------------------------------
// Configurations that ran, per project (shown again after a restart)
const useRanConfigs = create<{ root: string | null; ids: string[] }>(() => ({ root: null, ids: [] }));
/** The project's previously run configuration ids, most recent last. */
export function readRan(root: string): string[] {
try {
const raw = localStorage.getItem(RAN_KEY + root);
if (raw === null) return [];
const v: unknown = JSON.parse(raw);
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
} catch {
return [];
}
}
function ranIds(root: string | null): string[] {
const s = useRanConfigs.getState();
return s.root === root ? s.ids : root ? readRan(root) : [];
}
/** Records a run, so its configuration is back in Services after a restart. */
export function recordRun(configId: string) {
const root = useProject.getState().project?.root ?? null;
const ids = [...ranIds(root).filter((id) => id !== configId), configId];
useRanConfigs.setState({ root, ids });
if (!root) return;
try {
localStorage.setItem(RAN_KEY + root, JSON.stringify(ids));
} catch {
/* storage unavailable */
}
}
// ---------------------------------------------------------------------------
// Project removal: a workspace member's data leaves with it
@@ -126,7 +165,7 @@ function insideRoot(path: string, root: string): boolean {
* Drops a removed workspace member's data from Services: stops and forgets its
* sessions (a finished one still groups the tree), removes its temporary
* configurations, reloads (the backend no longer lists the member) and clears
* the added types that would otherwise render empty groups.
* the added types and remembered runs that would otherwise render empty groups.
*/
export async function cleanupRemovedProject(removedRoot: string): Promise<void> {
const { configs, sessions, temporary } = useRun.getState();
@@ -157,6 +196,20 @@ export async function cleanupRemovedProject(removedRoot: string): Promise<void>
const { configs: fresh, sessions: liveSessions } = useRun.getState();
const liveKinds = new Set([...fresh.map((c) => c.kind), ...liveSessions.map((s) => s.config.kind)]);
for (const kind of kinds) if (!liveKinds.has(kind)) removeType(kind);
const root = useProject.getState().project?.root ?? null;
if (root) {
const freshIds = new Set(fresh.map((c) => c.id));
const ids = ranIds(root).filter((id) => freshIds.has(id));
if (ids.length !== ranIds(root).length) {
useRanConfigs.setState({ root, ids });
try {
localStorage.setItem(RAN_KEY + root, JSON.stringify(ids));
} catch {
/* storage unavailable */
}
}
}
}
// Configurations hidden from Services, per project (removed one by one; "Add Service" restores)
@@ -200,7 +253,7 @@ function saveHidden(hidden: Record<string, string[]>) {
}
}
/** Removes one configuration from Services at once, even while it runs (its console is in the Run window). */
/** Removes one configuration from Services; it reappears while it runs (its console stays reachable). */
function hideConfig(kind: string, id: string) {
const hidden = currentHidden();
if ((hidden[kind] ?? []).includes(id)) return;
@@ -258,15 +311,15 @@ function executionDetail(s: ServiceSession | undefined): string | undefined {
}
/**
* Groups by configuration type: only the types added in this window list their
* configurations, and a configuration removed from the window stays out even
* while it runs (its console is in the Run tool window). A configuration deleted
* since it ran (`removed`) stays only while its run is live.
* Groups by configuration type: added types list all their configurations, other
* types only those that ran. A default type (Spring Boot) without configurations is hidden.
* A configuration deleted since it ran (`removed`) stays only while its run is live.
*/
export function runServiceItems(
configs: readonly RunConfig[],
sessions: readonly RunSession[],
added: readonly string[],
ran: readonly string[] = [],
order: ServiceOrder = {},
debug: readonly DebugServiceSession[] = [],
removed: (id: string) => boolean = () => false,
@@ -276,12 +329,28 @@ export function runServiceItems(
const latest = currentServiceSessions(executions);
const kinds = added.filter((kind) => !DOCKER_PROVIDER_KINDS.has(kind));
const shown = (s: ServiceSession) => liveServiceSession(s) || !removed(s.config.id);
for (const s of executions)
if (shown(s) && !DOCKER_PROVIDER_KINDS.has(s.config.kind) && !kinds.includes(s.config.kind))
kinds.push(s.config.kind);
for (const id of ran) {
const kind = configs.find((c) => c.id === id)?.kind;
if (kind && !DOCKER_PROVIDER_KINDS.has(kind) && !kinds.includes(kind)) kinds.push(kind);
}
return kinds.flatMap((kind) => {
const entries: RunConfig[] = configs.filter((c) => c.kind === kind);
const entries: RunConfig[] = added.includes(kind)
? configs.filter((c) => c.kind === kind)
: ran.map((id) => configs.find((c) => c.id === id)).filter((c): c is RunConfig => !!c && c.kind === kind);
for (const s of latest.values())
if (s.config.kind === kind && shown(s) && !entries.some((c) => c.id === s.config.id)) entries.push(s.config);
// Hidden configurations reappear only while they run (their console stays reachable).
const hiddenIds = new Set(hidden[kind] ?? []);
const visible = entries.filter((c) => !hiddenIds.has(c.id));
const visible = entries.filter((c) => {
if (!hiddenIds.has(c.id)) return true;
const s = latest.get(c.id);
return !!s && liveServiceSession(s);
});
// Keep an empty group only when its existing configurations can be restored.
if (!visible.length && DEFAULT_TYPES.includes(kind) && !configs.some((c) => c.kind === kind)) return [];
const children = orderServices(visible, order[kind]).map((c): ServiceTreeItem => {
const s = latest.get(c.id);
return {
@@ -319,24 +388,28 @@ function useRoots(): ServiceTreeItem[] {
const debug = useDebugRunSessions((s) => s.serviceSessions);
const types = useAddedTypes((s) => s.types);
const typesRoot = useAddedTypes((s) => s.root);
const ran = useRanConfigs((s) => s.ids);
const ranRoot = useRanConfigs((s) => s.root);
const hidden = useHiddenConfigs((s) => s.hidden);
const hiddenLocation = useHiddenConfigs((s) => s.location);
useEffect(() => {
if (typesRoot !== root) useAddedTypes.setState({ root, types: root ? readTypes(root) : [] });
if (ranRoot !== root) useRanConfigs.setState({ root, ids: root ? readRan(root) : [] });
if (hiddenLocation !== location) useHiddenConfigs.setState({ location, hidden: readHidden(location) });
}, [root, typesRoot, hiddenLocation, location]);
}, [root, typesRoot, ranRoot, hiddenLocation, location]);
return useMemo(
() =>
runServiceItems(
configs,
sessions,
typesRoot === root ? types : [],
ranRoot === root ? ran : [],
order,
debug,
configRemoved,
hiddenLocation === location ? hidden : {},
),
[configs, sessions, types, typesRoot, root, order, debug, hidden, hiddenLocation, location],
[configs, sessions, types, typesRoot, ran, ranRoot, root, order, debug, hidden, hiddenLocation, location],
);
}
@@ -404,6 +477,7 @@ function groupConfigs(kind: string): RunConfig[] {
configs,
sessions,
currentTypes(),
ranIds(root),
location ? currentServiceOrder(location) : {},
debug,
configRemoved,
@@ -670,11 +744,20 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
</div>
</EmptyState>
);
// The configuration ran: its console, as in the Run tool window. Run / Debug / Stop
// come from this window's toolbar (the selection), so the console strip leaves them out.
// The configuration ran: its console, as in the Run tool window.
if (r.session?.run) {
const execution = r.session;
return <SessionPanel key={execution.run!.id} session={execution.run!} showLifecycle={false} />;
const d = serviceDebugger(execution);
const rerun = d ? (d.rerunInPlace ?? d.rerun) : undefined;
return (
<SessionPanel
key={execution.run!.id}
session={execution.run!}
onRerun={d ? rerun : () => run(r)}
onDebug={d ? rerun : () => debugSession(execution.run!.id, { show: false })}
onStop={d ? () => void stopServiceSessions([execution]) : undefined}
/>
);
}
const d = r.session?.debug[0];
if (d && Console)
@@ -825,6 +908,7 @@ export const runServiceProvider: ServiceProviderContribution = {
configs,
sessions,
currentTypes(),
ranIds(useProject.getState().project?.root ?? null),
order,
useDebugRunSessions.getState().serviceSessions,
configRemoved,
+3
Переглянути файл
@@ -59,6 +59,7 @@ import { remoteLabel, startWithRemedies } from "./remote";
import { TerminalOutput } from "./terminalOutput";
import { typeFor } from "./types";
import { loadRunTemplates } from "./runTemplates";
import { recordRun } from "./services";
import { startedPort } from "@/platform/serverPort";
import { tomcatBrowserUrl } from "./tomcat";
import { gradleBootLaunch, gradleDelegation, gradleTestLaunch } from "./gradleRun";
@@ -831,6 +832,8 @@ export async function startRun(
useRun.setState((s) => ({ sessions: [...s.sessions, created], activeSession: created.id }));
}
bump(session.id);
// The Services tool window lists the configuration again after a restart.
recordRun(config.id);
const sessionId = session.id;
const rt = runtimes.get(sessionId)!;
const generation = rt.generation;
+11 -18
Переглянути файл
@@ -56,8 +56,6 @@ let dispose: () => void;
let disposeActions: () => void;
beforeEach(() => {
localStorage.clear();
// The types are added by hand, as in the real window (nothing shows by default).
localStorage.setItem("openidea.services.runTypes:/services-debug", JSON.stringify(["spring-boot", "shell"]));
useProject.setState({
project: { root: "/services-debug", name: "app", isGit: false, settings: validateSettings({}) } as never,
});
@@ -146,7 +144,7 @@ it("reruns a debug service in place from the Services panel", () => {
expect(d.rerun).not.toHaveBeenCalled();
});
it("starts a debug session in place from the Services toolbar", async () => {
it("starts a debug session in place from a run service's detail toolbar", async () => {
const start = vi.fn();
const disposeAction = registerActions([
{ id: "run.debugConfig", title: "Debug Configuration", run: ({ arg }) => start(arg) },
@@ -155,18 +153,18 @@ it("starts a debug session in place from the Services toolbar", async () => {
const s = await startRun(c);
expect(s).not.toBeNull();
useRun.setState({ configs: [c], sessions: [{ ...s!, config: c, status: "running" as const }] });
useServicesTree.setState({ expanded: new Set(["run:type:shell"]) });
try {
render(<ServicesTreeView />);
select();
fireEvent.click(toolbar().getByRole("button", { name: "Debug" }));
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
fireEvent.click(actions.getByRole("button", { name: "Debug" }));
await vi.waitFor(() => expect(start).toHaveBeenCalledWith({ config: c, show: false }));
} finally {
disposeAction();
}
});
it("reruns a plain run service in place from the Services toolbar", async () => {
it("reruns a plain run service in place from its detail toolbar", async () => {
const c = { ...config, kind: "shell", command: "echo", debugAdapter: null };
const s = await startRun(c);
expect(s).not.toBeNull();
@@ -177,12 +175,12 @@ it("reruns a plain run service in place from the Services toolbar", async () =>
const previousRuntime = runtime(s!.id);
render(<ServicesTreeView />);
select();
fireEvent.click(toolbar().getByRole("button", { name: /^(Run|Rerun)$/ }));
fireEvent.click(within(screen.getByRole("toolbar", { name: "Run actions" })).getByRole("button", { name: "Rerun" }));
await vi.waitFor(() => expect(runtime(s!.id)).not.toBe(previousRuntime));
expect(show).not.toHaveBeenCalled();
});
it("reruns an attached debugger in place from the Services toolbar", async () => {
it("reruns an attached debugger in place from a run service's detail toolbar", async () => {
const c = { ...config, kind: "shell", command: "echo", debugAdapter: null };
const s = await startRun(c);
expect(s).not.toBeNull();
@@ -193,7 +191,8 @@ it("reruns an attached debugger in place from the Services toolbar", async () =>
useDebugRunSessions.setState({ serviceSessions: [d] });
render(<ServicesTreeView />);
select();
fireEvent.click(toolbar().getByRole("button", { name: "Debug" }));
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
fireEvent.click(actions.getByRole("button", { name: "Debug" }));
expect(d.rerunInPlace).toHaveBeenCalledOnce();
expect(d.rerun).not.toHaveBeenCalled();
});
@@ -216,7 +215,7 @@ it("keeps the other parallel instance alive and then displays it", async () => {
expect(screen.getByRole("log")).toHaveTextContent("first instance");
});
it("shows the owning Run output for attached debugging and routes the controls through the Services toolbar", async () => {
it("shows the owning Run output for attached debugging and overrides both sets of controls", async () => {
const stopRun = vi.spyOn(commands, "runStop").mockImplementation(async (id) => {
queueMicrotask(() => onRunExited(id, 130));
return { status: "ok", data: null };
@@ -232,14 +231,8 @@ it("shows the owning Run output for attached debugging and routes the controls t
render(<ServicesTreeView />);
select();
expect(screen.getByRole("log")).toHaveTextContent("Maven application log");
// The console strip keeps only console controls: the window toolbar owns Run / Debug / Stop.
const strip = within(screen.getByRole("toolbar", { name: "Run actions" }));
expect(strip.queryByRole("button", { name: "Rerun" })).toBeNull();
expect(strip.queryByRole("button", { name: "Debug" })).toBeNull();
expect(strip.queryByRole("button", { name: "Stop" })).toBeNull();
expect(strip.getByRole("button", { name: "Clear All" })).toBeTruthy();
const actions = toolbar();
fireEvent.click(actions.getByRole("button", { name: /^(Run|Rerun)$/ }));
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
fireEvent.click(actions.getByRole("button", { name: "Rerun" }));
expect(d.rerun).toHaveBeenCalledOnce();
await act(async () => fireEvent.click(actions.getByRole("button", { name: "Stop" })));
expect(stopRun).toHaveBeenCalledExactlyOnceWith(7);
+1 -8
Переглянути файл
@@ -272,14 +272,7 @@ export function ServicesTreeView() {
</div>
</SplitPanel>
<SplitHandle />
<SplitPanel
id="services-detail"
minSize="200px"
// The panel library puts `overflow: auto` inline; the detail content
// (a console, a log) owns its scrolling, so the pane must not add a second
// bar. A column flex box lets that content fill the pane.
style={{ overflow: "hidden", height: "100%", display: "flex", flexDirection: "column" }}
>
<SplitPanel id="services-detail" minSize="200px">
{selected && Detail && shown ? (
<Detail key={selected.item.key} item={selected.item} />
) : (
-2
Переглянути файл
@@ -140,8 +140,6 @@ export function dockerItems(
icon: snap?.availability.kind === "ready" ? "docker-connected" : "file-docker",
detail: connectionDetail(state),
dim: snap?.availability.kind !== "ready",
// A connection the user just added opens once, so its groups are in sight.
expanded: true,
children: children(root)?.map(convert) ?? [],
};
});
+1 -1
Переглянути файл
@@ -21,7 +21,7 @@ export const useServicesTree = create<TreeState>(() => ({
roots: {},
selectedKey: null,
selectedKeys: new Set(),
expanded: new Set(),
expanded: new Set(["docker:default", "docker:default:group:containers"]),
}));
/** Keys of nodes asking to start expanded that were shown once (collapsing them then sticks). */
+2 -47
Переглянути файл
@@ -116,55 +116,12 @@ describe("scheme actions", () => {
it("shows a malformed-file error without staging any changes", async () => {
mocks.read.mockResolvedValueOnce({ status: "ok", data: '<scheme name="bad">' });
await run("import");
await waitFor(() =>
expect(mocks.error).toHaveBeenCalledWith("Import Scheme", expect.stringContaining("Invalid .icls color scheme")),
);
await waitFor(() => expect(mocks.error).toHaveBeenCalledWith("Color Scheme", "Invalid .icls color scheme"));
expect(useSettingsDialog.getState().staged).toEqual({});
});
it("offers .xml scheme files in the chooser and imports one (#2714)", async () => {
mocks.open.mockResolvedValueOnce("/downloads/Material Darker.xml");
mocks.read.mockResolvedValueOnce({
status: "ok",
data: readFileSync("src/platform/__fixtures__/colorSchemes/material-darker.xml", "utf8"),
});
await run("import");
expect(mocks.open).toHaveBeenCalledWith({
multiple: false,
filters: [{ name: "IntelliJ Color Scheme", extensions: ["icls", "xml"] }],
});
expect(value("colorScheme")).toMatch(/^custom-/);
expect(screen.getByRole("status")).toHaveTextContent("Applied 12 values; skipped 3");
const schemes = value("customSchemes") as Record<string, { name: string }>;
expect(Object.values(schemes).some((s) => s.name === "Material Darker")).toBe(true);
});
it("names a scheme without a name attribute after its file (#2714)", async () => {
mocks.open.mockResolvedValueOnce("/downloads/one-dark-wrapped.xml");
mocks.read.mockResolvedValueOnce({
status: "ok",
data: readFileSync("src/platform/__fixtures__/colorSchemes/one-dark-wrapped.xml", "utf8"),
});
await run("import");
const schemes = value("customSchemes") as Record<string, { name: string }>;
expect(Object.values(schemes).some((s) => s.name === "one-dark-wrapped")).toBe(true);
});
});
describe("python scheme attributes", () => {
it("groups Python attributes as PyCharm does", () => {
schemePage("editor.colorScheme.python");
const tree = screen.getByRole("tree", { name: "Color scheme attributes" });
// The tree virtualizes; a collapsed group renders before its siblings, so a group near
// the top is enough to prove grouping, and expanding it shows its leaves.
expect(within(tree).getByRole("treeitem", { name: "Functions" })).toBeInTheDocument();
for (const flat of ["Byte string", "F-string", "Method call"])
expect(within(tree).queryByRole("treeitem", { name: flat })).toBeNull();
const functions = within(tree).getByRole("treeitem", { name: "Functions" });
act(() => fireEvent.mouseDown(within(functions).getByText("Functions").previousElementSibling!, { button: 0 }));
expect(within(tree).getByRole("treeitem", { name: "Method call" })).toBeInTheDocument();
});
describe("doc comment scheme attributes", () => {
it("selects Python docstring tags and keywords from their preview", () => {
schemePage("editor.colorScheme.python");
const preview = screen.getByLabelText("Color scheme preview");
@@ -177,9 +134,7 @@ describe("python scheme attributes", () => {
act(() => fireEvent.click(keyword));
expect(screen.getByRole("treeitem", { name: "Keyword", selected: true })).toBeInTheDocument();
});
});
describe("doc comment scheme attributes", () => {
it.each([
["en", "Doc comment", "Tag", "Tag value", "Markup"],
["zh", "文档注释", "标签", "标签值", "标记"],
+3 -6
Переглянути файл
@@ -104,7 +104,7 @@ export interface ValidSettings extends WorkflowSettings {
/** Tools › Agents › Chat: the meters in an agent task's header. */
agents: Required<AgentSettings>;
/** Agents › IDE MCP Server (global). */
mcpServer: { enabled: boolean; runWithoutConfirmation: boolean };
mcpServer: { enabled: boolean };
}
/** One `languageServers.<name>` entry; every field optional, like in settings.toml. */
@@ -193,7 +193,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
defaults: {},
mcpServers: {},
},
mcpServer: { enabled: false, runWithoutConfirmation: false },
mcpServer: { enabled: false },
...DEFAULT_WORKFLOW,
};
@@ -359,10 +359,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
defaults: agentDefaults(agents.defaults),
mcpServers: agentMcpServers(agents.mcpServers),
},
mcpServer: {
enabled: bool(obj(root.mcpServer).enabled, d.mcpServer.enabled),
runWithoutConfirmation: bool(obj(root.mcpServer).runWithoutConfirmation, d.mcpServer.runWithoutConfirmation),
},
mcpServer: { enabled: bool(obj(root.mcpServer).enabled, d.mcpServer.enabled) },
...validateWorkflow(root),
};
}
+6 -13
Переглянути файл
@@ -28,7 +28,7 @@ import styles from "./Editor.module.css";
import { executeAction, registerActions } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { ask, confirm, showError } from "@/workbench/messages";
import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
import { parseIcls, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
import { tx, useTx } from "@/platform/i18n";
import { selectPage } from "../../model/staging";
@@ -1158,17 +1158,10 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
file ??
(await open({
multiple: false,
// IDEA schemes ship as .icls, but the ones people download are frequently .xml.
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls", "xml"] }],
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }],
}));
if (!path) return;
// A scheme element without a name is named after its file, as IntelliJ does.
const fallbackName =
path
.split(/[\\/]/)
.at(-1)
?.replace(/\.[^.]+$/, "") || "Imported scheme";
const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName);
const parsed = parseIcls(await call(commands.fsReadText(path)));
let overwrite = false;
if (schemes.some((s) => s.name === parsed.scheme.name)) {
const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name);
@@ -1239,9 +1232,9 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
await handlers.current[name]!(typeof arg === "string" ? arg : undefined);
} catch (error) {
await showError(
tx("Import Scheme"),
error instanceof SchemeParseError
? `${tx("Invalid .icls color scheme")}: ${error.message}`
tx("Color Scheme"),
error instanceof Error && error.message === "Invalid .icls color scheme"
? tx("Invalid .icls color scheme")
: String(error),
);
} finally {
-6
Переглянути файл
@@ -128,12 +128,6 @@ export const MCP_SERVER_PAGE: PageSpec = {
label: "Enable MCP server",
hint: "Agents can read, edit, and run projects open in OpenIDEA through its built-in tools. Run tools ask for confirmation. The server listens on 127.0.0.1 only and requires a token.",
},
{
kind: "toggle",
key: "mcpServer.runWithoutConfirmation",
label: "Run tools without confirmation (brave mode)",
hint: "Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.",
},
{
kind: "custom",
label: "Endpoint",
-7
Переглянути файл
@@ -1,7 +0,0 @@
<scheme name="Bom Light" version="142" parent_scheme="Default">
<colors><option name="CARET_COLOR" value="ff00ff" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="1122ff" /><option name="FONT_TYPE" value="1" /></value></option>
<option name="TEXT"><value><option name="FOREGROUND" value="334455" /><option name="BACKGROUND" value="f0f0f0" /></value></option>
</attributes>
</scheme>
-9
Переглянути файл
@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="windows-1252"?>
<!-- Saved by a Windows editor: the declaration describes the file's bytes, while a
caller hands parseIcls already decoded text. The name must survive unchanged. -->
<scheme name="Café Solar" version="142" parent_scheme="Default">
<colors><option name="CARET_COLOR" value="ffcc00" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="cc7832" /></value></option>
</attributes>
</scheme>
-89
Переглянути файл
@@ -1,89 +0,0 @@
<!--
~ The MIT License (MIT)
~
~ Copyright (c) 2015-2021 Elior "Mallowigi" Boukhobza
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all
~ copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
~ SOFTWARE.
~
~
-->
<scheme name="Material Darker" version="142" parent_scheme="Darcula">
<option name="FONT_SCALE" value="1.0" />
<metaInfo>
<property name="created">2017-04-10T18:10:53</property>
<property name="ide">idea</property>
<property name="ideVersion">2020.1.0.0</property>
<property name="modified">2020-04-18T11:14:57</property>
<property name="originalScheme">Material Darker</property>
</metaInfo>
<option name="LINE_SPACING" value="1.4" />
<option name="EDITOR_FONT_SIZE" value="12" />
<font>
<option name="EDITOR_FONT_NAME" value="Menlo" />
<option name="EDITOR_FONT_SIZE" value="12" />
</font>
<font>
<option name="EDITOR_FONT_NAME" value="Fira Code" />
<option name="EDITOR_FONT_SIZE" value="12" />
</font>
<console-font>
<option name="EDITOR_FONT_NAME" value="Menlo" />
<option name="EDITOR_FONT_SIZE" value="12" />
</console-font>
<console-font>
<option name="EDITOR_FONT_NAME" value="Fira Code" />
<option name="EDITOR_FONT_SIZE" value="12" />
</console-font>
<colors>
<option name="CARET_COLOR" value="ffcc00" />
<option name="CARET_ROW_COLOR" value="181818" />
<option name="CONSOLE_BACKGROUND_KEY" value="212121" />
<option name="DELETED_LINES_COLOR" value="f07178" />
<option name="GUTTER_BACKGROUND" value="212121" />
<option name="LINE_NUMBERS_COLOR" value="424242" />
<option name="SELECTION_BACKGROUND" value="353535" />
</colors>
<attributes>
<option name="DEFAULT_KEYWORD">
<value>
<option name="FOREGROUND" value="c792ea" />
<option name="FONT_TYPE" value="2" />
</value>
</option>
<option name="DEFAULT_STRING">
<value>
<option name="FOREGROUND" value="c3e88d" />
</value>
</option>
<option name="DEFAULT_LINE_COMMENT">
<value>
<option name="FOREGROUND" value="616161" />
<option name="FONT_TYPE" value="2" />
</value>
</option>
<option name="TEXT">
<value>
<option name="FOREGROUND" value="eeffff" />
<option name="BACKGROUND" value="212121" />
<option name="EFFECT_TYPE" value="5" />
</value>
</option>
</attributes>
</scheme>
-11
Переглянути файл
@@ -1,11 +0,0 @@
<application>
<component name="EditorColorsSchemeImpl">
<scheme version="142" parent_scheme="Darcula">
<colors><option name="SELECTION_BACKGROUND" value="3a3d41" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="c678dd" /><option name="FONT_TYPE" value="1" /></value></option>
<option name="TEXT"><value><option name="FOREGROUND" value="abb2bf" /><option name="BACKGROUND" value="282c34" /></value></option>
</attributes>
</scheme>
</component>
</application>
-15
Переглянути файл
@@ -58,21 +58,6 @@ describe("color schemes", () => {
expect(css).toContain("--syn-constant: #224466 !important");
});
it("groups Python attributes as PyCharm's color settings page does", () => {
const python = (name: string) => ATTRIBUTES.find((a) => a.id === `py${name}`)!;
expect(python("FString").name).toBe("String › f-string › Expression braces");
expect(python("Bytes").name).toBe("String › Binary (bytes)");
expect(python("Docstring").name).toBe("Docstring › Text");
expect(python("MethodCall").name).toBe("Functions › Method call");
expect(python("NestedFunction").name).toBe("Functions › Nested function definition");
expect(python("Self").name).toBe("Parameters › 'self' parameter");
expect(python("PredefinedDefinition").name).toBe("Special names › Definition");
expect(python("PredefinedUsage").name).toBe("Special names › Usage");
expect(python("Parentheses").name).toBe("Braces and Operators › Parentheses");
// Attribute ids (the override and .icls keys) keep their old, stable names.
for (const a of ATTRIBUTES.filter((a) => a.path[0] === "Python")) expect(a.id).toMatch(/^py[A-Z]/);
});
it("resolves scheme attribute state and editor defaults", () => {
expect(resolvedAttribute("light", "lineComment")).toMatchObject({
foreground: "#8c8c8c",
+24 -25
Переглянути файл
@@ -154,32 +154,18 @@ const BASE_ATTRIBUTES: readonly AttributeDef[] = [
...[1, 2, 3, 4, 5].map((n) => syn(`semantic${n}`, `Semantic highlighting › Color ${n}`, [LD], `rainbow-${n}`)),
...[1, 2, 3].map((n) => syn(`bracket${n}`, `Rainbow brackets › Level ${n}`, [LD], `bracket-${n}`)),
// Python's tree mirrors PyCharm's groups and their order (PySyntaxBundle.properties in python-syntax).
syn("pyBytes", "String › Binary (bytes)", ["Python"], "python-bytes"),
syn("pyFString", "String › f-string › Expression braces", ["Python"], "python-fstring"),
syn("pyFormat", "String › f-string › Format spec number", ["Python"], "python-format"),
syn("pyDocstring", "Docstring › Text", ["Python"], "docstring", { defaultItalic: true }),
syn("pyDocstringTag", "Docstring › Tag", ["Python"], "python-docstring-tag"),
syn("pyDocstringKeyword", "Docstring › Keyword", ["Python"], "python-docstring-keyword"),
syn("pyParentheses", "Braces and Operators › Parentheses", ["Python"], "python-parentheses"),
syn("pyBrackets", "Braces and Operators › Brackets", ["Python"], "python-brackets"),
syn("pyBraces", "Braces and Operators › Braces", ["Python"], "python-braces"),
syn("pyNestedFunction", "Functions › Nested function definition", ["Python"], "python-nested-function"),
syn("pyMethodCall", "Functions › Method call", ["Python"], "python-method-call"),
syn("pySelf", "Parameters › 'self' parameter", ["Python"], "self"),
syn("pyKeywordArg", "Keyword argument", ["Python"], "keyword-arg"),
syn("pyPredefinedDefinition", "Special names › Definition", ["Python"], "python-predefined-definition"),
syn("pyPredefinedUsage", "Special names › Usage", ["Python"], "python-predefined-usage"),
syn("pyBuiltin", "Built-in name", ["Python"], "python-builtin"),
syn("pyDecorator", "Decorator", ["Python"], "annotation"),
syn("pyMethodCall", "Method call", ["Python"], "python-method-call"),
syn("pyAnnotation", "Type annotation", ["Python"], "python-annotation"),
syn("pyLocalVariable", "Local variables", ["Python"], "python-local-variable"),
syn("pyTypeParameter", "Type parameters", ["Python"], "python-type-parameter"),
syn("pyGlobalVariable", "Global variable", ["Python"], "python-global-variable"),
syn("pyInstanceAttribute", "Instance attribute", ["Python"], "python-instance-attribute"),
syn("pyClassAttribute", "Class attribute", ["Python"], "python-class-attribute"),
syn("pyConstant", "Constant", ["Python"], "python-constant"),
syn("pyProperty", "Property", ["Python"], "python-property"),
syn("pyParentheses", "Parentheses", ["Python"], "python-parentheses"),
syn("pyBrackets", "Brackets", ["Python"], "python-brackets"),
syn("pyBraces", "Braces", ["Python"], "python-braces"),
syn("pyNestedFunction", "Nested function definition", ["Python"], "python-nested-function"),
syn("pyBytes", "Byte string", ["Python"], "python-bytes"),
syn("pyFString", "F-string", ["Python"], "python-fstring"),
syn("pyPredefinedDefinition", "Predefined function definition", ["Python"], "python-predefined-definition"),
syn("pyPredefinedUsage", "Predefined name usage", ["Python"], "python-predefined-usage"),
syn("pyFormat", "Format specifier", ["Python"], "python-format"),
syn("pySelf", "Self parameter", ["Python"], "self"),
{
id: "pyStaticSymbol",
name: "Static symbol",
@@ -188,6 +174,19 @@ const BASE_ATTRIBUTES: readonly AttributeDef[] = [
italicOnly: true,
defaultItalic: false,
},
syn("pyKeywordArg", "Keyword argument", ["Python"], "keyword-arg"),
syn("pyDocstring", "Docstring", ["Python"], "docstring", { defaultItalic: true }),
syn("pyDocstringTag", "Docstring › Tag", ["Python"], "python-docstring-tag"),
syn("pyDocstringKeyword", "Docstring › Keyword", ["Python"], "python-docstring-keyword"),
syn("pyBuiltin", "Built-in name", ["Python"], "python-builtin"),
syn("pyDecorator", "Decorator", ["Python"], "annotation"),
syn("pyLocalVariable", "Local variable", ["Python"], "python-local-variable"),
syn("pyGlobalVariable", "Global variable", ["Python"], "python-global-variable"),
syn("pyInstanceAttribute", "Instance attribute", ["Python"], "python-instance-attribute"),
syn("pyClassAttribute", "Class attribute", ["Python"], "python-class-attribute"),
syn("pyConstant", "Constant", ["Python"], "python-constant"),
syn("pyProperty", "Property", ["Python"], "python-property"),
syn("pyTypeParameter", "Type parameter", ["Python"], "python-type-parameter"),
syn("mdHeading", "Heading", ["Markdown"], "markup-heading", { defaultBold: true }),
syn("mdCode", "Code span", ["Markdown"], "markup-code"),
syn("mdLink", "Link", ["Markdown"], "link", { defaultEffect: "underline" }),
-1
Переглянути файл
@@ -283,7 +283,6 @@ describe("catalogs", () => {
"Yarn",
"Cargo",
"CMake",
"f-string",
"Tailwind CSS",
]);
const translated = SUPPORTED_LOCALES.filter((locale) => locale !== "en").sort();
+13 -61
Переглянути файл
@@ -9,15 +9,14 @@ import {
SCHEMES,
schemeCss,
} from "./colorScheme";
import { deleteScheme, exportIcls, importScheme, parseIcls, SchemeParseError } from "./icls";
import { deleteScheme, exportIcls, importScheme, parseIcls } from "./icls";
import { validateSettings } from "@/features/settings/model/schema";
import { colorSchemeItems } from "@/workbench/quickSwitch";
import { useProject } from "./project";
import type { Settings } from "./ipc";
import { isClientSetting } from "./clientSettings";
const fixture = (name: string, ext = "icls") =>
readFileSync(`src/platform/__fixtures__/colorSchemes/${name}.${ext}`, "utf8");
const fixture = (name: string) => readFileSync(`src/platform/__fixtures__/colorSchemes/${name}.icls`, "utf8");
beforeAll(() => _setSchemeSource(readFileSync("src/styles/tokens.css", "utf8")));
describe(".icls schemes", () => {
@@ -178,65 +177,18 @@ describe(".icls schemes", () => {
expect([sign.applied, sign.skipped]).toEqual([1, 2]);
});
it.each(["", "<scheme", '<scheme name="A"><attributes></scheme>', "<nope>", '<html name="x"/>'])(
"rejects malformed or non-scheme XML without mutating schemes: %s",
(xml) => {
const customs = importScheme({}, parseIcls(fixture("forest")).scheme).customs;
const before = structuredClone(customs);
expect(() => parseIcls(xml)).toThrow(SchemeParseError);
expect(customs).toEqual(before);
},
);
it("names what is wrong with a rejected file", () => {
expect(() => parseIcls("<nope>")).toThrow(/not valid XML/);
try {
parseIcls('<html name="x"/>');
expect.unreachable();
} catch (error) {
expect(error).toBeInstanceOf(SchemeParseError);
expect((error as Error).message).toMatch(/<scheme> element/);
}
});
it("imports a real-world .xml scheme from Material Theme UI (#2714)", () => {
const { scheme, applied, skipped } = parseIcls(fixture("material-darker", "xml"));
expect(scheme.name).toBe("Material Darker");
expect(scheme.parent).toBe("dark");
expect(scheme.attributes.keyword).toEqual({ foreground: "#c792ea", bold: false, italic: true });
expect(scheme.attributes.string?.foreground).toBe("#c3e88d");
expect(scheme.attributes.lineComment).toEqual({ foreground: "#616161", bold: false, italic: true });
expect(scheme.attributes.text).toEqual({ foreground: "#eeffff", background: "#212121" });
expect(scheme.attributes.caret?.foreground).toBe("#ffcc00");
expect(scheme.attributes.gutter?.background).toBe("#212121");
expect(scheme.attributes.lineNumber?.foreground).toBe("#424242");
expect(scheme.attributes.selection?.background).toBe("#353535");
expect([applied, skipped]).toEqual([12, 3]);
});
it.each([
["bom-utf8", "Bom Light"],
["declared-encoding", "Café Solar"],
] as const)("accepts the BOM and encoding-declaration variants of a scheme: %s", (name, schemeName) => {
const { scheme } = parseIcls(fixture(name));
expect(scheme.name).toBe(schemeName);
expect(scheme.attributes.keyword?.foreground).toBe(name === "bom-utf8" ? "#1122ff" : "#cc7832");
// Byte-order and encoding marks do not change what a scheme says.
expect(parseIcls(`\uFEFF${fixture(name)}`).scheme).toEqual(scheme);
});
it("unwraps a scheme element from its settings export and names a scheme after its file (#2714)", () => {
const { scheme } = parseIcls(fixture("one-dark-wrapped", "xml"));
expect(scheme.name).toBe("Imported scheme");
expect(scheme.attributes.keyword).toEqual({ foreground: "#c678dd", bold: true, italic: false });
expect(scheme.attributes.text).toEqual({ foreground: "#abb2bf", background: "#282c34" });
expect(parseIcls(fixture("one-dark-wrapped", "xml"), "One Dark").scheme.name).toBe("One Dark");
});
it("accepts a DOCTYPE prolog, which XML allows and old exporters emit (#2714)", () => {
const { scheme } = parseIcls('<!DOCTYPE scheme SYSTEM "scheme.dtd"><scheme name="D"><colors/></scheme>');
expect(scheme.name).toBe("D");
expect(() => parseIcls('<!DOCTYPE scheme [<!ENTITY a "red">]><scheme name="x"/>')).not.toThrow();
"",
"<scheme",
'<scheme name="A"><attributes></scheme>',
"<scheme/>",
'<html name="x"/>',
'<!DOCTYPE scheme [<!ENTITY a "red">]><scheme name="x"/>',
])("rejects malformed XML without mutating schemes: %s", (xml) => {
const customs = importScheme({}, parseIcls(fixture("forest")).scheme).customs;
const before = structuredClone(customs);
expect(() => parseIcls(xml)).toThrow("Invalid .icls color scheme");
expect(customs).toEqual(before);
});
it.each([
+11 -40
Переглянути файл
@@ -274,45 +274,16 @@ function attributeEntries(section: Element): Element[] {
return entries.filter((e) => e.getAttribute("name") !== "DEFAULT_BLOCK_COMMENT");
}
/** A scheme file that is not an IntelliJ color scheme; `message` says what is wrong with it. */
export class SchemeParseError extends Error {
constructor(message: string) {
super(message);
this.name = "SchemeParseError";
}
}
/**
* The variants real IDEA scheme files come in: a BOM, an `encoding=` declaration
* (both describe the file's bytes, while this text has already been decoded), and
* a DOCTYPE prolog. None of them change the scheme, so drop the first two.
*/
const prepareIclsXml = (xml: string) =>
xml
.replace(/^\uFEFF+/, "")
.replace(/^\s*<\?xml\s[^>]*\?>(\r\n|\r|\n)?/i, "")
.replace(/^\s*(\r\n|\r|\n)?/, "");
const parserDetail = (doc: Document): string => {
const detail = (doc.querySelector("parsererror")?.textContent ?? "").replace(/\s+/g, " ").trim();
return detail.length ? detail.slice(0, 200) : "no scheme element found";
};
export function parseIcls(
xml: string,
fallbackName = "Imported scheme",
): { scheme: CustomColorScheme; applied: number; skipped: number } {
const doc = new DOMParser().parseFromString(prepareIclsXml(xml), "application/xml");
// Some distributors wrap the scheme element (an <application>/<component> export), or leave the name out.
const root =
doc.documentElement?.tagName === "scheme"
? doc.documentElement
: (doc.getElementsByTagName("scheme")[0] ?? undefined);
if (doc.querySelector("parsererror") || !root)
throw new SchemeParseError(
doc.querySelector("parsererror") ? `not valid XML (${parserDetail(doc)})` : "no IntelliJ <scheme> element found",
);
const name = root.getAttribute("name")?.trim() || fallbackName;
export function parseIcls(xml: string): { scheme: CustomColorScheme; applied: number; skipped: number } {
const doc = new DOMParser().parseFromString(xml, "application/xml");
const root = doc.documentElement;
if (
doc.querySelector("parsererror") ||
doc.doctype ||
root.tagName !== "scheme" ||
!root.getAttribute("name")?.trim()
)
throw new Error("Invalid .icls color scheme");
const attributes: Record<string, TextAttributesOverride> = {};
const entries = new Map(
children(root, "attributes").flatMap((section) =>
@@ -426,7 +397,7 @@ export function parseIcls(
: dark
? "dark"
: "light";
return { scheme: { name, parent, attributes }, applied, skipped };
return { scheme: { name: root.getAttribute("name")!.trim(), parent, attributes }, applied, skipped };
}
/** Name collisions include built-ins; imports never replace a built-in. */
-3
Переглянути файл
@@ -594,7 +594,6 @@
"Invalid log stream configuration": "Invalid log stream configuration",
"Find in Logs": "Find in Logs",
"Waiting for output…": "Waiting for output…",
"Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.": "Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.",
"Soft-wrap": "Soft-wrap",
"Clear": "Clear",
"\n[Process finished]": "\n[Process finished]",
@@ -674,8 +673,6 @@
"Gradle Tasks": "Gradle Tasks",
"IDE MCP Server": "IDE MCP Server",
"Enable MCP server": "Enable MCP server",
"Run tools without confirmation (brave mode)": "Run tools without confirmation (brave mode)",
"Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.": "Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.",
"Status": "Status",
"Running on port {port}": "Running on port {port}",
"Failed to start: {error}": "Failed to start: {error}",
-3
Переглянути файл
@@ -1073,7 +1073,6 @@
"Install Plugin from Disk…": "Instalar complemento desde el disco…",
"Install a plugin folder with": "Instala una carpeta de complemento con",
"Install and Debug": "Instalar y depurar",
"Reinstall and Debug": "Reinstalar y depurar",
"Install gh…": "Instalar gh…",
"Installed": "Instalados",
"Installed packages": "Paquetes instalados",
@@ -1890,7 +1889,6 @@
"Running": "En ejecución",
"Running processes requires the desktop app.": "Ejecutar procesos requiere la aplicación de escritorio.",
"Runs Gradle with --offline": "Ejecuta Gradle con --offline",
"Runs Gradle with -x test": "Ejecuta Gradle con -x test",
"Runs Maven with -DskipTests": "Ejecuta Maven con -DskipTests",
"Runs Maven with -o": "Ejecuta Maven con -o",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "Ejecuta Optimizar importaciones cuando el archivo no tiene errores, a menos que modifique la línea del cursor.",
@@ -4045,7 +4043,6 @@
"{count} classes": "{count} clases",
"The JavaScript debugger (vscode-js-debug) is not installed": "El depurador de JavaScript (vscode-js-debug) no está instalado",
"Delve is not installed": "Delve no está instalado",
"Delve is too old for Go {go}": "Delve es demasiado antiguo para Go {go}",
"CodeLLDB is not installed": "CodeLLDB no está instalado",
"{name} (child)": "{name} (hijo)",
"Enable breakpoint at {path}:{line}": "Habilitar punto de interrupción en {path}:{line}",
-3
Переглянути файл
@@ -1010,7 +1010,6 @@
"Install Plugin from Disk…": "Installer un plugin depuis le disque…",
"Install a plugin folder with": "Installez un dossier de plugin avec",
"Install and Debug": "Installer et déboguer",
"Reinstall and Debug": "Réinstaller et déboguer",
"Install gh…": "Installer gh…",
"Installed": "Installés",
"Installed packages": "Paquets installés",
@@ -1806,7 +1805,6 @@
"Running": "En cours d'exécution",
"Running processes requires the desktop app.": "L'exécution de processus nécessite l'application de bureau.",
"Runs Gradle with --offline": "Exécute Gradle avec --offline",
"Runs Gradle with -x test": "Exécute Gradle avec -x test",
"Runs Maven with -DskipTests": "Exécute Maven avec -DskipTests",
"Runs Maven with -o": "Exécute Maven avec -o",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "Exécute Optimiser les imports lorsque le fichier ne contient pas d'erreur, sauf si cela modifie la ligne du curseur.",
@@ -3909,7 +3907,6 @@
"{class} reloaded": "{class} rechargée",
"The JavaScript debugger (vscode-js-debug) is not installed": "Le débogueur JavaScript (vscode-js-debug) n'est pas installé",
"Delve is not installed": "Delve n'est pas installé",
"Delve is too old for Go {go}": "Delve est trop ancien pour Go {go}",
"CodeLLDB is not installed": "CodeLLDB n'est pas installé",
"{name} (child)": "{name} (enfant)",
"Enable breakpoint at {path}:{line}": "Activer le point d'arrêt à {path}:{line}",
+5 -3
Переглянути файл
@@ -26,6 +26,11 @@
"Braces": "중괄호",
"Parentheses": "소괄호",
"Type annotation": "타입 어노테이션",
"Format specifier": "형식 지정자",
"Predefined name usage": "사전 정의된 이름 사용",
"Predefined function definition": "사전 정의된 함수 정의",
"Byte string": "바이트 문자열",
"F-string": "F-문자열",
"Nested function definition": "중첩 함수 정의",
"Local variable": "지역 변수",
"Global variable": "전역 변수",
@@ -1109,7 +1114,6 @@
"Install Plugin from Disk…": "디스크에서 플러그인 설치…",
"Install a plugin folder with": "다음으로 플러그인 폴더 설치",
"Install and Debug": "설치 및 디버그",
"Reinstall and Debug": "다시 설치 및 디버그",
"Install gh…": "gh 설치…",
"Installed": "설치됨",
"Installed packages": "설치된 패키지",
@@ -1941,7 +1945,6 @@
"Running": "실행 중",
"Running processes requires the desktop app.": "프로세스를 실행하려면 데스크톱 앱이 필요합니다.",
"Runs Gradle with --offline": "--offline으로 Gradle을 실행합니다",
"Runs Gradle with -x test": "-x test로 Gradle을 실행합니다",
"Runs Maven with -DskipTests": "-DskipTests로 Maven을 실행합니다",
"Runs Maven with -o": "-o로 Maven을 실행합니다",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "파일에 오류가 없으면 import 최적화를 실행합니다. 단, 캐럿 줄이 변경되는 경우는 제외합니다.",
@@ -4104,7 +4107,6 @@
"{count} classes": "클래스 {count}개",
"The JavaScript debugger (vscode-js-debug) is not installed": "JavaScript 디버거(vscode-js-debug)가 설치되어 있지 않습니다",
"Delve is not installed": "Delve가 설치되어 있지 않습니다",
"Delve is too old for Go {go}": "Delve가 Go {go}을(를) 지원할 수 없을 만큼 오래되었습니다",
"CodeLLDB is not installed": "CodeLLDB가 설치되어 있지 않습니다",
"PHP Debug (Xdebug) is not installed": "PHP Debug(Xdebug)가 설치되어 있지 않습니다",
"Bash Debug is not installed": "Bash Debug가 설치되어 있지 않습니다",
-3
Переглянути файл
@@ -1065,7 +1065,6 @@
"Install Plugin from Disk…": "Zainstaluj wtyczkę z dysku…",
"Install a plugin folder with": "Zainstaluj folder wtyczki za pomocą",
"Install and Debug": "Zainstaluj i debuguj",
"Reinstall and Debug": "Zainstaluj ponownie i debuguj",
"Install gh…": "Zainstaluj gh…",
"Installed": "Zainstalowane",
"Installed packages": "Zainstalowane pakiety",
@@ -1881,7 +1880,6 @@
"Running": "Uruchomiono",
"Running processes requires the desktop app.": "Uruchamianie procesów wymaga aplikacji stacjonarnej.",
"Runs Gradle with --offline": "Uruchamia Gradle z opcją --offline",
"Runs Gradle with -x test": "Uruchamia Gradle z opcją -x test",
"Runs Maven with -DskipTests": "Uruchamia Maven z opcją -DskipTests",
"Runs Maven with -o": "Uruchamia Maven z opcją -o",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "Uruchamia Optymalizację importów, gdy plik nie zawiera błędów, chyba że zmieniłoby to wiersz kursora.",
@@ -4004,7 +4002,6 @@
"{count} classes": "Liczba klas: {count}",
"The JavaScript debugger (vscode-js-debug) is not installed": "Debuger JavaScript (vscode-js-debug) nie jest zainstalowany",
"Delve is not installed": "Delve nie jest zainstalowane",
"Delve is too old for Go {go}": "Delve jest zbyt stary dla Go {go}",
"CodeLLDB is not installed": "CodeLLDB nie jest zainstalowane",
"{name} (child)": "{name} (potomny)",
"Enable breakpoint at {path}:{line}": "Włącz punkt przerwania w {path}:{line}",
-3
Переглянути файл
@@ -1065,7 +1065,6 @@
"Install Plugin from Disk…": "Instalar plugin do disco…",
"Install a plugin folder with": "Instalar uma pasta de plugin com",
"Install and Debug": "Instalar e depurar",
"Reinstall and Debug": "Reinstalar e depurar",
"Install gh…": "Instalar gh…",
"Installed": "Instalados",
"Installed packages": "Pacotes instalados",
@@ -1881,7 +1880,6 @@
"Running": "Em execução",
"Running processes requires the desktop app.": "A execução de processos requer o aplicativo desktop.",
"Runs Gradle with --offline": "Executa o Gradle com --offline",
"Runs Gradle with -x test": "Executa o Gradle com -x test",
"Runs Maven with -DskipTests": "Executa o Maven com -DskipTests",
"Runs Maven with -o": "Executa o Maven com -o",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "Executa Otimizar importações quando o arquivo não tiver erros, a menos que isso altere a linha do cursor.",
@@ -4010,7 +4008,6 @@
"{count} classes": "{count} classes",
"The JavaScript debugger (vscode-js-debug) is not installed": "O depurador JavaScript (vscode-js-debug) não está instalado",
"Delve is not installed": "O Delve não está instalado",
"Delve is too old for Go {go}": "O Delve é antigo demais para o Go {go}",
"CodeLLDB is not installed": "O CodeLLDB não está instalado",
"{name} (child)": "{name} (filho)",
"Enable breakpoint at {path}:{line}": "Ativar ponto de interrupção em {path}:{line}",
+6 -18
Переглянути файл
@@ -275,24 +275,18 @@
"Braces": "花括号",
"Parentheses": "圆括号",
"Type annotation": "类型注解",
"Binary (bytes)": "二进制(字节)",
"f-string": "f-string",
"Expression braces": "表达式花括号",
"Format spec number": "格式说明符编号",
"'self' parameter": "'self' 参数",
"Special names": "特殊名称",
"Usage": "引用",
"Built-in name": "内置名称",
"Decorator": "装饰器",
"Keyword argument": "关键字实参",
"Format specifier": "格式说明符",
"Predefined name usage": "预定义名称引用",
"Predefined function definition": "预定义函数定义",
"Byte string": "字节字符串",
"F-string": "F 字符串",
"Nested function definition": "嵌套函数定义",
"Local variable": "局部变量",
"Local variables": "局部变量",
"Global variable": "全局变量",
"Instance attribute": "实例属性",
"Class attribute": "类属性",
"Constant": "常量",
"Type parameters": "类型参数",
"Type parameter": "类型参数",
"Unity": "Unity 项目",
"Show Meta Files": "显示 Meta 文件",
"Show Generated Files": "显示生成的文件",
@@ -313,7 +307,6 @@
"Edited within moved code": "移动代码中的修改",
"The language server JDK ({path}) must be a full JDK with jdk.compiler, jdk.jdi and jdk.unsupported for Java language support and debugging. jdtls needs JDK {version} or newer. Download JDK {version}, choose a full JDK in {setting}, or set it to Auto.": "语言服务器 JDK({path})必须是包含 jdk.compiler、jdk.jdi 和 jdk.unsupported 的完整 JDK,才能支持 Java 语言功能和调试。jdtls 需要 JDK {version} 或更高版本。请下载 JDK {version},在 {setting} 中选择完整 JDK,或设为自动。",
"Apple's clangd does not run clang-tidy, so checks from .clang-tidy are not shown. Install clangd (LLVM) to get them.": "Apple 的 clangd 不运行 clang-tidy,因此不会显示 .clang-tidy 中配置的检查。请安装 clangd(LLVM)以启用这些检查。",
"Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.": "Vue 2(Options API)的模板跳转需要在 jsconfig.json / tsconfig.json 的 compilerOptions 里设置 'strictFunctionTypes': true(或 'strict': true):缺少该选项时,Vue 2.7 的类型会把 this 上的 methods、computed 推断为 any,模板内跳转定义和悬停都无法解析。加上该选项(若项目还没有配置文件则新建 jsconfig.json),然后重新打开文件或重启语言服务即可。",
"Auto-detect ({defaultProgram})": "自动检测({defaultProgram})",
"Custom executable": "自定义可执行文件",
"Found on PATH": "已在 PATH 中找到",
@@ -1396,7 +1389,6 @@
"Install Plugin from Disk…": "从磁盘安装插件…",
"Install a plugin folder with": "安装插件文件夹:",
"Install and Debug": "安装并调试",
"Reinstall and Debug": "重新安装并调试",
"Install gh…": "安装 gh…",
"Installed": "已安装",
"Installed packages": "已安装的软件包",
@@ -2346,7 +2338,6 @@
"Running": "正在运行",
"Running processes requires the desktop app.": "运行进程需要桌面应用。",
"Runs Gradle with --offline": "使用 --offline 运行 Gradle",
"Runs Gradle with -x test": "使用 -x test 运行 Gradle",
"Runs Maven with -DskipTests": "使用 -DskipTests 运行 Maven",
"Runs Maven with -o": "使用 -o 运行 Maven",
"Runs Optimize Imports when the file has no errors, unless it would change the caret line.": "文件没有错误时运行“优化导入”,除非这会更改光标所在行。",
@@ -4552,7 +4543,6 @@
"{count} classes": "{count} 个类",
"The JavaScript debugger (vscode-js-debug) is not installed": "JavaScript 调试器 (vscode-js-debug) 未安装",
"Delve is not installed": "Delve 未安装",
"Delve is too old for Go {go}": "Delve 版本过旧,不支持 Go {go}",
"CodeLLDB is not installed": "CodeLLDB 未安装",
"PHP Debug (Xdebug) is not installed": "PHP Debug (Xdebug) 未安装",
"Bash Debug is not installed": "Bash Debug 未安装",
@@ -7025,8 +7015,6 @@
"Gradle Tasks": "Gradle 任务",
"IDE MCP Server": "IDE MCP 服务器",
"Enable MCP server": "启用 MCP 服务器",
"Run tools without confirmation (brave mode)": "运行工具时不再确认(勇敢模式)",
"Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.": "运行配置、终端命令以及其他会修改项目的工具直接执行、不再询问,适合无人值守的智能体。只能在 IDE 自身的设置里开启,项目设置无法开启。",
"Running on port {port}": "正在端口 {port} 上运行",
"Failed to start: {error}": "启动失败:{error}",
"Not running": "未运行",
-30
Переглянути файл
@@ -535,33 +535,3 @@ describe("Tree indents", () => {
expect(placeholder?.style.paddingLeft).toBe("calc(24px + 1 * var(--tree-indent, 20px))");
});
});
describe("Tree double-click", () => {
it("selects on the first press without cancelling its default", () => {
const { tree } = setup();
const row = within(tree).getByRole("treeitem", { name: "README.md" });
expect(fireEvent.mouseDown(row, { button: 0, detail: 1 })).toBe(true);
expect(row).toHaveAttribute("aria-selected", "true");
});
it("cancels the second press so double-clicking cannot select label text, and still activates", () => {
const { tree, onActivate } = setup();
const row = within(tree).getByRole("treeitem", { name: "README.md" });
fireEvent.mouseDown(row, { button: 0, detail: 1 });
// The browser starts its word selection on this press; cancelling it keeps
// the labels unselected (jsdom reports cancellation through dispatchEvent).
expect(fireEvent.mouseDown(row, { button: 0, detail: 2 })).toBe(false);
fireEvent.doubleClick(row);
expect(onActivate).toHaveBeenCalledWith(expect.objectContaining({ id: "README.md" }), expect.anything());
expect(row).toHaveAttribute("aria-selected", "true");
});
it("still expands a folder on double-click", () => {
const { tree } = setup();
const row = within(tree).getByRole("treeitem", { name: "src" });
fireEvent.mouseDown(row, { button: 0, detail: 1 });
fireEvent.mouseDown(row, { button: 0, detail: 2 });
fireEvent.doubleClick(row);
expect(labels(tree)).toEqual(["src", "main", "util.ts", "README.md"]);
});
});
-11
Переглянути файл
@@ -590,17 +590,6 @@ export function Tree<T>(props: TreeProps<T>) {
return;
}
if (e.button !== 0) return;
// The second press of a double-click starts the browser's word selection,
// which in a virtualized tree spills onto the rows an expanding folder just
// inserted and highlights neighbouring labels. Prevent it: rows are
// controls, not text (the shared List does the same via `user-select`), the
// first press already selected, and the dblclick below still fires, so
// activation keeps working. Rows can host editors (inline rename), so this
// is scoped to repeated clicks instead of unselecting all row content.
if (e.detail >= 2) {
e.preventDefault();
return;
}
setQuery("");
if (e.shiftKey) selectIndex(i, "range");
else if (e.metaKey || e.ctrlKey) selectIndex(i, "toggle");