fix(search): read * in Go to File queries as a wildcard (#8329)

Typing * in Go to File or Search Everywhere (User*Service, *Account*) found no files: the file index matches the query as a fuzzy subsequence but matched the * itself as a literal character. When the query as typed finds nothing, the Files search now runs again without its * wildcards (unless nothing but wildcards, a root prefix or a line suffix would be left), and a file's weight uses the same fallback so wildcard matches rank like the bare query. A file whose name really contains * is still found first.

Closes #8316

Co-authored-by: audichuang <[email protected]>
Цей коміт міститься в:
audichuang authored and GitHub committed 2026-12-06 21:55:13 +08:00
1 джерело d7a7dde9f3
коміт da97f50866
4 files changed
+132 -15

No files matched your search

+63
Переглянути файл
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import type { FileMatches, SearchQuery } from "@/platform/ipc";
import { SeController, type SeDeps, type SeSnapshot } from "../everywhere/controller";
import { buildRows } from "../everywhere/model";
import type { ResolvedFilter } from "../everywhere/filters";
function deferred<T>() {
let resolve!: (v: T) => void;
@@ -180,6 +181,68 @@ describe("SeController", () => {
).not.toContain("f:/data/scratches/scratch_3.md");
});
it("reads * in a Files query as a wildcard when the query as typed finds nothing", async () => {
const index: Record<string, string[]> = {
"User*Service": ["src/User*Service.kt"],
UserService: ["src/User*Service.kt", "src/UserService.java"],
"foo*.txt": [],
"foo.txt": ["foo.txt"],
"*Account*": [],
Account: ["src/UserAccountService.java"],
};
const findFiles = vi.fn(async (q: string) => (index[q] ?? []).map(fm));
const { c, last } = setup({
findFiles,
outsideFiles: async () => [{ path: "/data/scratches/foo*.txt", relPath: "Scratches/foo*.txt" }],
});
const files = () =>
last()
.sections.get("files")!
.items.map((i) => i.key);
const run = async (query: string, filter?: ResolvedFilter) => {
c.run({ query, tab: "files", includeNonProject: false, filter, extra: {} });
await flush();
await flush();
};
await run("*Account*");
expect(files()).toEqual(["f:/p/src/UserAccountService.java"]);
await run("User*Service");
expect(files()).toEqual(["f:/p/src/User*Service.kt"]);
// The match as typed is filtered out: what is shown decides, not what the index found.
await run("User*Service", {
excludedLanguages: ["kotlin"],
languageOf: (p) => (p.endsWith(".kt") ? "kotlin" : "java"),
});
expect(files()).toEqual(["f:/p/src/UserService.java"]);
// A scratch file named with a `*` keeps the project's `foo.txt` out.
await run("foo*.txt");
expect(files()).toEqual(["f:/data/scratches/foo*.txt"]);
// Nothing but wildcards stays a query that finds nothing.
findFiles.mockClear();
await run("./*");
expect(findFiles.mock.calls.map(([q]) => q)).toEqual(["./*"]);
});
it("still searches without the * when another section shows more meanwhile", async () => {
const typed = deferred<ReturnType<typeof fm>[]>();
const findFiles = vi.fn(async (q: string) =>
q === "Account" ? [fm("src/UserAccountService.java")] : typed.promise,
);
const { c, last } = setup({ findFiles });
c.run({ query: "*Account*", tab: "all", includeNonProject: false, extra: {} });
await flush();
c.run({ query: "*Account*", tab: "all", includeNonProject: false, extra: { text: 50 } });
typed.resolve([]);
await flush();
await flush();
expect(
last()
.sections.get("files")!
.items.map((i) => i.key),
).toEqual(["f:/p/src/UserAccountService.java"]);
});
// #4079 follow-up: a plain Windows absolute path names an indexed file.
it("searches a pasted Windows absolute path as its project-relative path", async () => {
const findFiles = vi.fn(async () => [fm("pkg/service/Config.go")]);
+23
Переглянути файл
@@ -5,6 +5,9 @@ import type { SymbolMatch, WorkspaceSymbol } from "@/platform/ipc";
import {
buildRows,
fileItem,
itemWeight,
TEXT_WEIGHT,
withoutWildcards,
matchActions,
matchOutsideFiles,
mergeSymbols,
@@ -238,6 +241,26 @@ describe("items and rows", () => {
expect(matchOutsideFiles(files, "bit.matcher")).toEqual([]);
});
it("itemWeight weighs a file as if a * in the query were not there", () => {
const f = fileItem({ path: "/p/src/UserService.java", relPath: "src/UserService.java", indices: [] }, null, null);
expect(itemWeight(f, "User*Service")).toBe(itemWeight(f, "UserService"));
});
it("itemWeight prefers the query as typed, on the path too, to the one without *", () => {
const f = fileItem({ path: "/p/src/foo-bar*/foo.ts", relPath: "src/foo-bar*/foo.ts", indices: [] }, null, null);
// `foo*` matches the path as typed; the name `foo` without the `*` would outrank text hits.
expect(itemWeight(f, "foo*")).toBeLessThan(TEXT_WEIGHT);
});
it("withoutWildcards skips a query the index would read as empty", () => {
expect(withoutWildcards("User*Service")).toBe("UserService");
expect(withoutWildcards("UserService")).toBeNull();
for (const q of ["*", "./*", "/*", "*:0", "* :12:3"]) expect(withoutWildcards(q), q).toBeNull();
expect(withoutWildcards("c:/proj*ect", "C:/project")).toBeNull();
expect(withoutWildcards("c:/proj*ect/", "C:\\project\\")).toBeNull();
expect(withoutWildcards("C:/project/src/*.kt", "C:/project")).toBe("C:/project/src/.kt");
});
it("fileItem splits name and directory highlights", () => {
const f = fileItem(
{ path: "/p/src/orders/OrderController.kt", relPath: "src/orders/OrderController.kt", indices: [4, 11, 12, 16] },
+19 -13
Переглянути файл
@@ -36,6 +36,7 @@ import {
sectionsFor,
splitSymbolQuery,
textItems,
withoutWildcards,
type OutsideFile,
type SeItem,
type SeTab,
@@ -336,19 +337,24 @@ export class SeController {
// Directories rank with the files (equal scores: the file first); a file type filter
// and a `File.kt:42` query ask for files only.
const withDirs = !!this.deps.findDirs && !!text && !filter && q.line === null;
const [indexed, dirs, outside] = await Promise.all([
this.deps.findFiles(text, want),
withDirs ? this.deps.findDirs!(text, want).catch(() => []) : [],
text && this.deps.outsideFiles ? this.deps.outsideFiles().catch(() => []) : [],
]);
const fetched = outside.length ? [...indexed, ...matchOutsideFiles(outside, text)] : indexed;
const merged =
dirs.length || outside.length
? [...fetched.map((m) => ({ m, folder: false })), ...dirs.map((m) => ({ m, folder: true }))].sort(
(a, b) => b.m.score - a.m.score || Number(a.folder) - Number(b.folder),
)
: fetched.map((m) => ({ m, folder: false }));
const matches = keep ? merged.filter(({ m }) => keep(m.path)) : merged;
const search = async (query: string) => {
const [indexed, dirs, outside] = await Promise.all([
this.deps.findFiles(query, want),
withDirs ? this.deps.findDirs!(query, want).catch(() => []) : [],
query && this.deps.outsideFiles ? this.deps.outsideFiles().catch(() => []) : [],
]);
const fetched = outside.length ? [...indexed, ...matchOutsideFiles(outside, query)] : indexed;
const merged =
dirs.length || outside.length
? [...fetched.map((m) => ({ m, folder: false })), ...dirs.map((m) => ({ m, folder: true }))].sort(
(a, b) => b.m.score - a.m.score || Number(a.folder) - Number(b.folder),
)
: fetched.map((m) => ({ m, folder: false }));
return keep ? merged.filter(({ m }) => keep(m.path)) : merged;
};
let matches = await search(text);
const bare = matches.length ? null : withoutWildcards(text, this.deps.root());
if (bare !== null && this.isLive(id, gen)) matches = await search(bare);
this.set(
id,
gen,
+27 -2
Переглянути файл
@@ -505,12 +505,37 @@ const MIXED: readonly SectionId[] = ["classes", "files", "symbols", "endpoints",
*/
export const TEXT_WEIGHT = 350;
/**
* A Files query without IDEA's `*` wildcard, when it has one and a name is left to search for.
* File search matches a subsequence already, so `*` needs no character of its own; the query as
* typed is searched first, so a name that really contains `*` is still found.
*/
export function withoutWildcards(query: string, root?: string | null): string | null {
if (!query.includes("*")) return null;
const q = query.replaceAll("*", "");
// What the index would search for (`normalize_file_query`): an empty query lists recent files instead.
let rest = q.replace(/\s+/g, "").replace(/(:\d+)+$/, "");
// A drive-letter root compares like Windows, where case does not matter.
const base = root?.replace(/\\/g, "/").replace(/\/+$/, "");
if (base && rest.toLowerCase().startsWith(base.toLowerCase())) rest = rest.slice(base.length);
return rest.replace(/^(\.?\/)+/, "") ? q : null;
}
/** Comparable match degree of an item's name against the query (IDEA's `MatchingDegree`). */
export function itemWeight(item: SeItem, query: string): number {
const name = (text: string) => matchText(text, query)?.score;
switch (item.kind) {
case "file":
return name(item.name) ?? (name(item.rel) ?? 0) - 200;
case "file": {
// As file search does: the query as typed, else without its `*` wildcards.
const weigh = (q: string) => {
const byName = matchText(item.name, q)?.score;
if (byName !== undefined) return byName;
const byPath = matchText(item.rel, q)?.score;
return byPath === undefined ? undefined : byPath - 200;
};
const bare = withoutWildcards(query);
return weigh(query) ?? (bare === null ? undefined : weigh(bare)) ?? -200;
}
case "symbol":
if (item.score !== undefined) return item.score;
return name(item.name) ?? (item.container ? name(`${item.container}.${item.name}`) : undefined) ?? 0;