mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 09:39:27 -10:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
891432c2d9 | ||
|
|
160ecf4693 | ||
|
|
cb087fff48 | ||
|
|
70e0215f46 | ||
|
|
460d30030e | ||
|
|
edf9affa8e | ||
|
|
070c795de5 | ||
|
|
5c9290fefd |
No files matched your search
Generated
+1
@@ -6734,6 +6734,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows",
|
||||
"windows-sys 0.61.2",
|
||||
|
||||
@@ -752,6 +752,8 @@ pub struct AppearanceSettings {
|
||||
pub compact_mode: bool,
|
||||
/// IDEA "Use smaller indents in trees": tool window trees indent less per level.
|
||||
pub small_tree_indents: bool,
|
||||
/// Linux: WebKit animates each mouse wheel step
|
||||
pub smooth_scrolling: bool,
|
||||
pub full_path_in_title: bool,
|
||||
pub project_colors_in_toolbar: bool,
|
||||
pub dnd_with_alt_only: bool,
|
||||
@@ -887,6 +889,7 @@ impl Default for AppearanceSettings {
|
||||
different_tool_window_background: false,
|
||||
compact_mode: false,
|
||||
small_tree_indents: false,
|
||||
smooth_scrolling: true,
|
||||
full_path_in_title: false,
|
||||
project_colors_in_toolbar: true,
|
||||
dnd_with_alt_only: false,
|
||||
@@ -1755,6 +1758,16 @@ mod tests {
|
||||
assert_eq!(kept.appearance.theme, "solarized-dark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_scrolling_defaults_on_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"zoom":110}}"#).unwrap();
|
||||
assert!(old.appearance.smooth_scrolling);
|
||||
let off: Settings = serde_json::from_str(r#"{"appearance":{"smoothScrolling":false}}"#).unwrap();
|
||||
assert!(!off.appearance.smooth_scrolling);
|
||||
let json = serde_json::to_value(&off).unwrap();
|
||||
assert_eq!(json["appearance"]["smoothScrolling"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_close_settings_default_off_and_round_trip() {
|
||||
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
|
||||
|
||||
@@ -32,7 +32,7 @@ struct Session {
|
||||
/// The response format: a names line, a types line, then one JSON array per row, so rows past
|
||||
/// the grid's limit are skipped without being parsed.
|
||||
const FORMAT: &str = "JSONCompactEachRowWithNamesAndTypes";
|
||||
const SESSION_LOST: &str = "ClickHouse HTTP session not found on this node (code 372). Use one node or session affinity, or set use_http_session=false in Advanced for independent queries.";
|
||||
const SESSION_LOST: &str = "ClickHouse HTTP session expired or is missing on this node (code 372). Reconnect to start a new session. Behind a load balancer, use one node or session affinity, or set use_http_session=false in Advanced for independent queries.";
|
||||
|
||||
pub(crate) fn transaction_error() -> IdeError {
|
||||
IdeError::invalid("ClickHouse HTTP does not support SQL transactions; use auto-commit and run writes directly")
|
||||
@@ -133,7 +133,7 @@ impl ClickhousePool {
|
||||
endpoint,
|
||||
user: if source.user.is_empty() { "default".into() } else { source.user.clone() },
|
||||
password: password.unwrap_or_default().to_owned(),
|
||||
database: if database.is_empty() { "default".into() } else { database.into() },
|
||||
database: database.into(),
|
||||
settings,
|
||||
read_only: source.read_only,
|
||||
session: Mutex::new(Session {
|
||||
@@ -233,7 +233,7 @@ impl ClickhousePool {
|
||||
request = request.query(&[("session_check", "1")]);
|
||||
}
|
||||
}
|
||||
if session.id.is_none() || !session.initialized {
|
||||
if !self.0.database.is_empty() && (session.id.is_none() || !session.initialized) {
|
||||
request = request.query(&[("database", &self.0.database)]);
|
||||
}
|
||||
if self.0.read_only && !session.strict_read_only {
|
||||
@@ -808,6 +808,19 @@ mod tests {
|
||||
assert!(pool.execute("SELECT 1", 1, &CancellationToken::new()).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unset_database_uses_the_accounts_default_in_both_modes() {
|
||||
for mode in ["true", "false"] {
|
||||
let (port, requests) = server(vec![("200 OK", "", ONE); 2]).await;
|
||||
let source = DataSource { properties: vec![property("use_http_session", mode)], ..source(port) };
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
pool.execute("SELECT 1", 1, &CancellationToken::new()).await.unwrap();
|
||||
for request in requests.await.unwrap() {
|
||||
assert_eq!(query_value(&request_url(&request), "database"), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stateless_requests_keep_database_settings_readonly_and_limits() {
|
||||
let (port, requests) = server(vec![("200 OK", "", ONE); 3]).await;
|
||||
@@ -855,6 +868,7 @@ mod tests {
|
||||
let error = pool.execute(sql, 0, &CancellationToken::new()).await.unwrap_err();
|
||||
assert!(error.message.contains("372"));
|
||||
assert!(error.message.contains("one node or session affinity"));
|
||||
assert!(error.message.contains("Reconnect"));
|
||||
assert!(error.message.contains("use_http_session=false"));
|
||||
pool.execute("SELECT 1", 1, &CancellationToken::new()).await.unwrap();
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.11.0";
|
||||
pub const ENGINE_VERSION: &str = "1.12.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
|
||||
@@ -869,6 +869,7 @@ async fn occurrences(
|
||||
scope,
|
||||
max_matches: 0,
|
||||
context,
|
||||
include_excluded: false,
|
||||
};
|
||||
let host = call.host();
|
||||
let request = crate::mcp::tool::request_id();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::page::{OFFSET, Page};
|
||||
use super::scope::{self, Scope};
|
||||
use super::search::{PathScope, paths_param};
|
||||
use super::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use ide_core::{Diagnostic, IdeResult, Severity};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -16,7 +16,7 @@ pub fn tools() -> Vec<Tool> {
|
||||
Use this tool to explore current open editors.",
|
||||
open_editors,
|
||||
)
|
||||
.param(scope::param()),
|
||||
.param(paths_param()),
|
||||
Tool::new(
|
||||
"get_current_file",
|
||||
"Returns the focused editor's file and selection reported by the IDE.
|
||||
@@ -45,20 +45,20 @@ Lines and UTF-16 columns are 1-based.",
|
||||
project_problems,
|
||||
)
|
||||
.param(Param::optional("errorsOnly", ParamType::Boolean, "Only errors (default) or warnings too"))
|
||||
.param(scope::param())
|
||||
.param(paths_param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Problems to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET)),
|
||||
]
|
||||
}
|
||||
|
||||
async fn open_editors(call: Call) -> IdeResult<Output> {
|
||||
let dir = Scope::of(&call)?;
|
||||
let paths = PathScope::of(&call)?;
|
||||
let windows = call.host.mcp_windows(call.root());
|
||||
let open = call.host.mcp_reports.editors(&windows);
|
||||
let active = call.host.mcp_reports.focused(call.window()).filter(|e| dir.contains(&e.path.0));
|
||||
let active = call.host.mcp_reports.focused(call.window()).filter(|e| paths.matches_path(&e.path.0));
|
||||
Output::json(json!({
|
||||
"activeFilePath": active.map(|e| call.display(&e.path.0)),
|
||||
"openFiles": open.iter().filter(|p| dir.contains(p)).map(|p| call.display(p)).collect::<Vec<_>>(),
|
||||
"openFiles": open.iter().filter(|p| paths.matches_path(p)).map(|p| call.display(p)).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -103,11 +103,11 @@ async fn file_problems(call: Call) -> IdeResult<Output> {
|
||||
async fn project_problems(call: Call) -> IdeResult<Output> {
|
||||
let page = Page::of(&call, PROBLEMS_LIMIT)?;
|
||||
let errors_only = call.flag("errorsOnly", true)?;
|
||||
let dir = Scope::of(&call)?;
|
||||
let paths = PathScope::of(&call)?;
|
||||
let files = call.host.mcp_reports.problems(&call.host.mcp_windows(call.root()));
|
||||
let problems: Vec<(String, Value)> = files
|
||||
.into_iter()
|
||||
.filter(|f| dir.contains(&f.path.0))
|
||||
.filter(|f| paths.matches_path(&f.path.0))
|
||||
.flat_map(|f| {
|
||||
let path = call.display(&f.path.0);
|
||||
let wanted = f.items.into_iter().filter(|d| !errors_only || d.severity == Severity::Error);
|
||||
|
||||
@@ -8,9 +8,10 @@ use crate::mcp::util::{
|
||||
self, RELATIVE_PATH_IN_PROJECT_DESCRIPTION, TIMED_OUT_DESCRIPTION, TIMEOUT_MILLISECONDS_DESCRIPTION,
|
||||
};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_search::FileMask;
|
||||
use serde::Serialize;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const DEFAULT_READ_LIMIT: i64 = 2000;
|
||||
@@ -166,7 +167,9 @@ fn list_directory_tree() -> Tool {
|
||||
"Provides a tree representation of the specified directory in the pseudo graphic format like `tree` utility does.
|
||||
Use this tool to explore the contents of a directory or the whole project.
|
||||
You MUST prefer this tool over listing directories via command line utilities like `ls` or `dir`.
|
||||
A page that starts inside a directory repeats the lines of the directories above it.",
|
||||
A page that starts inside a directory repeats the lines of the directories above it.
|
||||
What `.gitignore` ignores is marked [git-ignored] and what the project excludes [ide-excluded]; entries inside a
|
||||
marked directory are not marked again.",
|
||||
|call| async move {
|
||||
let directory = call.str("directoryPath")?;
|
||||
let max_depth = call.opt_i64("maxDepth")?.unwrap_or(DEFAULT_TREE_DEPTH);
|
||||
@@ -181,6 +184,12 @@ A page that starts inside a directory repeats the lines of the directories above
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_millis(timeout.max(0) as u64);
|
||||
let cancel = call.cancel.clone();
|
||||
let marks = Marks {
|
||||
root: call.root().to_path_buf(),
|
||||
excludes: FileMask::new(&[], &call.project().search_excludes()).ok(),
|
||||
};
|
||||
// The directory itself, when it or one above it is left out.
|
||||
let root_mark = marker(ide_index::walk_skips(call.root(), &dir), marks.ide_excluded(&dir, true));
|
||||
let mut tree = TreeRender {
|
||||
out: String::new(),
|
||||
errors: Vec::new(),
|
||||
@@ -190,11 +199,12 @@ A page that starts inside a directory repeats the lines of the directories above
|
||||
page,
|
||||
seen: 0,
|
||||
above: Vec::new(),
|
||||
marks,
|
||||
};
|
||||
let tree = call
|
||||
.host()
|
||||
.blocking(move || {
|
||||
tree.render(&dir, "", true, max_depth, true);
|
||||
tree.render(&dir, "", true, max_depth, true, root_mark, !root_mark.is_empty());
|
||||
Ok(tree)
|
||||
})
|
||||
.await?;
|
||||
@@ -234,7 +244,8 @@ A page that starts inside a directory repeats the lines of the directories above
|
||||
|
||||
/// The `tree`-like listing: the directory's absolute path, then every entry (hidden and
|
||||
/// ignored ones too) by lower-cased name, directories marked with `/`; entries outside the
|
||||
/// page are counted, not listed.
|
||||
/// page are counted, not listed. An entry left out of the project is marked, the entries
|
||||
/// inside it are not.
|
||||
struct TreeRender {
|
||||
out: String,
|
||||
errors: Vec<String>,
|
||||
@@ -246,10 +257,48 @@ struct TreeRender {
|
||||
seen: usize,
|
||||
/// The lines of the directories above the entry, and whether this page shows them yet.
|
||||
above: Vec<(String, bool)>,
|
||||
marks: Marks,
|
||||
}
|
||||
|
||||
/// What the project leaves out, to mark in the listing.
|
||||
struct Marks {
|
||||
root: PathBuf,
|
||||
/// The project's exclusions (excluded folders, "Exclude files" names), as Find in Files applies them.
|
||||
excludes: Option<FileMask>,
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
fn ide_excluded(&self, path: &Path, is_dir: bool) -> bool {
|
||||
let (Some(mask), Ok(rel)) = (&self.excludes, path.strip_prefix(&self.root)) else { return false };
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
// A directory is excluded with the files in it.
|
||||
!rel.is_empty() && !mask.matches(&if is_dir { format!("{rel}/x") } else { rel })
|
||||
}
|
||||
}
|
||||
|
||||
/// Spelled out, so that the listing says what it means.
|
||||
fn marker(git_ignored: bool, ide_excluded: bool) -> &'static str {
|
||||
match (git_ignored, ide_excluded) {
|
||||
(true, true) => " [git-ignored] [ide-excluded]",
|
||||
(true, false) => " [git-ignored]",
|
||||
(false, true) => " [ide-excluded]",
|
||||
(false, false) => "",
|
||||
}
|
||||
}
|
||||
|
||||
impl TreeRender {
|
||||
fn render(&mut self, path: &Path, indent: &str, is_last: bool, max_depth: i64, is_root: bool) {
|
||||
/// `mark`: the entry's marker; `marked`: it or a directory above it is marked.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render(
|
||||
&mut self,
|
||||
path: &Path,
|
||||
indent: &str,
|
||||
is_last: bool,
|
||||
max_depth: i64,
|
||||
is_root: bool,
|
||||
mark: &str,
|
||||
marked: bool,
|
||||
) {
|
||||
if max_depth <= 0 || self.timed_out || self.cancel.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
@@ -268,7 +317,7 @@ impl TreeRender {
|
||||
path.file_name().unwrap_or_default().to_string_lossy().into_owned()
|
||||
};
|
||||
let is_dir = path.is_dir() && !path.is_symlink();
|
||||
let line = format!("{indent}{prefix}{name}{}\n", if is_dir { "/" } else { "" });
|
||||
let line = format!("{indent}{prefix}{name}{}{mark}\n", if is_dir { "/" } else { "" });
|
||||
let shown = if is_root {
|
||||
self.out.push_str(&line);
|
||||
true
|
||||
@@ -278,22 +327,38 @@ impl TreeRender {
|
||||
if !is_dir {
|
||||
return;
|
||||
}
|
||||
let mut children: Vec<_> = match std::fs::read_dir(path) {
|
||||
Ok(entries) => entries.filter_map(|e| e.ok().map(|e| e.path())).collect(),
|
||||
// Without exclusions, `ignored` is what `.gitignore` says.
|
||||
let mut children: Vec<(PathBuf, bool)> = match ide_vfs::read_dir(path, &[]) {
|
||||
Ok(entries) => entries.into_iter().map(|e| (e.path.0, e.ignored)).collect(),
|
||||
Err(e) => {
|
||||
self.errors.push(format!("Failed to read {}: {e}", path.display()));
|
||||
self.errors.push(format!("Failed to read {}: {}", path.display(), e.message));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let key = |p: &std::path::PathBuf| p.file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
children.sort_by_cached_key(|p| (key(p).to_lowercase(), key(p)));
|
||||
let key = |p: &PathBuf| p.file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
children.sort_by_cached_key(|(p, _)| (key(p).to_lowercase(), key(p)));
|
||||
let child_indent = format!("{indent}{}", if is_last { " " } else { "│ " });
|
||||
let n = children.len();
|
||||
if !is_root {
|
||||
self.above.push((line, shown));
|
||||
}
|
||||
for (i, child) in children.iter().enumerate() {
|
||||
self.render(child, &child_indent, i + 1 == n, max_depth - 1, false);
|
||||
// Inside a marked directory nothing is marked again.
|
||||
for (i, (child, git_ignored)) in children.iter().enumerate() {
|
||||
let child_mark = if marked {
|
||||
""
|
||||
} else {
|
||||
let child_dir = child.is_dir() && !child.is_symlink();
|
||||
marker(*git_ignored, self.marks.ide_excluded(child, child_dir))
|
||||
};
|
||||
self.render(
|
||||
child,
|
||||
&child_indent,
|
||||
i + 1 == n,
|
||||
max_depth - 1,
|
||||
false,
|
||||
child_mark,
|
||||
marked || !child_mark.is_empty(),
|
||||
);
|
||||
}
|
||||
if !is_root {
|
||||
self.above.pop();
|
||||
@@ -383,8 +448,9 @@ mod tests {
|
||||
page: Page { offset, limit },
|
||||
seen: 0,
|
||||
above: Vec::new(),
|
||||
marks: Marks { root: tmp.path().to_path_buf(), excludes: None },
|
||||
};
|
||||
tree.render(tmp.path(), "", true, 5, true);
|
||||
tree.render(tmp.path(), "", true, 5, true, "", false);
|
||||
let root = format!("{}/\n", tmp.path().display());
|
||||
(tree.out.strip_prefix(&root).unwrap().to_owned(), tree.seen)
|
||||
};
|
||||
@@ -396,4 +462,48 @@ mod tests {
|
||||
);
|
||||
assert_eq!(render(0, 100).0, " ├── a/\n │ ├── x.txt\n │ └── y.txt\n └── b.txt\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_project_leaves_out_is_marked_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for file in ["ign/deep/a.txt", "out/b.txt", "both/c.txt", "src/d.txt", "src/e.log"] {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
std::fs::write(root.join(".gitignore"), "ign/\nboth/\n*.log\n").unwrap();
|
||||
let excludes = ["out/**".to_owned(), "both/**".to_owned()];
|
||||
let mut tree = TreeRender {
|
||||
out: String::new(),
|
||||
errors: Vec::new(),
|
||||
timed_out: false,
|
||||
deadline: Instant::now() + Duration::from_secs(10),
|
||||
cancel: CancellationToken::new(),
|
||||
page: Page { offset: 0, limit: 100 },
|
||||
seen: 0,
|
||||
above: Vec::new(),
|
||||
marks: Marks { root: root.clone(), excludes: FileMask::new(&[], &excludes).ok() },
|
||||
};
|
||||
tree.render(&root, "", true, 5, true, "", false);
|
||||
let listing = tree.out.strip_prefix(&format!("{}/\n", root.display())).unwrap().to_owned();
|
||||
assert_eq!(
|
||||
listing,
|
||||
[
|
||||
" ├── .gitignore",
|
||||
" ├── both/ [git-ignored] [ide-excluded]",
|
||||
" │ └── c.txt",
|
||||
" ├── ign/ [git-ignored]",
|
||||
" │ └── deep/",
|
||||
" │ └── a.txt",
|
||||
" ├── out/ [ide-excluded]",
|
||||
" │ └── b.txt",
|
||||
" └── src/",
|
||||
" ├── d.txt",
|
||||
" └── e.log [git-ignored]",
|
||||
"",
|
||||
]
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ mod files;
|
||||
mod http;
|
||||
mod page;
|
||||
pub mod reports;
|
||||
mod scope;
|
||||
mod search;
|
||||
mod symbols;
|
||||
mod tool;
|
||||
|
||||
@@ -305,7 +305,7 @@ pub fn list_runs() -> Tool {
|
||||
start of the command, exit code and times. `get_run_status` gives a tab's whole status.",
|
||||
|call| async move {
|
||||
let page = Page::of(&call, LIST_LIMIT)?;
|
||||
let dir = crate::mcp::scope::Scope::of(&call)?;
|
||||
let paths = crate::mcp::search::PathScope::of(&call)?;
|
||||
let wanted = call.opt_str("state")?.filter(|s| s != "all");
|
||||
let states = match wanted.as_deref() {
|
||||
None => None,
|
||||
@@ -327,7 +327,7 @@ start of the command, exit code and times. `get_run_status` gives a tab's whole
|
||||
.rev()
|
||||
.map(|r| r.status())
|
||||
// A tab belongs where its command runs.
|
||||
.filter(|s| dir.contains_shown(call.root(), s["workingDirectory"].as_str().unwrap_or_default()))
|
||||
.filter(|s| paths.matches_dir(&call.root().join(s["workingDirectory"].as_str().unwrap_or_default())))
|
||||
.filter(|s| {
|
||||
states.as_ref().is_none_or(|states| s["state"].as_str().is_some_and(|v| states.contains(&v)))
|
||||
})
|
||||
@@ -344,7 +344,7 @@ start of the command, exit code and times. `get_run_status` gives a tab's whole
|
||||
ParamType::String,
|
||||
"all (default), running, idle (not running), error (failed, crashed, startFailed), or one state",
|
||||
))
|
||||
.param(crate::mcp::scope::param())
|
||||
.param(crate::mcp::search::paths_param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Tabs to return at most (default 10)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
}
|
||||
|
||||
@@ -139,12 +139,14 @@ the whole command. Run points are found in Rust, JavaScript/TypeScript, Python a
|
||||
}
|
||||
let page = Page::of(&call, CONFIGURATIONS_LIMIT)?;
|
||||
let query = call.opt_str("query")?.map(|q| q.to_lowercase());
|
||||
let dir = crate::mcp::scope::Scope::of(&call)?;
|
||||
let paths = crate::mcp::search::PathScope::of(&call)?;
|
||||
let list: Vec<Value> = configs
|
||||
.iter()
|
||||
// A configuration belongs where it runs.
|
||||
.filter(|c| {
|
||||
dir.contains(&c.cwd.as_deref().map_or_else(|| call.root().to_path_buf(), |d| call.root().join(d)))
|
||||
paths.matches_dir(
|
||||
&c.cwd.as_deref().map_or_else(|| call.root().to_path_buf(), |d| call.root().join(d)),
|
||||
)
|
||||
})
|
||||
.filter(|c| {
|
||||
query.as_ref().is_none_or(|q| {
|
||||
@@ -169,7 +171,7 @@ the whole command. Run points are found in Rust, JavaScript/TypeScript, Python a
|
||||
in the file instead of project-wide run configurations.",
|
||||
))
|
||||
.param(Param::optional("query", ParamType::String, "Only configurations whose name, type or command contains it"))
|
||||
.param(crate::mcp::scope::param())
|
||||
.param(crate::mcp::search::paths_param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Configurations to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
//! The `scope` argument of the query tools: the directory their results are limited to, a
|
||||
//! folder of the project or a project attached to it.
|
||||
|
||||
use crate::mcp::tool::{Call, Param, ParamType};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub fn param() -> Param {
|
||||
Param::optional(
|
||||
"scope",
|
||||
ParamType::String,
|
||||
"Directory to limit results to: relative to the project root, or absolute",
|
||||
)
|
||||
}
|
||||
|
||||
/// No `scope`: everything.
|
||||
pub struct Scope(Option<PathBuf>);
|
||||
|
||||
impl Scope {
|
||||
pub fn of(call: &Call) -> IdeResult<Self> {
|
||||
let Some(raw) = call.opt_str("scope")?.filter(|s| !s.trim().is_empty()) else { return Ok(Self(None)) };
|
||||
let given = Path::new(raw.trim());
|
||||
let path = crate::mcp::tool::normalize(&if given.is_absolute() {
|
||||
given.to_path_buf()
|
||||
} else {
|
||||
call.root().join(given)
|
||||
});
|
||||
let roots: Vec<PathBuf> =
|
||||
std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots()).collect();
|
||||
// Before touching the file system: on Windows, resolving `\\host\share` signs in to that host.
|
||||
if !ide_vfs::content_path_allowed(&path, &roots) {
|
||||
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
|
||||
}
|
||||
let path = dunce::canonicalize(&path).unwrap_or(path);
|
||||
if !path.is_dir() {
|
||||
return Err(IdeError::not_found(format!("scope {raw} is not a directory")));
|
||||
}
|
||||
if !roots.iter().any(|root| path.starts_with(root)) {
|
||||
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
|
||||
}
|
||||
Ok(Self(Some(path)))
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> Option<&Path> {
|
||||
self.0.as_deref()
|
||||
}
|
||||
|
||||
pub fn contains(&self, path: &Path) -> bool {
|
||||
self.0.as_ref().is_none_or(|dir| path.starts_with(dir))
|
||||
}
|
||||
|
||||
/// For a path the tools return: project-relative with `/`, or absolute.
|
||||
pub fn contains_shown(&self, root: &Path, path: &str) -> bool {
|
||||
self.0.is_none() || self.contains(&root.join(path))
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
//! the editor (one per character except emoji and other astral characters).
|
||||
|
||||
use crate::mcp::page::{OFFSET, Page};
|
||||
use crate::mcp::scope::{self, Scope};
|
||||
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use crate::mcp::util::{INDEXING_PARTIAL_RESULT_REASON, MEDIUM_TIMEOUT};
|
||||
use crate::ops::search::SearchEvent;
|
||||
@@ -37,8 +36,10 @@ const MIN_UNMASKED_MATCHES: usize = 10_000;
|
||||
/// outside the window of a longer line are left out.
|
||||
const LINE_WINDOW: usize = 500;
|
||||
|
||||
const PATHS_DESCRIPTION: &str = "Optional list of project-relative glob patterns to filter results. Supports '!' \
|
||||
excludes. Trailing '/' expands to '**'. Patterns without '/' are treated as '**/pattern'. Empty strings are ignored.";
|
||||
const INCLUDE_EXCLUDED_DESCRIPTION: &str = "Whether to include excluded/ignored files in results";
|
||||
const PATHS_DESCRIPTION: &str = "Optional list of project-relative glob patterns to filter results (absolute ones for a \
|
||||
project attached outside it). Supports '!' excludes. Trailing '/' expands to '**'. Patterns without '/' are treated as \
|
||||
'**/pattern'. Empty strings are ignored.";
|
||||
const LIMIT_DESCRIPTION: &str = "Results to return at most (default 100)";
|
||||
const SYMBOL_LIMIT_DESCRIPTION: &str = "Results to return at most (default 50)";
|
||||
const CONTEXT_DESCRIPTION: &str = "Lines around each match to return besides the matched line (`lineText`): \"+N\" the \
|
||||
@@ -68,8 +69,8 @@ Examples: [\"src/**\", \"!**/test/**\"], [\"**/*.kt\"], [\"foo/\"].",
|
||||
|call| async move { text_search(call, false).await },
|
||||
)
|
||||
.param(Param::required("q", ParamType::String, "Text to search for"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
|
||||
.param(paths_param())
|
||||
.param(Param::optional("includeExcluded", ParamType::Boolean, INCLUDE_EXCLUDED_DESCRIPTION))
|
||||
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
.param(Param::optional("context", ParamType::String, CONTEXT_DESCRIPTION))
|
||||
@@ -91,8 +92,8 @@ Examples: [\"src/**\", \"!**/test/**\"], [\"**/*.kt\"], [\"foo/\"].",
|
||||
|call| async move { text_search(call, true).await },
|
||||
)
|
||||
.param(Param::required("q", ParamType::String, "Regex pattern to search for"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
|
||||
.param(paths_param())
|
||||
.param(Param::optional("includeExcluded", ParamType::Boolean, INCLUDE_EXCLUDED_DESCRIPTION))
|
||||
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
.param(Param::optional("context", ParamType::String, CONTEXT_DESCRIPTION))
|
||||
@@ -113,8 +114,7 @@ If you don't find a suitable result, try again with include_external=true to sea
|
||||
|call| async move { symbol_search(call).await },
|
||||
)
|
||||
.param(Param::required("q", ParamType::String, "Symbol query text"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
|
||||
.param(paths_param())
|
||||
.param(Param::optional(
|
||||
"include_external",
|
||||
ParamType::Boolean,
|
||||
@@ -140,13 +140,8 @@ Paths are optional additional glob filters relative to the project root.",
|
||||
|call| async move { file_search(call).await },
|
||||
)
|
||||
.param(Param::required("q", ParamType::String, "Glob pattern to search for"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
|
||||
.param(Param::optional(
|
||||
"includeExcluded",
|
||||
ParamType::Boolean,
|
||||
"Whether to include excluded/ignored files in results",
|
||||
))
|
||||
.param(paths_param())
|
||||
.param(Param::optional("includeExcluded", ParamType::Boolean, INCLUDE_EXCLUDED_DESCRIPTION))
|
||||
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
.output(result_schema())
|
||||
@@ -336,22 +331,39 @@ async fn fill_lines(
|
||||
|
||||
// --- path globs ----------------------------------------------------------------
|
||||
|
||||
/// The `paths` argument: project-relative globs, `!` excludes.
|
||||
struct PathScope {
|
||||
/// The `paths` argument every query tool takes.
|
||||
pub(crate) fn paths_param() -> Param {
|
||||
Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION)
|
||||
}
|
||||
|
||||
/// The `paths` argument: project-relative globs (absolute ones in a project attached outside
|
||||
/// the project), `!` excludes. It only narrows: what the project leaves out stays out.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PathScope {
|
||||
root: PathBuf,
|
||||
/// `None` when only excludes were given (everything is included).
|
||||
include: Option<GlobSet>,
|
||||
exclude: GlobSet,
|
||||
/// The globs as `FileMask` masks for Find in Files (`{a,b}` expanded, as masks
|
||||
/// split on commas), `None` when they cannot be expressed.
|
||||
masks: Option<(Vec<String>, Vec<String>)>,
|
||||
/// The folders the included globs lie in, `None` when one may match anywhere (`**/a.rs`).
|
||||
roots: Option<Vec<PathBuf>>,
|
||||
}
|
||||
|
||||
impl PathScope {
|
||||
fn new(root: &Path, patterns: &[String]) -> IdeResult<Self> {
|
||||
pub(crate) fn of(call: &Call) -> IdeResult<Self> {
|
||||
Self::new(call.root(), &call.project().content_roots(), &call.str_list("paths")?)
|
||||
}
|
||||
|
||||
/// `attached`: the content roots, whose files outside `root` the globs name by absolute path.
|
||||
fn new(root: &Path, attached: &[PathBuf], patterns: &[String]) -> IdeResult<Self> {
|
||||
let (mut include, mut exclude) = (GlobSetBuilder::new(), GlobSetBuilder::new());
|
||||
let (mut include_masks, mut exclude_masks) = (Vec::new(), Vec::new());
|
||||
let mut roots = Vec::new();
|
||||
let mut has_include = false;
|
||||
let mut maskable = true;
|
||||
let mut anywhere = false;
|
||||
for raw in patterns {
|
||||
let raw = raw.trim();
|
||||
if raw.is_empty() {
|
||||
@@ -362,12 +374,18 @@ impl PathScope {
|
||||
Some(rest) => (true, rest.trim()),
|
||||
None => (false, raw),
|
||||
};
|
||||
let mut glob = normalize_glob(pattern, root)?;
|
||||
let mut glob = normalize_glob(pattern, root, attached)?;
|
||||
// A path naming an existing directory covers the files below it.
|
||||
if index_of_glob_char(&glob).is_none() && root.join(&glob).is_dir() {
|
||||
glob.push_str("/**");
|
||||
}
|
||||
let alternatives = expand_braces(&glob);
|
||||
if !negated {
|
||||
match glob_folder(&glob, root) {
|
||||
Some(folder) => roots.push(folder),
|
||||
None => anywhere = true,
|
||||
}
|
||||
}
|
||||
let alternatives = expand_braces(&engine_mask(&glob, attached));
|
||||
maskable &= alternatives.is_some();
|
||||
let (set, masks) =
|
||||
if negated { (&mut exclude, &mut exclude_masks) } else { (&mut include, &mut include_masks) };
|
||||
@@ -376,27 +394,83 @@ impl PathScope {
|
||||
has_include |= !negated;
|
||||
}
|
||||
let build = |b: GlobSetBuilder| b.build().map_err(|e| IdeError::invalid(format!("Invalid glob pattern: {e}")));
|
||||
// A folder inside another one is walked with it.
|
||||
roots.sort();
|
||||
roots.dedup_by(|inner, outer| inner.starts_with(outer));
|
||||
Ok(Self {
|
||||
root: root.to_path_buf(),
|
||||
include: if has_include { Some(build(include)?) } else { None },
|
||||
exclude: build(exclude)?,
|
||||
masks: maskable.then_some((include_masks, exclude_masks)),
|
||||
roots: (has_include && !anywhere).then_some(roots),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_all(&self) -> bool {
|
||||
pub(crate) fn is_all(&self) -> bool {
|
||||
self.include.is_none() && self.exclude.is_empty()
|
||||
}
|
||||
|
||||
/// `path` is project-relative with `/` (absolute outside the project).
|
||||
fn matches(&self, path: &str) -> bool {
|
||||
pub(crate) fn matches(&self, path: &str) -> bool {
|
||||
self.include.as_ref().is_none_or(|s| s.is_match(path)) && !self.exclude.is_match(path)
|
||||
}
|
||||
|
||||
pub(crate) fn matches_path(&self, path: &Path) -> bool {
|
||||
self.is_all() || self.matches(&shown(&self.root, path))
|
||||
}
|
||||
|
||||
/// Whether `dir` or a file in it is in: a directory something runs in.
|
||||
pub(crate) fn matches_dir(&self, dir: &Path) -> bool {
|
||||
if self.is_all() {
|
||||
return true;
|
||||
}
|
||||
let dir = shown(&self.root, dir);
|
||||
self.matches(&dir) || self.matches(&if dir.is_empty() { "x".into() } else { format!("{dir}/x") })
|
||||
}
|
||||
|
||||
/// The folders to walk instead of the whole project, `None` when a glob may match anywhere.
|
||||
pub(crate) fn roots(&self) -> Option<&[PathBuf]> {
|
||||
self.roots.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` as the tools give it: relative to `root` with `/`, absolute (with `/`) outside it.
|
||||
fn shown(root: &Path, path: &Path) -> String {
|
||||
path.strip_prefix(root).unwrap_or(path).to_string_lossy().replace('\\', "/")
|
||||
}
|
||||
|
||||
/// The folder a normalized glob lies in (the whole segments before its first glob character),
|
||||
/// `None` for one that may match anywhere.
|
||||
fn glob_folder(glob: &str, root: &Path) -> Option<PathBuf> {
|
||||
let end = index_of_glob_char(glob).map_or(glob.len(), |i| glob[..i].rfind('/').unwrap_or(0));
|
||||
let prefix = glob[..end].trim_end_matches('/');
|
||||
if prefix.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = root.join(prefix);
|
||||
// A file named by its path lies in its folder.
|
||||
Some(if index_of_glob_char(glob).is_none() && !path.is_dir() { path.parent()?.to_path_buf() } else { path })
|
||||
}
|
||||
|
||||
/// `glob` as Find in Files matches it: a project attached outside the project goes by its
|
||||
/// folder name there (as `search_project` shows its files), not by its absolute path.
|
||||
fn engine_mask(glob: &str, attached: &[PathBuf]) -> String {
|
||||
if is_absolute_pattern(glob) {
|
||||
for root in attached {
|
||||
let shown = root.to_string_lossy().replace('\\', "/");
|
||||
if let Some(rest) = glob.strip_prefix(&shown).filter(|r| r.is_empty() || r.starts_with('/')) {
|
||||
return format!("{}{rest}", root.file_name().unwrap_or_default().to_string_lossy());
|
||||
}
|
||||
}
|
||||
}
|
||||
glob.to_owned()
|
||||
}
|
||||
|
||||
/// A glob as a project-relative pattern: `\` → `/`, leading `./` dropped, `dir/` → `dir/**`,
|
||||
/// `name` → `**/name`, and its leading directories (`..`, absolute paths) resolved against
|
||||
/// `root`. Errors when that points outside the project.
|
||||
fn normalize_glob(raw: &str, root: &Path) -> IdeResult<String> {
|
||||
/// `root`; absolute in a project of `attached` outside it. Errors when that points outside the
|
||||
/// project.
|
||||
fn normalize_glob(raw: &str, root: &Path, attached: &[PathBuf]) -> IdeResult<String> {
|
||||
let mut value = raw.trim().replace('\\', "/");
|
||||
if value.is_empty() {
|
||||
return Err(IdeError::invalid("Glob pattern is empty"));
|
||||
@@ -411,7 +485,7 @@ fn normalize_glob(raw: &str, root: &Path) -> IdeResult<String> {
|
||||
if !value.contains('/') {
|
||||
value = format!("**/{value}");
|
||||
}
|
||||
let value = normalize_path_pattern(&value, root)?;
|
||||
let value = normalize_path_pattern(&value, root, attached)?;
|
||||
if value.is_empty() {
|
||||
return Err(IdeError::invalid(format!("Invalid glob pattern: {raw}")));
|
||||
}
|
||||
@@ -421,7 +495,7 @@ fn normalize_glob(raw: &str, root: &Path) -> IdeResult<String> {
|
||||
/// Resolves the whole directory segments before the first glob character against `root`.
|
||||
/// (JetBrains resolves up to the glob character itself, turning `src/Foo*.java` into
|
||||
/// `src/Foo/*.java`; only whole segments are resolved here.)
|
||||
fn normalize_path_pattern(pattern: &str, root: &Path) -> IdeResult<String> {
|
||||
fn normalize_path_pattern(pattern: &str, root: &Path, attached: &[PathBuf]) -> IdeResult<String> {
|
||||
let outside = || {
|
||||
IdeError::invalid(format!("Specified path '{pattern}' points to the location outside of the project directory"))
|
||||
};
|
||||
@@ -442,8 +516,16 @@ fn normalize_path_pattern(pattern: &str, root: &Path) -> IdeResult<String> {
|
||||
} else {
|
||||
root.join(prefix_path)
|
||||
});
|
||||
let relative = relative_to_root(root, &absolute).ok_or_else(outside)?;
|
||||
let suffix = pattern[prefix_len..].trim_start_matches('/');
|
||||
let Some(relative) = relative_to_root(root, &absolute) else {
|
||||
// A project attached outside the project goes by its absolute path, as its files do.
|
||||
let absolute = dunce::canonicalize(&absolute).unwrap_or(absolute);
|
||||
if !attached.iter().any(|r| absolute.starts_with(r)) {
|
||||
return Err(outside());
|
||||
}
|
||||
let absolute = absolute.to_string_lossy().replace('\\', "/");
|
||||
return Ok(if suffix.is_empty() { absolute } else { format!("{absolute}/{suffix}") });
|
||||
};
|
||||
Ok(match (relative.is_empty(), suffix.is_empty()) {
|
||||
(true, _) => suffix.to_owned(),
|
||||
(false, true) => relative,
|
||||
@@ -544,8 +626,7 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
let pattern = query(&call, if is_regex { "Regex pattern is empty" } else { "Search text is empty" })?;
|
||||
let (page, limit) = page(&call, DEFAULT_LIMIT)?;
|
||||
let around = context(&call)?;
|
||||
let dir = Scope::of(&call)?;
|
||||
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
|
||||
let scope = PathScope::of(&call)?;
|
||||
// Globs Find in Files cannot take are applied afterwards, so the engine must not
|
||||
// stop at `limit` matches the filter may drop.
|
||||
let (masks, max_matches) = match scope.masks.clone() {
|
||||
@@ -565,22 +646,18 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
whole_word: false,
|
||||
include,
|
||||
exclude,
|
||||
// Only `scope` is walked.
|
||||
scope: dir.dir().map_or(SearchScope::Project, |d| SearchScope::Directory { path: d.to_path_buf().into() }),
|
||||
scope: SearchScope::Project,
|
||||
max_matches,
|
||||
context: Default::default(),
|
||||
include_excluded: call.flag("includeExcluded", false)?,
|
||||
};
|
||||
if is_regex && let Err(e) = ide_search::match_ranges("", &query) {
|
||||
return Err(IdeError::invalid(format!("Invalid regex pattern: {pattern} ({})", e.message)));
|
||||
}
|
||||
let (files, summary, timed_out) = run_search(&call, query.clone()).await?;
|
||||
// Content roots outside the project are reported by absolute path.
|
||||
let mut files: Vec<(String, FileMatches)> = files
|
||||
.into_iter()
|
||||
.filter(|f| dir.contains(&f.path.0))
|
||||
.map(|f| (call.display(&f.path.0), f))
|
||||
.filter(|(path, _)| scope.matches(path))
|
||||
.collect();
|
||||
let mut files: Vec<(String, FileMatches)> =
|
||||
files.into_iter().map(|f| (call.display(&f.path.0), f)).filter(|(path, _)| scope.matches(path)).collect();
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
// Only these can match a line break.
|
||||
let may_span = is_regex || pattern.contains('\n');
|
||||
@@ -750,27 +827,35 @@ async fn run_search(call: &Call, query: SearchQuery) -> IdeResult<(Vec<FileMatch
|
||||
async fn file_search(call: Call) -> IdeResult<Output> {
|
||||
let q = query(&call, "Glob pattern is empty")?;
|
||||
let (page, limit) = page(&call, DEFAULT_LIMIT)?;
|
||||
let dir = Scope::of(&call)?;
|
||||
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
|
||||
let scope = PathScope::of(&call)?;
|
||||
let include_excluded = call.flag("includeExcluded", false)?;
|
||||
let glob = GlobSetBuilder::new()
|
||||
.add(build_glob(&normalize_glob(&q, call.root())?)?)
|
||||
.add(build_glob(&normalize_glob(&q, call.root(), &[])?)?)
|
||||
.build()
|
||||
.map_err(|_| IdeError::invalid(format!("Invalid glob pattern: {q}")))?;
|
||||
// Ignored names and "Exclude files" patterns, which `read_dir` does not flag.
|
||||
let excludes = if include_excluded { None } else { Some(FileMask::new(&[], &call.project().search_excludes())?) };
|
||||
let root = call.root().to_path_buf();
|
||||
// `scope`, or the project folder and the content roots its walk does not cover: those
|
||||
// outside it and those inside it that it skips as ignored.
|
||||
let roots: Vec<PathBuf> = match dir.dir() {
|
||||
Some(dir) => vec![dir.to_path_buf()],
|
||||
let content = call.project().content_roots();
|
||||
// Where a folder's exclusions are matched from: the content root holding it, or the project.
|
||||
let base_of =
|
||||
|dir: &Path| content.iter().filter(|r| dir.starts_with(r)).max_by_key(|r| r.components().count()).cloned();
|
||||
// The folders of `paths`, or the project folder and the content roots its walk does not
|
||||
// cover: those outside it and those inside it that it skips as ignored.
|
||||
let roots: Vec<(PathBuf, PathBuf)> = match scope.roots() {
|
||||
Some(dirs) => dirs
|
||||
.iter()
|
||||
.filter(|d| d.is_dir())
|
||||
.map(|d| (d.clone(), base_of(d).unwrap_or_else(|| root.clone())))
|
||||
.collect(),
|
||||
None => std::iter::once(root.clone())
|
||||
.chain(
|
||||
call.project()
|
||||
.content_roots()
|
||||
.into_iter()
|
||||
.filter(|r| relative_to_root(&root, r).is_none() || ide_index::walk_skips(&root, r)),
|
||||
content
|
||||
.iter()
|
||||
.filter(|r| relative_to_root(&root, r).is_none() || ide_index::walk_skips(&root, r))
|
||||
.cloned(),
|
||||
)
|
||||
.map(|r| (r.clone(), r))
|
||||
.collect(),
|
||||
};
|
||||
let host = call.host();
|
||||
@@ -790,7 +875,7 @@ async fn file_search(call: Call) -> IdeResult<Output> {
|
||||
let (paths, more, timed_out) = host
|
||||
.blocking(move || {
|
||||
let mut found = Vec::new();
|
||||
let more = roots.iter().any(|base| walk.dir(base, base, &mut found));
|
||||
let more = roots.iter().any(|(dir, base)| walk.dir(dir, base, &mut found));
|
||||
if walk.cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -877,23 +962,23 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
|
||||
let q = query(&call, "Search query is empty")?;
|
||||
let (page, limit) = page(&call, SYMBOL_SEARCH_DEFAULT_LIMIT)?;
|
||||
let around = context(&call)?;
|
||||
let dir = Scope::of(&call)?;
|
||||
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
|
||||
let scope = PathScope::of(&call)?;
|
||||
let external = call.flag("include_external", false)?;
|
||||
let host = call.host();
|
||||
let project = call.project().clone();
|
||||
let indexing_before = project.index.status().indexing;
|
||||
let pool = if scope.is_all() { limit + 1 } else { ((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL) };
|
||||
let found = {
|
||||
let (project, q, dir) = (project.clone(), q.clone(), dir.dir().map(Path::to_path_buf));
|
||||
let (project, q, within) = (project.clone(), q.clone(), scope.clone());
|
||||
host.blocking(move || {
|
||||
Ok(match dir {
|
||||
Ok(if within.is_all() {
|
||||
project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool)
|
||||
} else {
|
||||
// Filtered in the index: a pool cut before the filter could miss every match.
|
||||
Some(dir) => project
|
||||
project
|
||||
.index
|
||||
.find_symbols_until(&q, ide_index::SymbolFilter::All, pool, &|p| p.starts_with(&dir), &|| false)
|
||||
.unwrap_or_default(),
|
||||
None => project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool),
|
||||
.find_symbols_until(&q, ide_index::SymbolFilter::All, pool, &|p| within.matches_path(p), &|| false)
|
||||
.unwrap_or_default()
|
||||
})
|
||||
})
|
||||
.await?
|
||||
@@ -902,7 +987,6 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
|
||||
.into_iter()
|
||||
// By the path the other tools give: the index shows a root outside the project by its
|
||||
// folder name, which is no path to read.
|
||||
.filter(|s| dir.contains(&s.path.0))
|
||||
.map(|s| (call.display(&s.path.0), s))
|
||||
.filter(|(path, _)| scope.matches(path))
|
||||
.map(|(path, s)| SearchItem {
|
||||
@@ -920,11 +1004,11 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
|
||||
roots.extend(crate::mcp::tool::attached_projects(call.root()));
|
||||
for (name, container, location) in symbols {
|
||||
let path = location.uri.clone().unwrap_or_else(|| call.display(&location.path));
|
||||
// Project files (attached projects' too) obey `scope` and `paths`; library symbols
|
||||
// are what was asked for.
|
||||
// Project files (attached projects' too) obey `paths`; library symbols are what was
|
||||
// asked for.
|
||||
let inside = location.uri.is_none()
|
||||
&& (!Path::new(&path).is_absolute() || roots.iter().any(|r| location.path.starts_with(r)));
|
||||
if inside && !(dir.contains_shown(call.root(), &path) && scope.matches(&path)) {
|
||||
if inside && !scope.matches(&path) {
|
||||
continue;
|
||||
}
|
||||
let item = SearchItem {
|
||||
@@ -999,13 +1083,13 @@ mod tests {
|
||||
}
|
||||
|
||||
fn scope(root: &Path, p: &[&str]) -> PathScope {
|
||||
PathScope::new(root, &p.iter().map(|s| s.to_string()).collect::<Vec<_>>()).unwrap()
|
||||
PathScope::new(root, &[], &p.iter().map(|s| s.to_string()).collect::<Vec<_>>()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_globs() {
|
||||
let (_dir, root) = root();
|
||||
let n = |p: &str| normalize_glob(p, &root);
|
||||
let n = |p: &str| normalize_glob(p, &root, &[]);
|
||||
assert_eq!(n("*.rs").unwrap(), "**/*.rs");
|
||||
assert_eq!(n("./foo/bar.txt").unwrap(), "foo/bar.txt");
|
||||
assert_eq!(n("foo/").unwrap(), "foo/**");
|
||||
@@ -1082,9 +1166,33 @@ mod tests {
|
||||
assert!(s.matches("a.rs") && !s.matches("docs/a.md"));
|
||||
assert!(scope(root, &["*.{rs,ts}"]).masks.is_some());
|
||||
assert!(scope(root, &["*.{rs,{ts,js}}"]).masks.is_none());
|
||||
let err = |p: &str| PathScope::new(root, &[p.to_owned()]).err().unwrap().message;
|
||||
let err = |p: &str| PathScope::new(root, &[], &[p.to_owned()]).err().unwrap().message;
|
||||
assert!(err("a[").contains("Invalid glob pattern"));
|
||||
assert!(err("!").contains("Exclude pattern is empty"));
|
||||
assert!(err("../x/**").contains("outside of the project directory"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_name_the_folders_to_walk_and_projects_attached_outside() {
|
||||
let (dir, root) = root();
|
||||
let roots = |p: &[&str]| scope(&root, p).roots().map(<[PathBuf]>::to_vec);
|
||||
// Only the folders the globs lie in, a folder inside another one walked with it.
|
||||
assert_eq!(roots(&["subdir1/**", "subdir1/nested/*.rs", "!**/gen/**"]), Some(vec![root.join("subdir1")]));
|
||||
assert_eq!(roots(&["subdir1/nested/x.rs"]), Some(vec![root.join("subdir1/nested")]));
|
||||
// A glob matching anywhere, or none included, means the whole project.
|
||||
assert_eq!(roots(&["subdir1/**", "**/*.rs"]), None);
|
||||
assert_eq!(roots(&["!**/*.md"]), None);
|
||||
|
||||
let attached = dunce::canonicalize(dir.path()).unwrap().join("attached");
|
||||
std::fs::create_dir_all(attached.join("src")).unwrap();
|
||||
let shown = attached.to_string_lossy().replace('\\', "/");
|
||||
let s = PathScope::new(&root, std::slice::from_ref(&attached), &[format!("{shown}/src/**")]).unwrap();
|
||||
assert!(s.matches(&format!("{shown}/src/a.rs")) && !s.matches("src/a.rs"));
|
||||
assert!(s.matches_path(&attached.join("src/a.rs")));
|
||||
assert_eq!(s.roots(), Some(&[attached.join("src")][..]));
|
||||
// Find in Files shows such a project's files under its folder name.
|
||||
assert_eq!(s.masks.unwrap().0, ["attached/src/**"]);
|
||||
let unattached = PathScope::new(&root, &[], &[format!("{shown}/src/**")]);
|
||||
assert!(unattached.err().unwrap().message.contains("outside of the project directory"));
|
||||
}
|
||||
}
|
||||
@@ -214,7 +214,7 @@ pub fn find_references() -> Tool {
|
||||
Tool::new("find_references", "Find references using the language service and the IDE's project index. Positions are 1-based UTF-16. Reports incomplete results when analysis is still running.", |call| async move {
|
||||
let path = call.resolve_readable(&call.str("filePath")?).await?;
|
||||
let page = super::page::Page::of(&call, REFERENCES_LIMIT)?;
|
||||
let dir = super::scope::Scope::of(&call)?;
|
||||
let paths = super::search::PathScope::of(&call)?;
|
||||
let opened = open_at(&call, path).await?;
|
||||
let request = super::tool::request_id();
|
||||
let work = crate::ops::lsp::lsp_references(&call.host, &call.window, request, opened.doc, opened.pos, call.flag("includeDeclaration", true)?, true, false, crate::ops::Channel::new(|_| {}));
|
||||
@@ -237,8 +237,8 @@ pub fn find_references() -> Tool {
|
||||
if let serde_json::Value::Object(map) = &mut value {
|
||||
let mut list = |key: &str| match map.remove(key) { Some(serde_json::Value::Array(items)) => items, _ => Vec::new() };
|
||||
let (mut locations, mut classified) = (list("locations"), list("classified"));
|
||||
if dir.dir().is_some() {
|
||||
let inside = |l: &serde_json::Value| l["path"].as_str().is_some_and(|p| dir.contains(std::path::Path::new(p)));
|
||||
if !paths.is_all() {
|
||||
let inside = |l: &serde_json::Value| l["path"].as_str().is_some_and(|p| paths.matches_path(std::path::Path::new(p)));
|
||||
locations.retain(inside);
|
||||
classified.retain(|c| inside(&c["location"]));
|
||||
}
|
||||
@@ -253,7 +253,7 @@ pub fn find_references() -> Tool {
|
||||
.param(Param::required("line", ParamType::Integer, "1-based line"))
|
||||
.param(Param::required("column", ParamType::Integer, "1-based UTF-16 column"))
|
||||
.param(Param::optional("includeDeclaration", ParamType::Boolean, "Include declarations (default true)"))
|
||||
.param(super::scope::param())
|
||||
.param(super::search::paths_param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "References to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, super::page::OFFSET))
|
||||
}
|
||||
@@ -336,7 +336,7 @@ pub fn get_call_hierarchy() -> Tool {
|
||||
.param(Param::required("line", ParamType::Integer, "1-based line"))
|
||||
.param(Param::required("column", ParamType::Integer, "1-based UTF-16 column"))
|
||||
.param(Param::optional("direction", ParamType::String, "incoming (callers, default) or outgoing (callees)"))
|
||||
.param(super::scope::param())
|
||||
.param(super::search::paths_param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Items to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, super::page::OFFSET))
|
||||
}
|
||||
@@ -354,7 +354,7 @@ async fn call_hierarchy(call: Call) -> IdeResult<Output> {
|
||||
Some(_) => return Err(IdeError::invalid("direction must be incoming or outgoing")),
|
||||
};
|
||||
let page = super::page::Page::of(&call, CALLS_LIMIT)?;
|
||||
let scope = super::scope::Scope::of(&call)?;
|
||||
let paths = super::search::PathScope::of(&call)?;
|
||||
let path = call.resolve_readable(&call.str("filePath")?).await?;
|
||||
let opened = open_at(&call, path).await?;
|
||||
let hierarchy_at = |pos| {
|
||||
@@ -378,8 +378,8 @@ async fn call_hierarchy(call: Call) -> IdeResult<Output> {
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
if scope.dir().is_some() {
|
||||
found.items.retain(|i| i.uri.is_none() && scope.contains(&i.path.0));
|
||||
if !paths.is_all() {
|
||||
found.items.retain(|i| i.uri.is_none() && paths.matches_path(&i.path.0));
|
||||
}
|
||||
let incomplete = found.incomplete;
|
||||
let (mut root, items) = call_items(found, |p| call.display(p));
|
||||
|
||||
@@ -266,33 +266,39 @@ By default all Git repositories are returned.",
|
||||
.map(|r| (r.root.into_path_buf(), r.head))
|
||||
.collect();
|
||||
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
|
||||
let scope = super::scope::Scope::of(&call)?;
|
||||
let paths = super::search::PathScope::of(&call)?;
|
||||
let git = git_executable(&call);
|
||||
// A repository asked for, or the one holding `scope`.
|
||||
let target = match &wanted {
|
||||
Some(wanted) => Some(call.resolve_inside(wanted)?),
|
||||
None => scope.dir().map(Path::to_path_buf),
|
||||
// The repository asked for, or those holding the folders of `paths`.
|
||||
let targets: Vec<PathBuf> = match &wanted {
|
||||
Some(wanted) => vec![call.resolve_inside(wanted)?],
|
||||
None => paths.roots().map(<[PathBuf]>::to_vec).unwrap_or_default(),
|
||||
};
|
||||
let mut roots: Vec<(PathBuf, Option<String>)> = match target {
|
||||
None => repos,
|
||||
Some(path) => {
|
||||
let mut roots: Vec<(PathBuf, Option<String>)> = if targets.is_empty() {
|
||||
repos
|
||||
} else {
|
||||
let mut picked: Vec<(PathBuf, Option<String>)> = Vec::new();
|
||||
for path in targets {
|
||||
// The innermost repository containing the path.
|
||||
match innermost_repo(repos, &path) {
|
||||
Some(repo) => vec![repo],
|
||||
let repo = match innermost_repo(repos.clone(), &path) {
|
||||
Some(repo) => repo,
|
||||
None => match find_git_root(call.root(), &path) {
|
||||
Some(root) => {
|
||||
// JetBrains reads the branch of any repository it reports.
|
||||
let (git, dir) = (git.clone(), root.clone());
|
||||
let branch = host.blocking(move || Ok(read_branch(&git, &dir))).await?;
|
||||
vec![(root, branch)]
|
||||
(root, branch)
|
||||
}
|
||||
None => {
|
||||
let shown = wanted.unwrap_or_else(|| call.display(&path));
|
||||
let shown = wanted.clone().unwrap_or_else(|| call.display(&path));
|
||||
return Err(IdeError::not_found(format!("No git repository found for path: {shown}")));
|
||||
}
|
||||
},
|
||||
};
|
||||
if !picked.iter().any(|p| p.0 == repo.0) {
|
||||
picked.push(repo);
|
||||
}
|
||||
}
|
||||
picked
|
||||
};
|
||||
roots.sort_by_key(|r| relative_to_project(&call, &r.0));
|
||||
let mut repositories = Vec::new();
|
||||
@@ -305,7 +311,7 @@ By default all Git repositories are returned.",
|
||||
.map_err(|e| {
|
||||
IdeError::internal(format!("Failed to get git status for repository '{rel}': {}", e.message))
|
||||
})?;
|
||||
entries.retain(|e| scope.contains(&root.join(e.path.trim_end_matches('/'))));
|
||||
entries.retain(|e| paths.matches_path(&root.join(e.path.trim_end_matches('/'))));
|
||||
let count = |f: fn(&StatusEntry) -> bool| entries.iter().filter(|e| f(e)).count();
|
||||
let listed: Vec<Value> = entries
|
||||
.iter()
|
||||
@@ -352,7 +358,7 @@ By default all Git repositories are returned.",
|
||||
))
|
||||
.param(Param::optional("includeUntracked", ParamType::Boolean, "Whether to include untracked files"))
|
||||
.param(Param::optional("includeIgnored", ParamType::Boolean, "Whether to include ignored files"))
|
||||
.param(super::scope::param())
|
||||
.param(super::search::paths_param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Entries to return per repository at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
}
|
||||
|
||||
@@ -34,8 +34,10 @@ pub async fn search_start(
|
||||
) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
// Excluded roots (Project Structure marks and detected `target`, `node_modules`, …) and
|
||||
// ignored names are never searched.
|
||||
query.exclude.extend(project.search_excludes());
|
||||
// ignored names are not searched, unless the query asks for them.
|
||||
if !query.include_excluded {
|
||||
query.exclude.extend(project.search_excludes());
|
||||
}
|
||||
let cancel = host.begin_request(request);
|
||||
let events = on_event.clone();
|
||||
let syntax = host.syntax();
|
||||
@@ -80,10 +82,15 @@ pub(crate) fn search_project(
|
||||
query.scope,
|
||||
ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. }
|
||||
));
|
||||
let content_roots = match query.scope {
|
||||
let content_roots: Vec<std::path::PathBuf> = match query.scope {
|
||||
ide_search::SearchScope::Project
|
||||
| ide_search::SearchScope::FileSet { .. }
|
||||
| ide_search::SearchScope::Pattern { .. } => project.content_roots(),
|
||||
| ide_search::SearchScope::Pattern { .. } => project
|
||||
.content_roots()
|
||||
.into_iter()
|
||||
// Kept out of the root's walk only by its ignore rules, which this search does not apply.
|
||||
.filter(|r| !(query.include_excluded && include_root && r.starts_with(root)))
|
||||
.collect(),
|
||||
_ => within.into_iter().collect(),
|
||||
};
|
||||
let filter = |rel: &str| match set {
|
||||
@@ -144,7 +151,7 @@ pub(crate) fn search_project(
|
||||
/// Project-relative `masks` (each a comma-separated list) for a search from the content root
|
||||
/// shown as `prefix`: paths below it lose the prefix, other paths can match nothing there and
|
||||
/// are dropped, names and `**/` patterns (`*.rs`, `**/build/**`) stay as they are.
|
||||
fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
|
||||
pub(crate) fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
|
||||
let prefix = format!("{}/", prefix.trim_end_matches('/'));
|
||||
masks
|
||||
.iter()
|
||||
|
||||
@@ -568,6 +568,8 @@ pub(super) struct Shared {
|
||||
/// (plugin, item id) → item, for windows opened later.
|
||||
output: Mutex<BTreeMap<(String, String), String>>,
|
||||
decorations: Mutex<BTreeMap<String, Vec<super::DecorationSet>>>,
|
||||
/// plugin → its console highlight rules, in order.
|
||||
console_rules: Mutex<BTreeMap<String, Vec<ide_plugin::ConsoleRule>>>,
|
||||
status: Mutex<BTreeMap<(String, String), StatusItem>>,
|
||||
setting_snapshots: Mutex<SettingSnapshots>,
|
||||
window_status: Mutex<BTreeMap<(String, String, String), StatusItem>>,
|
||||
@@ -648,6 +650,7 @@ impl Shared {
|
||||
status: Mutex::default(),
|
||||
output: Mutex::default(),
|
||||
decorations: Mutex::default(),
|
||||
console_rules: Mutex::default(),
|
||||
window_status: Mutex::default(),
|
||||
setting_snapshots: Mutex::default(),
|
||||
contexts: Mutex::default(),
|
||||
@@ -874,6 +877,9 @@ impl Shared {
|
||||
if self.decorations.lock().remove(plugin).is_some() {
|
||||
self.sink.emit(None, PluginEvent::DecorationsChanged { plugin_id: plugin.into(), sets: Vec::new() });
|
||||
}
|
||||
if self.console_rules.lock().remove(plugin).is_some() {
|
||||
self.sink.emit(None, PluginEvent::ConsoleRulesChanged { plugin_id: plugin.into(), rules: Vec::new() });
|
||||
}
|
||||
self.withdraw_prompts(plugin);
|
||||
self.net_prompts.lock().remove(plugin);
|
||||
self.session_net_hosts.lock().remove(plugin);
|
||||
@@ -1706,6 +1712,18 @@ impl HostApi for PluginApi {
|
||||
fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError> {
|
||||
self.set_file_icon_decorations(set, items)
|
||||
}
|
||||
fn console_rules(&self, rules: Vec<ide_plugin::ConsoleRule>) -> Result<(), HostError> {
|
||||
let rules = super::console_rules::normalize(rules).map_err(HostError::Invalid)?;
|
||||
let mut all = self.shared.console_rules.lock();
|
||||
if rules.is_empty() {
|
||||
all.remove(self.id());
|
||||
} else {
|
||||
all.insert(self.id().into(), rules.clone());
|
||||
}
|
||||
// Emitted under the lock so replacements cannot arrive out of order.
|
||||
self.shared.sink.emit(None, PluginEvent::ConsoleRulesChanged { plugin_id: self.id().into(), rules });
|
||||
Ok(())
|
||||
}
|
||||
fn vcs_log(
|
||||
&self,
|
||||
root: &Path,
|
||||
@@ -3276,6 +3294,7 @@ impl PluginWorkspace for HostWorkspace {
|
||||
scope: ide_search::SearchScope::Project,
|
||||
max_matches: limit.min(10_000).saturating_add(1),
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
};
|
||||
query.exclude.extend(project.search_excludes());
|
||||
let files = Mutex::new(Vec::new());
|
||||
@@ -4441,6 +4460,9 @@ impl Shared {
|
||||
pub(super) fn decoration_sets(&self) -> BTreeMap<String, Vec<super::DecorationSet>> {
|
||||
self.decorations.lock().clone()
|
||||
}
|
||||
pub(super) fn console_rules(&self) -> BTreeMap<String, Vec<ide_plugin::ConsoleRule>> {
|
||||
self.console_rules.lock().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -4612,6 +4634,34 @@ mod workbench_tests {
|
||||
assert!(api.shared.decoration_sets().is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn console_rules_replace_keep_the_last_valid_list_and_go_with_the_plugin() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let api = api(dir.path(), false, None);
|
||||
let rule = |pattern: &str| ide_plugin::ConsoleRule {
|
||||
pattern: pattern.into(),
|
||||
ignore_case: false,
|
||||
foreground: Some("bright-yellow".into()),
|
||||
background: Some("navy".into()),
|
||||
styles: vec!["bold".into()],
|
||||
whole_line: true,
|
||||
enabled: true,
|
||||
};
|
||||
// No capability, and no trusted project, is needed: the rules read nothing.
|
||||
api.console_rules(vec![rule(r"\[AUDIT\]"), rule(r"JOB-\d+")]).unwrap();
|
||||
let rules = &api.shared.console_rules()["test"];
|
||||
assert_eq!(rules.len(), 2);
|
||||
assert_eq!((rules[0].foreground.as_deref(), rules[0].background.as_deref()), (Some("bright-yellow"), None));
|
||||
assert!(matches!(api.console_rules(vec![rule("(a+)+b")]), Err(HostError::Invalid(_))));
|
||||
assert_eq!(api.shared.console_rules()["test"].len(), 2);
|
||||
api.console_rules(vec![rule("x")]).unwrap();
|
||||
assert_eq!(api.shared.console_rules()["test"].len(), 1);
|
||||
api.console_rules(Vec::new()).unwrap();
|
||||
assert!(api.shared.console_rules().is_empty());
|
||||
api.console_rules(vec![rule("x")]).unwrap();
|
||||
api.shared.clear_plugin("test", true);
|
||||
assert!(api.shared.console_rules().is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn decoration_styles_keep_the_severity_palette_the_editor_renders() {
|
||||
// Inspection Lens colours typos and weak warnings with their own styles; the
|
||||
// host must keep them, not silently drop them the way an unknown style is dropped.
|
||||
|
||||
@@ -184,6 +184,12 @@ pub fn plugin_decoration_sets(plugins: &Arc<PluginHost>) -> BTreeMap<String, Vec
|
||||
plugins.decoration_sets()
|
||||
}
|
||||
|
||||
/// Every plugin's console highlight rules (later changes arrive as `consoleRulesChanged`).
|
||||
#[command(trust = trusted)]
|
||||
pub fn plugin_console_rules(plugins: &Arc<PluginHost>) -> BTreeMap<String, Vec<ide_plugin::ConsoleRule>> {
|
||||
plugins.console_rules()
|
||||
}
|
||||
|
||||
/// Reports exactly one completion from the operation's launching window.
|
||||
#[command(trust = trusted)]
|
||||
pub fn plugin_finish_operation(
|
||||
@@ -296,6 +302,7 @@ ide_command::domain!(
|
||||
plugin_answer_prompt,
|
||||
plugin_cancel_task,
|
||||
plugin_choose_program,
|
||||
plugin_console_rules,
|
||||
plugin_content_tab_action,
|
||||
plugin_context_keys,
|
||||
plugin_debug_attach_target,
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Console highlight rules (API 1.12, `ui.set-console-rules`): validated here,
|
||||
//! matched by the windows with JavaScript's backtracking `RegExp`. A rule is
|
||||
//! refused unless its worst case on a line of [`LINE_LEN`] characters stays
|
||||
//! within [`MAX_STEPS`] backtracking steps, estimated from its structure.
|
||||
|
||||
use ide_plugin::ConsoleRule;
|
||||
use regex_syntax::hir::{Class, ClassUnicode, ClassUnicodeRange, Hir, HirKind, Look};
|
||||
|
||||
pub(crate) const MAX_RULES: usize = 100;
|
||||
/// The characters of a line the windows match rules against (`src/ui/consoleRules.ts`).
|
||||
const LINE_LEN: u64 = 2000;
|
||||
/// About 4 · 2000², a few milliseconds of `RegExp` work for one line.
|
||||
const MAX_STEPS: u64 = 4 * LINE_LEN * LINE_LEN;
|
||||
|
||||
const COLORS: &[&str] = &["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"];
|
||||
const STYLES: &[&str] = &["bold", "italic", "underline", "strikethrough", "dim"];
|
||||
|
||||
/// Validates every rule and drops colours and styles this host doesn't know.
|
||||
pub(crate) fn normalize(rules: Vec<ConsoleRule>) -> Result<Vec<ConsoleRule>, String> {
|
||||
if rules.len() > MAX_RULES {
|
||||
return Err(format!("at most {MAX_RULES} console rules"));
|
||||
}
|
||||
rules
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, rule)| {
|
||||
validate_pattern(&rule.pattern, rule.ignore_case).map_err(|e| format!("console rule {i}: {e}"))?;
|
||||
let mut styles: Vec<String> = Vec::new();
|
||||
for style in rule.styles {
|
||||
if STYLES.contains(&style.as_str()) && !styles.contains(&style) {
|
||||
styles.push(style);
|
||||
}
|
||||
}
|
||||
Ok(ConsoleRule {
|
||||
foreground: rule.foreground.filter(|c| known_color(c)),
|
||||
background: rule.background.filter(|c| known_color(c)),
|
||||
styles,
|
||||
..rule
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn known_color(name: &str) -> bool {
|
||||
COLORS.contains(&name.strip_prefix("bright-").unwrap_or(name))
|
||||
}
|
||||
|
||||
fn validate_pattern(pattern: &str, ignore_case: bool) -> Result<(), String> {
|
||||
if pattern.is_empty() {
|
||||
return Err("empty pattern".into());
|
||||
}
|
||||
if pattern.len() > super::icon_patterns::MAX_PATTERN_LEN {
|
||||
return Err(format!("pattern {pattern:?} is too long (max {})", super::icon_patterns::MAX_PATTERN_LEN));
|
||||
}
|
||||
if let Some(construct) = super::icon_patterns::unsupported_construct(pattern) {
|
||||
return Err(format!("pattern {pattern:?}: {construct} is not supported"));
|
||||
}
|
||||
let parse = |p: &str| {
|
||||
regex_syntax::ParserBuilder::new()
|
||||
.case_insensitive(ignore_case)
|
||||
.build()
|
||||
.parse(p)
|
||||
.map_err(|e| format!("invalid pattern {pattern:?}: {e}"))
|
||||
};
|
||||
parse(pattern)?;
|
||||
let hir = parse(&javascript_classes(pattern))?;
|
||||
let anchored = starts_anchored(&hir);
|
||||
let cost = cost(&hir, &ClassUnicode::empty(), true)
|
||||
.map_err(|why| format!("pattern {pattern:?}: {why} is not supported"))?;
|
||||
let starts = if anchored { 1 } else { LINE_LEN };
|
||||
if cost.work.saturating_mul(starts) > MAX_STEPS {
|
||||
return Err(format!(
|
||||
"pattern {pattern:?} could take too long on a long line: avoid two repetitions that can match the same text (`.*a.*b`, `\\w+\\w+`); a class such as `[^)]*` often helps"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn starts_anchored(hir: &Hir) -> bool {
|
||||
match hir.kind() {
|
||||
HirKind::Look(Look::Start) => true,
|
||||
HirKind::Capture(c) => starts_anchored(&c.sub),
|
||||
HirKind::Concat(items) => items.first().is_some_and(starts_anchored),
|
||||
HirKind::Alternation(items) => items.iter().all(starts_anchored),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// From one start: `ways` the expression can end (each a backtracking point for
|
||||
/// what follows) and the `work` of trying them all when what follows fails.
|
||||
/// `scan`: the work is one pass over a run of characters.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Cost {
|
||||
ways: u64,
|
||||
work: u64,
|
||||
scan: bool,
|
||||
}
|
||||
|
||||
const ONE: Cost = Cost { ways: 1, work: 1, scan: false };
|
||||
|
||||
/// `follow`: the characters what comes after `hir` can start with (empty when
|
||||
/// only assertions follow). `last`: nothing follows, so the first way to end is the match.
|
||||
fn cost(hir: &Hir, follow: &ClassUnicode, last: bool) -> Result<Cost, &'static str> {
|
||||
match hir.kind() {
|
||||
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => Ok(ONE),
|
||||
HirKind::Capture(c) => cost(&c.sub, follow, last),
|
||||
HirKind::Concat(items) => {
|
||||
let mut total = Cost { ways: 1, work: 0, scan: false };
|
||||
let mut fixed = false;
|
||||
let mut scanned = None;
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
let rest = &items[i + 1..];
|
||||
// Nothing after this can fail: the first way to end is the match.
|
||||
if last && rest.is_empty() && nullable(item) {
|
||||
total.work = total.work.saturating_add(total.ways);
|
||||
break;
|
||||
}
|
||||
let next = first_of_seq(rest, follow);
|
||||
let c = cost(item, &next, last && rest.is_empty())?;
|
||||
// In a run of single characters (`[Ee][Rr]…`) only the first one is tried each way,
|
||||
// and runs of one way cover different parts of the line: one pass in all.
|
||||
let single = c.ways == 1 && c.work == 1;
|
||||
let rescan = c.scan && scanned == Some(total.ways);
|
||||
if !(single && fixed) && !rescan {
|
||||
total.work = total.work.saturating_add(total.ways.saturating_mul(c.work));
|
||||
}
|
||||
fixed = single;
|
||||
if c.scan {
|
||||
scanned = Some(total.ways);
|
||||
}
|
||||
total.ways = total.ways.saturating_mul(c.ways);
|
||||
}
|
||||
Ok(Cost { ways: total.ways, work: total.work.max(1), scan: false })
|
||||
}
|
||||
HirKind::Alternation(items) => items.iter().try_fold(Cost { ways: 0, work: 0, scan: false }, |acc, h| {
|
||||
let c = cost(h, follow, last)?;
|
||||
Ok(Cost { ways: acc.ways.saturating_add(c.ways), work: acc.work.saturating_add(c.work), scan: false })
|
||||
}),
|
||||
HirKind::Repetition(r) => match r.max {
|
||||
None if matches!(r.sub.kind(), HirKind::Literal(_) | HirKind::Class(_)) => {
|
||||
// A run that what follows can't start inside ends in one place.
|
||||
let ways = if overlaps(&first(&r.sub), follow) { LINE_LEN } else { 1 };
|
||||
Ok(Cost { ways, work: LINE_LEN, scan: true })
|
||||
}
|
||||
None => Err("a repeated group (`(…)*`, `(…)+`)"),
|
||||
Some(max) => {
|
||||
// Each copy may end in `c.ways` places, and the count itself may vary.
|
||||
let c = cost(&r.sub, &union(&first(&r.sub), follow), false)?;
|
||||
let ways = c.ways.saturating_pow(max).saturating_mul(u64::from(max - r.min) + 1);
|
||||
Ok(Cost { ways, work: ways.saturating_mul(c.work).saturating_add(u64::from(max)), scan: false })
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn overlaps(a: &ClassUnicode, b: &ClassUnicode) -> bool {
|
||||
let mut both = a.clone();
|
||||
both.intersect(b);
|
||||
!both.ranges().is_empty()
|
||||
}
|
||||
|
||||
/// `pattern` with JavaScript's ASCII-only `\w` and `\d` (Rust's are Unicode), so that
|
||||
/// `\W` and `\D` include letters such as `é` as they do where the rules run.
|
||||
fn javascript_classes(pattern: &str) -> String {
|
||||
let mut out = String::with_capacity(pattern.len());
|
||||
let mut chars = pattern.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
match chars.next() {
|
||||
Some('w') => out.push_str("[0-9A-Za-z_]"),
|
||||
Some('W') => out.push_str("[^0-9A-Za-z_]"),
|
||||
Some('d') => out.push_str("[0-9]"),
|
||||
Some('D') => out.push_str("[^0-9]"),
|
||||
Some(next) => {
|
||||
out.push('\\');
|
||||
out.push(next);
|
||||
}
|
||||
None => out.push('\\'),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn nullable(hir: &Hir) -> bool {
|
||||
hir.properties().minimum_len() == Some(0)
|
||||
}
|
||||
|
||||
/// The characters `hir` can start with (everything, for a byte class).
|
||||
fn first(hir: &Hir) -> ClassUnicode {
|
||||
match hir.kind() {
|
||||
HirKind::Empty | HirKind::Look(_) => ClassUnicode::empty(),
|
||||
HirKind::Literal(lit) => match std::str::from_utf8(&lit.0).ok().and_then(|s| s.chars().next()) {
|
||||
Some(c) => ClassUnicode::new([ClassUnicodeRange::new(c, c)]),
|
||||
None => any(),
|
||||
},
|
||||
HirKind::Class(Class::Unicode(class)) => class.clone(),
|
||||
HirKind::Class(Class::Bytes(_)) => any(),
|
||||
HirKind::Capture(c) => first(&c.sub),
|
||||
HirKind::Repetition(r) => first(&r.sub),
|
||||
HirKind::Concat(items) => first_of_seq(items, &ClassUnicode::empty()),
|
||||
HirKind::Alternation(items) => items.iter().fold(ClassUnicode::empty(), |acc, h| union(&acc, &first(h))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters a sequence can start with, then `follow` if it may match nothing.
|
||||
fn first_of_seq(items: &[Hir], follow: &ClassUnicode) -> ClassUnicode {
|
||||
let mut set = ClassUnicode::empty();
|
||||
for item in items {
|
||||
set = union(&set, &first(item));
|
||||
if !nullable(item) {
|
||||
return set;
|
||||
}
|
||||
}
|
||||
union(&set, follow)
|
||||
}
|
||||
|
||||
fn union(a: &ClassUnicode, b: &ClassUnicode) -> ClassUnicode {
|
||||
let mut out = a.clone();
|
||||
out.union(b);
|
||||
out
|
||||
}
|
||||
|
||||
fn any() -> ClassUnicode {
|
||||
ClassUnicode::new([ClassUnicodeRange::new('\0', char::MAX)])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn rule(pattern: &str) -> ConsoleRule {
|
||||
ConsoleRule {
|
||||
pattern: pattern.into(),
|
||||
ignore_case: false,
|
||||
foreground: Some("red".into()),
|
||||
background: None,
|
||||
styles: Vec::new(),
|
||||
whole_line: false,
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn err(pattern: &str) -> String {
|
||||
validate_pattern(pattern, false).unwrap_err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_typical_log_rules() {
|
||||
for pattern in [
|
||||
r"\[AUDIT\]",
|
||||
r"\[(AUDIT|METRIC|TASK-FAIL)\]",
|
||||
r"JOB-\d+",
|
||||
r"Exception in thread .*",
|
||||
r".*ERROR.*",
|
||||
r"took \d+(\.\d+)?ms",
|
||||
r"\d+\.\d+\.\d+\.\d+",
|
||||
r"\w+@\w+\.com",
|
||||
r"user=\S+\s+id=\d+",
|
||||
r#"^\s*at [^(]*\([^)]*\)$"#,
|
||||
r"^\[service-a\].*",
|
||||
r"SELECT .* FROM",
|
||||
r"\b(GET|POST|PUT|DELETE) /\S*",
|
||||
r"\d+(\.\d+){0,3}",
|
||||
r"\w+(-\w+){0,4}",
|
||||
r"(ERROR|WARN)\b.*$",
|
||||
] {
|
||||
assert!(validate_pattern(pattern, false).is_ok(), "{pattern}: {:?}", validate_pattern(pattern, false));
|
||||
assert!(validate_pattern(pattern, true).is_ok(), "{pattern} (ignore case)");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_patterns_that_backtrack_for_too_long() {
|
||||
// Each takes seconds or more on a 2000-character line in V8.
|
||||
assert!(err(r"(a+)+$").contains("repeated group"));
|
||||
assert!(err(r"^(a|aa)+b$").contains("repeated group"));
|
||||
assert!(err(r"a*a*a*b").contains("too long"));
|
||||
assert!(err(r".*a.*b").contains("too long"));
|
||||
assert!(err(r"\w+\w+!").contains("too long"));
|
||||
assert!(err(r"^(a?){30}a{30}$").contains("too long"));
|
||||
// A group before `$` or `\b` is not the end of the pattern: those can still fail.
|
||||
assert!(err(r"(x(a+)*)$").contains("repeated group"));
|
||||
assert!(err(r"(?:foo|x(a+)*)\b").contains("repeated group"));
|
||||
assert!(err(r"^(x\w*\w*\w*)$").contains("too long"));
|
||||
// JavaScript's `\W` matches `é` and `\D` matches `٣`, Rust's don't.
|
||||
assert!(err(r"\W+é+!").contains("too long"));
|
||||
assert!(err(r"[\D]+[٣]+!").contains("too long"));
|
||||
assert!(validate_pattern(r"\\w+\\w+!", false).is_ok(), "an escaped backslash, then `w`");
|
||||
assert!(validate_pattern(r"[0-9a-f]{32}", false).is_ok());
|
||||
// Anchored, the same shape tries one start instead of every position.
|
||||
assert!(validate_pattern(r"^\w+\w+!", false).is_ok());
|
||||
assert!(err(r"^.*a.*b.*c").contains("too long"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_constructs_javascript_reads_differently() {
|
||||
for pattern in [r"(?i)error", r"(?P<n>a)", r"(?=a)", r"\Aerror", r"error\z", r"\p{L}", r"[[:alpha:]]"] {
|
||||
assert!(err(pattern).contains("not supported"), "{pattern}");
|
||||
}
|
||||
assert!(err("(").contains("invalid pattern"));
|
||||
assert!(err("").contains("empty"));
|
||||
assert!(err(&"a".repeat(513)).contains("too long"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizing_keeps_known_colours_and_styles_and_bounds_the_list() {
|
||||
let mut r = rule("x");
|
||||
r.foreground = Some("bright-cyan".into());
|
||||
r.background = Some("#ff0000".into());
|
||||
r.styles = vec!["bold".into(), "blink".into(), "bold".into(), "dim".into()];
|
||||
let out = normalize(vec![r, ConsoleRule { foreground: Some("teal".into()), ..rule("y") }]).unwrap();
|
||||
assert_eq!(out[0].foreground.as_deref(), Some("bright-cyan"));
|
||||
assert_eq!(out[0].background, None);
|
||||
assert_eq!(out[0].styles, ["bold", "dim"]);
|
||||
assert_eq!(out[1].foreground, None);
|
||||
|
||||
let e = normalize(vec![rule("ok"), rule(".*a.*b")]).unwrap_err();
|
||||
assert!(e.starts_with("console rule 1:"), "{e}");
|
||||
assert!(normalize(vec![rule("x"); MAX_RULES]).is_ok());
|
||||
assert!(normalize(vec![rule("x"); MAX_RULES + 1]).unwrap_err().contains("at most 100"));
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ pub(crate) fn validate_pattern(pattern: &str) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_construct(pattern: &str) -> Option<&'static str> {
|
||||
pub(crate) fn unsupported_construct(pattern: &str) -> Option<&'static str> {
|
||||
if pattern.match_indices("(?").any(|(at, _)| !pattern[at + 2..].starts_with(':')) {
|
||||
return Some("an inline flag, lookaround or named group");
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ mod auth;
|
||||
mod build_graph;
|
||||
pub mod commands;
|
||||
pub mod commit;
|
||||
mod console_rules;
|
||||
mod database;
|
||||
mod dependencies;
|
||||
pub(crate) mod diagnostics;
|
||||
@@ -438,6 +439,11 @@ impl PluginHost {
|
||||
self.shared.decoration_sets()
|
||||
}
|
||||
|
||||
/// Every plugin's console highlight rules, for windows opening after they were set.
|
||||
pub fn console_rules(&self) -> std::collections::BTreeMap<String, Vec<ide_plugin::ConsoleRule>> {
|
||||
self.shared.console_rules()
|
||||
}
|
||||
|
||||
/// Creates the host; call [`load_all`](Self::load_all) to load installed plugins.
|
||||
pub fn new(plugins_dir: PathBuf, sink: Arc<dyn PluginEventSink>, limits: Limits) -> IdeResult<Self> {
|
||||
std::fs::create_dir_all(&plugins_dir)?;
|
||||
|
||||
@@ -144,6 +144,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
|
||||
| PluginEvent::ContentTabReply { .. }
|
||||
| PluginEvent::OpenDiff { .. }
|
||||
| PluginEvent::DecorationsChanged { .. }
|
||||
| PluginEvent::ConsoleRulesChanged { .. }
|
||||
| PluginEvent::EditorOpen { .. }
|
||||
| PluginEvent::EditorRanges { .. }
|
||||
| PluginEvent::Notification { .. }
|
||||
|
||||
@@ -241,6 +241,9 @@ pub enum PluginEvent {
|
||||
/// Complete replacement of one plugin's project-scoped decorations.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
DecorationsChanged { plugin_id: String, sets: Vec<DecorationSet> },
|
||||
/// Complete replacement of one plugin's console highlight rules (empty: none).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
ConsoleRulesChanged { plugin_id: String, rules: Vec<ide_plugin::ConsoleRule> },
|
||||
/// Open a file in the invoking window.
|
||||
EditorOpen { path: ide_core::IpcPath, selection: Option<ide_core::Range> },
|
||||
/// Change selection or scrolling only in this window's already open editor.
|
||||
|
||||
@@ -284,6 +284,18 @@ async fn files_of_a_project_attached_outside_go_by_their_absolute_path_everywher
|
||||
.map(|r| r["repositoryPathRelativeToProject"].as_str().unwrap())
|
||||
.collect();
|
||||
assert!(repos.contains(&shown("").trim_end_matches('/')), "{repos:?}");
|
||||
|
||||
// `paths` names such a project by its absolute path, in every tool.
|
||||
let only = json!([format!("{}/src/**", shown(""))]);
|
||||
let files = h.json("search_file", json!({"q":"*.rs","paths":only})).await;
|
||||
assert_eq!(files["items"], json!([{ "filePath": shown("src/lib.rs") }]));
|
||||
let text = h.json("search_text", json!({"q":"attached_marker","paths":only})).await;
|
||||
assert_eq!(text["items"][0]["filePath"], shown("src/lib.rs"), "{text}");
|
||||
let symbols = h.json("search_symbol", json!({"q":"attached_marker","paths":only})).await;
|
||||
assert_eq!(symbols["items"][0]["filePath"], shown("src/lib.rs"), "{symbols}");
|
||||
let status = h.json("git_status", json!({"paths":only})).await;
|
||||
assert_eq!(status["repositories"].as_array().unwrap().len(), 1, "{status}");
|
||||
assert_eq!(status["repositories"][0]["repositoryPathRelativeToProject"], shown("").trim_end_matches('/'));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -442,7 +454,7 @@ async fn git_status_and_diff_on_a_temporary_repository() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn scope_limits_the_query_tools_to_a_directory() {
|
||||
async fn paths_limit_the_query_tools_to_folders() {
|
||||
let h = Harness::new();
|
||||
std::fs::create_dir_all(h.root.join("lib")).unwrap();
|
||||
std::fs::write(h.root.join("lib/c.txt"), "needle\n").unwrap();
|
||||
@@ -452,17 +464,20 @@ async fn scope_limits_the_query_tools_to_a_directory() {
|
||||
out.dedup();
|
||||
out
|
||||
};
|
||||
assert_eq!(paths(&h.json("search_text", json!({"q":"needle","scope":"lib"})).await), ["lib/c.txt"]);
|
||||
assert_eq!(paths(&h.json("search_regex", json!({"q":"need.e","scope":"lib/"})).await), ["lib/c.txt"]);
|
||||
assert_eq!(paths(&h.json("search_text", json!({"q":"needle","paths":["lib/"]})).await), ["lib/c.txt"]);
|
||||
assert_eq!(paths(&h.json("search_regex", json!({"q":"need.e","paths":["lib/**"]})).await), ["lib/c.txt"]);
|
||||
let absolute = h.root.join("src").to_string_lossy().into_owned();
|
||||
assert_eq!(paths(&h.json("search_file", json!({"q":"*.txt","scope":absolute})).await), ["src/a.txt", "src/b.txt"]);
|
||||
// Within the scope, `paths` narrows further.
|
||||
assert_eq!(
|
||||
paths(&h.json("search_text", json!({"q":"needle","scope":"src","paths":["**/b.txt"]})).await),
|
||||
["src/b.txt"]
|
||||
paths(&h.json("search_file", json!({"q":"*.txt","paths":[absolute]})).await),
|
||||
["src/a.txt", "src/b.txt"]
|
||||
);
|
||||
assert!(h.error("search_text", json!({"q":"needle","scope":"missing"})).await.contains("is not a directory"));
|
||||
assert!(h.error("search_text", json!({"q":"needle","scope":".."})).await.contains("outside the project"));
|
||||
// Several folders at once, and exclusions.
|
||||
assert_eq!(
|
||||
paths(&h.json("search_text", json!({"q":"needle","paths":["src/**","lib/**","!**/a.txt"]})).await),
|
||||
["lib/c.txt", "src/b.txt"]
|
||||
);
|
||||
let outside = h.error("search_text", json!({"q":"needle","paths":["../**"]})).await;
|
||||
assert!(outside.contains("outside of the project directory"), "{outside}");
|
||||
|
||||
let git = |args: &[&str]| {
|
||||
let output = std::process::Command::new("git").current_dir(&h.root).args(args).output().unwrap();
|
||||
@@ -473,7 +488,7 @@ async fn scope_limits_the_query_tools_to_a_directory() {
|
||||
git(&["-c", "user.name=Test", "-c", "[email protected]", "commit", "-m", "Initial"]);
|
||||
std::fs::write(h.root.join("src/a.txt"), "changed\n").unwrap();
|
||||
std::fs::write(h.root.join("lib/c.txt"), "changed\n").unwrap();
|
||||
let status = h.json("git_status", json!({"scope":"lib"})).await;
|
||||
let status = h.json("git_status", json!({"paths":["lib/"]})).await;
|
||||
assert_eq!(status["repositories"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
status["repositories"][0]["entries"],
|
||||
@@ -482,7 +497,63 @@ async fn scope_limits_the_query_tools_to_a_directory() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_scoped_symbol_search_finds_matches_past_the_unscoped_ones() {
|
||||
async fn excluded_and_ignored_folders_are_searched_when_asked_for() {
|
||||
let h = Harness::new();
|
||||
// `ignored/` is ignored by the project's `.gitignore`; `excluded/` is excluded in its settings.
|
||||
std::fs::create_dir_all(h.root.join("excluded")).unwrap();
|
||||
std::fs::write(h.root.join("excluded/e.txt"), "needle\n").unwrap();
|
||||
std::fs::create_dir_all(h.root.join("src/ignored")).unwrap();
|
||||
std::fs::write(h.root.join("src/ignored/x.txt"), "needle\n").unwrap();
|
||||
ide_host::ops::project::set_settings(
|
||||
&h.host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"projectStructure.excluded",
|
||||
"[\"excluded\"]",
|
||||
)
|
||||
.unwrap();
|
||||
let found = |args: Value| {
|
||||
let h = &h;
|
||||
async move {
|
||||
let v = h.json(args["tool"].as_str().unwrap(), args["args"].clone()).await;
|
||||
let mut out: Vec<String> = v["items"]
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|i| i["filePath"].as_str().unwrap().to_owned())
|
||||
.collect();
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
};
|
||||
let text = |args: Value| json!({ "tool": "search_text", "args": args });
|
||||
assert_eq!(found(text(json!({"q":"needle"}))).await, ["src/a.txt", "src/b.txt"]);
|
||||
let every = ["excluded/e.txt", "ignored/a.txt", "src/a.txt", "src/b.txt", "src/ignored/x.txt"];
|
||||
assert_eq!(found(text(json!({"q":"needle","includeExcluded":true}))).await, every);
|
||||
assert_eq!(found(json!({"tool":"search_regex","args":{"q":"need.e","includeExcluded":true}})).await, every);
|
||||
// `paths` only narrows: a folder the project leaves out stays out when named ...
|
||||
let nothing: Vec<String> = Vec::new();
|
||||
assert_eq!(found(text(json!({"q":"needle","paths":["ignored/"]}))).await, nothing);
|
||||
assert_eq!(found(text(json!({"q":"needle","paths":["excluded/"]}))).await, nothing);
|
||||
// ... and is searched, alone, when asked for.
|
||||
assert_eq!(
|
||||
found(text(json!({"q":"needle","paths":["ignored/","excluded/"],"includeExcluded":true}))).await,
|
||||
["excluded/e.txt", "ignored/a.txt"]
|
||||
);
|
||||
let file = |dir: &str| json!({"tool":"search_file","args":{"q":"*.txt","paths":[dir],"includeExcluded":true}});
|
||||
assert_eq!(found(file("excluded/")).await, ["excluded/e.txt"]);
|
||||
assert_eq!(found(file("ignored/")).await, ["ignored/a.txt"]);
|
||||
assert_eq!(found(text(json!({"q":"needle","paths":["src/"]}))).await, ["src/a.txt", "src/b.txt"]);
|
||||
assert_eq!(
|
||||
found(text(json!({"q":"needle","paths":["src/"],"includeExcluded":true}))).await,
|
||||
["src/a.txt", "src/b.txt", "src/ignored/x.txt"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_symbol_search_with_paths_finds_matches_past_the_others() {
|
||||
let h = Harness::new();
|
||||
std::fs::create_dir_all(h.root.join("many")).unwrap();
|
||||
for i in 0..60 {
|
||||
@@ -498,12 +569,12 @@ async fn a_scoped_symbol_search_finds_matches_past_the_unscoped_ones() {
|
||||
assert!(std::time::Instant::now() < deadline, "the files were never indexed");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
let found = h.json("search_symbol", json!({"q":"pool_marker","scope":"zz","limit":1})).await;
|
||||
let found = h.json("search_symbol", json!({"q":"pool_marker","paths":["zz/"],"limit":1})).await;
|
||||
assert_eq!(found["items"][0]["filePath"], "zz/last.rs", "{found}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn scope_reaches_an_attached_worktree_the_repository_ignores() {
|
||||
async fn paths_reach_an_attached_worktree_the_repository_ignores() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let git = |dir: &Path, args: &[&str]| {
|
||||
@@ -545,10 +616,14 @@ async fn scope_reaches_an_attached_worktree_the_repository_ignores() {
|
||||
let everywhere = found(json!({"q":"needle"})).await;
|
||||
assert!(everywhere.contains(&".wt/feature/src/b.txt".to_owned()), "{everywhere:?}");
|
||||
assert_eq!(
|
||||
found(json!({"q":"needle","scope":".wt/feature/src"})).await,
|
||||
found(json!({"q":"needle","paths":[".wt/feature/src/"]})).await,
|
||||
[".wt/feature/src/a.txt", ".wt/feature/src/b.txt"]
|
||||
);
|
||||
assert_eq!(found(json!({"q":"needle","paths":[".wt/feature/src/b.txt"]})).await, [".wt/feature/src/b.txt"]);
|
||||
// With `includeExcluded` the root's walk enters the ignored worktree: its files still come once.
|
||||
let all = h.json("search_text", json!({"q":"needle","includeExcluded":true})).await;
|
||||
let items = all["items"].as_array().unwrap();
|
||||
assert_eq!(items.iter().filter(|i| i["filePath"] == ".wt/feature/src/b.txt").count(), 1, "{all}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1217,8 +1292,8 @@ async fn call_hierarchy_pages_are_sorted_and_scoped() {
|
||||
assert_eq!((&first["more"], &first["nextOffset"]), (&json!(true), &json!(2)));
|
||||
let next = h.json("get_call_hierarchy", at(json!({"limit":2,"offset":2}))).await;
|
||||
assert_eq!(names(&next), ["main"]);
|
||||
let scoped = h.json("get_call_hierarchy", at(json!({"scope":"src"}))).await;
|
||||
let scoped = h.json("get_call_hierarchy", at(json!({"paths":["src/"]}))).await;
|
||||
assert_eq!(names(&scoped), ["main"]);
|
||||
assert_eq!(scoped["total"], 1);
|
||||
assert_eq!(scoped["root"]["name"], "price", "the root is shown whatever the scope");
|
||||
assert_eq!(scoped["root"]["name"], "price", "the root is shown whatever the paths");
|
||||
}
|
||||
@@ -121,6 +121,7 @@ impl PluginWorkspace for TestWorkspace {
|
||||
scope: ide_search::SearchScope::Project,
|
||||
max_matches: limit,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
};
|
||||
let files = Mutex::new(Vec::new());
|
||||
let summary = ide_search::search(root, &query, &|_| None, cancel, &|file| files.lock().push(file))
|
||||
@@ -4860,6 +4861,49 @@ fn plugins_set_their_own_context_keys() {
|
||||
assert!(f.host.context_keys(Some("main")).is_empty(), "cleared when the plugin stops");
|
||||
}
|
||||
|
||||
/// `ui.set-console-rules` (API 1.12) replaces the plugin's rules for every window without a
|
||||
/// capability; unknown colours are dropped, an invalid rule keeps the previous list.
|
||||
#[test]
|
||||
fn plugins_replace_their_console_rules_and_lose_them_when_they_stop() {
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("jobs"));
|
||||
f.take_events();
|
||||
f.run("jobs", "console-rules", None).unwrap();
|
||||
let changed: Vec<_> = f
|
||||
.take_events()
|
||||
.into_iter()
|
||||
.filter_map(|(client, e)| match e {
|
||||
PluginEvent::ConsoleRulesChanged { plugin_id, rules } => Some((client, plugin_id, rules)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(changed.len(), 1);
|
||||
let (client, plugin_id, rules) = &changed[0];
|
||||
assert_eq!((client.as_deref(), plugin_id.as_str()), (None, "jobs"));
|
||||
assert_eq!(rules.iter().map(|r| r.pattern.as_str()).collect::<Vec<_>>(), [r"\[AUDIT\]", r"job-\d+"]);
|
||||
assert!(
|
||||
rules[0].whole_line && rules[0].styles == ["bold"] && rules[0].foreground.as_deref() == Some("bright-yellow")
|
||||
);
|
||||
assert!(rules[1].ignore_case && rules[1].foreground.as_deref() == Some("cyan") && rules[1].background.is_none());
|
||||
assert_eq!(f.host.console_rules()["jobs"], *rules);
|
||||
|
||||
let err = f.run("jobs", "console-rules", Some("(a+)+b")).unwrap_err();
|
||||
assert!(err.contains("invalid") && err.contains("repeated group"), "{err}");
|
||||
assert!(f.run("jobs", "console-rules", Some(".*a.*b")).unwrap_err().contains("too long"));
|
||||
assert_eq!(f.host.console_rules()["jobs"].len(), 2, "an invalid list keeps the previous one");
|
||||
|
||||
f.run("jobs", "console-rules", Some("")).unwrap();
|
||||
assert!(f.host.console_rules().is_empty());
|
||||
|
||||
f.run("jobs", "console-rules", None).unwrap();
|
||||
f.take_events();
|
||||
f.host.set_enabled("jobs", false).unwrap();
|
||||
assert!(f.host.console_rules().is_empty(), "cleared when the plugin stops");
|
||||
assert!(f.take_events().iter().any(
|
||||
|(_, e)| matches!(e, PluginEvent::ConsoleRulesChanged { plugin_id, rules } if plugin_id == "jobs" && rules.is_empty())
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_keys_are_capped_and_windows_overlay_global_ones() {
|
||||
let f = fixture(Limits::default());
|
||||
|
||||
@@ -47,6 +47,7 @@ async fn find(host: &Host, paths: Vec<PathBuf>, pattern: &str) -> Vec<ide_search
|
||||
scope: SearchScope::Files { paths: paths.into_iter().map(Into::into).collect() },
|
||||
max_matches: 0,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
},
|
||||
ide_host::ops::Channel::new(move |event| {
|
||||
if let search::SearchEvent::File { file } = event {
|
||||
@@ -165,6 +166,7 @@ async fn properties_search_git_and_document_coordinates_agree() {
|
||||
scope: SearchScope::Files { paths: vec![closed_path.clone().into()] },
|
||||
max_matches: 0,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
};
|
||||
search::replace_in_files(
|
||||
&host,
|
||||
|
||||
+128
-139
@@ -2,15 +2,12 @@
|
||||
//! `ignore` crate) plus the user's `files.exclude` globs, below the project root
|
||||
//! and the extra content roots (Project Structure).
|
||||
//!
|
||||
//! Like IDEA, ignored directories are left out entirely, while ignored files in
|
||||
//! the remaining directories (`.env`) are listed by name only, so Go to File finds
|
||||
//! them but their symbols stay out of the index.
|
||||
//! Git-ignored files and folders are listed by name only: Go to File finds them
|
||||
//! without reading their contents or indexing their symbols. Excluded folders
|
||||
//! (including project-model outputs and dependencies) are not walked at all.
|
||||
|
||||
use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
|
||||
use ignore::gitignore::{Gitignore, GitignoreBuilder};
|
||||
use ignore::{WalkBuilder, WalkState};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
@@ -25,9 +22,6 @@ pub(crate) struct PathFilter {
|
||||
/// Content roots outside `root`, indexed as `<folder name>/<path>`.
|
||||
extra: Vec<ExtraRoot>,
|
||||
excludes: GlobSet,
|
||||
/// Root-level ignore files, for paths reported by the watcher (the walker
|
||||
/// applies nested ignore files itself).
|
||||
gitignore: Gitignore,
|
||||
/// What the filter was built from: `(extra roots, exclude globs)`.
|
||||
config: (crate::IndexRoots, Vec<String>),
|
||||
}
|
||||
@@ -36,25 +30,11 @@ struct ExtraRoot {
|
||||
path: PathBuf,
|
||||
/// Shown before the paths inside it (`shared-lib/src/x.rs`).
|
||||
name: String,
|
||||
gitignore: Gitignore,
|
||||
}
|
||||
|
||||
fn root_ignores(root: &Path) -> Gitignore {
|
||||
let mut gi = GitignoreBuilder::new(root);
|
||||
for f in [".gitignore", ".ignore", ".git/info/exclude"] {
|
||||
let path = root.join(f);
|
||||
if path.is_file()
|
||||
&& let Some(e) = gi.add(&path)
|
||||
{
|
||||
tracing::debug!("{}: {e}", path.display());
|
||||
}
|
||||
}
|
||||
gi.build().unwrap_or_else(|_| Gitignore::empty())
|
||||
}
|
||||
|
||||
/// Whether walking `root` leaves out `dir`, a folder below it: `dir` or a folder between
|
||||
/// them is ignored (`.gitignore`, `.ignore`, `info/exclude`, the global excludes). Such a
|
||||
/// folder can be a root of its own, with its own rules, without its files being walked twice.
|
||||
/// Whether an ignore-aware content walk of `root` leaves out `dir` or an ancestor.
|
||||
/// An ignored folder can be an explicit content root with its own ignore rules,
|
||||
/// promoting its files from filename-only entries to indexable content.
|
||||
pub fn walk_skips(root: &Path, dir: &Path) -> bool {
|
||||
if dir == root || !dir.starts_with(root) || !dir.is_dir() {
|
||||
return false;
|
||||
@@ -150,14 +130,13 @@ impl PathFilter {
|
||||
Ok(rel) if extra_roots.include_root => rel_string(rel),
|
||||
_ => path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
};
|
||||
extra.push(ExtraRoot { gitignore: root_ignores(&path), name, path });
|
||||
extra.push(ExtraRoot { name, path });
|
||||
}
|
||||
Self {
|
||||
root: root.to_owned(),
|
||||
include_root: extra_roots.include_root,
|
||||
extra,
|
||||
excludes,
|
||||
gitignore: root_ignores(root),
|
||||
config: (extra_roots.clone(), exclude_globs.to_vec()),
|
||||
}
|
||||
}
|
||||
@@ -170,7 +149,7 @@ impl PathFilter {
|
||||
/// Stable fingerprint of the persisted-scope configuration; a start-up
|
||||
/// snapshot is only trusted when this still matches.
|
||||
pub(crate) fn stamp(&self) -> String {
|
||||
let mut stamp = format!("include_root={}\n", self.config.0.include_root);
|
||||
let mut stamp = format!("ignored_folders=names\ninclude_root={}\n", self.config.0.include_root);
|
||||
for folder in &self.config.0.folders {
|
||||
stamp.push_str(&folder.to_string_lossy());
|
||||
stamp.push('\n');
|
||||
@@ -203,13 +182,13 @@ impl PathFilter {
|
||||
.chain(self.extra.iter().map(|e| e.path.as_path()))
|
||||
}
|
||||
|
||||
/// The root containing `path`, its display prefix (`None` for the project root) and ignore rules.
|
||||
fn base_of(&self, path: &Path) -> Option<(&Path, Option<&str>, &Gitignore)> {
|
||||
/// The root containing `path` and its display prefix (`None` for the project root).
|
||||
fn base_of(&self, path: &Path) -> Option<(&Path, Option<&str>)> {
|
||||
// An extra root inside the project root wins: its own rules apply below it.
|
||||
if let Some(e) = self.extra.iter().find(|e| path.starts_with(&e.path)) {
|
||||
return Some((e.path.as_path(), Some(e.name.as_str()), &e.gitignore));
|
||||
return Some((e.path.as_path(), Some(e.name.as_str())));
|
||||
}
|
||||
(self.include_root && path.starts_with(&self.root)).then_some((self.root.as_path(), None, &self.gitignore))
|
||||
(self.include_root && path.starts_with(&self.root)).then_some((self.root.as_path(), None))
|
||||
}
|
||||
|
||||
/// Whether `path` is (at or) below one of the roots.
|
||||
@@ -220,7 +199,7 @@ impl PathFilter {
|
||||
/// `/`-separated path relative to its root, as displayed; paths in extra
|
||||
/// content roots start with the root's folder name.
|
||||
pub(crate) fn rel(&self, path: &Path) -> Option<String> {
|
||||
let (base, prefix, _) = self.base_of(path)?;
|
||||
let (base, prefix) = self.base_of(path)?;
|
||||
let rel = rel_string(path.strip_prefix(base).ok()?);
|
||||
if rel.is_empty() {
|
||||
return None;
|
||||
@@ -258,11 +237,10 @@ impl PathFilter {
|
||||
ALWAYS_SKIP.contains(&name)
|
||||
}
|
||||
|
||||
/// Whether a path reported by the watcher should be left out (outside the
|
||||
/// root, excluded, or an ignored directory or inside one). Ignored files
|
||||
/// elsewhere stay in, listed by name only.
|
||||
pub(crate) fn is_excluded(&self, path: &Path, is_dir: bool) -> bool {
|
||||
let Some((base, _, gitignore)) = self.base_of(path) else { return true };
|
||||
/// Whether a path is outside the roots, VCS metadata, or explicitly excluded.
|
||||
/// Git-ignore rules classify files as filename-only, not excluded.
|
||||
pub(crate) fn is_excluded(&self, path: &Path) -> bool {
|
||||
let Some((base, _)) = self.base_of(path) else { return true };
|
||||
let rel = path.strip_prefix(base).map(rel_string).unwrap_or_default();
|
||||
if rel.is_empty() {
|
||||
return true;
|
||||
@@ -280,32 +258,32 @@ impl PathFilter {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let dir = if is_dir { Some(path) } else { path.parent().filter(|p| *p != base) };
|
||||
dir.is_some_and(|d| gitignore.matched_path_or_any_parents(d, true).is_ignore())
|
||||
false
|
||||
}
|
||||
|
||||
/// A filename walk: only explicit exclusions prune directories. Extra roots
|
||||
/// inside another root are walked separately, with their own ignore rules.
|
||||
fn walker(&self, dir: &Path) -> Option<WalkBuilder> {
|
||||
let (root, _) = self.base_of(dir)?;
|
||||
if dir != root && self.is_excluded(dir) {
|
||||
return None;
|
||||
}
|
||||
let root = root.to_path_buf();
|
||||
let excludes = self.excludes.clone();
|
||||
let extra: Vec<PathBuf> = self.extra.iter().filter(|e| e.path != dir).map(|e| e.path.clone()).collect();
|
||||
let mut builder = WalkBuilder::new(dir);
|
||||
builder.standard_filters(false).follow_links(false).filter_entry(move |e| {
|
||||
!Self::skip_name(&e.file_name().to_string_lossy())
|
||||
&& !glob_excluded(&excludes, &root, e.path())
|
||||
&& !extra.iter().any(|r| e.path() == r)
|
||||
});
|
||||
Some(builder)
|
||||
}
|
||||
|
||||
/// All directories at or below `dir` that the index would walk, in walk order.
|
||||
pub(crate) fn dirs(&self, dir: &Path) -> Vec<PathBuf> {
|
||||
let Some((root, _, _)) = self.base_of(dir) else { return Vec::new() };
|
||||
let root = root.to_path_buf();
|
||||
let excludes = self.excludes.clone();
|
||||
let walk_root = root.clone();
|
||||
let walk_excludes = excludes.clone();
|
||||
let walker = WalkBuilder::new(dir)
|
||||
.hidden(false)
|
||||
.parents(true)
|
||||
.ignore(true)
|
||||
.git_ignore(true)
|
||||
.git_global(true)
|
||||
.git_exclude(true)
|
||||
.require_git(ide_core::ignored::inside_git_repo(dir))
|
||||
.follow_links(false)
|
||||
.filter_entry(move |e| {
|
||||
let name = e.file_name().to_string_lossy();
|
||||
!Self::skip_name(&name) && !glob_excluded(&walk_excludes, &walk_root, e.path())
|
||||
})
|
||||
.build();
|
||||
walker.flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect()
|
||||
let Some(builder) = self.walker(dir) else { return Vec::new() };
|
||||
builder.build().flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect()
|
||||
}
|
||||
|
||||
/// All indexable files at or below `dir`, walked in parallel.
|
||||
@@ -320,57 +298,35 @@ impl PathFilter {
|
||||
}
|
||||
|
||||
fn walk_to(&self, dir: &Path, max_depth: Option<usize>, cancel: &AtomicBool) -> Vec<Found> {
|
||||
let (tx, rx) = mpsc::channel::<Vec<Found>>();
|
||||
let Some((root, _, _)) = self.base_of(dir) else { return Vec::new() };
|
||||
let root = root.to_path_buf();
|
||||
let excludes = self.excludes.clone();
|
||||
let (walk_root, walk_excludes) = (root.clone(), excludes.clone());
|
||||
let walker = WalkBuilder::new(dir)
|
||||
let Some(mut builder) = self.walker(dir) else { return Vec::new() };
|
||||
let Some((root, _)) = self.base_of(dir) else { return Vec::new() };
|
||||
// Keep the matcher's root at the content root, even for a watcher scan
|
||||
// starting inside an ignored folder, so ancestor rules still apply.
|
||||
let matcher = WalkBuilder::new(root)
|
||||
.hidden(false)
|
||||
.parents(true)
|
||||
.ignore(true)
|
||||
.git_ignore(true)
|
||||
.git_global(true)
|
||||
.git_exclude(true)
|
||||
.require_git(ide_core::ignored::inside_git_repo(dir))
|
||||
.follow_links(false)
|
||||
.max_depth(max_depth)
|
||||
.filter_entry(move |e| {
|
||||
let name = e.file_name().to_string_lossy();
|
||||
!Self::skip_name(&name) && !glob_excluded(&walk_excludes, &walk_root, e.path())
|
||||
})
|
||||
.build_parallel();
|
||||
walker.run(|| {
|
||||
let (root, excludes) = (&root, &excludes);
|
||||
.require_git(ide_core::ignored::inside_git_repo(root))
|
||||
.build_matchers()
|
||||
.pop()
|
||||
.expect("one content root");
|
||||
let (tx, rx) = mpsc::channel::<Vec<Found>>();
|
||||
builder.max_depth(max_depth).build_parallel().run(|| {
|
||||
let mut matcher = matcher.clone();
|
||||
let mut batch = Batch { tx: tx.clone(), items: Vec::with_capacity(256) };
|
||||
Box::new(move |entry| {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return WalkState::Quit;
|
||||
}
|
||||
let Ok(entry) = entry else { return WalkState::Continue };
|
||||
let Some(file_type) = entry.file_type() else { return WalkState::Continue };
|
||||
if file_type.is_dir() && max_depth.is_none_or(|max| entry.depth() < max) {
|
||||
// The walker drops ignored files unseen: list every file of a
|
||||
// walked directory; those the walker doesn't report are ignored.
|
||||
let Ok(children) = std::fs::read_dir(entry.path()) else { return WalkState::Continue };
|
||||
for child in children.flatten() {
|
||||
let path = child.path();
|
||||
if child.file_type().is_ok_and(|t| t.is_file())
|
||||
&& !Self::skip_name(&child.file_name().to_string_lossy())
|
||||
&& !glob_excluded(excludes, root, &path)
|
||||
&& let Ok(meta) = child.metadata()
|
||||
{
|
||||
batch.items.push(Found { path, mtime: mtime_of(&meta), size: meta.len(), ignored: true });
|
||||
}
|
||||
}
|
||||
} else if file_type.is_file()
|
||||
if entry.file_type().is_some_and(|t| t.is_file())
|
||||
&& let Ok(meta) = entry.metadata()
|
||||
&& let Ok(rel) = entry.path().strip_prefix(root)
|
||||
{
|
||||
let ignored = matcher.matched(rel, false).is_ignore();
|
||||
batch.items.push(Found {
|
||||
path: entry.into_path(),
|
||||
mtime: mtime_of(&meta),
|
||||
size: meta.len(),
|
||||
ignored: false,
|
||||
ignored,
|
||||
});
|
||||
}
|
||||
if batch.items.len() >= 256 && batch.tx.send(std::mem::take(&mut batch.items)).is_err() {
|
||||
@@ -380,17 +336,7 @@ impl PathFilter {
|
||||
})
|
||||
});
|
||||
drop(tx);
|
||||
// Each file comes once from its directory listing and, unless ignored, once from the walker.
|
||||
let mut by_path: HashMap<PathBuf, Found> = HashMap::new();
|
||||
for f in rx.into_iter().flatten() {
|
||||
match by_path.entry(f.path.clone()) {
|
||||
Entry::Occupied(mut e) => e.get_mut().ignored &= f.ignored,
|
||||
Entry::Vacant(e) => {
|
||||
e.insert(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
by_path.into_values().collect()
|
||||
rx.into_iter().flatten().collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,23 +381,26 @@ mod tests {
|
||||
touch(&root, f);
|
||||
}
|
||||
std::fs::write(root.join(".gitignore"), "build/\n").unwrap();
|
||||
let filter =
|
||||
PathFilter::new(&root, &vec![].into(), &["**/node_modules".into(), "target".into(), "docs/**".into()]);
|
||||
let filter = PathFilter::new(
|
||||
&root,
|
||||
&vec![].into(),
|
||||
&["**/node_modules".into(), "target".into(), "/build".into(), "docs/**".into()],
|
||||
);
|
||||
let mut found: Vec<String> =
|
||||
filter.walk(&root, &AtomicBool::new(false)).iter().filter_map(|f| filter.rel(&f.path)).collect();
|
||||
found.sort();
|
||||
assert_eq!(found, vec![".github/workflows/ci.yml", ".gitignore", "src/a.rs", "src/deep/b.rs"]);
|
||||
|
||||
assert!(filter.is_excluded(&root.join("node_modules/y.js"), false));
|
||||
assert!(filter.is_excluded(&root.join("a/target/z.rs"), false));
|
||||
assert!(filter.is_excluded(&root.join("build/new.rs"), false));
|
||||
assert!(filter.is_excluded(&root.join(".git/HEAD"), false));
|
||||
assert!(filter.is_excluded(Path::new("/elsewhere/x.rs"), false));
|
||||
assert!(!filter.is_excluded(&root.join("src/new.rs"), false));
|
||||
assert!(filter.is_excluded(&root.join("node_modules/y.js")));
|
||||
assert!(filter.is_excluded(&root.join("a/target/z.rs")));
|
||||
assert!(filter.is_excluded(&root.join("build/new.rs")));
|
||||
assert!(filter.is_excluded(&root.join(".git/HEAD")));
|
||||
assert!(filter.is_excluded(Path::new("/elsewhere/x.rs")));
|
||||
assert!(!filter.is_excluded(&root.join("src/new.rs")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_files_are_listed_but_ignored_directories_are_not() {
|
||||
fn ignored_files_and_directories_are_listed_by_name_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
for f in [
|
||||
@@ -497,11 +446,15 @@ src/local/
|
||||
let expected = [
|
||||
(".env", true),
|
||||
(".gitignore", false),
|
||||
("build/nested/deep.rs", true),
|
||||
("build/out.rs", true),
|
||||
("logs/app.log", true),
|
||||
("pkg/.gitignore", false),
|
||||
("pkg/gen.rs", true),
|
||||
("pkg/keep.rs", false),
|
||||
("src/a.rs", false),
|
||||
("src/debug.log", true),
|
||||
("src/local/secrets.json", true),
|
||||
];
|
||||
assert_eq!(found, expected.map(|(p, i)| (p.to_owned(), i)));
|
||||
|
||||
@@ -514,18 +467,15 @@ src/local/
|
||||
let top: Vec<String> = filter.list_dir(&root).iter().filter_map(|f| filter.rel(&f.path)).collect();
|
||||
assert!(top.iter().all(|p| !p.contains('/')), "{top:?}");
|
||||
|
||||
for (rel, excluded) in [
|
||||
(".env", false),
|
||||
("src/new.log", false),
|
||||
("src/new.rs", false),
|
||||
("build/x.rs", true),
|
||||
("logs/app.log", true),
|
||||
("src/local/x.json", true),
|
||||
] {
|
||||
assert_eq!(filter.is_excluded(&root.join(rel), false), excluded, "{rel}");
|
||||
for rel in
|
||||
[".env", "src/new.log", "src/new.rs", "build/x.rs", "logs/app.log", "src/local/x.json", "build", "src"]
|
||||
{
|
||||
assert!(!filter.is_excluded(&root.join(rel)), "{rel}");
|
||||
}
|
||||
assert!(filter.is_excluded(&root.join("build"), true));
|
||||
assert!(!filter.is_excluded(&root.join("src"), true));
|
||||
let listed = filter.list_dir(&root.join("src/local"));
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].path, root.join("src/local/secrets.json"));
|
||||
assert!(listed[0].ignored);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -544,7 +494,7 @@ src/local/
|
||||
let mut found: Vec<String> =
|
||||
filter.walk(&root, &AtomicBool::new(false)).iter().filter_map(|f| filter.rel(&f.path)).collect();
|
||||
found.sort();
|
||||
assert_eq!(found, [".gitignore", "src/a.rs"]);
|
||||
assert_eq!(found, [".gitignore", "out/x.rs", "src/a.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -564,12 +514,12 @@ src/local/
|
||||
.filter_map(|f| filter.rel(&f.path))
|
||||
.collect();
|
||||
found.sort();
|
||||
assert_eq!(found, ["shared-lib/.gitignore", "shared-lib/src/b.rs", "src/a.rs"]);
|
||||
assert_eq!(found, ["shared-lib/.gitignore", "shared-lib/out/x.rs", "shared-lib/src/b.rs", "src/a.rs"]);
|
||||
assert_eq!(filter.store_key(&shared.join("src/b.rs")), None, "extra roots are not persisted");
|
||||
assert_eq!(filter.store_key(&root.join("src/a.rs")).as_deref(), Some("src/a.rs"));
|
||||
assert!(!filter.is_excluded(&shared.join("src/new.rs"), false));
|
||||
assert!(filter.is_excluded(&shared.join("target/y.rs"), false));
|
||||
assert!(filter.is_excluded(&shared.join("out/y.rs"), false));
|
||||
assert!(!filter.is_excluded(&shared.join("src/new.rs")));
|
||||
assert!(filter.is_excluded(&shared.join("target/y.rs")));
|
||||
assert!(!filter.is_excluded(&shared.join("out/y.rs")));
|
||||
assert!(filter.same_config(&vec![shared.clone(), root.join("src")].into(), &["target".into()]));
|
||||
assert!(!filter.same_config(&vec![shared].into(), &["target".into()]));
|
||||
}
|
||||
@@ -598,10 +548,49 @@ src/local/
|
||||
.filter_map(|f| filter.rel(&f.path))
|
||||
.collect();
|
||||
found.sort();
|
||||
assert_eq!(found, [".wt/feature/.gitignore", ".wt/feature/src/b.rs", "lib/d.rs", "src/a.rs"]);
|
||||
assert_eq!(
|
||||
found,
|
||||
[".wt/feature/.gitignore", ".wt/feature/out/c.rs", ".wt/feature/src/b.rs", "lib/d.rs", "src/a.rs"]
|
||||
);
|
||||
assert_eq!(filter.store_key(&nested.join("src/b.rs")), None, "extra roots are not persisted");
|
||||
assert!(!filter.is_excluded(&nested.join("src/new.rs"), false));
|
||||
assert!(filter.is_excluded(&nested.join("out/new.rs"), false));
|
||||
assert!(filter.is_excluded(&root.join(".wt/other/x.rs"), false));
|
||||
assert!(!filter.is_excluded(&nested.join("src/new.rs")));
|
||||
assert!(!filter.is_excluded(&nested.join("out/new.rs")));
|
||||
assert!(!filter.is_excluded(&root.join(".wt/other/x.rs")));
|
||||
let own_files = filter.walk(&nested, &AtomicBool::new(false));
|
||||
assert!(!own_files.iter().find(|f| f.path == nested.join("src/b.rs")).unwrap().ignored);
|
||||
assert!(own_files.iter().find(|f| f.path == nested.join("out/c.rs")).unwrap().ignored);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_exclusions_prune_filename_walks_and_watcher_subtrees() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
// The caller supplies files.exclude and the project model's anchored
|
||||
// output/dependency/environment roots; ignored business folders stay in.
|
||||
let excluded = ["node_modules", "jvm/build", "rust/target", ".venv", "python/__pycache__", "private"];
|
||||
for folder in excluded {
|
||||
touch(&root, &format!("{folder}/nested/hidden.ts"));
|
||||
}
|
||||
touch(&root, "notes/nested/todo.ts");
|
||||
touch(&root, "internal/build/source.ts");
|
||||
std::fs::write(root.join(".gitignore"), "notes/\ninternal/\n").unwrap();
|
||||
let globs: Vec<String> = excluded.iter().map(|p| format!("/{p}")).collect();
|
||||
let filter = PathFilter::new(&root, &vec![].into(), &globs);
|
||||
let mut found = filter.walk(&root, &AtomicBool::new(false));
|
||||
found.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
assert_eq!(
|
||||
found.iter().map(|f| filter.rel(&f.path).unwrap()).collect::<Vec<_>>(),
|
||||
[".gitignore", "internal/build/source.ts", "notes/nested/todo.ts"]
|
||||
);
|
||||
assert!(found[1..].iter().all(|f| f.ignored));
|
||||
let dirs = filter.dirs(&root);
|
||||
assert!(dirs.contains(&root.join("notes/nested")));
|
||||
for folder in excluded {
|
||||
let subtree = root.join(folder).join("nested");
|
||||
assert!(filter.is_excluded(&subtree));
|
||||
assert!(filter.walk(&subtree, &AtomicBool::new(false)).is_empty());
|
||||
assert!(filter.list_dir(&subtree).is_empty());
|
||||
assert!(!dirs.iter().any(|d| d.starts_with(root.join(folder))));
|
||||
}
|
||||
}
|
||||
}
|
||||
+139
-16
@@ -57,6 +57,15 @@ fn files(idx: &ProjectIndex, q: &str) -> Vec<String> {
|
||||
idx.find_files(q, 20).into_iter().map(|m| m.rel_path).collect()
|
||||
}
|
||||
|
||||
fn assert_filename_only(idx: &ProjectIndex, path: &str) {
|
||||
assert!(files(idx, path).iter().any(|found| found == path), "{path} must be findable");
|
||||
let data = idx.shared.data.read();
|
||||
let entry = data.files.iter().flatten().find(|entry| entry.rel.as_ref() == path).unwrap();
|
||||
assert!(entry.ignored, "{path} must remain classified as ignored");
|
||||
assert_eq!(entry.hash, [0; 32], "{path} must not be content-hashed");
|
||||
assert_eq!(entry.sym_len, 0, "{path} must not have symbols");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_file_names_keep_all_source_candidates() {
|
||||
let f = Fixture::new(&[
|
||||
@@ -368,7 +377,7 @@ fn go_to_file_finds_ignored_files_but_not_their_symbols() {
|
||||
let idx = fx.open();
|
||||
assert_eq!(files(&idx, ".env"), vec![".env"], "the reported case: a git-ignored root file");
|
||||
assert_eq!(files(&idx, "config.local"), vec!["src/config.local.ts"]);
|
||||
assert!(files(&idx, "bundle").is_empty(), "ignored directories stay out");
|
||||
assert_eq!(files(&idx, "bundle"), ["dist/bundle.js"]);
|
||||
assert!(symbols(&idx, "localOnly", SymbolFilter::All).is_empty(), "ignored files are listed by name only");
|
||||
assert_eq!(symbols(&idx, "app", SymbolFilter::All), vec!["app"]);
|
||||
|
||||
@@ -379,7 +388,8 @@ fn go_to_file_finds_ignored_files_but_not_their_symbols() {
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(files(&idx, "fresh.local"), vec!["src/fresh.local.ts"]);
|
||||
assert!(symbols(&idx, "freshLocal", SymbolFilter::All).is_empty());
|
||||
assert!(files(&idx, "more.js").is_empty());
|
||||
assert_eq!(files(&idx, "more.js"), ["dist/more.js"]);
|
||||
assert!(symbols(&idx, "more", SymbolFilter::All).is_empty());
|
||||
|
||||
// Nested ignore files apply to watcher updates as they do to the scan.
|
||||
fx.write("pkg/.gitignore", "gen.ts\n");
|
||||
@@ -406,6 +416,93 @@ fn go_to_file_finds_ignored_files_but_not_their_symbols() {
|
||||
assert_eq!(files(&idx, "bundle"), vec!["dist/bundle.js"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_to_file_finds_files_in_ignored_folders() {
|
||||
let fx = Fixture::new(&[
|
||||
(".git/info/exclude", "/notes/\n"),
|
||||
(".gitignore", "/local/\n"),
|
||||
(".ignore", "/scratch/\n"),
|
||||
("pkg/.gitignore", "private/\n"),
|
||||
("notes/todo.ts", "export class IgnoredNote {}\n"),
|
||||
("notes/deep/other.ts", "export class IgnoredOther {}\n"),
|
||||
("local/config.ts", "export class IgnoredConfig {}\n"),
|
||||
("scratch/draft.ts", "export class IgnoredDraft {}\n"),
|
||||
("pkg/private/data.ts", "export class IgnoredData {}\n"),
|
||||
("pkg/public.ts", "export class PublicThing {}\n"),
|
||||
("node_modules/dep.ts", "export class Dependency {}\n"),
|
||||
("target/gen.ts", "export class Generated {}\n"),
|
||||
]);
|
||||
std::fs::create_dir(fx.root.join("notes/empty")).unwrap();
|
||||
let idx = fx.open();
|
||||
for path in ["notes/todo.ts", "notes/deep/other.ts", "local/config.ts", "scratch/draft.ts", "pkg/private/data.ts"] {
|
||||
assert_filename_only(&idx, path);
|
||||
}
|
||||
assert!(symbols(&idx, "Ignored", SymbolFilter::All).is_empty());
|
||||
assert_eq!(symbols(&idx, "PublicThing", SymbolFilter::Types), ["PublicThing"]);
|
||||
assert!(files(&idx, "node_modules/dep.ts").is_empty());
|
||||
assert!(files(&idx, "target/gen.ts").is_empty());
|
||||
|
||||
let fresh = fx.write("pkg/private/new.ts", "export class IgnoredFresh {}\n");
|
||||
fx.write("notes/new/deep.ts", "export class IgnoredDeep {}\n");
|
||||
let dependency = fx.write("node_modules/new.ts", "export class DependencyFresh {}\n");
|
||||
idx.update(&[fresh.clone(), fx.root.join("notes/new"), dependency], &[]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_filename_only(&idx, "pkg/private/new.ts");
|
||||
assert_filename_only(&idx, "notes/new/deep.ts");
|
||||
assert!(files(&idx, "node_modules/new.ts").is_empty());
|
||||
assert!(symbols(&idx, "Ignored", SymbolFilter::All).is_empty());
|
||||
|
||||
std::fs::remove_file(&fresh).unwrap();
|
||||
std::fs::remove_dir_all(fx.root.join("notes/deep")).unwrap();
|
||||
idx.update(&[], &[fresh, fx.root.join("notes/deep")]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(files(&idx, "pkg/private/new.ts").is_empty());
|
||||
assert!(files(&idx, "notes/deep/other.ts").is_empty());
|
||||
drop(idx);
|
||||
|
||||
// New files in populated and previously empty ignored directories invalidate the manifest.
|
||||
let idx = fx.open();
|
||||
assert_eq!(files(&idx, "notes/todo.ts"), ["notes/todo.ts"]);
|
||||
drop(idx);
|
||||
fx.write("notes/offline.ts", "export class IgnoredOffline {}\n");
|
||||
fx.write("notes/empty/offline.ts", "export class IgnoredEmptyOffline {}\n");
|
||||
let idx = fx.open();
|
||||
assert_filename_only(&idx, "notes/offline.ts");
|
||||
assert_filename_only(&idx, "notes/empty/offline.ts");
|
||||
assert!(symbols(&idx, "Ignored", SymbolFilter::All).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_content_roots_keep_their_own_ignored_files_filename_only() {
|
||||
let fx = Fixture::new(&[("src/app.ts", "export class App {}\n")]);
|
||||
let shared = fx._dir.path().join("shared");
|
||||
std::fs::create_dir_all(shared.join("private")).unwrap();
|
||||
std::fs::create_dir_all(shared.join("node_modules")).unwrap();
|
||||
std::fs::write(shared.join(".ignore"), "private/\n").unwrap();
|
||||
std::fs::write(shared.join("private/local.ts"), "export class SharedIgnored {}\n").unwrap();
|
||||
std::fs::write(shared.join("public.ts"), "export class SharedPublic {}\n").unwrap();
|
||||
std::fs::write(shared.join("node_modules/dep.ts"), "export class SharedDependency {}\n").unwrap();
|
||||
let idx = fx.open();
|
||||
idx.set_scope(vec![shared.clone()], vec!["**/node_modules".into(), "**/target".into()]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_filename_only(&idx, "shared/private/local.ts");
|
||||
assert_eq!(symbols(&idx, "SharedPublic", SymbolFilter::Types), ["SharedPublic"]);
|
||||
assert!(symbols(&idx, "SharedIgnored", SymbolFilter::All).is_empty());
|
||||
assert!(files(&idx, "shared/node_modules/dep.ts").is_empty());
|
||||
|
||||
std::fs::create_dir(shared.join("private/new")).unwrap();
|
||||
std::fs::write(shared.join("private/new/fresh.ts"), "export class SharedFresh {}\n").unwrap();
|
||||
idx.update(&[shared.join("private/new")], &[]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_filename_only(&idx, "shared/private/new/fresh.ts");
|
||||
assert!(symbols(&idx, "SharedFresh", SymbolFilter::All).is_empty());
|
||||
std::fs::remove_dir_all(shared.join("private/new")).unwrap();
|
||||
idx.update(&[], &[shared.join("private/new")]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(files(&idx, "shared/private/new/fresh.ts").is_empty());
|
||||
assert_filename_only(&idx, "shared/private/local.ts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_window_on_same_project_works_in_memory() {
|
||||
let fx = sample();
|
||||
@@ -854,13 +951,19 @@ fn warm_start_detects_changed_ignore_rules() {
|
||||
let f = Fixture::new(&[("sub/generated/a.rs", "fn a() {}\n"), (".git/HEAD", "ref: refs/heads/main\n")]);
|
||||
f.write("sub/.gitignore", "");
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 2, "generated/a.rs plus .gitignore itself");
|
||||
assert_eq!(symbols(&idx, "a", SymbolFilter::All), ["a"]);
|
||||
drop(idx);
|
||||
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
f.write("sub/.gitignore", "generated/\n");
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 1, "an updated ignore rule invalidates the warm snapshot");
|
||||
assert_filename_only(&idx, "sub/generated/a.rs");
|
||||
assert!(symbols(&idx, "a", SymbolFilter::All).is_empty(), "changed rules invalidate cached symbols");
|
||||
drop(idx);
|
||||
|
||||
f.write("sub/.gitignore", "");
|
||||
let idx = f.open();
|
||||
assert_eq!(symbols(&idx, "a", SymbolFilter::All), ["a"], "unchanged contents are parsed after unignoring");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -871,20 +974,24 @@ fn warm_start_detects_changed_ignore_rules_above_the_project() {
|
||||
std::fs::create_dir_all(repo.join(".git/info")).unwrap();
|
||||
std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 2);
|
||||
assert_eq!(symbols(&idx, "a", SymbolFilter::All), ["a"]);
|
||||
assert_eq!(symbols(&idx, "b", SymbolFilter::All), ["b"]);
|
||||
drop(idx);
|
||||
|
||||
std::fs::write(repo.join(".gitignore"), "proj/generated/\n").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 1, "a new ignore file above the project invalidates the warm snapshot");
|
||||
assert_filename_only(&idx, "generated/a.rs");
|
||||
assert!(symbols(&idx, "a", SymbolFilter::All).is_empty(), "new ancestor rules invalidate cached symbols");
|
||||
assert_eq!(symbols(&idx, "b", SymbolFilter::All), ["b"]);
|
||||
drop(idx);
|
||||
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
std::fs::write(repo.join(".gitignore"), "").unwrap();
|
||||
std::fs::write(repo.join(".git/info/exclude"), "proj/src/\n").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 1, "so do the enclosing repository's changed rules");
|
||||
assert!(!symbols(&idx, "a", SymbolFilter::All).is_empty());
|
||||
assert_filename_only(&idx, "src/b.rs");
|
||||
assert!(symbols(&idx, "b", SymbolFilter::All).is_empty());
|
||||
assert_eq!(symbols(&idx, "a", SymbolFilter::All), ["a"], "unignored contents are re-parsed unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -901,12 +1008,20 @@ fn warm_start_detects_a_changed_exclude_file_of_a_linked_worktree() {
|
||||
std::fs::write(worktree.join("commondir"), "../..\n").unwrap();
|
||||
std::fs::write(f.root.join(".git"), format!("gitdir: {}\n", worktree.display())).unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 2);
|
||||
assert_eq!(symbols(&idx, "a", SymbolFilter::All), ["a"]);
|
||||
assert_eq!(symbols(&idx, "b", SymbolFilter::All), ["b"]);
|
||||
drop(idx);
|
||||
|
||||
std::fs::write(main.join("info/exclude"), "generated/\n").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 1, "the shared exclude file invalidates the warm snapshot");
|
||||
assert_filename_only(&idx, "generated/a.rs");
|
||||
assert!(symbols(&idx, "a", SymbolFilter::All).is_empty(), "shared exclude rules invalidate cached symbols");
|
||||
assert_eq!(symbols(&idx, "b", SymbolFilter::All), ["b"]);
|
||||
drop(idx);
|
||||
|
||||
std::fs::write(main.join("info/exclude"), "").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(symbols(&idx, "a", SymbolFilter::All), ["a"], "unignored contents are re-parsed unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -939,19 +1054,24 @@ fn rule_changes_refresh_only_the_affected_index_subtree() {
|
||||
fx.write(rule, "");
|
||||
let idx = fx.open();
|
||||
assert_eq!(files(&idx, "file.ts"), ["sub/generated/file.ts"]);
|
||||
assert_eq!(symbols(&idx, "generated", SymbolFilter::All), ["generated"]);
|
||||
assert_eq!(symbols(&idx, "localOnly", SymbolFilter::All), ["localOnly"]);
|
||||
fx.write(rule, "generated/\nlocal.ts\n");
|
||||
let dirs = [fx.root.join(subtree)];
|
||||
idx.ignore_rules_changed(&dirs);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(files(&idx, "file.ts").is_empty(), "{rule}: ignored directory remained indexed");
|
||||
assert_eq!(files(&idx, "local.ts"), ["sub/local.ts"]);
|
||||
assert_filename_only(&idx, "sub/generated/file.ts");
|
||||
assert!(symbols(&idx, "generated", SymbolFilter::All).is_empty(), "{rule}: ignored symbols remained indexed");
|
||||
assert_filename_only(&idx, "sub/local.ts");
|
||||
assert!(symbols(&idx, "localOnly", SymbolFilter::All).is_empty());
|
||||
assert_eq!(files(&idx, "keep.ts"), ["other/keep.ts"]);
|
||||
assert_eq!(symbols(&idx, "keep", SymbolFilter::All), ["keep"]);
|
||||
|
||||
fx.write(rule, "");
|
||||
idx.ignore_rules_changed(&dirs);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(files(&idx, "file.ts"), ["sub/generated/file.ts"]);
|
||||
assert_eq!(symbols(&idx, "generated", SymbolFilter::All), ["generated"]);
|
||||
assert_eq!(symbols(&idx, "localOnly", SymbolFilter::All), ["localOnly"]);
|
||||
// The cached root matcher must also follow the rules for later watcher updates.
|
||||
let fresh = fx.write("sub/generated/new.ts", "export function fresh() {}\n");
|
||||
@@ -966,7 +1086,7 @@ fn repository_rule_changes_refresh_members_of_an_unindexed_container() {
|
||||
let fx = Fixture::new(&[
|
||||
(".git/HEAD", "ref: refs/heads/main\n"),
|
||||
(".git/info/exclude", ""),
|
||||
("member/generated/item.txt", "x"),
|
||||
("member/generated/item.rs", "fn member_item() {}\n"),
|
||||
]);
|
||||
let idx = ProjectIndex::open(
|
||||
&fx.root,
|
||||
@@ -979,15 +1099,18 @@ fn repository_rule_changes_refresh_members_of_an_unindexed_container() {
|
||||
)
|
||||
.unwrap();
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(files(&idx, "item.txt"), ["member/generated/item.txt"]);
|
||||
assert_eq!(files(&idx, "item.rs"), ["member/generated/item.rs"]);
|
||||
assert_eq!(symbols(&idx, "member_item", SymbolFilter::All), ["member_item"]);
|
||||
fx.write(".git/info/exclude", "generated/\n");
|
||||
idx.ignore_rules_changed(std::slice::from_ref(&fx.root));
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(files(&idx, "item.txt").is_empty());
|
||||
assert_filename_only(&idx, "member/generated/item.rs");
|
||||
assert!(symbols(&idx, "member_item", SymbolFilter::All).is_empty());
|
||||
fx.write(".git/info/exclude", "");
|
||||
idx.ignore_rules_changed(std::slice::from_ref(&fx.root));
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(files(&idx, "item.txt"), ["member/generated/item.txt"]);
|
||||
assert_eq!(files(&idx, "item.rs"), ["member/generated/item.rs"]);
|
||||
assert_eq!(symbols(&idx, "member_item", SymbolFilter::All), ["member_item"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -926,7 +926,7 @@ impl Shared {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { continue };
|
||||
if filter.is_excluded(&path, meta.is_dir()) {
|
||||
if filter.is_excluded(&path) {
|
||||
continue;
|
||||
}
|
||||
if meta.is_dir() {
|
||||
|
||||
@@ -56,7 +56,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.11";
|
||||
pub const API_VERSION: &str = "1.12";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
|
||||
@@ -391,6 +391,11 @@ pub trait HostApi: Send + Sync {
|
||||
let _ = (client, id, item);
|
||||
Err(HostError::Invalid("window status unavailable".into()))
|
||||
}
|
||||
/// Replaces the plugin's console highlight rules (API 1.12); empty removes them.
|
||||
fn console_rules(&self, rules: Vec<crate::ConsoleRule>) -> Result<(), HostError> {
|
||||
let _ = rules;
|
||||
Err(HostError::Failed("console rules unavailable".into()))
|
||||
}
|
||||
/// Sets (`Some`, validated JSON text) or removes the plugin's context key,
|
||||
/// for window `client` (every window if `None`).
|
||||
fn set_context(&self, client: Option<&str>, key: &str, value: Option<String>) -> Result<(), HostError> {
|
||||
|
||||
@@ -72,6 +72,22 @@ pub struct StatusItem {
|
||||
pub command: Option<String>,
|
||||
}
|
||||
|
||||
/// A plugin's highlight rule for Run and Debug console output (API 1.12, `ui.set-console-rules`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ConsoleRule {
|
||||
pub pattern: String,
|
||||
pub ignore_case: bool,
|
||||
/// A console palette colour (`red`, `bright-blue`); `None` keeps the text's own.
|
||||
pub foreground: Option<String>,
|
||||
pub background: Option<String>,
|
||||
/// `bold`, `italic`, `underline`, `strikethrough`, `dim`.
|
||||
pub styles: Vec<String>,
|
||||
/// The whole line, or only the matched text.
|
||||
pub whole_line: bool,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// An entry of a plugin's `pick` or `pick-many`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -506,6 +506,21 @@ impl ui::Host for StoreData {
|
||||
.window_status_item(self.invocation.client.as_deref().expect("checked"), &clip(id, 64), None)
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn set_console_rules(&mut self, rules: Vec<ui::ConsoleRule>) -> Fallible<()> {
|
||||
let rules = rules
|
||||
.into_iter()
|
||||
.map(|r| crate::ConsoleRule {
|
||||
pattern: r.pattern,
|
||||
ignore_case: r.ignore_case,
|
||||
foreground: r.foreground,
|
||||
background: r.background,
|
||||
styles: r.styles,
|
||||
whole_line: r.whole_line,
|
||||
enabled: r.enabled,
|
||||
})
|
||||
.collect();
|
||||
Ok(self.host.console_rules(rules).map_err(to_wit))
|
||||
}
|
||||
fn set_context(&mut self, key: String, value: ui::ContextValue) -> Fallible<()> {
|
||||
let valid_key =
|
||||
(1..=64).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'));
|
||||
|
||||
@@ -91,16 +91,28 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.11.0");
|
||||
for ok in ["1.0.0", "1.3.0", "1.4.7", "1.5.0", "1.6.0", "1.7.0", "1.8.0", "1.9.0", "1.10.0", "1.11.0", "1.0.0-rc.1"]
|
||||
{
|
||||
let host = v("1.12.0");
|
||||
for ok in [
|
||||
"1.0.0",
|
||||
"1.3.0",
|
||||
"1.4.7",
|
||||
"1.5.0",
|
||||
"1.6.0",
|
||||
"1.7.0",
|
||||
"1.8.0",
|
||||
"1.9.0",
|
||||
"1.10.0",
|
||||
"1.11.0",
|
||||
"1.12.0",
|
||||
"1.0.0-rc.1",
|
||||
] {
|
||||
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
|
||||
}
|
||||
let newer = check_api(&v("1.12.0"), &host).unwrap_err();
|
||||
let newer = check_api(&v("1.13.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.12") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
|
||||
let older = check_api(&v("0.2.0"), &host).unwrap_err();
|
||||
assert!(older.contains("rebuild it with the 1.11 SDK"), "{older}");
|
||||
assert!(older.contains("rebuild it with the 1.12 SDK"), "{older}");
|
||||
// 0.x: every minor is its own API.
|
||||
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
|
||||
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
ada68dfdf2875668eff1765ec22678315f18ac6f1364c5f7eda742cb58dc3c60
|
||||
36b8ec8be8a65e60d601cd53e9ae0e8ab2865cb69de9b83ca31a9cb277aa0801
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
2279ae4f79c565c4cd59d9191f394c4d7d5b23ef955f1bd30c2e5396d608e46c
|
||||
631e3140cbd600a3e9af8ee1871e4461fc92fb7e492226507ed2089e5ee6d411
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
77be736c11c39de3a1b021a5e66e905c76e2d32352d889d6bcc9315607c54271
|
||||
ac15b6576fb3536d92d388a9a35775cfa380ad7c8b17fc8375ac403a32cc6b5e
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
304690bf13cba5d262d54d709d6f18c627880954f0140919118aea0439fbaaf3
|
||||
90d0d2643fb70422ac4f8cccd1d74bda4dfe89b4b2e9d28cc5136e4d5b2969f1
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
b24767627e7445ec093cc79cd6c18844e4dcdf123c6b04c24bc37f109c5cdb0f
|
||||
a8639ee0478bad01370c9117b02ba791d7283e5728c982f7dc6a66e540b06781
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
0fa52a91772ceb3d45307db4f2561c132df4b966d15f7f9ce177b7a373f7163d
|
||||
a3f38583f118bf8ae4c85994293b77fec599cef6a4e15509f94fb3c1cc4a69e2
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
34ea07edc731ab28748b99c398f7e1ee4d41aa22c0760d57027adad40759292f
|
||||
b4629333f12d2b227c9da8411f7a11a5fe832ce15e93d7c9a33644b5d022d50f
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
470a54d825e84e8ec0418a244c1fc46426c02f299f4a456ff4cc83fa604d08a0
|
||||
d4914c689dacb014dcc9af6952a8620f32ed0d13e43e458de3f23d49311467f2
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
20a4f662437478b20e5a80aa30afe20b155001f94c2934843ab11b69192833d4
|
||||
9547bea771af3ea663455282a1fc4f5d0ed95ea4a3c794b98106dc54744d3717
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
c118a6562e0398e7f0deb64abc9913dd14acec74869d5c04c452923a81455463
|
||||
d1789382c8508b18e243b7812678a2ad98187f289a818a1935bc63e771ba8d26
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
194fa719b8c96ca23f2da73d2d7225c4805b5c48af67b1efff8e76852f0a6a1c
|
||||
a3980ccb70b911f218d0809985531c133861732d4ed04302896ce79c473f358f
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
3db661dd4d45a242b79caf642510d71841ba9f09b3b5eaa1854eabe9fcf6292e
|
||||
297774561d9383cf5c364483bca25810cd5271f4e5081b53bd6d6cb06224d200
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
196769808ae37ede0a7564f42cae087a18f756b3cd31acb7d99470f1bfd70ea6
|
||||
c5005462f40a2a1e384f87c6ca3d2651cc5bd1d75148dd6f16c904c15d622be7
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
dcd05de6c207f4594d347ad3dc44089204353dc898e53873f437e3db1928d629
|
||||
b89751bbab2ab1f1cb27b22c36ede99dfc090d78d03bd0325aaa64b0d08deacf
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
ece50a864d5a85263cb30eb39dceae90fe174336904e9208ae5c9d5da5cbb036
|
||||
e45d268957df9650d2766206638a485bd44878fd5cf31f96733b23ed25e990dc
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
a2854d3c357d976b5ee1bf7b31fa541a55581102d37ec85ea719d4fdedd962cb
|
||||
b110ed23919ae6c7d35c0cddb690731470280da4a2c97c6723baca0976990e2f
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
dbebe5cfa79092169689d43945e4d71e1a61303ce88f6b4f02216ab69083b955
|
||||
5dc1e01c268c7a755346bb9459600a5e6b605a60b0ce9cd62132dbeb6656dbb1
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
993b0f11e8cae470b0529fcfcbe9a520c855069ef63f242da3b26a3da2574d5d
|
||||
7e271a84f33e4f477dbaedc723f9fbe2decdcccf67f4df418a33cfb48cb83688
|
||||
@@ -87,6 +87,20 @@ impl Plugin for Jobs {
|
||||
host::copy_to_clipboard(arg.unwrap_or_default())?;
|
||||
Ok(None)
|
||||
}
|
||||
"console-rules" => {
|
||||
// No argument: two rules; `""` clears; anything else is one rule with that pattern.
|
||||
use openidea_plugin::ConsoleRule;
|
||||
let rules = match arg {
|
||||
None => vec![
|
||||
ConsoleRule::new(r"\[AUDIT\]").foreground("bright-yellow").style("bold").whole_line(),
|
||||
ConsoleRule::new(r"job-\d+").ignore_case().foreground("cyan").background("teal"),
|
||||
],
|
||||
Some("") => Vec::new(),
|
||||
Some(pattern) => vec![ConsoleRule::new(pattern).foreground("red")],
|
||||
};
|
||||
host::set_console_rules(&rules)?;
|
||||
Ok(None)
|
||||
}
|
||||
"open-url" => {
|
||||
host::open_url(arg.unwrap_or_default())?;
|
||||
Ok(None)
|
||||
|
||||
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
d803928d82cbb2991b3f0c53b73dbe2da625b7b2ce25050706b6da09687f2873
|
||||
8b1eb9f66077c8bbccb4ac39bbee1d8474846341260f4b2c4391741292ab268e
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
1c779c4913a2b83fa51980ee0017e3f2625041f1b4de921cedcdcb3bd4120d67
|
||||
834b204b6417860ccc9c0dfc4ab8ee5c2fda2a57cb452d34198dbbdebc61d49c
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
bd09f3b47470087095ae50c3b0f134c471dd9ba1e5f812cd0285cef904065725
|
||||
6981a004f521cab1cc8c1c53252d8790ecae15e8c736b2817b78549d34c1d8c9
|
||||
+3
-3
@@ -5,9 +5,9 @@ wit_bindgen::generate!({
|
||||
inline: "
|
||||
package fixture:misbehave;
|
||||
world misbehave {
|
||||
include openidea:plugin/plugin-syntax@1.11.0;
|
||||
export openidea:plugin/providers@1.11.0;
|
||||
export openidea:plugin/file-actions@1.11.0;
|
||||
include openidea:plugin/plugin-syntax@1.12.0;
|
||||
export openidea:plugin/providers@1.12.0;
|
||||
export openidea:plugin/file-actions@1.12.0;
|
||||
}
|
||||
",
|
||||
path: "../../../../../wit",
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
ada14d3aa0e462478de7dff28be356b2105f4d3ec8d4dff8a7a4a858d15c4613
|
||||
6effad574d5bee69cabd68503b1f870118afbcd3260d3d49472b15b7140bfc40
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
3d628f747d13d3d2fae9a75adeb951c8af09b1db5fb15523fc71289857d97d99
|
||||
04b41e556a8a2984f367cddec6cd7077e6990275313c781fe58a6723b2321c8a
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
43e7552ae0f8b42383cade84924adc81952c78253186a71c2693b11d98f01acd
|
||||
bd2e104a54f46eeff56945c43e71369dd0a67c4ed55b0aa8a71e5cac4c20c037
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
373188558b7925b4f9c9f975b0b6aa7b13acdf8da0c622a4ab12f39b69c1f071
|
||||
d196a3cec49a5bf4909242903561aa4f74248122fa63bb1de78126c815a4a4b9
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
9c91a083fd31e57658f28c34329e061dc17cc08871fe09b3b96fa557bc085c8d
|
||||
084a3036772ac0dfe7c18f4d036a67e67462f3acc080dd6a5130595db3c03b3c
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
1a2182ca4e272d3473084451932a1d8df861ac2e67ad1814c0e01e089584ab3f
|
||||
39f86e1c941e73a2a5cba9edd45e035459503eb7280e4dfc5c19192c123d5c29
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
d5e8c538e410f480d79454c616bf9b0e7eaa7e502ed0268bf20f75214ca93d17
|
||||
54210827ba484cb857649f08c2cd7d35918d717fd5e82d9516568492e376c0df
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
756f2a459f2aa17d6eb1d9dbe089a3d6dc5079012ed68ee47e55d5256c589359
|
||||
7a56e3d76935a0133b07eff1e3ce95d149fafae372747a6a41ca7c4deff61222
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
28327a76a68737fda8ae0b22a439f5bbe86dd53347a7ee2806bb66ae90714238
|
||||
523369be2d76af64f487f1576775a44c08450b283a8dbe2f39a016492d9b8a73
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
ac3a564273429fcaad2c443e3463f06694953889ad894c9f68b824e87e291ae0
|
||||
f17b5186d47d47a3b4387594e10e8acc86a6ca1d2ed723d2cad89b9bb4f30d4b
|
||||
@@ -14,7 +14,7 @@ pub use deploy::{
|
||||
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
|
||||
};
|
||||
pub use mapping::{Excludes, Mappings, ResolvedMapping};
|
||||
pub use service::{DeployedPath, DeploymentRoot, RemoteService};
|
||||
pub use service::{DeployedPath, DeploymentRoot, RemoteService, default_targets};
|
||||
pub use target::{RemoteRuns, RemoteStart};
|
||||
|
||||
pub mod plugin_target;
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Deployment over SFTP, FTP or local folders, and SSH run targets.
|
||||
//! Shared by IPC commands and project save/delete hooks.
|
||||
|
||||
use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, TransferReport, status};
|
||||
use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, TransferError, TransferReport, status};
|
||||
use crate::mapping::{Excludes, Mappings, ResolvedMapping, posix};
|
||||
use crate::target::{RemoteRuns, RemoteStart, SyncFn, rewrite_external_classpath};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentServer, DeploymentType, RunTarget};
|
||||
@@ -65,6 +65,39 @@ pub fn server(settings: &Settings, id: Option<&str>) -> IdeResult<DeploymentServ
|
||||
.ok_or_else(|| IdeError::not_found(format!("no deployment server {id}")))
|
||||
}
|
||||
|
||||
/// The servers automatic upload goes to: the default server, or each server of the default group.
|
||||
pub fn default_targets(settings: &Settings) -> Vec<String> {
|
||||
let d = &settings.deployment;
|
||||
match d.groups.iter().find(|g| g.id == d.default_server) {
|
||||
Some(group) => group.servers.iter().filter(|id| d.servers.iter().any(|s| &s.id == *id)).cloned().collect(),
|
||||
None if d.default_server.is_empty() => Vec::new(),
|
||||
None => vec![d.default_server.clone()],
|
||||
}
|
||||
}
|
||||
|
||||
/// One report for transfers to several servers, failures named after their server.
|
||||
fn merge_reports(reports: Vec<(String, IdeResult<TransferReport>)>) -> IdeResult<TransferReport> {
|
||||
if let [(_, _)] = reports.as_slice() {
|
||||
return reports.into_iter().next().map(|(_, r)| r).unwrap_or_else(|| Ok(TransferReport::default()));
|
||||
}
|
||||
let mut out = TransferReport::default();
|
||||
for (server, report) in reports {
|
||||
match report {
|
||||
Ok(r) => {
|
||||
out.files += r.files;
|
||||
out.skipped += r.skipped;
|
||||
out.errors.extend(
|
||||
r.errors.into_iter().map(|e| TransferError { message: format!("{server}: {}", e.message), ..e }),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
out.errors.push(TransferError { path: String::new(), message: format!("{server}: {}", e.message) })
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn run_target(settings: &Settings, id: &str) -> IdeResult<RunTarget> {
|
||||
settings
|
||||
.run_targets
|
||||
@@ -391,15 +424,17 @@ impl RemoteService {
|
||||
.await;
|
||||
return Some(r);
|
||||
}
|
||||
if settings.deployment.auto_upload == AutoUpload::Never
|
||||
|| settings.deployment.default_server.is_empty()
|
||||
|| !path.starts_with(root)
|
||||
{
|
||||
let targets = default_targets(settings);
|
||||
if settings.deployment.auto_upload == AutoUpload::Never || targets.is_empty() || !path.starts_with(root) {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
self.upload(settings, root, None, &[path.to_path_buf()], CancellationToken::new(), &mut |_, _, _| {}).await,
|
||||
)
|
||||
let mut reports = Vec::new();
|
||||
for id in targets {
|
||||
let paths = [path.to_path_buf()];
|
||||
let r = self.upload(settings, root, Some(&id), &paths, CancellationToken::new(), &mut |_, _, _| {}).await;
|
||||
reports.push((id, r));
|
||||
}
|
||||
Some(merge_reports(reports))
|
||||
}
|
||||
|
||||
/// After files were deleted locally: their remote copies too (automatic upload + Delete remote files).
|
||||
@@ -410,10 +445,16 @@ impl RemoteService {
|
||||
paths: &[PathBuf],
|
||||
) -> Option<IdeResult<TransferReport>> {
|
||||
let d = &settings.deployment;
|
||||
if d.auto_upload == AutoUpload::Never || !d.delete_remote || d.default_server.is_empty() {
|
||||
let targets = default_targets(settings);
|
||||
if d.auto_upload == AutoUpload::Never || !d.delete_remote || targets.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(self.delete_remote(settings, root, None, paths).await)
|
||||
let mut reports = Vec::new();
|
||||
for id in targets {
|
||||
let r = self.delete_remote(settings, root, Some(&id), paths).await;
|
||||
reports.push((id, r));
|
||||
}
|
||||
Some(merge_reports(reports))
|
||||
}
|
||||
|
||||
// --- run targets ---------------------------------------------------------------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Local deployment uses the service entry points used by SFTP and save hooks.
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentMapping, DeploymentServer, DeploymentType};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentGroup, DeploymentMapping, DeploymentServer, DeploymentType};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_remote::{RemoteService, SyncAction, SyncStatus, SyncStep};
|
||||
use ide_ssh::{FsConnection, SshFiles, SshManager};
|
||||
@@ -410,3 +410,40 @@ async fn download_into_copies_only_the_selected_items() {
|
||||
.unwrap();
|
||||
assert_eq!((report.files, report.errors.len()), (0, 1), "{report:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn automatic_upload_to_a_default_group_reaches_each_of_its_servers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let (staging, live) = (tmp.path().join("staging"), tmp.path().join("live"));
|
||||
for dir in [root.join("src"), staging.clone(), live.clone()] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("src/a.txt"), "v1").unwrap();
|
||||
let mut settings = settings(&staging);
|
||||
settings.deployment.servers.push(DeploymentServer {
|
||||
id: "live".into(),
|
||||
kind: DeploymentType::Local,
|
||||
root_path: live.to_string_lossy().into_owned(),
|
||||
mappings: vec![DeploymentMapping { deployment: "app".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
});
|
||||
settings.deployment.groups.push(DeploymentGroup {
|
||||
id: "all".into(),
|
||||
name: "All".into(),
|
||||
servers: vec!["local".into(), "live".into(), "gone".into()],
|
||||
});
|
||||
settings.deployment.default_server = "all".into();
|
||||
assert_eq!(ide_remote::default_targets(&settings), ["local", "live"]);
|
||||
|
||||
let service = service(tmp.path());
|
||||
let saved = service.on_saved(&settings, &root, &root.join("src/a.txt")).await.unwrap().unwrap();
|
||||
assert_eq!((saved.files, saved.errors.len()), (2, 0), "{saved:?}");
|
||||
for target in [&staging, &live] {
|
||||
assert_eq!(std::fs::read_to_string(target.join("app/src/a.txt")).unwrap(), "v1");
|
||||
}
|
||||
std::fs::remove_file(root.join("src/a.txt")).unwrap();
|
||||
let deleted = service.on_deleted(&settings, &root, &[root.join("src/a.txt")]).await.unwrap().unwrap();
|
||||
assert!(deleted.errors.is_empty(), "{deleted:?}");
|
||||
assert!(!staging.join("app/src/a.txt").exists() && !live.join("app/src/a.txt").exists());
|
||||
}
|
||||
@@ -36,6 +36,7 @@ fn query(pattern: &str, is_regex: bool) -> SearchQuery {
|
||||
scope: SearchScope::Project,
|
||||
max_matches: 0,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user