mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
fix(editor): refresh usage counts only when a source file changed (#5242)
The usages code lens re-asked the language server for every visible declaration on every fsChanged event, even ones carrying only images or logs. It now recounts only when a changed path can be a file a language server analyses (by the language registry and Settings > File Types), and still recounts when in doubt: unloaded languages or paths without an extension. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com>
This commit is contained in:
@@ -25,6 +25,7 @@ import { languages as languageData } from "@codemirror/language-data";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
import type { BracketSyntax } from "./rainbowBrackets";
|
||||
import { _languageMode, editorsFor } from "@/editor/api";
|
||||
import { wildcardMatch } from "@/platform/fileTypes";
|
||||
import { JS_TAGS } from "./jsTags";
|
||||
import { docCommentTags } from "./docCommentTags";
|
||||
import type { FencedCodeMode } from "./markdown";
|
||||
@@ -97,6 +98,45 @@ export function uiModeForPath(path: string): string | null | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let namesOf: {
|
||||
infos: Map<string, LanguageInfo>;
|
||||
byExtension: Map<string, LanguageInfo[]>;
|
||||
byName: Map<string, LanguageInfo[]>;
|
||||
patterns: Array<{ pattern: string; info: LanguageInfo }>;
|
||||
} | null = null;
|
||||
|
||||
/**
|
||||
* The backend languages whose definition claims `path`'s file name (an `extension`, longest first, or
|
||||
* a `filenames` entry); empty when none does, `undefined` while the languages are not loaded. Settings
|
||||
* › File Types and the file's first line are not consulted.
|
||||
*/
|
||||
export function languagesForPath(path: string): readonly LanguageInfo[] | undefined {
|
||||
if (!infos) return undefined;
|
||||
if (namesOf?.infos !== infos) {
|
||||
namesOf = { infos, byExtension: new Map(), byName: new Map(), patterns: [] };
|
||||
const add = (m: Map<string, LanguageInfo[]>, key: string, info: LanguageInfo) =>
|
||||
m.set(key, [...(m.get(key) ?? []), info]);
|
||||
for (const info of infos.values()) {
|
||||
for (const ext of info.extensions) add(namesOf.byExtension, ext.toLowerCase(), info);
|
||||
for (const name of info.filenames ?? []) {
|
||||
if (/[*?]/.test(name)) namesOf.patterns.push({ pattern: name.toLowerCase(), info });
|
||||
else add(namesOf.byName, name.toLowerCase(), info);
|
||||
}
|
||||
}
|
||||
}
|
||||
const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
|
||||
const found = new Set(namesOf.byName.get(name));
|
||||
for (const { pattern, info } of namesOf.patterns) if (wildcardMatch(pattern, name)) found.add(info);
|
||||
for (let rest = name, dot = rest.indexOf("."); dot >= 0; dot = rest.indexOf(".")) {
|
||||
rest = rest.slice(dot + 1);
|
||||
const claimed = namesOf.byExtension.get(rest);
|
||||
if (!claimed) continue;
|
||||
for (const info of claimed) found.add(info);
|
||||
break;
|
||||
}
|
||||
return [...found];
|
||||
}
|
||||
|
||||
const supports = new Map<string, Promise<LanguageSupport | null>>();
|
||||
|
||||
/** Frontend modes that extend or replace the bundled parsers. */
|
||||
|
||||
@@ -37,6 +37,7 @@ const { lspDoc } = await import("./lsp");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { emitLocalIdeEvent } = await import("@/platform/ipc");
|
||||
const { useProjectRoots } = await import("@/platform/projectRoots");
|
||||
const { _resetLanguages, loadLanguageInfos } = await import("@/editor/core/cm/languages");
|
||||
|
||||
const ctx = { doc: 7, path: "/p/a.rs", language: "rust", uiMode: "Rust", readOnly: false };
|
||||
const views: EditorView[] = [];
|
||||
@@ -81,6 +82,7 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
views.splice(0).forEach((v) => v.destroy());
|
||||
_resetLanguages();
|
||||
useProject.setState({ settings: null });
|
||||
vi.useRealTimers();
|
||||
});
|
||||
@@ -488,3 +490,86 @@ describe("recounting when the project's documents change", () => {
|
||||
expect(titles(view)).toEqual(["4 usages"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("file changes on disk", () => {
|
||||
const language = (id: string, extensions: string[], languageServers: string[], filenames: string[] = []) =>
|
||||
({ id, name: id, extensions, filenames, languageServers, uiMode: null }) as never;
|
||||
const fsChanged = (modified: string[], ignoreRules: string[] = []) =>
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified, removed: [], ignoreRules });
|
||||
|
||||
async function settledEditors(views: number) {
|
||||
await loadLanguageInfos({
|
||||
languages: async () => [
|
||||
language("rust", ["rs"], ["rust-analyzer"]),
|
||||
language("log", ["log"], []),
|
||||
language("dockerfile", [], ["docker-langserver"], ["Dockerfile.*"]),
|
||||
],
|
||||
} as never);
|
||||
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 60 }, (_, i) => item(`f${i}`, "function", i))));
|
||||
for (let i = 0; i < views; i++) editor(60);
|
||||
await settle();
|
||||
const first = ipc.lspReferences.mock.calls.length;
|
||||
expect(first).toBe(40 * views);
|
||||
return first;
|
||||
}
|
||||
|
||||
it.each([1, 4])("asks no new counts for events that no source file caused (%i views)", async (n) => {
|
||||
const first = await settledEditors(n);
|
||||
for (let i = 0; i < 10; i++) {
|
||||
fsChanged(["/p/logo.png"]);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
}
|
||||
fsChanged([], ["/p"]);
|
||||
fsChanged(["/p/debug.log", "/p/Cargo.lock"]);
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [] });
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(first);
|
||||
});
|
||||
|
||||
it("recounts once when a source file is among the changed paths", async () => {
|
||||
const first = await settledEditors(1);
|
||||
for (let i = 0; i < 5; i++) fsChanged(["/p/logo.png", "/p/b.rs", "/p/debug.log"]);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a created source file", { created: ["/p/new.rs"], modified: [], removed: [] }],
|
||||
["a removed source file", { created: [], modified: [], removed: ["/p/old.RS"] }],
|
||||
["a file the registry matches by name", { created: [], modified: ["/p/Dockerfile.dev"], removed: [] }],
|
||||
[
|
||||
"a path without an extension (a folder, or a script found by its first line)",
|
||||
{ created: [], modified: [], removed: ["/p/src/gen"] },
|
||||
],
|
||||
])("recounts for %s", async (_, paths) => {
|
||||
const first = await settledEditors(1);
|
||||
emitLocalIdeEvent({ type: "fsChanged", ...paths });
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
|
||||
});
|
||||
|
||||
it("recounts for a file Settings › File Types assigns to a language with a server", async () => {
|
||||
useProject.setState({
|
||||
settings: {
|
||||
editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false } },
|
||||
files: { fileTypes: { rust: { patterns: ["*.tpl"] } }, fileTypeOverrides: { "/p/x.log": "rust" } },
|
||||
} as never,
|
||||
});
|
||||
const first = await settledEditors(1);
|
||||
fsChanged(["/p/page.tpl"]);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
|
||||
fsChanged(["/p/x.log"]);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(3 * first);
|
||||
});
|
||||
|
||||
it("recounts for any path while the languages are not loaded", async () => {
|
||||
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 60 }, (_, i) => item(`f${i}`, "function", i))));
|
||||
editor(60);
|
||||
await settle();
|
||||
fsChanged(["/p/logo.png"]);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(80);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,6 +24,8 @@ import { featureBackoff, onLspRefresh, onServerSettled } from "./availability";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { languageInfo, languagesForPath } from "@/editor/core/cm/languages";
|
||||
import { overrideKey, userFileType, validateFileTypeOverrides, validateFileTypes } from "@/platform/fileTypes";
|
||||
|
||||
const LENS_KINDS = new Set<SymbolKind>([
|
||||
"class",
|
||||
@@ -50,6 +52,32 @@ const MARGIN_LINES = 10;
|
||||
const INCOMPLETE_RETRIES = 3;
|
||||
const usagesBackoff = featureBackoff();
|
||||
|
||||
/**
|
||||
* Whether a change on disk can alter a reference count: some changed path is a file a language
|
||||
* server analyses. A path no language claims counts too when it has no extension (a folder, or a
|
||||
* script told by its first line), and so does any path while the languages are not loaded: a
|
||||
* missed recount leaves a stale number, an extra one only repeats a pass.
|
||||
*/
|
||||
function touchesSource(e: { created: string[]; modified: string[]; removed: string[] }): boolean {
|
||||
const { settings, project } = useProject.getState();
|
||||
const assoc = validateFileTypes(settings?.files?.fileTypes);
|
||||
const overrides = validateFileTypeOverrides(settings?.files?.fileTypeOverrides);
|
||||
const root = project?.root ?? null;
|
||||
const served = (l: { languageServers?: string[] }) => !!l.languageServers?.length;
|
||||
const isSource = (path: string) => {
|
||||
const name = path.slice(path.lastIndexOf("/") + 1);
|
||||
const assigned = overrides[overrideKey(path, root)] ?? userFileType(assoc, name);
|
||||
if (assigned) {
|
||||
const info = languageInfo(assigned);
|
||||
return !info || served(info);
|
||||
}
|
||||
const languages = languagesForPath(path);
|
||||
if (!languages) return true;
|
||||
return languages.length ? languages.some(served) : name.lastIndexOf(".") <= 0;
|
||||
};
|
||||
return e.created.some(isSource) || e.modified.some(isSource) || e.removed.some(isSource);
|
||||
}
|
||||
|
||||
export interface LensTarget {
|
||||
name: string;
|
||||
/** 0-based line / UTF-16 col of the identifier. */
|
||||
@@ -172,7 +200,9 @@ class UsagesLensPlugin {
|
||||
});
|
||||
const offBackend = [
|
||||
onIdeEvent("workspaceEditApplied", () => this.invalidate()),
|
||||
onIdeEvent("fsChanged", () => this.invalidate()),
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
if (touchesSource(e)) this.invalidate();
|
||||
}),
|
||||
onNavigationProvidersChanged(() => this.invalidate()),
|
||||
];
|
||||
this.offChanges = () => {
|
||||
|
||||
Reference in New Issue
Block a user