mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 09:39:27 -10:00
Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
891432c2d9 | ||
|
|
160ecf4693 | ||
|
|
cb087fff48 | ||
|
|
70e0215f46 | ||
|
|
460d30030e | ||
|
|
edf9affa8e | ||
|
|
070c795de5 | ||
|
|
5c9290fefd | ||
|
|
0527ff4218 | ||
|
|
e5b2f4dfc7 | ||
|
|
a3617aa3e9 | ||
|
|
bd7d4c475b | ||
|
|
15e32d5af6 | ||
|
|
3de76f1a63 | ||
|
|
262b91d89a | ||
|
|
4d6a21c695 | ||
|
|
7de8fb850e | ||
|
|
acb850758a | ||
|
|
6bf69cfb2a | ||
|
|
6829022b71 | ||
|
|
54611ff80a | ||
|
|
cacfc4142f | ||
|
|
237f7ee5a5 | ||
|
|
2321929709 | ||
|
|
6d788cb6f8 | ||
|
|
662c32eb05 | ||
|
|
82ff84e69e | ||
|
|
7ec0d3dbec | ||
|
|
466556603d | ||
|
|
3b2deb6ad8 | ||
|
|
f2429a8c14 | ||
|
|
f3e80ba020 | ||
|
|
f767bd2e7c | ||
|
|
51174842cc | ||
|
|
e4ece2bd8d | ||
|
|
a5093c0cd1 | ||
|
|
9a0256c7d4 | ||
|
|
78b478ee38 |
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",
|
||||
|
||||
@@ -16,18 +16,55 @@ pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
/// For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
|
||||
///
|
||||
/// - Windows: release builds use the GUI subsystem, so without `CREATE_NO_WINDOW` every
|
||||
/// console child flashes a `cmd` window.
|
||||
/// console child flashes a `cmd` window. Batch files also need a PATH small enough for cmd.
|
||||
/// - Linux AppImage, reloaded and project variables: see [`host_env`].
|
||||
///
|
||||
/// Variables the call site has already set are kept; call it before `env_clear` and after
|
||||
/// `current_dir`, which picks the project environment.
|
||||
/// Explicit variables take precedence over the host environment. Call after setting
|
||||
/// `current_dir` and any explicit `PATH`, and before `env_clear`.
|
||||
pub fn prepare(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
host_env(cmd)
|
||||
host_env(cmd);
|
||||
#[cfg(windows)]
|
||||
compact_batch_path(cmd);
|
||||
cmd
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn compact_batch_path(cmd: &mut Command) {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Component, Prefix};
|
||||
|
||||
// Rust runs these files through cmd.exe, which drops inherited variables over this limit.
|
||||
const CMD_ENV_LIMIT: usize = 8191;
|
||||
let extension = Path::new(cmd.get_program()).extension();
|
||||
if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) {
|
||||
return;
|
||||
}
|
||||
let path = match cmd.get_envs().find(|(key, _)| key.eq_ignore_ascii_case("PATH")) {
|
||||
Some((_, path)) => path.map(OsStr::to_owned),
|
||||
None => std::env::var_os("PATH"),
|
||||
};
|
||||
let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return };
|
||||
|
||||
// The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are
|
||||
// missing now, keeping search precedence and leaving UNC and relative paths alone.
|
||||
let dirs = std::env::split_paths(&path).filter(|dir| {
|
||||
let local = dir.is_absolute()
|
||||
&& matches!(dir.components().next(), Some(Component::Prefix(p))
|
||||
if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)));
|
||||
!local
|
||||
|| !std::fs::symlink_metadata(dir)
|
||||
.is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory))
|
||||
});
|
||||
if let Ok(compact) = std::env::join_paths(dirs)
|
||||
&& compact.encode_wide().count() <= CMD_ENV_LIMIT
|
||||
{
|
||||
cmd.env("PATH", compact);
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
|
||||
@@ -885,6 +922,44 @@ mod tests {
|
||||
assert!(!process_alive(pid));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn batch_launch_keeps_runtime_paths_when_cmd_would_drop_path() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let script = root.path().join("server.CMD");
|
||||
std::fs::write(&script, "@echo off\r\nif not defined PATH exit /b 42\r\n").unwrap();
|
||||
let selected = root.path().join("Selected Runtime");
|
||||
let fallback = root.path().join("Fallback Runtime");
|
||||
std::fs::create_dir(&selected).unwrap();
|
||||
std::fs::create_dir(&fallback).unwrap();
|
||||
let relative = Path::new("relative");
|
||||
let unc = Path::new(r"\\openidea-test\share\bin");
|
||||
let missing = root.path().join("uninstalled-".repeat(12));
|
||||
let path = std::env::join_paths(
|
||||
std::iter::once(selected.as_path()).chain(std::iter::repeat_n(missing.as_path(), 60)).chain([
|
||||
unc,
|
||||
relative,
|
||||
fallback.as_path(),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let compact = std::env::join_paths([selected.as_path(), unc, relative, fallback.as_path()]).unwrap();
|
||||
|
||||
let path_in = |cmd: &Command| {
|
||||
cmd.get_envs()
|
||||
.find_map(|(key, value)| key.eq_ignore_ascii_case("PATH").then(|| value.map(OsStr::to_owned)))
|
||||
.flatten()
|
||||
};
|
||||
let mut cmd = Command::new(&script);
|
||||
cmd.current_dir(root.path()).env("PATH", &path);
|
||||
prepare(&mut cmd);
|
||||
assert_eq!(path_in(&cmd), Some(compact));
|
||||
assert!(cmd.status().unwrap().success());
|
||||
|
||||
let mut native = Command::new(root.path().join("server.exe"));
|
||||
assert_eq!(path_in(prepare(native.env("PATH", &path))), Some(path));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn process_alive_rejects_ids_that_are_not_a_single_process() {
|
||||
|
||||
@@ -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,
|
||||
@@ -770,6 +772,8 @@ pub struct AppearanceSettings {
|
||||
pub show_tool_window_names: bool,
|
||||
pub show_tool_window_badges: bool,
|
||||
pub widescreen_tool_windows: bool,
|
||||
/// Each tool window keeps its own size; off, the windows of a side share one.
|
||||
pub remember_tool_window_sizes: bool,
|
||||
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
|
||||
pub show_main_toolbar: bool,
|
||||
pub show_status_bar: bool,
|
||||
@@ -885,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,
|
||||
@@ -898,6 +903,7 @@ impl Default for AppearanceSettings {
|
||||
show_tool_window_names: false,
|
||||
show_tool_window_badges: true,
|
||||
widescreen_tool_windows: false,
|
||||
remember_tool_window_sizes: false,
|
||||
show_main_toolbar: true,
|
||||
show_status_bar: true,
|
||||
navigation_bar: NavigationBarPosition::StatusBar,
|
||||
@@ -1752,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}}"#] {
|
||||
|
||||
@@ -20,6 +20,34 @@ pub struct VcsSettings {
|
||||
pub shelf: ShelfSettings,
|
||||
/// Issue Navigation: commit-message patterns turned into links.
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
/// root (`.` for the root itself) or absolute outside it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct VcsMappings {
|
||||
/// Detected repositories the IDE leaves alone: no Git or Commit integration, files stay.
|
||||
pub excluded: Vec<String>,
|
||||
/// Repository roots detection does not reach (outside the project, or deeper).
|
||||
pub added: Vec<String>,
|
||||
}
|
||||
|
||||
impl VcsMappings {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.excluded.is_empty() && self.added.is_empty()
|
||||
}
|
||||
|
||||
/// `path` resolved against `project_root`.
|
||||
pub fn resolve(project_root: &std::path::Path, path: &str) -> std::path::PathBuf {
|
||||
match path {
|
||||
"" | "." => project_root.to_path_buf(),
|
||||
p if std::path::Path::new(p).is_absolute() => p.into(),
|
||||
p => project_root.join(p),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for VcsSettings {
|
||||
@@ -34,6 +62,7 @@ impl Default for VcsSettings {
|
||||
confirmation: VcsConfirmationSettings::default(),
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,6 +106,9 @@ pub struct GitSettings {
|
||||
/// The non-modal Commit tool window works on the index: Staged / Unstaged groups,
|
||||
/// stage and unstage instead of inclusion checkboxes, and no change lists.
|
||||
pub staging_area: bool,
|
||||
/// Scan the working tree with `git status` (for file systems whose metadata only
|
||||
/// the system git reads correctly) instead of in process.
|
||||
pub cli_status: bool,
|
||||
}
|
||||
|
||||
impl Default for GitSettings {
|
||||
@@ -101,6 +133,7 @@ impl Default for GitSettings {
|
||||
push_dialog_only_protected: false,
|
||||
combine_stash_and_shelf: false,
|
||||
staging_area: false,
|
||||
cli_status: 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))
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_vfs::FileEntry;
|
||||
use ide_workspace::DeletionUndo;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -163,14 +164,27 @@ pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool)
|
||||
/// Moving to the trash can take a while (large trees): kept off the main thread.
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
|
||||
// Local History keeps the contents so deleted files can be restored.
|
||||
let project = host.project(window).ok();
|
||||
let history = project.as_ref().map(|p| p.history.clone());
|
||||
delete_with_history(host, window, path, false).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Moves an item to the Trash and returns the snapshot for Project View Undo.
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_delete_with_undo(host: &Host, window: &str, path: PathBuf) -> IdeResult<DeletionUndo> {
|
||||
delete_with_history(host, window, path, true).await
|
||||
}
|
||||
|
||||
async fn delete_with_history(host: &Host, window: &str, path: PathBuf, undoable: bool) -> IdeResult<DeletionUndo> {
|
||||
let project = if undoable { Some(host.project(window)?) } else { host.project(window).ok() };
|
||||
host.blocking(move || {
|
||||
let paths = ide_workspace::file_ops::deletion_paths(&path)?;
|
||||
if let Some(h) = history {
|
||||
for p in &paths {
|
||||
h.record_deletion(p, DELETE_SNAPSHOT_LIMIT);
|
||||
let mut undo = DeletionUndo::default();
|
||||
if let Some(p) = &project {
|
||||
if undoable {
|
||||
undo = p.history.capture_deletion_undo(&paths, DELETE_SNAPSHOT_LIMIT);
|
||||
} else {
|
||||
for pth in &paths {
|
||||
p.history.record_deletion(pth, DELETE_SNAPSHOT_LIMIT);
|
||||
}
|
||||
}
|
||||
}
|
||||
ide_workspace::file_ops::delete(&path)?;
|
||||
@@ -178,11 +192,17 @@ pub async fn fs_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()
|
||||
if let Some(p) = project {
|
||||
let _ = p.with_backend_of(&path, |r| r.files_deleted(&paths));
|
||||
}
|
||||
Ok(())
|
||||
Ok(undo)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || Ok(project.history.restore_deletion_undo(undo))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_copy(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> IdeResult<()> {
|
||||
let project = host.project(window).ok();
|
||||
@@ -280,9 +300,11 @@ ide_command::domain!(
|
||||
fs_create_file,
|
||||
fs_create_file_bytes,
|
||||
fs_delete,
|
||||
fs_delete_with_undo,
|
||||
fs_entry_kind,
|
||||
fs_read_dir,
|
||||
fs_read_text,
|
||||
fs_rename,
|
||||
fs_set_writable,
|
||||
fs_undo_delete,
|
||||
);
|
||||
@@ -68,6 +68,31 @@ pub async fn find_files_named(host: &Host, window: &str, name: String) -> IdeRes
|
||||
blocking(move || Ok(project.index.files_named(&name).into_iter().map(Into::into).collect())).await
|
||||
}
|
||||
|
||||
/// The files of a custom scope (`file:src//*.ts`), for the Project view's scope panes.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScopeFiles {
|
||||
pub paths: Vec<IpcPath>,
|
||||
/// More files than `limit` matched; `paths` holds the first ones.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn scope_files(host: &Host, window: &str, pattern: String, limit: u32) -> IdeResult<ScopeFiles> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let mask = ide_search::FileMask::new(&[], &project.search_excludes())?;
|
||||
let scope = ide_search::SearchScope::Pattern { pattern };
|
||||
let mut files =
|
||||
ide_search::scope_files(&project.root, &scope, &mask, None, &ide_core::CancellationToken::new())?;
|
||||
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
let truncated = files.len() > limit as usize;
|
||||
files.truncate(limit as usize);
|
||||
Ok(ScopeFiles { paths: files.into_iter().map(|f| f.path.into()).collect(), truncated })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Folders holding indexed files, for `@` references.
|
||||
#[command(trust = always)]
|
||||
pub async fn find_dirs(host: &Host, window: &str, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
|
||||
@@ -375,6 +400,7 @@ ide_command::domain!(
|
||||
path_completions,
|
||||
recent_files,
|
||||
remove_recent,
|
||||
scope_files,
|
||||
web_goto,
|
||||
web_unresolved_references,
|
||||
);
|
||||
@@ -302,6 +302,15 @@ pub fn set_settings(
|
||||
}
|
||||
});
|
||||
}
|
||||
// Directory Mappings change which repositories the project has.
|
||||
if key == "vcs" || key == "vcs.mappings" || key.starts_with("vcs.mappings.") {
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
for project in affected {
|
||||
project.refresh_repositories();
|
||||
}
|
||||
});
|
||||
}
|
||||
if key == "ssh" || key.starts_with("ssh.") {
|
||||
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -18,6 +18,7 @@ pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>>
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
}
|
||||
repos.status()
|
||||
})
|
||||
@@ -40,6 +41,7 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::P
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
}
|
||||
repos.status_paths(&paths)
|
||||
})
|
||||
|
||||
@@ -338,6 +338,13 @@ fn keep_private(root: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Directory Mappings: the repository roots detection finds, before any are excluded or added.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult<Vec<PathBuf>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.detected_repository_roots()).await
|
||||
}
|
||||
|
||||
/// The project's repositories, the primary one first.
|
||||
#[command(trust = always)]
|
||||
pub fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
@@ -1061,6 +1068,22 @@ pub async fn vcs_config_get(
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.config_get(&key))).await
|
||||
}
|
||||
|
||||
/// Git User Name Is Not Defined: sets `user.name` / `user.email` for commits in the
|
||||
/// repository, or globally.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_set_user_identity(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
email: String,
|
||||
global: bool,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.set_user_identity(&name, &email, global))).await
|
||||
}
|
||||
|
||||
/// Local history operation that may take a while (hooks, large checkouts); git's
|
||||
/// output streams through `on_output`. Cancellable.
|
||||
#[command(trust = trusted)]
|
||||
@@ -1569,6 +1592,7 @@ ide_command::domain!(
|
||||
vcs_compare_paths,
|
||||
vcs_compare_scope,
|
||||
vcs_config_get,
|
||||
vcs_set_user_identity,
|
||||
vcs_conflict_versions,
|
||||
vcs_create_branch,
|
||||
vcs_create_patch,
|
||||
@@ -1616,6 +1640,7 @@ ide_command::domain!(
|
||||
vcs_revision_files,
|
||||
vcs_reword,
|
||||
vcs_roots,
|
||||
vcs_detected_roots,
|
||||
vcs_shelf_delete,
|
||||
vcs_shelf_diff,
|
||||
vcs_shelf_import,
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,8 @@ impl PluginHost {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a plugin receives for `document-changed`: the path relative to the file's own project.
|
||||
/// What a plugin receives for `document-changed`: the path relative to the file's own
|
||||
/// project, and that project's root, since two open projects can hold the same relative path.
|
||||
pub(super) fn relativize_documents(
|
||||
shared: &super::api::Shared,
|
||||
client: Option<&str>,
|
||||
@@ -181,6 +182,7 @@ impl PluginHost {
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
change.path = relative;
|
||||
change.project = Some(ide_core::ipc_path::to_ipc(&root));
|
||||
Some(WorkbenchEvent::DocumentChanged(change))
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! watchers and the per-project services, opened by [`crate::Host::open_project`].
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::workflow_settings::VcsMappings;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink};
|
||||
use ide_index::ProjectIndex;
|
||||
use ide_language::{FileTypes, LanguageRegistry, SyntaxCache};
|
||||
@@ -955,10 +956,27 @@ fn scan_repositories(
|
||||
}
|
||||
}
|
||||
|
||||
/// The repository containing `root` and those nested below it or below a content root.
|
||||
/// The repository containing `root` and those nested below it or below a content root,
|
||||
/// with the project's Directory Mappings applied.
|
||||
/// The project-open scan and the watcher's rescan share these skip rules.
|
||||
fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Path, trusted: bool) -> IdeResult<Repos> {
|
||||
let ignored = settings.effective().ignored_names();
|
||||
let settings = settings.effective();
|
||||
let found = detect_repositories(root, &settings, build_cache, trusted)?;
|
||||
let mappings = &settings.vcs.mappings;
|
||||
if mappings.is_empty() {
|
||||
return Ok(found);
|
||||
}
|
||||
let resolve = |list: &[String]| -> Vec<PathBuf> { list.iter().map(|p| VcsMappings::resolve(root, p)).collect() };
|
||||
Ok(found.mapped(&resolve(&mappings.excluded), &resolve(&mappings.added), root))
|
||||
}
|
||||
|
||||
fn detect_repositories(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
build_cache: &Path,
|
||||
trusted: bool,
|
||||
) -> IdeResult<Repos> {
|
||||
let ignored = settings.ignored_names();
|
||||
let skip = |p: &Path| {
|
||||
p.file_name().is_some_and(|n| {
|
||||
let name = n.to_string_lossy();
|
||||
@@ -968,11 +986,17 @@ fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Pa
|
||||
})
|
||||
};
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(&settings.effective(), root, build_cache, trusted));
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &skip)
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// The repository roots detection finds, before Directory Mappings exclude or add any.
|
||||
pub fn detected_repository_roots(&self) -> IdeResult<Vec<PathBuf>> {
|
||||
let settings = self.settings.effective();
|
||||
Ok(detect_repositories(&self.root, &settings, &self.build_cache_dir(), self.is_trusted())?.roots())
|
||||
}
|
||||
|
||||
pub fn refresh_repositories(&self) {
|
||||
scan_repositories(
|
||||
&self.root,
|
||||
@@ -1076,6 +1100,7 @@ impl Project {
|
||||
apply_git_executable(&settings);
|
||||
}
|
||||
repo.set_ignored_names(settings.ignored_names());
|
||||
repo.set_cli_status(settings.vcs.git.cli_status);
|
||||
f(repo)
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
@@ -5298,6 +5342,7 @@ fn document_changes_reach_plugins_relative_to_the_project() {
|
||||
let deliver = |path: &str| {
|
||||
let change = ide_plugin::DocumentChanged {
|
||||
path: to_ipc(&f.project.join(path)),
|
||||
project: None,
|
||||
base_version: 1,
|
||||
version: 2,
|
||||
changes: Vec::new(),
|
||||
@@ -5311,6 +5356,8 @@ fn document_changes_reach_plugins_relative_to_the_project() {
|
||||
// Queued with the absolute path, filtered again at delivery, handed over project-relative.
|
||||
deliver("config/app.yaml");
|
||||
assert_eq!(f.run("test.path-events", "document", None).unwrap().as_deref(), Some("config/app.yaml"));
|
||||
// With the project it is relative to: another open project may hold the same path.
|
||||
assert_eq!(f.run("test.path-events", "document-project", None).unwrap(), Some(to_ipc(&f.project)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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,
|
||||
|
||||
+137
-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;
|
||||
@@ -241,6 +220,15 @@ impl PathFilter {
|
||||
(!rel.is_empty()).then_some(rel)
|
||||
}
|
||||
|
||||
/// Recent Files' stored form: the store key for a project file, the absolute
|
||||
/// path for one outside it (a scratch file). Loading joins it to the root,
|
||||
/// which leaves an absolute path as it is.
|
||||
pub(crate) fn recent_key(&self, path: &Path) -> Option<String> {
|
||||
self.store_key(path).or_else(|| {
|
||||
(path.is_absolute() && !path.starts_with(&self.root)).then(|| path.to_str().map(str::to_owned))?
|
||||
})
|
||||
}
|
||||
|
||||
fn excluded_rel(&self, rel: &str) -> bool {
|
||||
self.excludes.is_match(rel)
|
||||
}
|
||||
@@ -249,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;
|
||||
@@ -271,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.
|
||||
@@ -311,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() {
|
||||
@@ -371,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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,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 [
|
||||
@@ -488,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)));
|
||||
|
||||
@@ -505,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]
|
||||
@@ -535,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]
|
||||
@@ -555,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()]));
|
||||
}
|
||||
@@ -589,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))));
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-15
@@ -400,15 +400,10 @@ impl ProjectIndex {
|
||||
|
||||
/// Boost for "recent files" ranking.
|
||||
/// Records a recently opened file; a virtual document's URI (library
|
||||
/// class) is kept verbatim, like IDEA lists library classes in Recent Files.
|
||||
/// class) is kept verbatim, and a file outside the project (a scratch file)
|
||||
/// by its absolute path.
|
||||
pub fn mark_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let Some(path) = self.recent_key(path) else { return };
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
r.retain(|p| p != &path);
|
||||
@@ -420,13 +415,7 @@ impl ProjectIndex {
|
||||
|
||||
/// Drops a file from Recent Files (Delete in the ⌘E popup).
|
||||
pub fn remove_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let Some(path) = self.recent_key(path) else { return };
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
let before = r.len();
|
||||
@@ -473,6 +462,20 @@ impl ProjectIndex {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// How Recent Files stores `path`: a virtual URI verbatim, a project file normalized,
|
||||
/// and an existing file outside the root canonicalized. Excluded files under the root
|
||||
/// are left out.
|
||||
fn recent_key(&self, path: &Path) -> Option<PathBuf> {
|
||||
if path.to_str().is_some_and(ide_core::text::is_virtual_uri) {
|
||||
return Some(path.to_owned());
|
||||
}
|
||||
if let Some(p) = self.normalize(path) {
|
||||
return Some(p);
|
||||
}
|
||||
let p = dunce::canonicalize(path).ok().filter(|p| p.is_file())?;
|
||||
(!p.starts_with(&self.root)).then_some(p)
|
||||
}
|
||||
|
||||
/// Absolute path inside the root (or a content root), or `None` for paths outside the project.
|
||||
fn normalize(&self, path: &Path) -> Option<PathBuf> {
|
||||
let filter = self.shared.filter();
|
||||
|
||||
+159
-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(&[
|
||||
@@ -251,6 +260,26 @@ fn recent_files_skip_deleted_files_but_keep_virtual_documents() {
|
||||
assert_eq!(idx.recent_files(), vec![virt]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_files_keep_files_outside_the_project() {
|
||||
let fx = sample();
|
||||
let scratches = tempfile::tempdir().unwrap();
|
||||
let scratch = dunce::canonicalize(scratches.path()).unwrap().join("generated-requests.http");
|
||||
std::fs::write(&scratch, "GET http://localhost\n").unwrap();
|
||||
let app = fx.root.join("web/app.py");
|
||||
{
|
||||
let idx = fx.open();
|
||||
idx.mark_recent(&app);
|
||||
idx.mark_recent(&scratch);
|
||||
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
}
|
||||
let idx = fx.open();
|
||||
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()], "persisted by absolute path");
|
||||
idx.remove_recent(&scratch);
|
||||
assert_eq!(idx.recent_files(), vec![app]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_skips_unchanged_files_on_reopen() {
|
||||
let fx = sample();
|
||||
@@ -348,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"]);
|
||||
|
||||
@@ -359,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");
|
||||
@@ -386,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();
|
||||
@@ -834,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]
|
||||
@@ -851,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]
|
||||
@@ -881,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]
|
||||
@@ -919,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");
|
||||
@@ -946,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,
|
||||
@@ -959,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]
|
||||
|
||||
@@ -591,7 +591,7 @@ impl Shared {
|
||||
let update_elapsed = update_started.elapsed();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Some(store) = &self.store {
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
|
||||
let d = self.data.read();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
|
||||
@@ -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() {
|
||||
@@ -976,7 +976,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
if save_recent && let Some(store) = &self.store {
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
|
||||
if let Err(e) = store.save_recent(&rels) {
|
||||
tracing::warn!("index cache: saving recent files failed: {e}");
|
||||
}
|
||||
|
||||
@@ -407,18 +407,14 @@ impl Peer {
|
||||
let resolved = resolve_spawn_program(command, env);
|
||||
let mut cmd = tokio::process::Command::new(&resolved);
|
||||
// The working directory first: it picks the project's environment.
|
||||
cmd.current_dir(cwd);
|
||||
cmd.current_dir(cwd)
|
||||
.envs(ide_core::process::shell_env_in(cwd))
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
// Wrappers (`npx`, `codex.cmd`, launcher scripts) start the real server as a child:
|
||||
// stopping the connection stops the whole tree.
|
||||
ide_core::process::own_group(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.envs(ide_core::process::shell_env_in(cwd))
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
let mut child = cmd.spawn()?;
|
||||
let stdin = child.stdin.take().ok_or_else(|| std::io::Error::other("child stdin unavailable"))?;
|
||||
let stdout = child.stdout.take().ok_or_else(|| std::io::Error::other("child stdout unavailable"))?;
|
||||
|
||||
@@ -23,6 +23,7 @@ pub(crate) mod configuration;
|
||||
mod extract_interface;
|
||||
mod formatter;
|
||||
mod generated;
|
||||
pub(crate) use generated::is_processor_output;
|
||||
mod hierarchy;
|
||||
pub(crate) mod jvm_inspect;
|
||||
mod move_refactoring;
|
||||
|
||||
@@ -25,6 +25,18 @@ pub(crate) struct GeneratedScan {
|
||||
pub roots: Vec<GeneratedRoot>,
|
||||
}
|
||||
|
||||
/// Whether `path` is in (or is) an annotation-processor output folder:
|
||||
/// `generated-sources/annotations` or `generated-test-sources/test-annotations`. jdtls
|
||||
/// runs the processors itself and writes there; javac (a Maven build) writes the same
|
||||
/// files, and jdtls must not take those as edits (#4128).
|
||||
pub(crate) fn is_processor_output(path: &Path) -> bool {
|
||||
let parts: Vec<_> = path.components().map(|c| c.as_os_str()).collect();
|
||||
parts.windows(2).any(|w| {
|
||||
(w[0] == "generated-sources" && w[1] == "annotations")
|
||||
|| (w[0] == "generated-test-sources" && w[1] == "test-annotations")
|
||||
})
|
||||
}
|
||||
|
||||
/// Generated Java source folders under `root` (a reactor or one module).
|
||||
pub(crate) fn scan(root: &Path) -> GeneratedScan {
|
||||
let mut modules = Vec::new();
|
||||
@@ -260,6 +272,20 @@ fn plugins_removed(build: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognizes_annotation_processor_output() {
|
||||
for (path, expected) in [
|
||||
("/p/m/target/generated-sources/annotations/com/x/FooMappingImpl.java", true),
|
||||
("/p/m/target/generated-sources/annotations", true),
|
||||
("/p/m/build-out/generated-test-sources/test-annotations/com/x/T.java", true),
|
||||
("/p/m/target/generated-sources/protobuf/java/com/x/Hello.java", false),
|
||||
("/p/m/src/main/java/annotations/Foo.java", false),
|
||||
("/p/m/target/classes/com/x/FooMappingImpl.class", false),
|
||||
] {
|
||||
assert_eq!(is_processor_output(Path::new(path)), expected, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
|
||||
@@ -160,12 +160,13 @@ const DEAD_SHIM_MESSAGES: &[&str] =
|
||||
/// server that dies like that on every start is missing (an install hint), not crashing.
|
||||
/// Anything but a clear "not installed" answer from the shim counts as working.
|
||||
fn reject_dead_shim(binary: PathBuf, search: &OsStr, root: &Path) -> Option<PathBuf> {
|
||||
if !binary.parent().is_some_and(|d| d.file_name().is_some_and(|n| n == "shims")) {
|
||||
if binary.parent().and_then(Path::file_name) != Some(OsStr::new("shims")) {
|
||||
return Some(binary);
|
||||
}
|
||||
let Ok(mut child) = ide_core::process::prepare(std::process::Command::new(&binary).current_dir(root))
|
||||
let mut cmd = std::process::Command::new(&binary);
|
||||
cmd.current_dir(root).env("PATH", search);
|
||||
let Ok(mut child) = ide_core::process::prepare(&mut cmd)
|
||||
.arg("--version")
|
||||
.env("PATH", search)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
|
||||
@@ -3057,7 +3057,12 @@ impl LspManager {
|
||||
for s in servers {
|
||||
let Some(run) = s.running() else { continue };
|
||||
let open = open.get(&(s.id, run.generation)).filter(|_| run.caps.read().sync != SyncKind::None);
|
||||
// jdtls owns its annotation-processor output; javac's copy of those files is not an edit.
|
||||
let jdtls = s.name == "jdtls";
|
||||
let send = |p: &PathBuf, change: Change| {
|
||||
if jdtls && jdtls::is_processor_output(p) {
|
||||
return false;
|
||||
}
|
||||
change == Change::Deleted
|
||||
|| !open
|
||||
.is_some_and(|paths| paths.contains(p) || canonical.get(p).is_some_and(|c| paths.contains(c)))
|
||||
|
||||
@@ -94,10 +94,9 @@ pub(crate) fn connect_or_start(
|
||||
let args = substitute_args(&config.args, port, root);
|
||||
|
||||
let mut cmd = tokio::process::Command::new(binary);
|
||||
cmd.current_dir(root);
|
||||
cmd.current_dir(root).envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(&args)
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
|
||||
@@ -991,6 +991,33 @@ async fn files_changed_on_disk_reach_the_servers_of_their_language() {
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// jdtls runs the annotation processors itself and writes their output; a Maven build's
|
||||
/// copy of those files must not reach it as an edit, or jdtls recompiles javac's copy and
|
||||
/// overwrites its classes with broken ones (#4128).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn jdtls_does_not_hear_of_annotation_processor_output() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let (doc, _) = h.open("Open.java", "class Open {}");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let source = h.root.join("m/src/main/java/com/x/FooMapping.java");
|
||||
let generated = h.root.join("m/target/generated-sources/annotations/com/x/FooMappingImpl.java");
|
||||
let test_generated = h.root.join("m/target/generated-test-sources/test-annotations/com/x/T.java");
|
||||
h.mgr.watched_files_changed(
|
||||
&[test_generated],
|
||||
&[generated.clone(), source.clone()],
|
||||
std::slice::from_ref(&generated),
|
||||
&[h.root.join("m/target/generated-sources/annotations")],
|
||||
);
|
||||
eventually(|| !s.notified("workspace/didChangeWatchedFiles").is_empty()).await;
|
||||
h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.unwrap();
|
||||
assert_eq!(
|
||||
s.notified("workspace/didChangeWatchedFiles"),
|
||||
vec![json!({ "changes": [{ "uri": uri_of(&source), "type": 2 }] })]
|
||||
);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// An external change to a document open on the server's current instance reaches it only
|
||||
/// through the reload's `didChange`: a watched-file change for it too would make a server
|
||||
/// that re-reads the file on one (csharp-ls) apply the reload and then the diff computed
|
||||
|
||||
@@ -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")]
|
||||
@@ -250,6 +266,9 @@ pub struct DocumentTextChange {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocumentChanged {
|
||||
pub path: String,
|
||||
/// The open project `path` is relative to, set when the event is handed to a plugin
|
||||
/// (the editor posts the absolute path and `null`).
|
||||
pub project: Option<String>,
|
||||
pub base_version: u64,
|
||||
pub version: u64,
|
||||
pub changes: Vec<DocumentTextChange>,
|
||||
|
||||
@@ -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 @@
|
||||
c10d6f373bd3a701e201350d0272a211da72b23cef010144760db5bae44e2c11
|
||||
36b8ec8be8a65e60d601cd53e9ae0e8ab2865cb69de9b83ca31a9cb277aa0801
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
cd7a14b6d4464a559c197ba7fcba30fb045a8927c074fd0c310bec6039af0e0f
|
||||
631e3140cbd600a3e9af8ee1871e4461fc92fb7e492226507ed2089e5ee6d411
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
017cb719d8c3a226cb6178d75da7ae0396b2d78799658ef560f729e8e06f36e3
|
||||
ac15b6576fb3536d92d388a9a35775cfa380ad7c8b17fc8375ac403a32cc6b5e
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
93a9660a0941f2f57d11ea7ae331bd6d209ddcb134729ee88ec2fd96e978e631
|
||||
90d0d2643fb70422ac4f8cccd1d74bda4dfe89b4b2e9d28cc5136e4d5b2969f1
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
6a0008339af0935c7c0128d23bf3e885a642c335ad57097cffb3f000766aba33
|
||||
a8639ee0478bad01370c9117b02ba791d7283e5728c982f7dc6a66e540b06781
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
09369df431bb6922463a242484eb82325ce8af287654af97a99eefb3884115a5
|
||||
a3f38583f118bf8ae4c85994293b77fec599cef6a4e15509f94fb3c1cc4a69e2
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
897898835f2f42763da34dad29b8f926b230b33f506830e4118e6c5914720bd4
|
||||
b4629333f12d2b227c9da8411f7a11a5fe832ce15e93d7c9a33644b5d022d50f
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
b56b918d1ff51c902dc956a7da944163194fcc93ba5bcf8baafa44fc2b6b039b
|
||||
d4914c689dacb014dcc9af6952a8620f32ed0d13e43e458de3f23d49311467f2
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
ec2f6463d1ce5d70ad7331ae51bca3c8205b55f1f9e5abfe2218d53be2b61437
|
||||
9547bea771af3ea663455282a1fc4f5d0ed95ea4a3c794b98106dc54744d3717
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
8a25727e09b96b35bc90f906215e13d29697b3792ed81f7f80024299e8b23d44
|
||||
d1789382c8508b18e243b7812678a2ad98187f289a818a1935bc63e771ba8d26
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
33d331d6ab59aa44f9884504ecc77a474e99c7223253735983c327bee6e75984
|
||||
a3980ccb70b911f218d0809985531c133861732d4ed04302896ce79c473f358f
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
b804f22b06f924aebce86f8bc2c24b5306913f2d2a4a0167af10ce86c8f606db
|
||||
297774561d9383cf5c364483bca25810cd5271f4e5081b53bd6d6cb06224d200
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
27e24e96578471e51dace84968daa6ee189aae0d63d27f3054bf4f3a0841fe0c
|
||||
c5005462f40a2a1e384f87c6ca3d2651cc5bd1d75148dd6f16c904c15d622be7
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
283320b057d39decafce4f86e09ace4df46ef2f31524b6cac0af22bd62795b0c
|
||||
b89751bbab2ab1f1cb27b22c36ede99dfc090d78d03bd0325aaa64b0d08deacf
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
dff4f3571bf72eedfbe2e0e2d6b8908e703e890639fb1b854eb4f35226ddbc98
|
||||
e45d268957df9650d2766206638a485bd44878fd5cf31f96733b23ed25e990dc
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
f5d7f62056547beffaadf68a04e8393ee29d73d57501d9f8bb39e902e9d9bf61
|
||||
b110ed23919ae6c7d35c0cddb690731470280da4a2c97c6723baca0976990e2f
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
8ea7d2a041efe6bcabe8f9bb58b216fe583a7ad39207f0f10b4bf423facc56e7
|
||||
5dc1e01c268c7a755346bb9459600a5e6b605a60b0ce9cd62132dbeb6656dbb1
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
3b5b541b94b674762d6c0494bb5e26bbc871460767015a669ecd2771dc063b8a
|
||||
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 @@
|
||||
64411ddd70ae2906710d03c90add26727aa319db38c5bd23971eb442943154c5
|
||||
8b1eb9f66077c8bbccb4ac39bbee1d8474846341260f4b2c4391741292ab268e
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
ff7468eabf0b09be01afda83ede9d8b540d17cbccb414e1972899bb851c19d84
|
||||
834b204b6417860ccc9c0dfc4ab8ee5c2fda2a57cb452d34198dbbdebc61d49c
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
b24fb8d5161006104698fb07a43432601b4f16fdc4a34cc70058cbef7e973066
|
||||
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 @@
|
||||
8ded9b882110bc6b1235b14797128d5999f20079178a6134f172f64f77922985
|
||||
6effad574d5bee69cabd68503b1f870118afbcd3260d3d49472b15b7140bfc40
|
||||
@@ -33,6 +33,10 @@ title = "off"
|
||||
id = "document"
|
||||
title = "document"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "document-project"
|
||||
title = "document-project"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "count"
|
||||
title = "count"
|
||||
@@ -33,6 +33,7 @@ impl Plugin for Fixture {
|
||||
}
|
||||
"count" => Ok(host::storage::get("count")?),
|
||||
"document" => Ok(host::storage::get("document")?),
|
||||
"document-project" => Ok(host::storage::get("document-project")?),
|
||||
_ => Err(Error::NotFound(id.into())),
|
||||
}
|
||||
}
|
||||
@@ -42,6 +43,7 @@ impl Plugin for Fixture {
|
||||
for event in events {
|
||||
if let Event::DocumentChanged(change) = event {
|
||||
host::storage::set("document", &change.path).unwrap();
|
||||
host::storage::set("document-project", change.project.as_deref().unwrap_or_default()).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
c38f6ca9e44f0a0674b9186ef105e73e0c66a914de92a1aec97b5985f31fc29a
|
||||
04b41e556a8a2984f367cddec6cd7077e6990275313c781fe58a6723b2321c8a
|
||||
Binary file not shown.
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user