Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat(vcs): Compare with Revision and Show Current Revision for files (#2422)

l0ng-ai64dad9c520de
diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts
index 28ad80b52..dc29636e2 100644
--- a/src/editor/core/controller.test.ts
+++ b/src/editor/core/controller.test.ts
@@ -361,7 +361,9 @@ describe("EditorController", () => {
"vcs.annotate",
"vcs.showDiff",
"vcs.compareWithBranch",
+ "vcs.compareWithRevision",
"vcs.showHistory",
+ "vcs.showCurrentRevision",
"vcs.showHistoryForSelection",
"vcs.rollback",
],
diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts
index 21bcb9436..513e9a841 100644
--- a/src/editor/core/controller.ts
+++ b/src/editor/core/controller.ts
@@ -1980,7 +1980,9 @@ function gitMenu(path: string): MenuItem {
{ kind: "action", action: "vcs.annotate", arg: path, label: "Annotate with Git Blame" },
{ kind: "action", action: "vcs.showDiff", arg: [path], label: "Show Diff" },
{ kind: "action", action: "vcs.compareWithBranch", arg: { path } },
+ { kind: "action", action: "vcs.compareWithRevision", arg: { path } },
{ kind: "action", action: "vcs.showHistory", arg: [path], label: "Show History" },
+ { kind: "action", action: "vcs.showCurrentRevision", arg: { path } },
{ kind: "action", action: "vcs.showHistoryForSelection", label: "Show History for Selection" },
{ kind: "action", action: "vcs.rollback", arg: [path], label: "Rollback…" },
{ kind: "separator" },
diff --git a/src/features/project-tree/contextMenu.test.ts b/src/features/project-tree/contextMenu.test.ts
index 4944b8c79..46b3d0c87 100644
--- a/src/features/project-tree/contextMenu.test.ts
+++ b/src/features/project-tree/contextMenu.test.ts
@@ -47,6 +47,8 @@ const OTHER_ACTIONS = [
"vcs.annotate",
"vcs.showDiff",
"vcs.compareWithBranch",
+ "vcs.compareWithRevision",
+ "vcs.showCurrentRevision",
"vcs.rollback",
"vcs.push",
];
@@ -154,6 +156,16 @@ describe("project view context menu", () => {
}
});
+ it("offers file revision actions only for a single file", () => {
+ expect(sub(contextMenuItems([node("/p/a.py")]), "Git")).toEqual(
+ expect.arrayContaining(["Compare with Revision…", "Show Current Revision"]),
+ );
+ for (const nodes of [[node("/p/src", true)], [node("/p/a.py"), node("/p/b.py")]]) {
+ expect(sub(contextMenuItems(nodes), "Git")).not.toContain("Compare with Revision…");
+ expect(sub(contextMenuItems(nodes), "Git")).not.toContain("Show Current Revision");
+ }
+ });
+
it("offers branch comparison for files, folders, their union and the project root", () => {
for (const nodes of [
[node("/p/a.py")],
diff --git a/src/features/project-tree/contextMenu.ts b/src/features/project-tree/contextMenu.ts
index 6dc182f71..bdc752fd6 100644
--- a/src/features/project-tree/contextMenu.ts
+++ b/src/features/project-tree/contextMenu.ts
@@ -356,7 +356,9 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
nodes.length > 0 &&
nodes.every((n) => !n.placeholder) &&
act("vcs.compareWithBranch", arg, "Compare with Branch…"),
+ singleFile && act("vcs.compareWithRevision", singleFile.path, "Compare with Revision…"),
nodes.length > 0 && nodes.every((n) => !n.placeholder) && act("vcs.showHistory", arg, "Show History"),
+ singleFile && act("vcs.showCurrentRevision", singleFile.path, "Show Current Revision"),
act("vcs.rollback", arg, "Rollback…"),
{ kind: "separator" },
act("vcs.push", undefined, "Push…"),
diff --git a/src/features/vcs/FileRevisionChooser.module.css b/src/features/vcs/FileRevisionChooser.module.css
new file mode 100644
index 000000000..76a021646
--- /dev/null
+++ b/src/features/vcs/FileRevisionChooser.module.css
@@ -0,0 +1,46 @@
+.search {
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--border-popup);
+}
+.body {
+ height: 280px;
+ display: flex;
+ flex-direction: column;
+ padding: 4px 0;
+}
+.list {
+ flex: 1;
+ min-height: 0;
+}
+.error {
+ padding: 8px 10px;
+ color: var(--danger);
+}
+.row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ min-width: 0;
+ width: 100%;
+}
+.hash {
+ font-family: var(--font-mono);
+ color: var(--accent);
+}
+.date {
+ color: var(--fg-subtle);
+ flex-shrink: 0;
+}
+.author {
+ flex: 0 0 110px;
+ color: var(--fg-secondary);
+}
+.author,
+.subject {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.subject {
+ flex: 1;
+}
diff --git a/src/features/vcs/FileRevisionChooser.tsx b/src/features/vcs/FileRevisionChooser.tsx
new file mode 100644
index 000000000..041f425cf
--- /dev/null
+++ b/src/features/vcs/FileRevisionChooser.tsx
@@ -0,0 +1,147 @@
+import { useEffect, useState, type KeyboardEvent } from "react";
+import type { Commit } from "@/bindings";
+import { call, commands, nextRequestId } from "@/platform/ipc";
+import { Dialog, List, SearchField, Spinner, T, listNavigate } from "@/ui";
+import { openDialog } from "./dialogs";
+import { openVcsDiff } from "./diffInput";
+import { hasFileHistory } from "./fileRevisions";
+import { formatTime } from "./model";
+import { repositoryPath } from "./repositoryPaths";
+import { repoOf } from "./store";
+import styles from "./FileRevisionChooser.module.css";
+
+export function compareWithFileRevision(path: string | null | undefined) {
+ if (!path || !hasFileHistory(path)) return;
+ const repo = repoOf(path);
+ openDialog((close) => (
+ <FileRevisionChooser
+ path={path}
+ repo={repo}
+ onClose={close}
+ onChoose={(commit) => {
+ close();
+ if (repoOf(path) !== repo) return;
+ void openVcsDiff({
+ path,
+ left: {
+ type: "rev",
+ rev: commit.id,
+ label: commit.shortId,
+ path: commit.historyPath ? repositoryPath(repo, commit.historyPath) : path,
+ },
+ right: { type: "worktree" },
+ });
+ }}
+ />
+ ));
+}
+
+function FileRevisionChooser({
+ path,
+ repo,
+ onClose,
+ onChoose,
+}: {
+ path: string;
+ repo: string | null;
+ onClose: () => void;
+ onChoose: (commit: Commit) => void;
+}) {
+ const [commits, setCommits] = useState<Commit[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [query, setQuery] = useState("");
+ const [active, setActive] = useState(0);
+ useEffect(() => {
+ let alive = true;
+ let pending = true;
+ const request = nextRequestId();
+ void call(
+ commands.vcsLog(repo, {
+ branch: null,
+ path,
+ author: null,
+ text: null,
+ skip: 0,
+ limit: 0,
+ follow: true,
+ summaryOnly: true,
+ request,
+ }),
+ )
+ .then((rows) => alive && setCommits(rows))
+ .catch((e) => alive && setError(String(e)))
+ .finally(() => {
+ pending = false;
+ });
+ return () => {
+ alive = false;
+ if (pending) void commands.cancelRequest(request).catch(() => undefined);
+ };
+ }, [path, repo]);
+ const q = query.trim().toLocaleLowerCase();
+ const items = (commits ?? []).filter((c) =>
+ `${c.id} ${formatTime(c.timeMs)} ${c.author} ${c.summary}`.toLocaleLowerCase().includes(q),
+ );
+ const idx = Math.min(active, items.length - 1);
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ if (items[idx]) onChoose(items[idx]);
+ return;
+ }
+ const next = listNavigate(e.key, { items, active: idx, wrap: true });
+ if (next !== null) {
+ e.preventDefault();
+ setActive(next);
+ }
+ };
+ return (
+ <Dialog open title="Compare with Revision…" onClose={onClose} width={720} position="top">
+ <div className={styles.search}>
+ <SearchField
+ data-autofocus
+ value={query}
+ onChange={(value) => {
+ setQuery(value);
+ setActive(0);
+ }}
+ onKeyDown={onKeyDown}
+ placeholder="Search file revisions"
+ aria-label="Search file revisions"
+ variant="bare"
+ />
+ </div>
+ <div className={styles.body}>
+ {error ? (
+ <div className={styles.error} role="alert">
+ {error}
+ </div>
+ ) : commits === null ? (
+ <Spinner size={14} />
+ ) : (
+ <List
+ items={items}
+ getKey={(c) => c.id}
+ activeIndex={idx}
+ onActiveChange={setActive}
+ onActivate={onChoose}
+ focusable={false}
+ hoverSelects
+ rowHeight={28}
+ aria-label="File revisions"
+ empty={<T>No commits</T>}
+ className={styles.list}
+ renderItem={(c) => (
+ <span className={styles.row} title={`${c.shortId} ${formatTime(c.timeMs)} ${c.author} ${c.summary}`}>
+ <span className={styles.hash}>{c.shortId}</span>
+ <span className={styles.date}>{formatTime(c.timeMs)}</span>
+ <span className={styles.author}>{c.author}</span>
+ <span className={styles.subject}>{c.summary}</span>
+ </span>
+ )}
+ />
+ )}
+ </div>
+ </Dialog>
+ );
+}
diff --git a/src/features/vcs/__tests__/fileRevisionChooser.test.tsx b/src/features/vcs/__tests__/fileRevisionChooser.test.tsx
new file mode 100644
index 000000000..99ebd0dc9
--- /dev/null
+++ b/src/features/vcs/__tests__/fileRevisionChooser.test.tsx
@@ -0,0 +1,99 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { compareWithFileRevision } from "../FileRevisionChooser";
+import { hasFileHistory, trackFileHistory } from "../fileRevisions";
+import { VcsDialogHost } from "../dialogs";
+import { useVcs } from "../store";
+
+const mocks = vi.hoisted(() => ({ files: vi.fn(), log: vi.fn(), cancel: vi.fn(), diff: vi.fn() }));
+vi.mock("../diffInput", () => ({ openVcsDiff: mocks.diff }));
+vi.mock("@/platform/ipc", async (original) => {
+ const actual = await original<typeof import("@/platform/ipc")>();
+ return {
+ ...actual,
+ commands: { ...actual.commands, vcsRevisionFiles: mocks.files, vcsLog: mocks.log, cancelRequest: mocks.cancel },
+ };
+});
+
+let stopTracking: () => void;
+beforeEach(async () => {
+ vi.clearAllMocks();
+ useVcs.setState({ roots: ["/repo"], statusLoaded: true, heads: {}, byPath: new Map() });
+ mocks.files.mockResolvedValue({ status: "ok", data: ["file.txt"] });
+ stopTracking = trackFileHistory();
+ await waitFor(() => expect(hasFileHistory("/repo/file.txt")).toBe(true));
+ mocks.cancel.mockResolvedValue({ status: "ok", data: null });
+ mocks.log.mockResolvedValue({
+ status: "ok",
+ data: [
+ {
+ id: "a".repeat(40),
+ shortId: "aaaaaaa",
+ author: "Alice",
+ timeMs: 1700000000000,
+ summary: "Initial file",
+ historyPath: "old.txt",
+ },
+ {
+ id: "b".repeat(40),
+ shortId: "bbbbbbb",
+ author: "Bob",
+ timeMs: 1700100000000,
+ summary: "Rename file",
+ historyPath: "file.txt",
+ },
+ ],
+ });
+});
+afterEach(() => {
+ stopTracking();
+ const dialog = screen.queryByRole("dialog");
+ if (dialog) fireEvent.keyDown(dialog, { key: "Escape" });
+});
+
+it.each(["Alice", "aaaaaaa", "Initial file"])(
+ "searches by %s and compares the renamed historical path against the working copy",
+ async (query) => {
+ render(<VcsDialogHost />);
+ compareWithFileRevision("/repo/file.txt");
+ const input = await screen.findByRole("textbox", { name: "Search file revisions" });
+ await waitFor(() =>
+ expect(mocks.log).toHaveBeenCalledWith(
+ "/repo",
+ expect.objectContaining({
+ path: "/repo/file.txt",
+ follow: true,
+ limit: 0,
+ }),
+ ),
+ );
+ fireEvent.change(input, { target: { value: query } });
+ fireEvent.keyDown(input, { key: "Enter" });
+ await waitFor(() =>
+ expect(mocks.diff).toHaveBeenCalledWith({
+ path: "/repo/file.txt",
+ left: { type: "rev", rev: "a".repeat(40), label: "aaaaaaa", path: "/repo/old.txt" },
+ right: { type: "worktree" },
+ }),
+ );
+ },
+);
+
+it("does not open a diff when cancelled", async () => {
+ render(<VcsDialogHost />);
+ compareWithFileRevision("/repo/file.txt");
+ fireEvent.keyDown(await screen.findByRole("dialog"), { key: "Escape" });
+ expect(mocks.diff).not.toHaveBeenCalled();
+});
+
+it("cancels a pending file-history request when closed", async () => {
+ mocks.log.mockReturnValue(new Promise(() => {}));
+ render(<VcsDialogHost />);
+ compareWithFileRevision("/repo/file.txt");
+ const dialog = await screen.findByRole("dialog");
+ await waitFor(() => expect(mocks.log).toHaveBeenCalled());
+ const request = mocks.log.mock.calls[0]![1].request;
+ fireEvent.keyDown(dialog, { key: "Escape" });
+ await waitFor(() => expect(mocks.cancel).toHaveBeenCalledWith(request));
+ expect(mocks.diff).not.toHaveBeenCalled();
+});
diff --git a/src/features/vcs/__tests__/fileRevisions.test.tsx b/src/features/vcs/__tests__/fileRevisions.test.tsx
new file mode 100644
index 000000000..af063f7d1
--- /dev/null
+++ b/src/features/vcs/__tests__/fileRevisions.test.tsx
@@ -0,0 +1,160 @@
+import { EditorState } from "@codemirror/state";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { getAction, isActionEnabled } from "@/platform/actions";
+import { registerVcsActions } from "../actions";
+import { showCurrentRevision } from "../fileRevisions";
+import { useVcs } from "../store";
+
+const mocks = vi.hoisted(() => ({
+ files: vi.fn(),
+ cursor: vi.fn(),
+ snapshot: vi.fn(),
+ active: vi.fn(),
+ editors: vi.fn(),
+ open: vi.fn(),
+ blame: vi.fn(),
+ reveal: vi.fn(),
+ show: vi.fn(),
+ notify: vi.fn(),
+}));
+vi.mock("@/editor/api", async (original) => ({
+ ...(await original<typeof import("@/editor/api")>()),
+ activeEditor: mocks.active,
+ editorsFor: mocks.editors,
+}));
+vi.mock("@/workbench/contributions", async (original) => ({
+ ...(await original<typeof import("@/workbench/contributions")>()),
+ maybeEditorService: () => ({ activePath: () => "/repo/file.txt" }),
+ editorService: () => ({ openFile: mocks.open, activeCursor: mocks.cursor }),
+ toolWindowService: () => ({ show: mocks.show }),
+ notifications: () => ({ notify: mocks.notify }),
+}));
+vi.mock("@/platform/ipc", async (original) => {
+ const actual = await original<typeof import("@/platform/ipc")>();
+ return {
+ ...actual,
+ commands: { ...actual.commands, vcsBlame: mocks.blame, vcsRevisionFiles: mocks.files, docSnapshot: mocks.snapshot },
+ };
+});
+vi.mock("../logStore", async (original) => ({
+ ...(await original<typeof import("../logStore")>()),
+ revealCommit: mocks.reveal,
+}));
+
+let dispose: () => void;
+beforeEach(async () => {
+ vi.clearAllMocks();
+ useVcs.setState({ roots: ["/repo", "/repo/nested"], statusLoaded: true, heads: {}, byPath: new Map() });
+ mocks.files.mockResolvedValue({ status: "ok", data: ["file.txt", "other.txt"] });
+ dispose = registerVcsActions();
+ await vi.waitFor(() =>
+ expect(isActionEnabled(getAction("vcs.compareWithRevision")!, { vcsAvailable: true })).toBe(true),
+ );
+ mocks.active.mockReturnValue({
+ ctx: { path: "/repo/file.txt" },
+ view: { state: EditorState.create({ doc: "first\nsecond\nunsaved", selection: { anchor: 7 } }) },
+ });
+});
+afterEach(() => dispose());
+
+for (const id of ["vcs.compareWithRevision", "vcs.showCurrentRevision"]) {
+ describe(id, () => {
+ it("requires Git and a file with committed history, including explicit menu targets", () => {
+ const action = getAction(id)!;
+ expect(isActionEnabled(action, { vcsAvailable: false })).toBe(false);
+ expect(isActionEnabled(action, { vcsAvailable: true })).toBe(true);
+ expect(isActionEnabled(action, { vcsAvailable: true }, { path: "/outside/file.txt" })).toBe(false);
+ expect(isActionEnabled(action, { vcsAvailable: true }, "/repo/ignored.txt")).toBe(false);
+ expect(isActionEnabled(action, { vcsAvailable: true }, "/repo/folder")).toBe(false);
+ for (const kind of ["untracked", "ignored", "added", "deleted"] as const) {
+ for (const side of ["staged", "unstaged"] as const) {
+ useVcs.setState({
+ byPath: new Map([
+ [
+ "/repo/other.txt",
+ {
+ path: "/repo/other.txt",
+ relPath: "other.txt",
+ renamedFrom: null,
+ staged: null,
+ unstaged: null,
+ [side]: kind,
+ },
+ ],
+ ]),
+ });
+ expect(isActionEnabled(action, { vcsAvailable: true }, "/repo/other.txt")).toBe(false);
+ expect(isActionEnabled(action, { vcsAvailable: true })).toBe(true);
+ }
+ }
+ useVcs.setState({ statusLoaded: false });
+ expect(isActionEnabled(action, { vcsAvailable: true })).toBe(false);
+ });
+ });
+}
+
+it("blames the caret line with unsaved text and selects its commit, not HEAD or the first line", async () => {
+ mocks.blame.mockResolvedValue({ status: "ok", data: [{ commit: "aaa" }, { commit: "bbb" }] });
+ await getAction("vcs.showCurrentRevision")!.run({ ctx: {}, arg: { path: "/repo/file.txt" } });
+ expect(mocks.blame).toHaveBeenCalledWith("/repo/file.txt", "first\nsecond\nunsaved", null);
+ expect(mocks.show).toHaveBeenCalledWith("git", true);
+ expect(mocks.reveal).toHaveBeenCalledWith("bbb", "/repo");
+});
+
+it("opens a project-view file and reveals its commit in its own repository", async () => {
+ mocks.editors.mockReturnValue([
+ { ctx: { path: "/repo/nested/other.txt" }, view: { state: EditorState.create({ doc: "other" }) } },
+ ]);
+ mocks.blame.mockResolvedValue({ status: "ok", data: [{ commit: "ccc" }] });
+ await showCurrentRevision("/repo/nested/other.txt");
+ expect(mocks.open).toHaveBeenCalledWith("/repo/nested/other.txt", { focus: true });
+ expect(mocks.reveal).toHaveBeenCalledWith("ccc", "/repo/nested");
+});
+
+it.each([{ lines: [] }, { lines: [{ commit: "aaa" }, { commit: "0".repeat(40) }] }])(
+ "does not select a commit for an uncommitted caret line",
+ async ({ lines }) => {
+ mocks.blame.mockResolvedValue({ status: "ok", data: lines });
+ await showCurrentRevision("/repo/file.txt");
+ expect(mocks.reveal).not.toHaveBeenCalled();
+ expect(mocks.notify).toHaveBeenCalled();
+ },
+);
+
+it("ignores blame that finishes after switching projects", async () => {
+ mocks.blame.mockImplementation(async () => {
+ useVcs.setState({ roots: ["/other"] });
+ return { status: "ok", data: [{ commit: "aaa" }, { commit: "bbb" }] };
+ });
+ await showCurrentRevision("/repo/file.txt");
+ expect(mocks.reveal).not.toHaveBeenCalled();
+});
+
+it("refreshes tracked-file enablement when HEAD changes", async () => {
+ mocks.files.mockResolvedValue({ status: "ok", data: ["new.txt"] });
+ useVcs.setState({ heads: { "/repo": { head: "main", headCommit: "new-head" } } });
+ const action = getAction("vcs.compareWithRevision")!;
+ expect(isActionEnabled(action, { vcsAvailable: true })).toBe(false);
+ await vi.waitFor(() => expect(isActionEnabled(action, { vcsAvailable: true }, "/repo/new.txt")).toBe(true));
+ expect(mocks.files).toHaveBeenCalledWith("/repo", "new-head");
+});
+
+it("reports blame failures", async () => {
+ mocks.blame.mockRejectedValue(new Error("Cannot read repository"));
+ await showCurrentRevision("/repo/file.txt");
+ expect(mocks.reveal).not.toHaveBeenCalled();
+ expect(mocks.notify).toHaveBeenCalledWith(
+ expect.objectContaining({ level: "error", body: "Cannot read repository" }),
+ );
+});
+
+it("blames a newly opened project-view file before its view mounts", async () => {
+ mocks.editors.mockReturnValue([]);
+ mocks.cursor.mockReturnValue({ path: "/repo/nested/other.txt", doc: 7, line: 0 });
+ mocks.snapshot.mockResolvedValue({ status: "ok", data: { text: "newly opened" } });
+ mocks.blame.mockResolvedValue({ status: "ok", data: [{ commit: "ccc" }] });
+ await showCurrentRevision("/repo/nested/other.txt");
+ expect(mocks.snapshot).toHaveBeenCalledWith(7);
+ expect(mocks.blame).toHaveBeenCalledWith("/repo/nested/other.txt", "newly opened", null);
+ expect(mocks.reveal).toHaveBeenCalledWith("ccc", "/repo/nested");
+});
diff --git a/src/features/vcs/__tests__/multiRoot.test.ts b/src/features/vcs/__tests__/multiRoot.test.ts
index 5b6aad9d9..c24508267 100644
--- a/src/features/vcs/__tests__/multiRoot.test.ts
+++ b/src/features/vcs/__tests__/multiRoot.test.ts
@@ -22,6 +22,7 @@ import {
openLogTab,
PAGE,
reloadLog,
+ revealCommit,
selectCommit,
selectedCommits,
selectGitTab,
@@ -311,3 +312,37 @@ describe("Git log background refresh", () => {
expect(useGitLog.getState().commits.map((c) => c.id)).toEqual(["filtered"]);
});
});
+
+it("reveals the requested commit after the log's first mount replaces its initial load", async () => {
+ let finishInitial!: () => void;
+ log.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishInitial = () => resolve({ status: "ok", data: [commit("target")] });
+ }),
+ );
+ const reveal = revealCommit("target", "/project/front");
+ await vi.waitFor(() => expect(finishInitial).toBeDefined());
+ log.mockResolvedValue({ status: "ok", data: [commit("target")] });
+ const mount = reloadLog();
+ finishInitial();
+ await Promise.all([reveal, mount]);
+ expect(useGitLog.getState().selection).toEqual([commitKey({ ...commit("target"), repo: "/project/front" })]);
+});
+
+it("does not replace a later filter choice with a pending commit reveal", async () => {
+ let finish!: () => void;
+ log.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = () => resolve({ status: "ok", data: [commit("target")] });
+ }),
+ );
+ const reveal = revealCommit("target", "/project/front");
+ await vi.waitFor(() => expect(finish).toBeDefined());
+ useGitLog.setState({ filters: { ...emptyFilters(), text: "chosen later" } });
+ finish();
+ await reveal;
+ expect(useGitLog.getState().selection).toEqual([]);
+ expect(useGitLog.getState().filters.text).toBe("chosen later");
+});
diff --git a/src/features/vcs/actions.tsx b/src/features/vcs/actions.tsx
index 8bb7b59c2..95c6d3c9e 100644
--- a/src/features/vcs/actions.tsx
+++ b/src/features/vcs/actions.tsx
@@ -60,6 +60,8 @@ import { refreshNow, repoName, useVcs } from "./store";
import { tx } from "@/platform/i18n";
import { addToIgnore } from "./ignore";
+import { hasFileHistory, showCurrentRevision, trackFileHistory } from "./fileRevisions";
+import { compareWithFileRevision } from "./FileRevisionChooser";
const VCS = "vcsAvailable";
const IN_COMMIT_WINDOW = "vcsAvailable && activeToolWindow == commit";
@@ -427,6 +429,15 @@ export function registerVcsActions(): () => void {
await comparePathsWithRevision(paths);
},
},
+ {
+ id: "vcs.compareWithRevision",
+ title: "Compare with Revision…",
+ category: "Git",
+ icon: "diff",
+ when: VCS,
+ enabled: ({ arg }) => hasFileHistory(argPath(arg) ?? maybeEditorService()?.activePath()),
+ run: ({ arg }) => compareWithFileRevision(argPath(arg) ?? maybeEditorService()?.activePath()),
+ },
{
id: "vcs.nextChange",
title: "Next Change",
@@ -537,6 +548,15 @@ export function registerVcsActions(): () => void {
showGitWindow();
},
},
+ {
+ id: "vcs.showCurrentRevision",
+ title: "Show Current Revision",
+ category: "Git",
+ icon: "commit",
+ when: VCS,
+ enabled: ({ arg }) => hasFileHistory(argPath(arg) ?? maybeEditorService()?.activePath()),
+ run: ({ arg }) => showCurrentRevision(argPath(arg) ?? maybeEditorService()?.activePath()),
+ },
{
id: "vcs.showHistoryForSelection",
title: "Show History for Selection",
@@ -638,5 +658,10 @@ export function registerVcsActions(): () => void {
run: () => void gotoConflict(-1),
},
];
- return registerActions(actions);
+ const stopTracking = trackFileHistory();
+ const unregister = registerActions(actions);
+ return () => {
+ unregister();
+ stopTracking();
+ };
}
diff --git a/src/features/vcs/fileRevisions.ts b/src/features/vcs/fileRevisions.ts
new file mode 100644
index 000000000..39988fbd4
--- /dev/null
+++ b/src/features/vcs/fileRevisions.ts
@@ -0,0 +1,86 @@
+import { activeEditor, editorsFor } from "@/editor/api";
+import { setContext } from "@/platform/context";
+import { call, commands } from "@/platform/ipc";
+import { editorService, notifications, toolWindowService } from "@/workbench/contributions";
+import { isUncommitted } from "./blame";
+import { revealCommit } from "./logStore";
+import { repoOf, statusOf, useVcs } from "./store";
+import { repositoryPath } from "./repositoryPaths";
+
+const historyFiles = new Map<string, { head: string | null; files: Set<string> }>();
+let availabilityVersion = 0;
+
+/** Status omits ignored files, so only files in HEAD can offer committed history. */
+export function trackFileHistory(): () => void {
+ let alive = true;
+ const refresh = () => {
+ const { roots, heads, statusLoaded } = useVcs.getState();
+ for (const root of historyFiles.keys()) if (!roots.includes(root)) historyFiles.delete(root);
+ if (!statusLoaded) return;
+ for (const root of roots) {
+ const head = heads[root]?.headCommit ?? null;
+ if (historyFiles.get(root)?.head === head) continue;
+ const entry = { head, files: new Set<string>() };
+ historyFiles.set(root, entry);
+ void call(commands.vcsRevisionFiles(root, head ?? "HEAD"))
+ .then((files) => {
+ if (!alive || historyFiles.get(root) !== entry) return;
+ entry.files = new Set(files.map((path) => repositoryPath(root, path)));
+ setContext("vcsFileHistoryVersion", ++availabilityVersion);
+ })
+ .catch(() => undefined);
+ }
+ };
+ const unsubscribe = useVcs.subscribe(refresh);
+ refresh();
+ return () => {
+ alive = false;
+ unsubscribe();
+ historyFiles.clear();
+ };
+}
+
+export function hasFileHistory(path: string | null | undefined): boolean {
+ if (!path || !useVcs.getState().statusLoaded) return false;
+ const repo = repoOf(path);
+ if (!repo || !historyFiles.get(repo)?.files.has(path)) return false;
+ const status = statusOf(path);
+ return ![status?.staged, status?.unstaged].some(
+ (kind) => kind === "untracked" || kind === "ignored" || kind === "added" || kind === "deleted",
+ );
+}
+
+export async function showCurrentRevision(path: string | null | undefined) {
+ if (!path || !hasFileHistory(path)) return;
+ let handle = activeEditor();
+ if (handle?.ctx.path !== path) {
+ await editorService().openFile(path, { focus: true });
+ handle = editorsFor(path)[0] ?? null;
+ }
+ const cursor = handle ? null : editorService().activeCursor();
+ if (!handle && cursor?.path !== path) return;
+ const repo = repoOf(path);
+ const state = handle?.view.state;
+ const line = state ? state.doc.lineAt(state.selection.main.head).number - 1 : cursor!.line;
+ let lines;
+ try {
+ const text = state ? state.doc.toString() : (await call(commands.docSnapshot(cursor!.doc))).text;
+ lines = await call(commands.vcsBlame(path, text, null));
+ } catch (e) {
+ notifications().notify({
+ group: "vcs",
+ level: "error",
+ title: "Cannot show current revision",
+ body: e instanceof Error ? e.message : String(e),
+ });
+ return;
+ }
+ if (repoOf(path) !== repo) return;
+ const blame = lines[line];
+ if (!blame || isUncommitted(blame)) {
+ notifications().notify({ group: "vcs", level: "info", title: "The current line has no committed revision" });
+ return;
+ }
+ toolWindowService().show("git", true);
+ await revealCommit(blame.commit, repo);
+}
diff --git a/src/features/vcs/logStore.ts b/src/features/vcs/logStore.ts
index 1f625c38d..281ea7cd9 100644
--- a/src/features/vcs/logStore.ts
+++ b/src/features/vcs/logStore.ts
@@ -1100,27 +1100,37 @@ async function pageUntil(find: () => boolean) {
export async function revealCommit(id: string, repo = currentRepo(), tab = "log") {
if (useGitLog.getState().logTabs.find((t) => t.id === tab)?.location === "editor") showLogView(tab);
else selectGitTab(tab);
- const f = useGitLog.getState().filters;
- const filtered = hasFilters(f);
+ if (tab === "log") initLogBranchFilter();
+ const filtered = hasFilters(useGitLog.getState().filters);
+ if (filtered) useGitLog.setState({ filters: emptyFilters() });
+ const { filters, selected } = useGitLog.getState();
+ const root = useVcs.getState().root;
+ const valid = () => {
+ const state = useGitLog.getState();
+ return (
+ useVcs.getState().root === root &&
+ state.shownLog === tab &&
+ state.filters === filters &&
+ state.selected === selected
+ );
+ };
const find = () =>
useGitLog
.getState()
.commits.find((c) => (!commitRepo(c) || commitRepo(c) === repo) && (c.id === id || c.id.startsWith(id)));
- if (filtered) {
- useGitLog.setState({ filters: emptyFilters() });
- const load = reloadLog();
- const generation = useGitLog.getState().generation;
- await load;
- if (useGitLog.getState().generation !== generation) return;
- } else if (!useGitLog.getState().commits.length) {
- const load = reloadLog();
- const generation = useGitLog.getState().generation;
- await load;
- if (useGitLog.getState().generation !== generation) return;
+ if (!useGitLog.getState().commits.length || filtered) {
+ await reloadLog();
+ // The log's first mount may replace this request with its own initial load.
+ while (valid()) {
+ const pending = loadPromises.get(tab);
+ if (!pending) break;
+ await pending;
+ }
+ if (!valid()) return;
}
const generation = useGitLog.getState().generation;
await pageUntil(() => !!find());
- if (useGitLog.getState().generation !== generation) return;
+ if (!valid() || useGitLog.getState().generation !== generation) return;
const hit = find();
if (hit) selectCommit(commitKey(hit), true);
}
diff --git a/src/platform/actions.test.ts b/src/platform/actions.test.ts
index 88f0b899d..5d5233a30 100644
--- a/src/platform/actions.test.ts
+++ b/src/platform/actions.test.ts
@@ -73,3 +73,21 @@ it("propagates host launch errors while retaining ordinary action error handling
log.mockRestore();
}
});
+
+it("checks argument-specific enablement before dispatch", async () => {
+ const run = vi.fn();
+ const dispose = registerAction({
+ id: "test.fileAction",
+ title: "Test",
+ enabled: ({ arg }) => arg === "/tracked.txt",
+ run,
+ });
+ try {
+ expect(await executeAction("test.fileAction", "/untracked.txt")).toBe(false);
+ expect(await executeAction("test.fileAction", "/tracked.txt")).toBe(true);
+ expect(run).toHaveBeenCalledOnce();
+ expect(run).toHaveBeenCalledWith(expect.objectContaining({ arg: "/tracked.txt" }));
+ } finally {
+ dispose();
+ }
+});
diff --git a/src/platform/actions.ts b/src/platform/actions.ts
index 7e763cbe5..d713a897e 100644
--- a/src/platform/actions.ts
+++ b/src/platform/actions.ts
@@ -36,6 +36,8 @@ export interface Action {
icon?: string;
/** Enablement; evaluated against context keys. */
when?: string;
+ /** Additional enablement for a parameterised action or the current selection. */
+ enabled?: (c: ActionContext) => boolean;
/**
* Extra condition for keyboard shortcuts only (menus and Find Action ignore
* it), e.g. to yield a shared shortcut to an editor action while typing.
@@ -142,13 +144,13 @@ export function allActions(): Action[] {
return [...useActions.getState().actions.values()];
}
-export function isActionEnabled(action: Action, ctx: ContextKeys = getContext()): boolean {
+export function isActionEnabled(action: Action, ctx: ContextKeys = getContext(), arg?: unknown): boolean {
if (
ctx.projectOpening &&
!["app.quit", "window.next", "window.previous", "window.toggleFullScreen"].includes(action.id)
)
return false;
- return evaluateWhen(action.when, ctx);
+ return evaluateWhen(action.when, ctx) && (action.enabled?.({ ctx, arg }) ?? true);
}
/** Whether a keyboard shortcut may run `action` (`when` and `keyWhen`). */
@@ -202,7 +204,7 @@ async function runAction(id: string, arg: unknown, propagateError: boolean): Pro
return false;
}
const ctx = getContext();
- if (!isActionEnabled(action, ctx)) return false;
+ if (!isActionEnabled(action, ctx, arg)) return false;
if (nesting === 0)
for (const l of listeners)
try {
diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json
index 32af3ddad..156f35b0d 100644
--- a/src/platform/locales/text/en.json
+++ b/src/platform/locales/text/en.json
@@ -1,4 +1,10 @@
{
+ "Cannot show current revision": "Cannot show current revision",
+ "Compare with Revision…": "Compare with Revision…",
+ "Show Current Revision": "Show Current Revision",
+ "Search file revisions": "Search file revisions",
+ "File revisions": "File revisions",
+ "The current line has no committed revision": "The current line has no committed revision",
"JAR Application": "JAR Application",
"Run an executable JAR": "Run an executable JAR",
"Path to JAR": "Path to JAR",
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index cf2534fd7..baabab728 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -1,4 +1,10 @@
{
+ "Cannot show current revision": "无法显示当前修订版",
+ "Compare with Revision…": "与修订版比较…",
+ "Show Current Revision": "显示当前修订版",
+ "Search file revisions": "搜索文件修订版",
+ "File revisions": "文件修订版",
+ "The current line has no committed revision": "当前行没有已提交的修订版",
"JAR Application": "JAR 应用程序",
"Run an executable JAR": "运行可执行 JAR",
"Path to JAR": "JAR 路径",
diff --git a/src/ui/Menu.tsx b/src/ui/Menu.tsx
index 7b09dd9e0..30c737a17 100644
--- a/src/ui/Menu.tsx
+++ b/src/ui/Menu.tsx
@@ -88,7 +88,7 @@ export function resolveMenuItems(items: MenuItem[]): Resolved[] {
label: tx(item.label) ?? a.title,
icon: item.icon ?? a.icon,
shortcut: shortcutLabel(item.action),
- disabled: !!item.disabled || !isActionEnabled(a),
+ disabled: !!item.disabled || !isActionEnabled(a, undefined, item.arg),
checked: item.checked ?? actionToggled(a),
run: () => void executeActionFrom("menu", item.action, item.arg),
});