From 026b493e939efefeeae4ac58dab2e9aa415bb218 Mon Sep 17 00:00:00 2001 From: Gregor Zeitlinger Date: Mon, 16 Nov 2026 17:03:26 +0100 Subject: [PATCH] fix(vcs): complete File History revision actions (#3775) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File History offered the repository-wide Git Log actions only. Its commit menu now has Show File at Revision (the file as it was in that commit, following renames through historyPath), and Compare with Local / Compare Versions diff just that file instead of the whole tree. ⌘/Ctrl+D in the File History list diffs the selected revision of the file against its parent, or the two selected revisions, without changing Show Diff elsewhere. Co-authored-by: <{ "message": "Not Found", "documentation_url": "https://docs.github.com/rest", "status": "404" }+@users.noreply.github.com> --- e2e/fileHistoryActions.spec.ts | 93 +++++ src/features/vcs/RevisionBrowser.tsx | 27 +- .../__tests__/fileHistoryNavigation.test.ts | 366 ++++++++++++++++++ src/features/vcs/__tests__/historyOps.test.ts | 28 ++ .../__tests__/revisionBrowserRouting.test.ts | 45 +++ src/features/vcs/actions.tsx | 2 +- src/features/vcs/historyActions.tsx | 111 +++++- src/features/vcs/log/CommitList.tsx | 12 + src/features/vcs/log/CommitRow.tsx | 4 +- src/features/vcs/log/commitMenu.ts | 19 +- src/features/vcs/logChanges.ts | 9 +- src/features/vcs/logPaneActions.ts | 50 ++- src/features/vcs/operations.tsx | 38 +- src/features/vcs/revisionInput.ts | 25 ++ src/platform/locales/text/en.json | 2 + src/platform/locales/text/zh.json | 2 + 16 files changed, 788 insertions(+), 45 deletions(-) create mode 100644 e2e/fileHistoryActions.spec.ts create mode 100644 src/features/vcs/__tests__/fileHistoryNavigation.test.ts create mode 100644 src/features/vcs/__tests__/revisionBrowserRouting.test.ts create mode 100644 src/features/vcs/revisionInput.ts diff --git a/e2e/fileHistoryActions.spec.ts b/e2e/fileHistoryActions.spec.ts new file mode 100644 index 000000000..49bc3ba81 --- /dev/null +++ b/e2e/fileHistoryActions.spec.ts @@ -0,0 +1,93 @@ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const ROOT = "/dev/acme-api"; +const FILE = `${ROOT}/src/new-name.ts`; +const REVISION = "a".repeat(40); + +test("File History opens its revision and compares only that file with the working copy", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate( + async ({ root, path, revision }) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: revision, operation: null }]; + h.vcs_branch_info = () => ({ + head: "main", + headCommit: revision, + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }); + h.vcs_branches = () => []; + h.vcs_status = () => []; + h.vcs_log = ({ query }) => + (query as { path?: string }).path + ? [ + { + id: revision, + shortId: revision.slice(0, 8), + parents: ["b".repeat(40)], + refs: [], + author: "Author", + email: "author@example.com", + timeMs: 1, + summary: "Rename historical file", + message: "Rename historical file", + historyPath: "src/old-name.ts", + }, + ] + : []; + h.vcs_log_refs = () => ({}); + h.vcs_log_users = () => ["Author "]; + h.vcs_log_details_batch = () => []; + h.vcs_commit_files = () => []; + h.vcs_file_at = ({ path: filePath }) => `historical contents of ${String(filePath)}\n`; + h.fs_probe = () => ({ size: 32, binary: false, tooLarge: false }); + + const storeModule = "/src/features/vcs/store.ts"; + const { useVcs } = await import(/* @vite-ignore */ storeModule); + useVcs.setState({ + available: true, + root, + repo: root, + roots: [root], + branchesLoaded: true, + statusLoaded: true, + }); + const contextModule = "/src/platform/context.ts"; + const { setContext } = await import(/* @vite-ignore */ contextModule); + setContext("vcsAvailable", true); + const actionsModule = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsModule); + await executeAction("vcs.showHistory", { path }); + }, + { root: ROOT, path: FILE, revision: REVISION }, + ); + + const commits = page.getByRole("listbox", { name: "Commits" }); + const row = commits.getByRole("option", { name: /Rename historical file/ }); + await expect(row).toBeVisible(); + + await row.click({ button: "right" }); + const menu = page.getByRole("menu", { name: "Context menu" }); + await expect(menu.getByRole("menuitem", { name: "Show File at Revision" })).toBeVisible(); + await menu.getByRole("menuitem", { name: "Compare with Local" }).click(); + + await expect + .poll(async () => ipcCalls(page, "vcs_file_at")) + .toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION }); + // The working copy side is the file itself (an editable document), not the historical path. + await expect.poll(async () => ipcCalls(page, "vcs_file_mode")).toContainEqual({ path: FILE, rev: "WT" }); + await expect(page.getByText(`historical contents of ${ROOT}/src/old-name.ts`).first()).toBeVisible(); + + await row.click({ button: "right" }); + await page + .getByRole("menu", { name: "Context menu" }) + .getByRole("menuitem", { name: "Show File at Revision" }) + .click(); + await expect + .poll(async () => ipcCalls(page, "vcs_file_at")) + .toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION }); +}); diff --git a/src/features/vcs/RevisionBrowser.tsx b/src/features/vcs/RevisionBrowser.tsx index 4e812e40c..1931c7ee1 100644 --- a/src/features/vcs/RevisionBrowser.tsx +++ b/src/features/vcs/RevisionBrowser.tsx @@ -4,7 +4,7 @@ import { EditorView } from "@codemirror/view"; import type { Commit } from "@/bindings"; import { call, commands, isTauri } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; -import { editorService, notifications, type EditorInput } from "@/workbench/contributions"; +import { notifications, type EditorInput } from "@/workbench/contributions"; import { Dialog, EmptyState, @@ -22,19 +22,13 @@ import { import { openDialog } from "./dialogs"; import { commitRepo, type RepoCommit } from "./multiRoot"; -import { currentRepoRoot, useVcs } from "./store"; +import { currentRepoRoot } from "./store"; import { repositoryPath } from "./repositoryPaths"; import { languageFor, viewerBase } from "./cm"; import styles from "./GitLog.module.css"; import { choosePath } from "@/platform/choosePath"; import { openLogTab } from "./logStore"; - -interface RevisionData { - repo: string; - revision: string; - path: string; - external?: boolean; -} +import { openRevisionFile, type RevisionData } from "./revisionInput"; export async function openExternalLog() { const picked = isTauri() @@ -118,20 +112,7 @@ function RevisionBrowser({ const children = await call(commands.vcsRevisionChildren(repo, revision, path.replace(/\/$/, ""))); setDirectories((current) => ({ ...current, [path]: children })); }; - const open = (path: string) => { - if (useVcs.getState().root) { - const bytes = new TextEncoder().encode(JSON.stringify({ repo, revision, path })); - const encoded = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); - void editorService().openFile(`git-revision:${encoded}/${encodeURIComponent(path.split("/").at(-1)!)}`, { - focus: true, - }); - } else - void editorService().openInput({ - kind: "git-revision", - key: `git-revision:${repo}\0${revision}\0${path}`, - data: { repo, revision, path, external } satisfies RevisionData, - }); - }; + const open = (path: string) => openRevisionFile(repo, revision, path, external); return (
diff --git a/src/features/vcs/__tests__/fileHistoryNavigation.test.ts b/src/features/vcs/__tests__/fileHistoryNavigation.test.ts new file mode 100644 index 000000000..63e652f76 --- /dev/null +++ b/src/features/vcs/__tests__/fileHistoryNavigation.test.ts @@ -0,0 +1,366 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Commit } from "@/bindings"; +import { getAction } from "@/platform/actions"; +import { setContext } from "@/platform/context"; +import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap"; +import { useGitLog } from "../logStore"; +import { toLogChanges, useLogChanges } from "../logChanges"; +import { registerLogPaneActions } from "../logPaneActions"; +import { useVcs } from "../store"; +import { registerVcsActions } from "../actions"; + +const mocks = vi.hoisted(() => ({ + openVcsDiff: vi.fn(), + openRevisionFile: vi.fn(), + showWorktreeComparison: vi.fn(), + openDialog: vi.fn(), + notify: vi.fn(), +})); + +vi.mock("../diffInput", async (importOriginal) => ({ + ...(await importOriginal()), + openVcsDiff: mocks.openVcsDiff, +})); +vi.mock("../revisionInput", async (importOriginal) => ({ + ...(await importOriginal()), + openRevisionFile: mocks.openRevisionFile, +})); +vi.mock("../compareTool", async (importOriginal) => ({ + ...(await importOriginal()), + showWorktreeComparison: mocks.showWorktreeComparison, +})); +vi.mock("../dialogs", async (importOriginal) => ({ + ...(await importOriginal()), + openDialog: mocks.openDialog, +})); +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + notifications: () => ({ notify: mocks.notify }), +})); + +import { showCompareVersions, showCompareWithLocal, showFileAtRevision } from "../operations"; +import { registerHistoryActions, type FileHistoryCommitArg, type FileHistoryCommitsArg } from "../historyActions"; + +const commit: Commit & { historyPath: string } = { + id: "1234567890abcdef1234567890abcdef12345678", + shortId: "12345678", + parents: ["p".repeat(40)], + author: "A", + email: "a@example.com", + timeMs: 0, + summary: "Rename file", + message: "Rename file", + refs: [], + historyPath: "old/name.ts", +}; + +const originalLog = useGitLog.getState(); +const originalVcs = useVcs.getState(); +let unregister: (() => void) | undefined; +let unregisterPane: (() => void) | undefined; + +beforeEach(() => { + mocks.openVcsDiff.mockReset(); + mocks.openRevisionFile.mockReset(); + mocks.showWorktreeComparison.mockReset(); + mocks.openDialog.mockReset(); + mocks.notify.mockReset(); + useGitLog.setState({ commits: [], selected: null, selection: [], shownLog: "log", logTabs: [] }); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"], branchesLoaded: true }); + setContext("vcsAvailable", true); + unregister = registerHistoryActions(); + unregisterPane = registerLogPaneActions(); +}); + +afterEach(() => { + unregister?.(); + unregister = undefined; + unregisterPane?.(); + unregisterPane = undefined; + useLogChanges.setState({ commits: [], all: [], selected: [] }); + useGitLog.setState(originalLog); + useVcs.setState(originalVcs); + setContext("vcsAvailable", false); +}); + +describe("File History actions", () => { + it("uses Ctrl/Cmd+D on a focused history row to diff the revision against its parent", async () => { + const renamed = { ...commit, historyPath: "old/name.ts" }; + const unrelated = toLogChanges([{ path: "unrelated.ts", oldPath: null, kind: "modified" }], renamed, "/repo"); + const historyFile = toLogChanges( + [{ path: "new/name.ts", oldPath: "old/name.ts", kind: "renamed" }], + renamed, + "/repo", + ); + const changes = [...unrelated, ...historyFile]; + useGitLog.setState({ + commits: [renamed], + selected: renamed.id, + selection: [renamed.id], + shownLog: "history", + logTabs: [{ id: "history", kind: "history", target: "/repo/new/name.ts" } as never], + }); + useLogChanges.setState({ commits: [renamed], all: changes, selected: changes }); + + const originalOverrides = useKeymap.getState().overrides; + const unregisterVcs = registerVcsActions(); + const uninstallDispatcher = installKeyboardDispatcher(window); + useKeymap.setState({ + overrides: { + ...originalOverrides, + "vcs.showDiff": ["Ctrl+D"], + "vcs.log.changes.showDiff": ["Ctrl+D"], + }, + }); + setContext("vcsLogRevisionFocus", true); + try { + expect(getAction("vcs.log.changes.showDiff")!.keyWhen).toBe("vcsLogChangesFocus || vcsLogRevisionFocus"); + expect(getAction("vcs.showDiff")!.keyWhen).toBe( + "!editorTextFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus", + ); + window.dispatchEvent(new KeyboardEvent("keydown", { code: "KeyD", key: "d", ctrlKey: true, bubbles: true })); + await vi.waitFor(() => expect(mocks.openVcsDiff).toHaveBeenCalledOnce()); + } finally { + setContext("vcsLogRevisionFocus", false); + useKeymap.setState({ overrides: originalOverrides }); + uninstallDispatcher(); + unregisterVcs(); + } + + expect(mocks.openVcsDiff).toHaveBeenCalledWith( + expect.objectContaining({ + path: "/repo/new/name.ts", + left: { type: "rev", rev: commit.parents[0], path: "/repo/old/name.ts", label: commit.parents[0]!.slice(0, 8) }, + right: { type: "rev", rev: commit.id, label: commit.shortId }, + }), + { preview: true }, + ); + expect(mocks.openVcsDiff.mock.calls[0]![0].chain).toBeUndefined(); + }); + + it("uses Compare Versions for two focused File History revisions", async () => { + const newer = { ...commit, historyPath: "new/name.ts" }; + const older = { + ...commit, + id: "a".repeat(40), + shortId: "aaaaaaaa", + parents: ["b".repeat(40)], + historyPath: "old/name.ts", + }; + useGitLog.setState({ + commits: [newer, older], + selected: newer.id, + selection: [newer.id, older.id], + shownLog: "history", + logTabs: [{ id: "history", kind: "history", target: "/repo/new/name.ts" } as never], + }); + useLogChanges.setState({ commits: [newer, older], all: [], selected: [] }); + + await getAction("vcs.log.changes.showDiff")!.run({ ctx: { vcsLogRevisionFocus: true } }); + + expect(mocks.openVcsDiff).toHaveBeenCalledWith({ + path: "/repo/new/name.ts", + left: { type: "rev", rev: older.id, path: "/repo/old/name.ts", label: older.shortId }, + right: { type: "rev", rev: newer.id, path: "/repo/new/name.ts", label: newer.shortId }, + }); + }); + + it("does not open a stale changed-files result while the selected revision is still loading", async () => { + const selected = { ...commit, id: "c".repeat(40) }; + useGitLog.setState({ + commits: [selected], + selected: selected.id, + selection: [selected.id], + shownLog: "history", + logTabs: [{ id: "history", kind: "history", target: "/repo/new/name.ts" } as never], + }); + useLogChanges.setState({ + commits: [commit], + all: toLogChanges([{ path: "stale.ts", oldPath: null, kind: "modified" }], commit, "/repo"), + selected: [], + }); + + await getAction("vcs.log.changes.showDiff")!.run({ ctx: { vcsLogRevisionFocus: true } }); + + expect(mocks.openVcsDiff).not.toHaveBeenCalled(); + expect(mocks.notify).toHaveBeenCalledWith({ + group: "vcs", + level: "info", + title: "Revision changes are still loading", + }); + }); + + it("keeps changed-file Show Diff on the same action when the revision list is not focused", async () => { + const changes = toLogChanges([{ path: "new/name.ts", oldPath: "old/name.ts", kind: "renamed" }], commit, "/repo"); + await getAction("vcs.log.changes.showDiff")!.run({ arg: changes, ctx: { vcsLogChangesFocus: true } }); + + expect(mocks.openVcsDiff).toHaveBeenCalledWith(expect.objectContaining({ path: "/repo/new/name.ts" }), { + preview: true, + }); + }); + + it("opens the selected snapshot, preserving the historical path after a rename", () => { + showFileAtRevision(commit, "/repo/new/name.ts"); + + expect(mocks.openRevisionFile).toHaveBeenCalledWith("/repo", commit.id, "old/name.ts", false); + }); + + it("derives a missing historical path from the scoped target using normalized Windows paths", () => { + const { historyPath: _historyPath, ...withoutHistoryPath } = commit; + useVcs.setState({ root: "C:/repo", repo: "C:/repo", roots: ["C:/repo"] }); + showFileAtRevision(withoutHistoryPath, "C:/repo/new/name.ts"); + + expect(mocks.openRevisionFile).toHaveBeenCalledWith("C:/repo", commit.id, "new/name.ts", false); + }); + + it("compares the selected historical file directly with its current working file", () => { + showCompareWithLocal(commit, "/repo/new/name.ts"); + + expect(mocks.openVcsDiff).toHaveBeenCalledWith({ + path: "/repo/new/name.ts", + left: { type: "rev", rev: commit.id, path: "/repo/old/name.ts", label: commit.shortId }, + right: { type: "worktree" }, + }); + expect(mocks.showWorktreeComparison).not.toHaveBeenCalled(); + }); + + it("keeps ordinary Git Log Compare with Local repository-scoped", () => { + showCompareWithLocal(commit); + + expect(mocks.openVcsDiff).not.toHaveBeenCalled(); + expect(mocks.showWorktreeComparison).toHaveBeenCalledWith(commit.id, commit.shortId); + }); + + it("compares each historical path at its revision in chronological order", () => { + const older = { ...commit, id: "a".repeat(40), shortId: "aaaaaaaa", historyPath: "old/name.ts" }; + const newer = { ...commit, id: "b".repeat(40), shortId: "bbbbbbbb", historyPath: "renamed/name.ts" }; + + showCompareVersions(older, newer, "/repo/current/name.ts"); + + expect(mocks.openVcsDiff).toHaveBeenCalledWith({ + path: "/repo/current/name.ts", + left: { type: "rev", rev: older.id, path: "/repo/old/name.ts", label: older.shortId }, + right: { type: "rev", rev: newer.id, path: "/repo/renamed/name.ts", label: newer.shortId }, + }); + expect(mocks.openDialog).not.toHaveBeenCalled(); + }); + + it("falls back to the File History target when either selected revision has no historical path", () => { + const { historyPath: _olderPath, ...older } = { ...commit, id: "a".repeat(40), shortId: "aaaaaaaa" }; + const { historyPath: _newerPath, ...newer } = { ...commit, id: "b".repeat(40), shortId: "bbbbbbbb" }; + + showCompareVersions(older, newer, "/repo/current/name.ts"); + + expect(mocks.openVcsDiff).toHaveBeenCalledWith({ + path: "/repo/current/name.ts", + left: { type: "rev", rev: older.id, path: "/repo/current/name.ts", label: older.shortId }, + right: { type: "rev", rev: newer.id, path: "/repo/current/name.ts", label: newer.shortId }, + }); + }); + + it("routes the revision-row Compare with Local action to the scoped file diff", async () => { + const arg: FileHistoryCommitArg = { kind: "file-history-commit", commit, target: "/repo/new/name.ts" }; + await getAction("vcs.log.compareWithLocal")!.run({ arg, ctx: {} }); + + expect(mocks.openVcsDiff).toHaveBeenCalledWith({ + path: "/repo/new/name.ts", + left: { type: "rev", rev: commit.id, path: "/repo/old/name.ts", label: commit.shortId }, + right: { type: "worktree" }, + }); + expect(mocks.showWorktreeComparison).not.toHaveBeenCalled(); + }); + + it("routes Show File at Revision through the read-only revision editor", async () => { + const arg: FileHistoryCommitArg = { kind: "file-history-commit", commit, target: "/repo/new/name.ts" }; + await getAction("vcs.log.showFileAtRevision")!.run({ arg, ctx: {} }); + + expect(mocks.openRevisionFile).toHaveBeenCalledWith("/repo", commit.id, "old/name.ts", false); + }); + + it("routes scoped Compare Versions with both selected revision paths", async () => { + const older = { ...commit, id: "a".repeat(40), shortId: "aaaaaaaa", historyPath: "old/name.ts" }; + const newer = { ...commit, id: "b".repeat(40), shortId: "bbbbbbbb", historyPath: "renamed/name.ts" }; + const arg: FileHistoryCommitsArg = { + kind: "file-history-commits", + commits: [newer, older], + target: "/repo/current/name.ts", + }; + + await getAction("vcs.log.compareVersions")!.run({ arg, ctx: {} }); + + expect(mocks.openVcsDiff).toHaveBeenCalledWith({ + path: "/repo/current/name.ts", + left: { type: "rev", rev: older.id, path: "/repo/old/name.ts", label: older.shortId }, + right: { type: "rev", rev: newer.id, path: "/repo/renamed/name.ts", label: newer.shortId }, + }); + }); + + it("does not attach a parked File History path to an explicit normal-log selection", async () => { + useGitLog.setState({ + shownLog: "history:1", + logTabs: [ + { id: "history:1", kind: "history", target: "/repo/current/name.ts", repo: "/repo", location: "toolWindow" }, + ], + }); + const older = { ...commit, id: "a".repeat(40), shortId: "aaaaaaaa", historyPath: "old/name.ts" }; + const newer = { ...commit, id: "b".repeat(40), shortId: "bbbbbbbb", historyPath: "renamed/name.ts" }; + + await getAction("vcs.log.compareVersions")!.run({ arg: [newer, older], ctx: {} }); + + expect(mocks.openVcsDiff).not.toHaveBeenCalled(); + expect(mocks.openDialog).toHaveBeenCalled(); + }); + + it("keeps Compare Versions restricted to exactly two commits", async () => { + const commits = ["a", "b", "c"].map((id) => ({ + ...commit, + id: id.repeat(40), + shortId: id.repeat(8), + })); + + await getAction("vcs.log.compareVersions")!.run({ arg: commits, ctx: {} }); + + expect(mocks.openVcsDiff).not.toHaveBeenCalled(); + expect(mocks.openDialog).not.toHaveBeenCalled(); + }); + + it("uses the active File History scope when Compare with Local is invoked without an argument", async () => { + useGitLog.setState({ + commits: [commit], + selected: commit.id, + selection: [commit.id], + shownLog: "history:1", + logTabs: [ + { id: "history:1", kind: "history", target: "/repo/new/name.ts", repo: "/repo", location: "toolWindow" }, + ], + }); + await getAction("vcs.log.compareWithLocal")!.run({ ctx: {} }); + + expect(mocks.openVcsDiff).toHaveBeenCalledWith({ + path: "/repo/new/name.ts", + left: { type: "rev", rev: commit.id, path: "/repo/old/name.ts", label: commit.shortId }, + right: { type: "worktree" }, + }); + }); + + it("does not apply a parked File History scope to an explicitly passed plain commit", async () => { + useGitLog.setState({ + shownLog: "history:1", + logTabs: [ + { id: "history:1", kind: "history", target: "/repo/new/name.ts", repo: "/repo", location: "toolWindow" }, + ], + }); + await getAction("vcs.log.compareWithLocal")!.run({ arg: commit, ctx: {} }); + + expect(mocks.openVcsDiff).not.toHaveBeenCalled(); + expect(mocks.showWorktreeComparison).toHaveBeenCalledWith(commit.id, commit.shortId); + }); + + it("keeps command-based Compare with Local repository-scoped in the normal log", async () => { + useGitLog.setState({ commits: [commit], selected: commit.id, selection: [commit.id], shownLog: "log" }); + await getAction("vcs.log.compareWithLocal")!.run({ ctx: {} }); + + expect(mocks.openVcsDiff).not.toHaveBeenCalled(); + expect(mocks.showWorktreeComparison).toHaveBeenCalledWith(commit.id, commit.shortId); + }); +}); diff --git a/src/features/vcs/__tests__/historyOps.test.ts b/src/features/vcs/__tests__/historyOps.test.ts index ba02724d0..b5405d0ab 100644 --- a/src/features/vcs/__tests__/historyOps.test.ts +++ b/src/features/vcs/__tests__/historyOps.test.ts @@ -84,6 +84,17 @@ describe("Git Log commit actions", () => { expect(items.every((i) => !("arg" in i) || i.arg === c)).toBe(true); }); + it("adds file-scoped revision actions only to a File History commit menu", () => { + const c = commit("Rename file"); + const items = commitMenu(c, [c], "/repo/new.txt"); + const show = items.find((i) => "action" in i && i.action === "vcs.log.showFileAtRevision"); + const compare = items.find((i) => "action" in i && i.action === "vcs.log.compareWithLocal"); + const scoped = { kind: "file-history-commit", commit: c, target: "/repo/new.txt" }; + expect(show).toMatchObject({ arg: scoped }); + expect(compare).toMatchObject({ arg: scoped }); + expect(commitMenu(c).some((i) => "action" in i && i.action === "vcs.log.showFileAtRevision")).toBe(false); + }); + it("offers history rewriting for pushed commits too (IDEA allows it; the run confirms)", () => { const local = commit("Local", "1".repeat(40)); const pushed = commit("Pushed", "2".repeat(40)); @@ -123,6 +134,23 @@ describe("Git Log commit actions", () => { expect(ids([a, b, c])).toContain("vcs.log.cherryPick"); }); + it("scopes only File History Compare Versions to its selected file", () => { + const older = { ...commit("Older", "a".repeat(40)), historyPath: "old/name.ts" }; + const newer = { ...commit("Newer", "b".repeat(40)), historyPath: "renamed/name.ts" }; + const target = "/repo/current/name.ts"; + const normal = commitMenu(newer, [newer, older]).find( + (i) => i.kind === "action" && i.action === "vcs.log.compareVersions", + ); + const history = commitMenu(newer, [newer, older], target).find( + (i) => i.kind === "action" && i.action === "vcs.log.compareVersions", + ); + + expect(normal).toMatchObject({ arg: [newer, older] }); + expect(history).toMatchObject({ + arg: { kind: "file-history-commits", commits: [newer, older], target }, + }); + }); + it("extends and toggles the log selection", () => { const list = ["1", "2", "3", "4"].map((d) => commit(d, d.repeat(40))); useGitLog.setState({ commits: list }); diff --git a/src/features/vcs/__tests__/revisionBrowserRouting.test.ts b/src/features/vcs/__tests__/revisionBrowserRouting.test.ts new file mode 100644 index 000000000..c028cde0e --- /dev/null +++ b/src/features/vcs/__tests__/revisionBrowserRouting.test.ts @@ -0,0 +1,45 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const editor = vi.hoisted(() => ({ openFile: vi.fn(), openInput: vi.fn() })); +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + editorService: () => editor, +})); + +import { openRevisionFile } from "../revisionInput"; +import { useVcs } from "../store"; + +beforeEach(() => { + editor.openFile.mockReset(); + editor.openInput.mockReset(); + useVcs.setState({ root: "/project" }); +}); + +describe("openRevisionFile", () => { + it("routes project revisions through the registered read-only file URI", () => { + openRevisionFile("/repo", "a".repeat(40), "old/name.ts"); + + const uri = editor.openFile.mock.calls[0]![0] as string; + const hex = uri.slice("git-revision:".length).split("/", 1)[0]!; + const encoded = Uint8Array.from(hex.match(/.{2}/g)!, (byte) => Number.parseInt(byte, 16)); + expect(JSON.parse(new TextDecoder().decode(encoded))).toEqual({ + repo: "/repo", + revision: "a".repeat(40), + path: "old/name.ts", + }); + expect(editor.openFile).toHaveBeenCalledWith(uri, { focus: true }); + expect(editor.openInput).not.toHaveBeenCalled(); + }); + + it("routes external revisions through the standalone read-only editor input", () => { + useVcs.setState({ root: null }); + openRevisionFile("/external/repo", "b".repeat(40), "src/file.ts", true); + + expect(editor.openInput).toHaveBeenCalledWith({ + kind: "git-revision", + key: `git-revision:/external/repo\0${"b".repeat(40)}\0src/file.ts`, + data: { repo: "/external/repo", revision: "b".repeat(40), path: "src/file.ts", external: true }, + }); + expect(editor.openFile).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/vcs/actions.tsx b/src/features/vcs/actions.tsx index d4fc88fae..515bd76f0 100644 --- a/src/features/vcs/actions.tsx +++ b/src/features/vcs/actions.tsx @@ -411,7 +411,7 @@ export function registerVcsActions(): () => void { when: VCS, // ⌘D duplicates the line inside a text editor; Git › Show Diff still works there. // In the Git Log's changed files it shows the commit's diff instead. - keyWhen: "!editorTextFocus && !vcsLogChangesFocus", + keyWhen: "!editorTextFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus", run: async ({ arg, ctx }) => { if (ctx.shelfFocus && arg === undefined) return showShelfDiff(); const line = diff --git a/src/features/vcs/historyActions.tsx b/src/features/vcs/historyActions.tsx index 99acf9cd1..1de40fdd8 100644 --- a/src/features/vcs/historyActions.tsx +++ b/src/features/vcs/historyActions.tsx @@ -35,6 +35,7 @@ import { revertCommits, showCompareVersions, showCompareWithLocal, + showFileAtRevision, showResetDialog, showTagDialog, } from "./operations"; @@ -75,6 +76,55 @@ export function commitArg(arg: unknown): Commit | null { return commits.find((c) => commitKey(c) === id) ?? null; } +export interface FileHistoryCommitArg { + kind: "file-history-commit"; + commit: Commit; + target: string; +} + +export interface FileHistoryCommitsArg { + kind: "file-history-commits"; + commits: Commit[]; + target: string; +} + +function isCommit(value: unknown): value is Commit { + return !!value && typeof value === "object" && "id" in value && "summary" in value; +} + +function isFileHistoryCommitArg(arg: unknown): arg is FileHistoryCommitArg { + return ( + !!arg && + typeof arg === "object" && + "kind" in arg && + arg.kind === "file-history-commit" && + "commit" in arg && + isCommit(arg.commit) && + "target" in arg && + typeof arg.target === "string" + ); +} + +function isFileHistoryCommitsArg(arg: unknown): arg is FileHistoryCommitsArg { + return ( + !!arg && + typeof arg === "object" && + "kind" in arg && + arg.kind === "file-history-commits" && + "commits" in arg && + Array.isArray(arg.commits) && + arg.commits.every(isCommit) && + "target" in arg && + typeof arg.target === "string" + ); +} + +function activeFileHistoryTarget(): string | null { + const state = useGitLog.getState(); + const tab = state.logTabs.find((t) => t.id === state.shownLog); + return tab?.kind === "history" ? tab.target : null; +} + /** Commits an action refers to: its argument (commit list or commit), else the Git Log selection. */ export function commitsArg(arg: unknown): Commit[] { if (Array.isArray(arg)) return arg.filter((x): x is Commit => !!x && typeof x === "object" && "id" in x); @@ -127,6 +177,42 @@ function withCommit(fn: (c: Commit) => unknown, allowReadOnly = false) { }; } +/** Compare with Local alone uses the active File History's file instead of the repository tree. */ +function withHistoryAwareCompare(fn: (c: Commit, historyTarget?: string | null) => unknown) { + return async ({ arg }: { arg?: unknown }) => { + const scoped = isFileHistoryCommitArg(arg) ? arg : null; + const historyTarget = scoped?.target ?? (arg == null ? activeFileHistoryTarget() : null); + const c = scoped?.commit ?? commitArg(arg); + if (!c) { + notifications().notify({ group: "vcs", level: "info", title: "Select a commit in the Git log" }); + return; + } + if ("readOnly" in c && c.readOnly === true) return; + const repo = commitRepo(c); + if (repo) await focusRepo(repo); + void fn(c, historyTarget); + }; +} + +/** Compare Versions uses the active File History file only for scoped or no-argument invocations. */ +function withHistoryAwareCompareVersions(fn: (cs: Commit[], historyTarget?: string | null) => unknown) { + return async ({ arg }: { arg?: unknown }) => { + const scoped = isFileHistoryCommitsArg(arg) ? arg : null; + const historyTarget = scoped?.target ?? (arg == null ? activeFileHistoryTarget() : null); + const cs = scoped?.commits ?? commitsArg(arg); + if (cs.length !== 2) { + notifications().notify({ group: "vcs", level: "info", title: "Select two commits to compare" }); + return; + } + if (new Set(cs.map(commitRepo)).size > 1) return; + const readOnly = cs.some((c) => "readOnly" in c && c.readOnly === true); + if (readOnly) return; + const repo = commitRepo(cs[0]!); + if (repo) await focusRepo(repo); + void fn(cs, historyTarget); + }; +} + /** Paths an action on changes refers to: argument, else the change tree's selection (Commit window or Git › Local Changes). */ function changePaths(arg: unknown): string[] | undefined { if (Array.isArray(arg)) return arg.filter((x): x is string => typeof x === "string"); @@ -311,7 +397,22 @@ export function registerHistoryActions(): () => void { category: "Git Log", icon: "diff", when: VCS, - run: withCommit(showCompareWithLocal), + run: withHistoryAwareCompare(showCompareWithLocal), + }, + { + id: "vcs.log.showFileAtRevision", + title: "Show File at Revision", + category: "Git Log", + icon: "file", + when: "vcsAvailable || projectOpen || vcsLogFocus", + hidden: true, + run: ({ arg }) => { + const scoped = isFileHistoryCommitArg(arg) ? arg : null; + const commit = scoped?.commit ?? commitArg(arg); + const target = scoped?.target ?? (arg == null ? activeFileHistoryTarget() : null); + const readOnly = !!commit && "readOnly" in commit && commit.readOnly === true; + if (commit && target) showFileAtRevision(commit, target, readOnly); + }, }, { id: "vcs.log.compareVersions", @@ -319,13 +420,9 @@ export function registerHistoryActions(): () => void { category: "Git Log", icon: "diff", when: VCS, - run: withCommits((cs) => { - if (cs.length !== 2) { - notifications().notify({ group: "vcs", level: "info", title: "Select two commits to compare" }); - return; - } + run: withHistoryAwareCompareVersions((cs, historyTarget) => { // Newest first, as the log shows them. - showCompareVersions(cs[1]!, cs[0]!); + showCompareVersions(cs[1]!, cs[0]!, historyTarget); }), }, { diff --git a/src/features/vcs/log/CommitList.tsx b/src/features/vcs/log/CommitList.tsx index aae07e850..cfb883450 100644 --- a/src/features/vcs/log/CommitList.tsx +++ b/src/features/vcs/log/CommitList.tsx @@ -1,4 +1,5 @@ import type { Commit } from "@/bindings"; +import { setContext } from "@/platform/context"; import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; import { Scrollbar, Spinner, T, hideNativeScrollbar } from "@/ui"; @@ -60,6 +61,11 @@ export function CommitList() { const active = !scope || scope === shown; const all = useGitLog((s) => s.commits); const selection = useGitLog((s) => s.selection); + const fileHistoryTarget = useGitLog((s) => { + const id = scope ?? s.shownLog; + const tab = s.logTabs.find((t) => t.id === id); + return tab?.kind === "history" ? tab.target : null; + }); const earlier = useMemo(() => { const seen = new Set(); return all.some((c) => { @@ -81,6 +87,7 @@ export function CommitList() { const speedGeneration = useRef(0); const speedTimer = useRef | undefined>(undefined); useEffect(() => () => clearTimeout(speedTimer.current), []); + useEffect(() => () => setContext("vcsLogRevisionFocus", false), []); const columns = useMemo(() => { const builtins: LogColumn[] = [ ...(opts.showAuthor ? [{ id: "author", title: "Author", width: 130, render: (c: Commit) => c.author }] : []), @@ -532,6 +539,10 @@ export function CommitList() { aria-multiselectable aria-activedescendant={selectedIndex >= 0 ? `commit-${scope ?? "log"}-${selectedIndex}` : undefined} tabIndex={0} + onFocusCapture={() => setContext("vcsLogRevisionFocus", !!active && !!fileHistoryTarget)} + onBlurCapture={(e) => { + if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("vcsLogRevisionFocus", false); + }} onScroll={(e) => { if (!e.currentTarget.hasAttribute("data-hover-paused")) e.currentTarget.dataset.hoverPaused = ""; setHoverColor(null); @@ -593,6 +604,7 @@ export function CommitList() { key={v.index % items.length} id={`commit-${scope ?? "log"}-${v.index}`} commit={c} + fileHistoryTarget={fileHistoryTarget} graph={rows[v.index]} top={v.start - ROW} selected={selectedSet.has(commitKey(c))} diff --git a/src/features/vcs/log/CommitRow.tsx b/src/features/vcs/log/CommitRow.tsx index 668a14d92..aa585e067 100644 --- a/src/features/vcs/log/CommitRow.tsx +++ b/src/features/vcs/log/CommitRow.tsx @@ -17,6 +17,7 @@ import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared"; function CommitRowView({ id, commit: c, + fileHistoryTarget, graph, top, selected, @@ -39,6 +40,7 @@ function CommitRowView({ }: { id: string; commit: Commit; + fileHistoryTarget: string | null; graph: GraphRow | undefined; top: number; selected: boolean; @@ -158,7 +160,7 @@ function CommitRowView({ }} onContextMenu={(e) => { e.preventDefault(); - showContextMenu(e, commitMenu(c, selectedCommits())); + showContextMenu(e, commitMenu(c, selectedCommits(), fileHistoryTarget)); }} > {opts.showRepository && commitRepo(c) && useVcs.getState().roots.length > 1 && ( diff --git a/src/features/vcs/log/commitMenu.ts b/src/features/vcs/log/commitMenu.ts index 182633eb1..b1e83b605 100644 --- a/src/features/vcs/log/commitMenu.ts +++ b/src/features/vcs/log/commitMenu.ts @@ -9,9 +9,13 @@ import { toggleCommitBookmark, useGitLog } from "../logStore"; import { commitKey, commitRepo, type RepoCommit } from "../multiRoot"; import { browseRepositoryAt } from "../RevisionBrowser"; import { useVcs } from "../store"; +import type { FileHistoryCommitArg, FileHistoryCommitsArg } from "../historyActions"; /** IDEA's Git Log commit context menu (Git.Log.ContextMenu); `selection` = all selected commits, newest first. */ -export function commitMenu(c: Commit, selection: Commit[] = [c]): MenuItem[] { +export function commitMenu(c: Commit, selection: Commit[] = [c], fileHistoryTarget?: string | null): MenuItem[] { + const actionCommit: Commit | FileHistoryCommitArg = fileHistoryTarget + ? { kind: "file-history-commit", commit: c, target: fileHistoryTarget } + : c; if ((c as RepoCommit).readOnly) return [ { kind: "action", action: "vcs.log.copyRevision", arg: c }, @@ -27,6 +31,9 @@ export function commitMenu(c: Commit, selection: Commit[] = [c]): MenuItem[] { { kind: "action", action: "vcs.log.goToParent", arg: c }, { kind: "action", action: "vcs.log.goToChild", arg: c }, { label: "Browse Repository at Revision", run: () => browseRepositoryAt(c) }, + ...(fileHistoryTarget + ? [{ kind: "action" as const, action: "vcs.log.showFileAtRevision", arg: actionCommit }] + : []), ]; const many = selection.length > 1 && selection.some((x) => commitKey(x) === commitKey(c)); const repo = commitRepo(c); @@ -34,12 +41,15 @@ export function commitMenu(c: Commit, selection: Commit[] = [c]): MenuItem[] { const head = (repo ? vcs.heads[repo]?.head : vcs.branch?.head) ?? null; const { outgoing } = useGitLog.getState(); if (many) { + const compareArg: Commit[] | FileHistoryCommitsArg = fileHistoryTarget + ? { kind: "file-history-commits", commits: selection, target: fileHistoryTarget } + : selection; return [ { kind: "action", action: "vcs.log.copyRevision", arg: selection, label: "Copy Revision Numbers" }, { kind: "action", action: "vcs.log.createPatch", arg: selection }, { kind: "action", action: "vcs.log.cherryPick", arg: selection }, ...(selection.length === 2 - ? [{ kind: "action", action: "vcs.log.compareVersions", arg: selection } satisfies MenuItem] + ? [{ kind: "action", action: "vcs.log.compareVersions", arg: compareArg } satisfies MenuItem] : []), { kind: "separator" }, { kind: "action", action: "vcs.log.revert", arg: selection, label: "Revert Commits" }, @@ -82,7 +92,10 @@ export function commitMenu(c: Commit, selection: Commit[] = [c]): MenuItem[] { { kind: "separator" }, { kind: "action", action: "vcs.log.checkoutRevision", arg: c }, { label: "Browse Repository at Revision", run: () => browseRepositoryAt(c) }, - { kind: "action", action: "vcs.log.compareWithLocal", arg: c }, + ...(fileHistoryTarget + ? [{ kind: "action" as const, action: "vcs.log.showFileAtRevision", arg: actionCommit }] + : []), + { kind: "action", action: "vcs.log.compareWithLocal", arg: actionCommit }, { kind: "separator" }, { kind: "action", action: "vcs.log.resetToHere", arg: c }, { kind: "action", action: "vcs.log.revert", arg: c }, diff --git a/src/features/vcs/logChanges.ts b/src/features/vcs/logChanges.ts index 2d369e597..c2dcfa538 100644 --- a/src/features/vcs/logChanges.ts +++ b/src/features/vcs/logChanges.ts @@ -223,7 +223,11 @@ export function changesArg(arg: unknown): LogChange[] { * editor's preview tab, so looking through a commit's files reuses one tab. * `preview`: without taking focus (selection in the pane). */ -export async function showChangesDiff(changes: readonly LogChange[], preview = false) { +export async function showChangesDiff( + changes: readonly LogChange[], + preview = false, + chainChanges: readonly LogChange[] = useLogChanges.getState().all, +) { const first = changes[0]; if (!first) return; if (first.mergeParents?.length === 2 && first.after) { @@ -241,8 +245,7 @@ export async function showChangesDiff(changes: readonly LogChange[], preview = f else await editorService().openInput(input, { preview: true, focus: !preview }); return; } - const all = useLogChanges.getState().all; - const chain = all.includes(first) ? all : [...changes]; + const chain = chainChanges.includes(first) ? chainChanges : [...changes]; const data = withChain( chain.map((c) => c.diff), Math.max(0, chain.indexOf(first)), diff --git a/src/features/vcs/logPaneActions.ts b/src/features/vcs/logPaneActions.ts index f3f98d0c1..014d19ff4 100644 --- a/src/features/vcs/logPaneActions.ts +++ b/src/features/vcs/logPaneActions.ts @@ -1,11 +1,11 @@ -import { focusRepo } from "./store"; /** * Actions of the Git Log's inner panes: the Branches pane toolbar, Graph Options' * linear-branch actions and the changed-files pane (toolbar and context menu). */ import { create } from "zustand"; import type { Branch } from "@/bindings"; -import { registerActions, type Action } from "@/platform/actions"; +import { executeAction, registerActions, type Action } from "@/platform/actions"; +import { relativePath } from "@/platform/project"; import { notifications, toolWindowService } from "@/workbench/contributions"; import { deleteBranches, newBranch, toggleFavoriteBranch, updateBranch } from "./branchOps"; import { @@ -18,11 +18,45 @@ import { useLogChanges, } from "./logChanges"; import { logOptions } from "./logOptions"; -import { goToRef, updateLogOptions } from "./logStore"; +import { goToRef, selectedCommits, updateLogOptions, useGitLog } from "./logStore"; +import { commitKey, commitRepo } from "./multiRoot"; +import { currentRepoRoot, focusRepo } from "./store"; const VCS = "vcsAvailable"; const LOG = "vcsAvailable || projectOpen || vcsLogFocus"; +function showFocusedHistoryDiff() { + const selected = selectedCommits(); + if (selected.length === 2) { + void executeAction("vcs.log.compareVersions"); + return; + } + if (selected.length !== 1) return; + + const state = useGitLog.getState(); + const tab = state.logTabs.find((item) => item.id === state.shownLog); + if (tab?.kind !== "history") return; + + const commit = selected[0]!; + const changes = useLogChanges.getState(); + // The details pane loads asynchronously after a row selection. Never diff a stale pane. + if (changes.commits.length !== 1 || commitKey(changes.commits[0]!) !== commitKey(commit)) { + notifications().notify({ group: "vcs", level: "info", title: "Revision changes are still loading" }); + return; + } + + const root = commitRepo(commit) ?? currentRepoRoot(); + const targetPath = root ? relativePath(root, tab.target) : tab.target; + const historyPath = "historyPath" in commit && typeof commit.historyPath === "string" ? commit.historyPath : null; + const relevant = changes.all.filter( + (change) => + change.path === targetPath || + change.oldPath === targetPath || + (historyPath !== null && (change.path === historyPath || change.oldPath === historyPath)), + ); + if (relevant.length) void showChangesDiff(relevant, false, relevant); +} + /** A ref selected in the Branches pane. */ export interface BranchTarget { ref: string; @@ -152,8 +186,14 @@ export function registerLogPaneActions(): () => void { icon: "diff", when: LOG, hidden: true, - keyWhen: "vcsLogChangesFocus", - run: ({ arg }) => void showChangesDiff(changesArg(arg)), + keyWhen: "vcsLogChangesFocus || vcsLogRevisionFocus", + run: ({ arg, ctx }) => { + if (ctx.vcsLogRevisionFocus) { + showFocusedHistoryDiff(); + return; + } + void showChangesDiff(changesArg(arg)); + }, }, { id: "vcs.log.changes.compareWithLocal", diff --git a/src/features/vcs/operations.tsx b/src/features/vcs/operations.tsx index 1db7f62af..2564fcf89 100644 --- a/src/features/vcs/operations.tsx +++ b/src/features/vcs/operations.tsx @@ -28,6 +28,8 @@ import { tx } from "@/platform/i18n"; import { displayPath } from "./compareData"; import { repositoryPath } from "./repositoryPaths"; import { RepoPicker } from "./gitMenuDialogs"; +import { openRevisionFile } from "./revisionInput"; +import { ipcPath } from "@/platform/paths"; // --------------------------------------------------------------------------- // Operation in progress @@ -518,17 +520,49 @@ function TagDialog({ onClose }: { onClose: () => void }) { } /** Compare with Local: files that differ between the commit and the working tree. */ -export function showCompareWithLocal(commit: Commit) { +export function showCompareWithLocal(commit: Commit, historyTarget?: string | null) { + if (historyTarget) { + const repo = commitRepo(commit) ?? repoOf(historyTarget) ?? currentRepoRoot(); + const historicalPath = commit.historyPath && repo ? repositoryPath(repo, commit.historyPath) : historyTarget; + void openVcsDiff({ + path: historyTarget, + left: { type: "rev", rev: commit.id, path: historicalPath, label: short(commit.id) }, + right: { type: "worktree" }, + }); + return; + } showDiffWithWorkingTree(commit.id, short(commit.id)); } +/** Opens the selected File History entry's file exactly as it exists in that commit. */ +export function showFileAtRevision(commit: Commit, target: string, external = false) { + const repo = commitRepo(commit) ?? repoOf(target) ?? currentRepoRoot(); + if (!repo) return; + const root = ipcPath(repo).replace(/\/$/, ""); + const file = ipcPath(target); + const relative = file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file; + const path = commit.historyPath ?? relative; + openRevisionFile(repo, commit.id, path, external); +} + /** Files that differ between `rev` (a commit or branch) and the working tree, in the Compare tool window. */ export function showDiffWithWorkingTree(rev: string, label = rev) { showWorktreeComparison(rev, label); } /** IDEA's Compare Versions of two Git Log commits: files that differ between them, older first. */ -export function showCompareVersions(older: Commit, newer: Commit) { +export function showCompareVersions(older: Commit, newer: Commit, historyTarget?: string | null) { + if (historyTarget) { + const repo = commitRepo(older) ?? commitRepo(newer) ?? repoOf(historyTarget) ?? currentRepoRoot(); + const olderPath = older.historyPath && repo ? repositoryPath(repo, older.historyPath) : historyTarget; + const newerPath = newer.historyPath && repo ? repositoryPath(repo, newer.historyPath) : historyTarget; + void openVcsDiff({ + path: historyTarget, + left: { type: "rev", rev: older.id, path: olderPath, label: short(older.id) }, + right: { type: "rev", rev: newer.id, path: newerPath, label: short(newer.id) }, + }); + return; + } showComparison({ rev: older.id, label: short(older.id) }, { rev: newer.id, label: short(newer.id) }); } diff --git a/src/features/vcs/revisionInput.ts b/src/features/vcs/revisionInput.ts new file mode 100644 index 000000000..f62b9580b --- /dev/null +++ b/src/features/vcs/revisionInput.ts @@ -0,0 +1,25 @@ +import { useVcs } from "./store"; +import { editorService } from "@/workbench/contributions"; + +export interface RevisionData { + repo: string; + revision: string; + path: string; + external?: boolean; +} + +/** Opens one file at a Git revision in the read-only revision editor. */ +export function openRevisionFile(repo: string, revision: string, path: string, external = false) { + if (useVcs.getState().root) { + const bytes = new TextEncoder().encode(JSON.stringify({ repo, revision, path })); + const encoded = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); + void editorService().openFile(`git-revision:${encoded}/${encodeURIComponent(path.split("/").at(-1)!)}`, { + focus: true, + }); + } else + void editorService().openInput({ + kind: "git-revision", + key: `git-revision:${repo}\0${revision}\0${path}`, + data: { repo, revision, path, external } satisfies RevisionData, + }); +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 762bd5078..fe612c5fb 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -316,8 +316,10 @@ "Cannot show current revision": "Cannot show current revision", "Compare": "Compare", "Compare with Revision…": "Compare with Revision…", + "Revision changes are still loading": "Revision changes are still loading", "Swap Sides": "Swap Sides", "Show Current Revision": "Show Current Revision", + "Show File at Revision": "Show File at 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", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 32027b036..9418a61b2 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -295,6 +295,7 @@ "Cannot show current revision": "无法显示当前修订版", "Compare with Revision…": "与修订版比较…", "Show Current Revision": "显示当前修订版", + "Show File at Revision": "显示此修订版中的文件", "Search file revisions": "搜索文件修订版", "File revisions": "文件修订版", "The current line has no committed revision": "当前行没有已提交的修订版", @@ -2615,6 +2616,7 @@ "Select Standard Library Sources": "选择标准库源代码", "Select TypeScript lib Directory": "选择 TypeScript lib 目录", "Select a changed file to show its diff": "选择一个已更改的文件以显示其差异", + "Revision changes are still loading": "修订的更改仍在加载", "Select a column": "选择一列", "Select a commit in the Git log": "在 Git 日志中选择一个提交", "Select a commit to view changes": "选择一个提交以查看更改",