fix(vcs): use symlink target history in the editor (#7891)

The repository scan skips symlinks, so a file opened through a file symlink or a symlinked directory whose target lies outside the registered Git roots had no Git Blame or change markers, even when Git tracked the target. Read-only editor commands (blame, line hunks) now use the target's repository, discovered with the restricted read policy and never registered for status or Commit; excluded mappings and a disabled Git integration are honoured. The editor probes once per open file whether the link has committed history: only then do Annotate and the markers apply, and ordinary files in projects without Git make no further backend calls on edits.

Co-authored-by: igallart <[email protected]>
Цей коміт міститься в:
Isaac Gallartтаigallart authored and GitHub committed 2026-12-04 18:57:51 +08:00
1 джерело 4eab243ef2
коміт 091dd85ef0
14 files changed
+531 -80

No files matched your search

+2
Переглянути файл
@@ -2762,6 +2762,8 @@ export const commands = {
vcsLfsStatus: (repo: string, request: RequestId) => typedError<LfsStatus, IdeError>(__TAURI_INVOKE("vcs_lfs_status", { repo, request })),
/** Gutter change markers for a file, computed against its current (unsaved) text. */
vcsLineHunks: (path: string) => typedError<LineHunk[], IdeError>(__TAURI_INVOKE("vcs_line_hunks", { path })),
/** Whether an editor file reached through a symlink has a tracked file at its target's HEAD. */
vcsLinkedFileHasHistory: (path: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("vcs_linked_file_has_history", { path })),
vcsLog: (repo: string | null, query: LogQuery) => typedError<Commit_Serialize[], IdeError>(__TAURI_INVOKE("vcs_log", { repo, query })),
vcsLogDetails: (repo: string | null, revision: string) => typedError<LogDetails, IdeError>(__TAURI_INVOKE("vcs_log_details", { repo, revision })),
vcsLogDetailsBatch: (repo: string | null, revisions: string[], request: RequestId) => typedError<LogDetails[], IdeError>(__TAURI_INVOKE("vcs_log_details_batch", { repo, revisions, request })),
+15 -1
Переглянути файл
@@ -3,7 +3,7 @@ import { getAction, isActionEnabled } from "@/platform/actions";
import { registerVcsActions } from "../actions";
import { useVcs } from "../store";
afterEach(() => useVcs.setState({ byPath: new Map() }));
afterEach(() => useVcs.setState({ byPath: new Map(), roots: [] }));
const status = (path: string, staged: string | null, unstaged: string | null) =>
[path, { path, relPath: path.slice(6), staged, unstaged, renamedFrom: null }] as const;
@@ -13,6 +13,7 @@ describe("Annotate with Git Blame", () => {
const unregister = registerVcsActions();
try {
useVcs.setState({
roots: ["/repo"],
byPath: new Map([
status("/repo/new.py", null, "untracked"),
status("/repo/ignored_test.py", null, "ignored"),
@@ -34,4 +35,17 @@ describe("Annotate with Git Blame", () => {
unregister();
}
});
it("does not offer annotation for files outside a registered root without confirmed history", () => {
const unregister = registerVcsActions();
try {
const path = "/repo/linked.txt";
useVcs.setState({ roots: ["/repo"], byPath: new Map([status(path, null, "untracked")]) as never });
const action = getAction("vcs.annotate")!;
expect(isActionEnabled(action, { vcsAvailable: true }, "/outside/notes.txt")).toBe(false);
expect(isActionEnabled(action, { projectOpen: true }, path)).toBe(false);
} finally {
unregister();
}
});
});
+105 -2
Переглянути файл
@@ -13,8 +13,14 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
calls.push(`base:${path}`);
return Promise.resolve({ status: "ok", data: [hunk] });
},
vcsLinkedFileHasHistory: (path: string) => {
calls.push(`history:${path}`);
return Promise.resolve({ status: "ok", data: path === "/p/linked/notes.txt" });
},
vcsStagingLineHunks: (path: string) => {
calls.push(`index:${path}`);
if (path === "/p/linked/notes.txt" || path === "/p/plain.txt")
return Promise.resolve({ status: "ok", data: null });
// A working copy has no index.
return Promise.resolve({ status: "error", error: { message: "not a git repository" } });
},
@@ -24,16 +30,113 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { getAction, isActionEnabled } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { _addEditor, _removeEditor, _setActiveEditor, documentSynced, type EditorDocContext } from "@/editor/api";
import { registerVcsActions } from "../actions";
import { changeMarkers, editorHunks } from "../gutter";
import { useVcs } from "../store";
afterEach(() => {
useVcs.setState({ available: false, roots: [], kinds: {} });
useProject.setState({ settings: null });
useVcs.setState({ available: false, roots: [], kinds: {}, byPath: new Map() });
useProject.setState({ project: null, settings: null });
vi.useRealTimers();
calls.length = 0;
});
function openEditor(path: string) {
const ctx = { path } as EditorDocContext;
const sync = vi.fn(async () => {});
const view = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "new\n", extensions: [changeMarkers(ctx), documentSynced.of(sync)] }),
});
const handle = { view, ctx };
_addEditor(handle);
_setActiveEditor(handle);
return {
view,
sync,
close() {
_removeEditor(handle);
view.destroy();
},
};
}
it("probes ordinary files in a non-VCS project once and does not request hunks on edits", async () => {
vi.useFakeTimers();
useProject.setState({ project: { root: "/p" } as never });
const path = "/p/plain.txt";
const editor = openEditor(path);
const unregister = registerVcsActions();
try {
await vi.advanceTimersByTimeAsync(40);
editor.view.dispatch({ changes: { from: 0, insert: "edit " } });
await vi.advanceTimersByTimeAsync(350);
expect(calls).toEqual([`history:${path}`]);
expect(editor.sync).not.toHaveBeenCalled();
expect(isActionEnabled(getAction("vcs.annotate")!, { projectOpen: true })).toBe(false);
} finally {
unregister();
editor.close();
}
});
it("keeps the staging gutter empty when an ordinary Git file has no index entry", async () => {
vi.useFakeTimers();
const settings = { vcs: { git: { stagingArea: true }, commit: { nonModal: true } } } as never;
useProject.setState({ project: { root: "/p", settings } as never, settings });
useVcs.setState({ available: true, roots: ["/p"] });
const path = "/p/plain.txt";
const { close, view } = openEditor(path);
try {
await vi.advanceTimersByTimeAsync(40);
view.dispatch({ changes: { from: 0, insert: "edit " } });
await vi.advanceTimersByTimeAsync(350);
expect(editorHunks(view.state)).toHaveLength(0);
expect(calls).toEqual([`index:${path}`, `history:${path}`, `index:${path}`]);
} finally {
close();
}
});
it.each([
{ available: false, roots: [] },
{ available: true, roots: ["/p"] },
])("shows linked-file changes against HEAD (registered roots: $roots)", async ({ available, roots }) => {
const settings = { vcs: { git: { stagingArea: true }, commit: { nonModal: true } } } as never;
useProject.setState({ project: { root: "/p", settings } as never, settings });
useVcs.setState({ available, roots });
const path = "/p/linked/notes.txt";
if (available)
useVcs.setState({
byPath: new Map([
[path, { path, relPath: "linked/notes.txt", staged: null, unstaged: "untracked", renamedFrom: null }],
]),
});
vi.useFakeTimers();
const { view, close } = openEditor(path);
const unregister = registerVcsActions();
try {
const action = getAction("vcs.annotate")!;
const context = { projectOpen: true, vcsAvailable: available };
expect(isActionEnabled(action, context, path)).toBe(false);
await vi.advanceTimersByTimeAsync(40);
expect(editorHunks(view.state)).toHaveLength(1);
expect(editorHunks(view.state)[0]?.staging).toBeUndefined();
expect(isActionEnabled(action, context, path)).toBe(true);
expect(isActionEnabled(action, context)).toBe(true);
expect(isActionEnabled(action, { ...context, vcsAvailable: false, gitDisabled: true }, path)).toBe(false);
view.dispatch({ changes: { from: 0, insert: "edit " } });
await vi.advanceTimersByTimeAsync(350);
expect(calls).toEqual([`history:${path}`, `base:${path}`, `base:${path}`]);
} finally {
unregister();
close();
}
});
describe("change markers of a working copy's file in a project with Git's staging area on", () => {
it("are read against its base, not Git's index (Review #2 P0 7)", async () => {
useProject.setState({ settings: { vcs: { git: { stagingArea: true }, commit: { nonModal: true } } } as never });
+22 -22
Переглянути файл
@@ -82,6 +82,7 @@ import {
editableHunk,
equivalentStagingHunk,
gotoChange,
hasLinkedHistory,
hunksInSelection,
rollbackSelectedLines,
updateStagedLines,
@@ -114,7 +115,17 @@ import {
} from "./gitMenuDialogs";
import { showNewWorktree } from "./NewWorktreeDialog";
import { OPEN_WORKTREE_REVIEW } from "./worktreeReviews";
import { currentRepo, currentRepoRoot, refreshNow, repoName, repoOf, rootOfKind, statusOf, useVcs } from "./store";
import {
currentRepo,
currentRepoRoot,
hasNoCommits,
refreshNow,
repoName,
repoOf,
rootOfKind,
statusOf,
useVcs,
} from "./store";
import {
bulkStagePaths,
canRestoreUnstaged,
@@ -167,18 +178,6 @@ function argPath(arg: unknown): string | undefined {
return undefined;
}
/** Whether Git has no commit of the file: unversioned, ignored, or added and not committed yet. */
function hasNoCommits(status: { staged: string | null; unstaged: string | null }): boolean {
return (
status.staged === "added" ||
// Subversion schedules an addition in the working copy (no staging area).
status.unstaged === "added" ||
status.unstaged === "untracked" ||
status.unstaged === "ignored" ||
status.staged === "ignored"
);
}
function argPaths(arg: unknown): string[] | undefined {
if (Array.isArray(arg)) return arg.filter((x): x is string => typeof x === "string");
const p = argPath(arg);
@@ -1101,7 +1100,7 @@ export function registerVcsActions(): () => void {
title: "Annotate with Git Blame",
category: "Git",
icon: "history",
when: VCS,
when: "vcsAvailable || (projectOpen && !gitDisabled)",
keywords: ["blame", "annotations"],
toggled: () => {
if (getContext().diffEditorFocus) {
@@ -1111,15 +1110,16 @@ export function registerVcsActions(): () => void {
const ed = activeEditor();
return !!ed && annotationsShown(ed.view);
},
// As in IDEA, a file Git has no commit of (unversioned, ignored, or added and not yet
// committed) has nothing to annotate; shown annotations can always be closed.
enabled: ({ arg, ctx }) => {
if (!argPath(arg) && ctx.diffEditorFocus) return !!focusedBlamePane();
const ed = activeEditor();
const path = argPath(arg) ?? ed?.ctx.path;
if (!path || (ed?.ctx.path === path && annotationsShown(ed.view))) return true;
const status = statusOf(path);
return !status || !hasNoCommits(status);
const target = argPath(arg);
if (!target && ctx.diffEditorFocus) return !!ctx.vcsAvailable && !!focusedBlamePane();
const active = activeEditor();
const path = target ?? active?.ctx.path;
if (!path) return false;
const editor = active?.ctx.path === path ? active : editorsFor(path)[0];
if (editor && (annotationsShown(editor.view) || (!ctx.gitDisabled && hasLinkedHistory(editor.view.state))))
return true;
return !!ctx.vcsAvailable && !!repoOf(path) && !hasNoCommits(statusOf(path));
},
run: ({ arg }) => annotate(arg),
},
+87 -36
Переглянути файл
@@ -9,6 +9,9 @@ import { EditorView, GutterMarker, ViewPlugin, type PluginValue, type ViewUpdate
import { foldState, foldedRanges } from "@codemirror/language";
import type { HunkKind, LineHunk } from "@/bindings";
import { call, commands, isTauri } from "@/platform/ipc";
import { gitEnabled } from "@/platform/gitEnabled";
import { useProject } from "@/platform/project";
import { onWorkflowSettingsChange } from "@/platform/workflowSettings";
import {
LaneMarker,
changeMarkerDisplay,
@@ -22,7 +25,7 @@ import {
import { renamedFromPath } from "./changes";
import { currentHunkText, lineStarts, rollbackEdit } from "./hunks";
import { hasIndex, onStagingAreaChange, stagingAreaOn } from "./staging";
import { statusOf, useVcs } from "./store";
import { hasNoCommits, repoOf, statusOf, useVcs } from "./store";
import { tx } from "@/platform/i18n";
import { runOp } from "./ops";
@@ -44,6 +47,14 @@ export interface EditorHunk extends TrackedHunk {
}
export const setHunksEffect = StateEffect.define<TrackedHunk[]>();
const setLinkedHistory = StateEffect.define<boolean>();
const linkedHistoryField = StateField.define<boolean>({
create: () => false,
update(value, tr) {
for (const effect of tr.effects) if (effect.is(setLinkedHistory)) return effect.value;
return value;
},
});
interface HunkState {
hunks: EditorHunk[];
@@ -144,33 +155,36 @@ export function editorHunks(state: EditorState): EditorHunk[] {
return state.field(hunkField, false)?.hunks ?? [];
}
export function hasLinkedHistory(state: EditorState): boolean {
return state.field(linkedHistoryField, false) ?? false;
}
export function editableHunk(view: EditorView, hunk: EditorHunk): boolean {
const state = view.state.field(hunkField, false);
return !!state?.hunks.includes(hunk) && (!hunk.staging || (state.fresh && stagingAreaOn()));
}
async function stagingHunks(path: string): Promise<TrackedHunk[]> {
async function stagingHunks(path: string): Promise<TrackedHunk[] | null> {
const file = statusOf(path);
const headPath = file?.staged === "renamed" ? renamedFromPath(file) : null;
const result = await call(commands.vcsStagingLineHunks(path, headPath));
return (
result?.hunks.map((h) => ({
kind: h.kind,
start: h.start,
lines: h.lines,
oldStart: h.headStart,
oldLines: h.headLines,
oldText: h.headText,
staging: {
indexVersion: result.indexVersion,
indexStart: h.indexStart,
indexLines: h.indexLines,
indexText: h.indexText,
staged: h.staged,
unstaged: h.unstaged,
},
})) ?? []
);
if (!result) return null;
return result.hunks.map((hunk) => ({
kind: hunk.kind,
start: hunk.start,
lines: hunk.lines,
oldStart: hunk.headStart,
oldLines: hunk.headLines,
oldText: hunk.headText,
staging: {
indexVersion: result.indexVersion,
indexStart: hunk.indexStart,
indexLines: hunk.indexLines,
indexText: hunk.indexText,
staged: hunk.staged,
unstaged: hunk.unstaged,
},
}));
}
function sameRange(a: TrackedHunk, b: TrackedHunk): boolean {
@@ -221,6 +235,7 @@ async function editStagingHunks(
await whenSynced(view);
const current = await stagingHunks(path);
if (
!current ||
view.state.doc !== doc ||
!stagingAreaOn() ||
!hunks.every((hunk) => current.some((range) => sameRange(hunk, range)))
@@ -340,6 +355,8 @@ class HunkFetcher implements PluginValue {
private destroyed = false;
private readonly unsub: () => void;
private readonly offStaging: () => void;
private readonly offGitSettings: () => void;
private linkedHistoryProbe: Promise<boolean> | undefined;
constructor(
private readonly view: EditorView,
@@ -347,13 +364,26 @@ class HunkFetcher implements PluginValue {
) {
this.schedule(30);
this.unsub = useVcs.subscribe((s, prev) => {
if (s.version !== prev.version || s.available !== prev.available) this.schedule(60);
const repositoryChanged =
s.available !== prev.available ||
(s.roots !== prev.roots && repoOf(this.path, s.roots) !== repoOf(this.path, prev.roots));
if (repositoryChanged) this.linkedHistoryProbe = undefined;
const historyStatusChanged = hasNoCommits(s.byPath.get(this.path)) !== hasNoCommits(prev.byPath.get(this.path));
if (s.version !== prev.version || repositoryChanged || historyStatusChanged) this.schedule(60);
});
this.offStaging = onStagingAreaChange(() => {
this.view.dispatch({ effects: setHunksEffect.of([]) });
popupHooks?.docChanged(this.view);
this.schedule(0);
});
this.offGitSettings = onWorkflowSettingsChange(
(s) => [s.vcs.git.enabled, s.vcs.mappings],
() => {
this.linkedHistoryProbe = undefined;
this.view.dispatch({ effects: setLinkedHistory.of(false) });
this.schedule(0);
},
);
}
update(u: ViewUpdate) {
@@ -370,31 +400,51 @@ class HunkFetcher implements PluginValue {
}
async fetch(ticket: number) {
if (this.destroyed) return;
if (!useVcs.getState().available || !isTauri()) {
if (editorHunks(this.view.state).length) this.view.dispatch({ effects: setHunksEffect.of([]) });
return;
}
// A file of another system (a Subversion working copy) has no index: its markers are
// against its base, also while the staging area is on for the Git repositories.
const staging = stagingAreaOn() && hasIndex(this.path);
if (this.destroyed || ticket !== this.seq || !isTauri()) return;
const { available } = useVcs.getState();
const inRepository = available && !!repoOf(this.path);
const canProbe = !!useProject.getState().project && gitEnabled();
// Both positive and negative probes are reused on edits.
const probe = () =>
(this.linkedHistoryProbe ??= call(commands.vcsLinkedFileHasHistory(this.path)).catch(() => false));
const current = () => !this.destroyed && ticket === this.seq;
try {
if (staging) await whenSynced(this.view);
if (this.destroyed || ticket !== this.seq) return;
const hunks = staging ? await stagingHunks(this.path) : await call(commands.vcsLineHunks(this.path));
if (this.destroyed || ticket !== this.seq) return;
this.view.dispatch({ effects: setHunksEffect.of(hunks) });
if (staging) popupHooks?.stagingChanged?.(this.view);
const mayBeLinked = !inRepository || hasNoCommits(statusOf(this.path)) || !!this.linkedHistoryProbe;
let linked = canProbe && mayBeLinked && (await probe());
if (!current()) return;
if (!inRepository && !linked) {
this.clearHunks();
return;
}
await whenSynced(this.view);
if (!current()) return;
// Linked files and non-Git working copies use base markers, not the workspace's index.
const staging = !linked && stagingAreaOn() && hasIndex(this.path);
const staged = staging ? await stagingHunks(this.path) : null;
if (staging && !staged && canProbe) linked = await probe();
if (!current()) return;
const hunks = staged ?? (!staging || linked ? await call(commands.vcsLineHunks(this.path)) : []);
if (!current()) return;
this.view.dispatch({ effects: [setHunksEffect.of(hunks), setLinkedHistory.of(linked)] });
if (staged) popupHooks?.stagingChanged?.(this.view);
} catch {
// Paths outside the repository etc.: no markers.
if (current()) this.clearHunks();
}
}
private clearHunks() {
const { state } = this.view;
if (editorHunks(state).length || hasLinkedHistory(state))
this.view.dispatch({ effects: [setHunksEffect.of([]), setLinkedHistory.of(false)] });
}
destroy() {
this.destroyed = true;
clearTimeout(this.timer);
this.unsub();
this.offStaging();
this.offGitSettings();
}
}
@@ -481,6 +531,7 @@ export function changeMarkers(ctx: EditorDocContext): Extension {
const path = ctx.path;
return [
hunkField,
linkedHistoryField,
gutterLaneMarkers.compute([hunkField, foldState, changeMarkerDisplay], laneMarkers),
scrollbarMarks.compute([hunkField, changeMarkerDisplay], scrollMarks),
laneClicks(path),
+10 -6
Переглянути файл
@@ -21,8 +21,7 @@ import {
registerTitleItem,
registerToolWindow,
} from "@/workbench/contributions";
import { executeAction, registerActions } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { executeAction, getAction, isActionEnabled, registerActions } from "@/platform/actions";
import { lazyComponent } from "@/ui";
import { commitWindowFocused, registerVcsActions } from "./actions";
import { installChangelists } from "./changelists";
@@ -52,7 +51,7 @@ import { activateDiffViewer } from "./diffViewer";
import { installDiffEditorHost } from "./DiffWindow";
import { VcsDialogHost } from "./dialogs";
import { installCloneHandoff } from "./clone";
import { changeMarkers } from "./gutter";
import { changeMarkers, hasLinkedHistory } from "./gutter";
import { installHunkPopup } from "./HunkPopup";
import { LOCAL_HISTORY_KIND } from "./localHistoryKind";
import { DIRECTORY_COMPARE_KIND, directoryCompareTitle, type DirectoryCompareData } from "./directoryCompareKind";
@@ -232,11 +231,16 @@ function registerGitContributions(): () => void {
menus: ["editorGutter"],
order: 10,
items: (_menu, { paths: [path] }) => {
if (!path || !getContext().vcsAvailable) return [];
const shown = editorsFor(path).some((h) => annotationsShown(h.view));
const action = getAction("vcs.annotate");
if (!path || !action || !isActionEnabled(action, undefined, path)) return [];
const editors = editorsFor(path);
const shown = editors.some((h) => annotationsShown(h.view));
const label = editors.some(({ view }) => hasLinkedHistory(view.state))
? "Annotate with Git Blame"
: annotateLabel(path);
return [
{
label: shown ? "Close Annotations" : annotateLabel(path),
label: shown ? "Close Annotations" : label,
run: () => void executeAction("vcs.annotate", path),
},
];
+12
Переглянути файл
@@ -663,6 +663,18 @@ export function statusOf(path: string): FileStatus | undefined {
return useVcs.getState().byPath.get(stripSlash(path));
}
/** Whether the workspace's status says the path has no committed history. */
export function hasNoCommits(status: FileStatus | undefined): boolean {
return (
status?.staged === "added" ||
// Subversion schedules an addition in the working copy (no staging area).
status?.unstaged === "added" ||
status?.unstaged === "untracked" ||
status?.unstaged === "ignored" ||
status?.staged === "ignored"
);
}
/** Repositories found below a project that is not itself under git (scanned in the background). */
export async function discoverRoots() {
if (!useVcs.getState().root || !isTauri()) return;