feat(vcs): Show Diff in the annotate gutter's context menu (#4355)

The annotate gutter's context menu gains Show Diff after Show Commit in Git Log. It opens what the line's commit changed in the file against the commit's first parent: an added file shows (does not exist) on the left, a renamed one its old path, and a file renamed later is diffed under its name at that commit (from its --follow history; a merge the history doesn't list is read directly).

Closes #4354

Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com>
This commit is contained in:
Mansur Akhmadi
2026-11-19 00:16:57 +08:00
committed by GitHub
co-authored by mansur-akhmadi
parent edf9affa8e
commit 460d30030e
4 changed files with 246 additions and 8 deletions
@@ -7,13 +7,20 @@ import {
annotatePreviousRevision,
previousRevisionDiffData,
revisionDiffData,
showRevisionDiff,
} from "../annotateRevision";
import { activateRevisionAnnotations } from "../annotateRevisionProvider";
import type { DiffData } from "../diffInput";
import { createDiffViewerContributions, type DiffViewerHost } from "../diffViewerProviders";
import { useVcs } from "../store";
const mocks = vi.hoisted(() => ({ openDiff: vi.fn(), blame: vi.fn(), log: vi.fn() }));
const mocks = vi.hoisted(() => ({
openDiff: vi.fn(),
blame: vi.fn(),
log: vi.fn(),
commitFiles: vi.fn(),
notify: vi.fn(),
}));
vi.mock("../diffInput", async (original) => ({
...(await original<typeof import("../diffInput")>()),
@@ -21,8 +28,15 @@ vi.mock("../diffInput", async (original) => ({
}));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return { ...actual, commands: { ...actual.commands, vcsBlame: mocks.blame, vcsLog: mocks.log } };
return {
...actual,
commands: { ...actual.commands, vcsBlame: mocks.blame, vcsLog: mocks.log, vcsCommitFiles: mocks.commitFiles },
};
});
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify: mocks.notify }),
}));
const sha = "f122f5afd61fa24a16a5e1c76c7ed6cbad833c93";
const parent = "12852f79a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6";
@@ -44,6 +58,7 @@ beforeEach(() => {
useVcs.setState({ available: true, root: "/repo", repo: "/repo", roots: ["/repo"] });
mocks.openDiff.mockResolvedValue(undefined);
mocks.log.mockResolvedValue({ status: "ok", data: [commit([parent])] });
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "a.py", kind: "modified", oldPath: null }] });
mocks.blame.mockResolvedValue({
status: "ok",
data: [
@@ -119,3 +134,120 @@ describe("annotate at a chosen revision", () => {
);
});
});
describe("show diff from the annotate gutter", () => {
const absent = (label: string) => ({ type: "text", text: "", label, absent: true });
it("opens the commit's change to the file against its first parent, not annotated", async () => {
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.log).toHaveBeenCalledWith(
"/repo",
expect.objectContaining({ branch: sha, path: "/repo/a.py", follow: true, limit: 1 }),
);
expect(mocks.commitFiles).toHaveBeenCalledWith("/repo", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(
{
path: "/repo/a.py",
left: { type: "rev", rev: parent, path: undefined, label: parent.slice(0, 8) },
right: { type: "rev", rev: sha, label: sha.slice(0, 8) },
},
{ preview: false },
);
});
it("shows the file as added when the commit added it", async () => {
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "a.py", kind: "added", oldPath: null }] });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(
expect.objectContaining({ left: absent("(does not exist)"), right: expect.objectContaining({ rev: sha }) }),
{ preview: false },
);
});
it("shows the old name on the left when the commit renamed the file", async () => {
mocks.commitFiles.mockResolvedValue({
status: "ok",
data: [
{ path: "b.py", kind: "modified", oldPath: null },
{ path: "a.py", kind: "renamed", oldPath: "old/a.py" },
],
});
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(
expect.objectContaining({
path: "/repo/a.py",
left: expect.objectContaining({ rev: parent, path: "/repo/old/a.py" }),
}),
{ preview: false },
);
});
it("has an empty left side for a root commit", async () => {
mocks.log.mockResolvedValue({ status: "ok", data: [commit([])] });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(expect.objectContaining({ left: absent("(does not exist)") }), {
preview: false,
});
});
it("asks the line's repository, not the selected one", async () => {
useVcs.setState({ repo: "/repo", roots: ["/repo", "/other"] });
mocks.commitFiles.mockResolvedValue({
status: "ok",
data: [{ path: "src/b.go", kind: "modified", oldPath: null }],
});
await showRevisionDiff("/other/src/b.go", sha);
expect(mocks.log).toHaveBeenCalledWith("/other", expect.anything());
expect(mocks.commitFiles).toHaveBeenCalledWith("/other", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(expect.objectContaining({ path: "/other/src/b.go" }), {
preview: false,
});
});
it("uses the file's name at the commit when it was renamed later", async () => {
mocks.log.mockResolvedValue({ status: "ok", data: [{ ...commit([parent]), historyPath: "old.py" }] });
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "old.py", kind: "modified", oldPath: null }] });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.log).toHaveBeenCalledTimes(1);
expect(mocks.openDiff).toHaveBeenCalledWith(
{
path: "/repo/old.py",
left: { type: "rev", rev: parent, path: undefined, label: parent.slice(0, 8) },
right: { type: "rev", rev: sha, label: sha.slice(0, 8) },
},
{ preview: false },
);
});
it("reads the commit itself when the file's history doesn't list it (a merge)", async () => {
const merge = { ...commit([parent, "abcdef0123456789abcdef0123456789abcdef01"]) };
mocks.log
.mockResolvedValueOnce({ status: "ok", data: [{ ...commit([]), id: parent, historyPath: "old.py" }] })
.mockResolvedValueOnce({ status: "ok", data: [merge] });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.log).toHaveBeenLastCalledWith("/repo", expect.objectContaining({ branch: sha, path: null }));
expect(mocks.openDiff).toHaveBeenCalledWith(
expect.objectContaining({
path: "/repo/a.py",
left: expect.objectContaining({ type: "rev", rev: parent }),
right: expect.objectContaining({ type: "rev", rev: sha }),
}),
{ preview: false },
);
});
it("falls back to the current path when the commit doesn't list the file", async () => {
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "b.py", kind: "modified", oldPath: null }] });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(expect.objectContaining({ path: "/repo/a.py" }), { preview: false });
});
it("reports a failure instead of opening a diff", async () => {
mocks.commitFiles.mockResolvedValue({ status: "error", error: "bad revision" });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).not.toHaveBeenCalled();
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", title: "Could not show diff" }),
);
});
});
+67 -2
View File
@@ -8,7 +8,15 @@ import { annotationsShown, blameSlot, toggleAnnotations } from "../blame";
import { closeBlamePopup } from "../BlamePopup";
import { useVcs } from "../store";
const mocks = vi.hoisted(() => ({ blame: vi.fn(), log: vi.fn(), action: vi.fn(), notify: vi.fn() }));
const mocks = vi.hoisted(() => ({
blame: vi.fn(),
log: vi.fn(),
action: vi.fn(),
notify: vi.fn(),
commitFiles: vi.fn(),
openDiff: vi.fn(),
menu: vi.fn(),
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify: mocks.notify, expire: vi.fn() }),
@@ -21,9 +29,17 @@ vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
commands: { ...actual.commands, vcsBlame: mocks.blame, vcsLog: mocks.log },
commands: { ...actual.commands, vcsBlame: mocks.blame, vcsLog: mocks.log, vcsCommitFiles: mocks.commitFiles },
};
});
vi.mock("../diffInput", async (original) => ({
...(await original<typeof import("../diffInput")>()),
openDiff: mocks.openDiff,
}));
vi.mock("@/ui", async (original) => ({
...(await original<typeof import("@/ui")>()),
showContextMenu: mocks.menu,
}));
const sha = "f122f5afd61fa24a16a5e1c76c7ed6cbad833c93";
const otherSha = "12852f79a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6";
@@ -121,4 +137,53 @@ describe("git blame gutter and commit popup", () => {
});
expect(mocks.action).toHaveBeenCalledWith("vcs.showCommit", sha);
});
it("shows the line's change from the gutter menu's Show Diff", async () => {
mocks.commitFiles.mockResolvedValue({
status: "ok",
data: [{ path: "src/main.py", kind: "added", oldPath: null }],
});
view = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "first\nsecond\nthird", extensions: [blameSlot()] }),
});
await toggleAnnotations(view, "/repo/src/main.py");
const firstLine = [...view.dom.querySelectorAll<HTMLElement>(".cm-vcs-blame .cm-gutterElement")].find((el) =>
el.querySelector(`[data-commit="${sha}"]`),
)!;
fireEvent.contextMenu(firstLine);
const items = mocks.menu.mock.calls[0]![1] as { label?: string; run?: () => void }[];
expect(items.map((i) => i.label).slice(0, 2)).toEqual(["Show Commit in Git Log", "Show Diff"]);
items[1]!.run!();
await vi.waitFor(() => expect(mocks.openDiff).toHaveBeenCalled());
expect(mocks.commitFiles).toHaveBeenCalledWith("/repo", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(
expect.objectContaining({
path: "/repo/src/main.py",
left: expect.objectContaining({ label: "(does not exist)" }),
right: expect.objectContaining({ type: "rev", rev: sha }),
}),
{ preview: false },
);
});
it("offers no Show Diff on a line that is not committed yet", async () => {
const zero = "0".repeat(40);
mocks.blame.mockResolvedValue({
status: "ok",
data: [{ commit: zero, author: "Not Committed Yet", timeMs: 0, summary: "" }, lines[0]],
});
view = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "edited\nsecond", extensions: [blameSlot()] }),
});
await toggleAnnotations(view, "/repo/src/main.py");
const edited = [...view.dom.querySelectorAll<HTMLElement>(".cm-vcs-blame .cm-gutterElement")].find((el) =>
el.querySelector('[title="Not committed yet"]'),
)!;
fireEvent.contextMenu(edited);
const items = mocks.menu.mock.calls[0]![1] as { label?: string }[];
expect(items.map((i) => i.label)).toEqual(["Close Annotations"]);
});
});
+40 -4
View File
@@ -7,11 +7,13 @@
import type { Commit } from "@/bindings";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
import { relativePath } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import type { DiffData } from "./diffInput";
import { openDiff } from "./diffInput";
import { commitFileDiffData, openDiff } from "./diffInput";
import { repositoryPath } from "./repositoryPaths";
import { repoOf } from "./store";
import { currentRepoRoot, repoOf } from "./store";
/** The diff that shows `commit` against its first parent; `null` for a root commit. */
export function previousRevisionDiffData(
@@ -46,11 +48,11 @@ export function revisionDiffData(
};
}
function notifyFailure(e: unknown): void {
function notifyFailure(e: unknown, title = tx("Cannot annotate")): void {
notifications().notify({
group: "vcs",
level: "error",
title: tx("Cannot annotate"),
title,
body: e instanceof Error ? e.message : String(e),
});
}
@@ -93,3 +95,37 @@ export async function annotatePreviousRevision(path: string, commit: string): Pr
notifyFailure(e);
}
}
/**
* The annotate gutter's Show Diff (IDEA's): what `commit` changed in the file, against its first
* parent, so a file the commit added or renamed shows as such. The file's history gives its name
* at that commit when it was renamed later.
*/
export async function showRevisionDiff(path: string, commit: string): Promise<void> {
const repo = repoOf(path) ?? currentRepoRoot();
if (!repo) return;
const relative = relativePath(ipcPath(repo).replace(/\/$/, ""), ipcPath(path));
const log = (file: string | null) =>
call(
commands.vcsLog(repo, {
branch: commit,
path: file,
follow: !!file,
author: null,
text: null,
skip: 0,
limit: 1,
}),
);
try {
const [[inHistory], files] = await Promise.all([log(path), call(commands.vcsCommitFiles(repo, commit))]);
// A line's commit is in its file's history; a merge commit may not be, so read it directly then.
const found = inHistory?.id === commit ? inHistory : (await log(null))[0];
if (!found) return;
const name = (found === inHistory && found.historyPath) || relative;
const changed = files.find((f) => f.path === name) ?? { path: name, kind: "modified", oldPath: null };
await openDiff(commitFileDiffData({ ...found, repo }, changed), { preview: false });
} catch (e) {
notifyFailure(e, tx("Could not show diff"));
}
}
+5
View File
@@ -277,6 +277,11 @@ function blameExtension(lines: BlameLine[], path: string, live: boolean): Extens
icon: "commit",
run: () => void executeAction("vcs.showCommit", l.commit),
},
{
label: "Show Diff",
icon: "diff",
run: () => void import("./annotateRevision").then((m) => m.showRevisionDiff(path, l.commit)),
},
{
label: "Copy Revision Number",
icon: "copy",