Skip to content

Commit 9399f16

Browse files
authored
feat(search): complete counts, linked paths and provider discovery (#126)
1 parent 6a2c082 commit 9399f16

18 files changed

Lines changed: 679 additions & 41 deletions

‎rust/contracts/rust-core-api.md‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,7 @@ or removing a command fails until the table changes in the same commit.
568568
| `workspace.configureIndexing` | Install a process-local, canonical-root indexing policy before workspace consumers run; returns a monotonic revision, effective directory reasons and Git failure state; see `rust/fixtures/workspace/indexing-policy-v1.json` |
569569
| `workspace.refreshIndexing` | Refresh external Git decisions for a live `root`, `ownerId`, `revision` lease without changing preferences or release tokens; returns lazy `IndexingStatus` |
570570
| `workspace.filterChanges` | Filter an array of workspace-relative paths, or `{ paths, hiddenFilePatterns }` whose `!` entries turn default exclusions off, against Core's default hidden folders and patterns, including the folders enabled plugins declare; preserve order, spelling, and the empty root path. Native event loss bypasses filtering. Hosts relativize to the most specific explicit watch root and retain explicitly watched files |
571-
| `workspace.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, symlinked, or nested-worktree paths are omitted, and each listing reports the nested worktrees it left out. Child directories have `children: []` only when a shallow probe proves them visibly empty; otherwise children remain omitted (unloaded), with no recursive tree allocation. Children list directories first, then names in IDEA's natural file-name order (digit runs compare by value, case-insensitive, `-` next to `_`; fixture `rust/fixtures/workspace/file-name-order-v1.json`) |
571+
| `workspace.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, external/cyclic symlink, or nested-worktree paths are omitted; workspace-internal aliases are browsable and each listing reports `linked: true` when reached through an alias, and each listing reports the nested worktrees it left out. Child directories have `children: []` only when a shallow probe proves them visibly empty; otherwise children remain omitted (unloaded), with no recursive tree allocation. Children list directories first, then names in IDEA's natural file-name order (digit runs compare by value, case-insensitive, `-` next to `_`; fixture `rust/fixtures/workspace/file-name-order-v1.json`) |
572572
| `workspace.orderEntries` | Order natively enumerated directory siblings |
573573
| `workspace.projectTree.rows` | Say which loaded project tree nodes show as rows, keep the selection on a row that shows, and find the row the top of the view was on, without reading the disk (from `lithe-project-tree`) |
574574
| `workspace.rowSelection.reduce` | Apply one plain, Cmd/Ctrl or Shift click, or the end of a batch, to the multi-selection of rows of workspace paths and return what a batch acts on (from `lithe-row-selection`) |
@@ -2332,7 +2332,41 @@ Without `projectPage`, its original capped literal-search response is unchanged.
23322332
Project pages use path/line continuation inside matching, including across pages
23332333
within one file; options and immutable `textOverrides` bind the cursor. There is
23342334
no 200-result total ceiling. Each page observes current files; edits before a
2335-
cursor require a fresh query.
2335+
cursor require a fresh query. Like Search Everywhere text queries, project pages
2336+
reuse ready content postings or search the names-only inventory directly; they
2337+
never synchronously build a full content index before returning the first page.
2338+
2339+
`workspace.search` with `countOnly: true` scans the same query, scope, decoding,
2340+
visibility and unsaved snapshots independently of the loaded page. It returns
2341+
`{ files, lines, occurrences, fileOccurrences }`: files with at least one content
2342+
match, matching lines, and every non-overlapping occurrence (including zero-width
2343+
regex matches). `countPaths` selects at most 200 loaded paths for per-file totals;
2344+
the map contains only selected matching paths, while the three totals cover the
2345+
entire query. No previews are retained or returned. The host publishes its first
2346+
page before starting this cancellable scan, labels counting/failure distinctly,
2347+
and discards totals when the query, snapshots or watched files change.
2348+
2349+
`workspace.search` with `languageSources` discovers relevant language providers
2350+
without opening documents. Each source has opaque `languageId`, optional
2351+
`fileExtensions` (with or without a dot) and `fileNames` (including project
2352+
markers). Core matches case-insensitively against the workspace name inventory
2353+
and returns sorted unique `{ languages }`. Sources are limited to 1024, each ID
2354+
to 256 bytes, each source to 1024 selectors and each selector to 1024 bytes.
2355+
The host reads enabled manifests, starts only relevant servers when symbol
2356+
search is requested, and queries their standard `workspace/symbol` capability
2357+
as readiness arrives. Core does not duplicate a language parser or semantic index.
2358+
2359+
Search, Search Everywhere and replacement accept query-local
2360+
`includeGenerated` and `followSymlinks`. Generated output declarations can be
2361+
included without overriding explicitly hidden names/globs or manual indexing
2362+
exclusions. Internal links retain lexical result paths; canonical targets must
2363+
stay inside the workspace and respect target exclusions and delegated roots.
2364+
Canonical ancestor checks stop cycles. External roots must be opened as workspace
2365+
roots rather than traversed implicitly. Link-aware indexes are rebuilt on native
2366+
file events and invalidated on saves, so a physical target change cannot leave
2367+
an alias stale. Replacement previews deduplicate canonical files to avoid writing
2368+
one file twice. Directory listings expose internal aliases and `linked`; hosts
2369+
refresh expanded linked listings when recursive physical-target events arrive.
23362370

23372371
Search and replacement accept `scopeExpression`: comma-separated relative paths,
23382372
include globs and `!`-prefixed exclude globs. `scopePaths` remains supported.

‎rust/crates/core/src/tests/project.rs‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2381,13 +2381,15 @@ fn file_encoding_options_are_optional_and_validated() {
23812381
serde_json::json!({"root": root, "path": "a.txt", "encoding": "ebcdic"}),
23822382
);
23832383
assert_eq!(unknown["error"]["code"], "invalid_request");
2384-
// Invalid bytes fail automatic detection but are repaired on an explicit reopen.
2385-
fs::write(root.join("bad.txt"), [0x41, 0xFF, 0xFE, 0x42, 0x81]).unwrap();
2384+
// Legacy bytes use the lossless Windows-1252 fallback; explicit UTF-8 repairs them.
2385+
fs::write(root.join("bad.txt"), b"caf\xE9").unwrap();
23862386
let auto = call(
23872387
"file.read",
23882388
serde_json::json!({"root": root, "path": "bad.txt"}),
23892389
);
2390-
assert_eq!(auto["error"]["code"], "parse_failed");
2390+
assert_eq!(auto["data"]["encoding"], "windows-1252", "{auto}");
2391+
assert_eq!(auto["data"]["text"], "café", "{auto}");
2392+
assert_eq!(auto["data"]["lossy"], false, "{auto}");
23912393
let lossy = call(
23922394
"file.read",
23932395
serde_json::json!({"root": root, "path": "bad.txt", "encoding": "utf-8"}),
@@ -2616,7 +2618,7 @@ fn search_reads_every_encoding_and_size_the_editor_opens() {
26162618
assert_eq!(search("binaryToken417", false), Vec::new());
26172619
assert_eq!(search("binary[T]oken417", true), Vec::new());
26182620

2619-
// Replacement writes UTF-8 back, so it must not offer the files that are not UTF-8.
2621+
// Replacement preserves the source encoding, so every searchable encoding is offered.
26202622
let replacement = run_project_command(
26212623
"workspace.replacePreview",
26222624
serde_json::json!({"root": root, "query": "Token417", "replacement": "Mark",
@@ -2629,10 +2631,17 @@ fn search_reads_every_encoding_and_size_the_editor_opens() {
26292631
.iter()
26302632
.map(|file| file["path"].as_str().expect("path should be text"))
26312633
.collect::<Vec<_>>();
2632-
assert!(replaced.contains(&"plain.txt"), "{replacement}");
2633-
for path in ["gbk.txt", "utf16-le.txt", "utf16-be.txt", "data.bin"] {
2634-
assert!(!replaced.contains(&path), "{path}: {replacement}");
2634+
for path in [
2635+
"plain.txt",
2636+
"gbk.txt",
2637+
"utf16-le.txt",
2638+
"utf16-be.txt",
2639+
"large.log",
2640+
] {
2641+
assert!(replaced.contains(&path), "{path}: {replacement}");
26352642
}
2643+
assert!(!replaced.contains(&"data.bin"), "{replacement}");
2644+
assert!(!replaced.contains(&"huge.log"), "{replacement}");
26362645
}
26372646

26382647
#[test]

‎rust/crates/project/src/contracts.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ pub struct DirectoryListingResponse {
4747
#[serde(rename_all = "camelCase")]
4848
/// One directory's children, each without its own children.
4949
pub struct DirectoryListing {
50+
/// This listing is reached through a workspace-internal alias and needs refresh on target events.
51+
pub linked: bool,
5052
/// Normalized workspace-relative path; empty for the root.
5153
pub path: String,
5254
/// Directories first, then case-insensitive names, as in snapshots.

‎rust/crates/project/src/files/matcher.rs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,40 @@ pub(crate) struct Matcher {
123123
}
124124

125125
impl Matcher {
126+
/// Counts occurrences without constructing replacement text.
127+
pub(crate) fn occurrence_count(&self, text: &str) -> usize {
128+
if let Some(regex) = &self.regex {
129+
regex.find_iter(text).count()
130+
} else {
131+
let haystack = if self.case_sensitive {
132+
std::borrow::Cow::Borrowed(text)
133+
} else {
134+
std::borrow::Cow::Owned(text.to_lowercase())
135+
};
136+
let needle = if self.case_sensitive {
137+
std::borrow::Cow::Borrowed(self.plain_query.as_str())
138+
} else {
139+
std::borrow::Cow::Owned(self.plain_query.to_lowercase())
140+
};
141+
if needle.is_empty() {
142+
return 0;
143+
}
144+
haystack
145+
.match_indices(needle.as_ref())
146+
.filter(|(start, matched)| {
147+
!self.whole_words
148+
|| (!haystack[..*start]
149+
.chars()
150+
.next_back()
151+
.is_some_and(is_word_character)
152+
&& !haystack[*start + matched.len()..]
153+
.chars()
154+
.next()
155+
.is_some_and(is_word_character))
156+
})
157+
.count()
158+
}
159+
}
126160
/// Projects original byte ranges into the editor's UTF-16 coordinate space.
127161
pub(crate) fn content_ranges(&self, text: &str) -> Vec<crate::contracts::SearchNameRange> {
128162
let ranges = if let Some(regex) = &self.regex {

‎rust/crates/project/src/files/paths.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,25 @@ pub(crate) fn safe_relative_path(root: &Path, value: &str) -> Result<PathBuf, Co
4343
Ok(canonical)
4444
}
4545

46+
/// Shares unsaved snapshots with internal aliases without copying their contents.
47+
pub(crate) fn canonical_text_overrides<'a>(
48+
root: &Path,
49+
overrides: impl IntoIterator<Item = (&'a String, &'a String)>,
50+
follow_links: bool,
51+
) -> HashMap<PathBuf, &'a str> {
52+
let mut result = HashMap::new();
53+
if follow_links {
54+
let mut paths: Vec<_> = overrides.into_iter().collect();
55+
paths.sort_by_key(|(path, _)| *path);
56+
for (path, text) in paths {
57+
if let Ok(canonical) = safe_relative_path(root, path) {
58+
result.entry(canonical).or_insert(text.as_str());
59+
}
60+
}
61+
}
62+
result
63+
}
64+
4665
pub(crate) fn writable_relative_path(root: &Path, value: &str) -> Result<PathBuf, CoreError> {
4766
let path = root.join(relative_request_path(value)?.as_ref());
4867
if let Some(parent) = path.parent() {

‎rust/crates/project/src/files/replace.rs‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,13 @@ pub fn replace_preview(
6767
request.hidden_file_patterns.clone(),
6868
)
6969
.with_workspace_roots(&root, &request.workspace_roots)
70-
.with_search_options(request.max_file_bytes, request.include_ignored)?;
71-
let shared_index = search_index::get_or_build(&root, &rules)?;
70+
.with_search_options(request.max_file_bytes, request.include_ignored)?
71+
.with_search_visibility(
72+
request.include_generated,
73+
request.follow_symlinks,
74+
&request.hidden_directory_names,
75+
);
76+
let shared_index = search_index::get_for_text(&root, &rules)?;
7277
let index = shared_index
7378
.read()
7479
.map_err(|_| CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned"))?;
@@ -78,7 +83,12 @@ pub fn replace_preview(
7883
request.whole_words,
7984
request.regular_expression,
8085
)?;
81-
let candidate_ids = index.candidate_ids(&query, request.regular_expression);
86+
let aliases = canonical_text_overrides(&root, &request.text_overrides, request.follow_symlinks);
87+
let candidate_ids = if aliases.is_empty() {
88+
index.candidate_ids(&query, request.regular_expression)
89+
} else {
90+
index.all_file_ids()
91+
};
8292
let candidate_set = candidate_ids.iter().copied().collect::<HashSet<_>>();
8393
let mut paths = if request.paths.is_empty() {
8494
candidate_ids
@@ -108,6 +118,7 @@ pub fn replace_preview(
108118
drop(index);
109119
let masks = parse_file_mask(&request.file_mask);
110120
let mut files = Vec::new();
121+
let mut canonical_files = HashSet::new();
111122
for path in paths {
112123
lithe_protocol::cancellation::check()?;
113124
let relative = safe_relative_path_string(&path)?;
@@ -120,6 +131,9 @@ pub fn replace_preview(
120131
let Ok(file) = safe_relative_path(&root, &relative) else {
121132
continue;
122133
};
134+
if !canonical_files.insert(file.clone()) {
135+
continue;
136+
}
123137
if rules.is_delegated(&file)
124138
|| indexing_policy
125139
.as_ref()
@@ -130,8 +144,13 @@ pub fn replace_preview(
130144
{
131145
continue;
132146
}
133-
let (text, source_identity) = if let Some(text) = request.text_overrides.get(&relative) {
134-
(text.clone(), None)
147+
let snapshot = request
148+
.text_overrides
149+
.get(&relative)
150+
.map(String::as_str)
151+
.or_else(|| aliases.get(&file).copied());
152+
let (text, source_identity) = if let Some(text) = snapshot {
153+
(text.to_owned(), None)
135154
} else {
136155
let Some(bytes) = read_searchable_bytes(&file, rules.max_file_bytes) else {
137156
continue;

‎rust/crates/project/src/files/requests.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,12 @@ pub struct DirectoryListingRequest {
4949
#[serde(rename_all = "camelCase")]
5050
/// Bounded file, content, and symbol search options.
5151
pub struct SearchRequest {
52+
/// Includes plugin-declared generated folders for this query, retaining manual exclusions.
53+
#[serde(default)]
54+
pub include_generated: bool,
55+
/// Follows only links whose canonical targets stay inside the workspace.
56+
#[serde(default)]
57+
pub follow_symlinks: bool,
5258
/// Comma-separated project paths and include/exclude globs; parsed only by Core.
5359
#[serde(default)]
5460
pub scope_expression: String,
@@ -190,6 +196,12 @@ pub struct SearchIndexStatusResponse {
190196
#[serde(rename_all = "camelCase")]
191197
/// Search and replacement options used to produce a non-mutating preview.
192198
pub struct ReplacementPreviewRequest {
199+
/// Uses the same request-local generated-folder visibility as search.
200+
#[serde(default)]
201+
pub include_generated: bool,
202+
/// Follows only workspace-internal links; previews deduplicate canonical files.
203+
#[serde(default)]
204+
pub follow_symlinks: bool,
193205
/// Same request-local path and glob expression used by content search.
194206
#[serde(default)]
195207
pub scope_expression: String,

0 commit comments

Comments
 (0)