дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
feat(vcs): create patches from selected historical files (#6981)
Git Log and File History changed files get Create Patch and Copy as Patch to Clipboard, in the toolbar and the context menu. Only the selected repository-relative paths are exported, as path-filtered revision diffs with Git's empty tree on the missing side of additions and deletions and both names for renames. The existing patch dialog, base directory defaults, reverse option and clipboard flow are reused; empty, malformed, no-op, mixed-repository and external-repository selections are disabled. Co-authored-by: muutot <[email protected]>
Цей коміт міститься в:
1 джерело
2b7a18ffd7
коміт
baab92c804
12 files changed
+493
-6
No files matched your search
@@ -99,3 +99,116 @@ test("File History opens its revision and compares only that file with the worki
|
||||
.poll(async () => ipcCalls(page, "vcs_file_at"))
|
||||
.toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION });
|
||||
});
|
||||
|
||||
test("File History creates and copies a patch for only the selected changed file", async ({ workbench: page }) => {
|
||||
const parent = "b".repeat(40);
|
||||
const selectedPath = "src/selected.ts";
|
||||
const otherPath = "src/other.ts";
|
||||
const patch = `diff --git a/${selectedPath} b/${selectedPath}\n`;
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ root, path, revision, parent, selectedPath, otherPath }) => {
|
||||
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: [parent],
|
||||
refs: [],
|
||||
author: "Author",
|
||||
email: "[email protected]",
|
||||
timeMs: 1,
|
||||
summary: "Export selected history file",
|
||||
message: "Export selected history file",
|
||||
historyPath: selectedPath,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
h.vcs_log_refs = () => ({});
|
||||
h.vcs_log_users = () => ["Author <[email protected]>"];
|
||||
h.vcs_log_details_batch = () => [];
|
||||
h.vcs_commit_files = () => [
|
||||
{ path: selectedPath, kind: "modified", oldPath: null },
|
||||
{ path: otherPath, kind: "modified", oldPath: null },
|
||||
];
|
||||
h.vcs_create_patch = ({ source }) => {
|
||||
const paths = (source as { paths?: string[] }).paths ?? [];
|
||||
return paths.map((entry) => `diff --git a/${entry} b/${entry}\n`).join("");
|
||||
};
|
||||
h.vcs_write_patch = () => null;
|
||||
h.clipboard_write_text = () => null;
|
||||
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectModule);
|
||||
useProject.setState((state: { settings: Record<string, unknown> }) => ({
|
||||
settings: {
|
||||
...state.settings,
|
||||
vcs: { confirmation: { onPatchCreated: "no" } },
|
||||
},
|
||||
}));
|
||||
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: `${ROOT}/${selectedPath}`, revision: REVISION, parent, selectedPath, otherPath },
|
||||
);
|
||||
|
||||
const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option", {
|
||||
name: /Export selected history file/,
|
||||
});
|
||||
await expect(row).toBeVisible();
|
||||
await row.click();
|
||||
const tree = page.getByRole("tree", { name: "Changed files" });
|
||||
const selected = tree.getByText("selected.ts", { exact: true });
|
||||
await expect(selected).toBeVisible();
|
||||
await expect(tree.getByText("other.ts", { exact: true })).toBeVisible();
|
||||
const toolbar = page.getByRole("toolbar", { name: "Changed files" });
|
||||
const create = toolbar.getByRole("button", { name: "Create Patch…", exact: true });
|
||||
await expect(create).toBeDisabled();
|
||||
await selected.click();
|
||||
await expect(create).toBeEnabled();
|
||||
await create.click();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Create Patch", exact: true });
|
||||
await expect(dialog.getByRole("textbox", { name: "Base directory" })).toHaveValue(ROOT);
|
||||
const destination = await dialog.getByRole("textbox", { name: "Patch file" }).inputValue();
|
||||
expect(destination).toBe(`${ROOT}/Export_selected_history_file.patch`);
|
||||
await dialog.getByRole("button", { name: "Create", exact: true }).click();
|
||||
const source = { from: "revisions", before: parent, after: REVISION, paths: [selectedPath] };
|
||||
await expect.poll(() => ipcCalls(page, "vcs_create_patch")).toEqual([{ repo: ROOT, base: ROOT, source }]);
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_write_patch"))
|
||||
.toEqual([expect.objectContaining({ path: destination, patch })]);
|
||||
|
||||
await selected.click({ button: "right" });
|
||||
await page
|
||||
.getByRole("menu", { name: "Context menu" })
|
||||
.getByRole("menuitem", { name: "Copy as Patch to Clipboard", exact: true })
|
||||
.click();
|
||||
await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: patch }]);
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_create_patch"))
|
||||
.toEqual([
|
||||
{ repo: ROOT, base: ROOT, source },
|
||||
{ repo: ROOT, base: null, source },
|
||||
]);
|
||||
});
|
||||
@@ -308,6 +308,13 @@ describe("Git Log commit actions", () => {
|
||||
"Fix_crash_on_start.patch",
|
||||
);
|
||||
expect(suggestedPatchName({ kind: "commits", commits: [commit("a"), commit("b")] }, "x")).toBe("2_commits.patch");
|
||||
expect(
|
||||
suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("Fix: historical file!")] }, "x"),
|
||||
).toBe("Fix_historical_file.patch");
|
||||
expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("a"), commit("b")] }, "x")).toBe(
|
||||
"2_commits.patch",
|
||||
);
|
||||
expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [] }, "Changes")).toBe("0_files.patch");
|
||||
expect(suggestedPatchName({ kind: "changes", files: [] }, "///")).toBe("changes.patch");
|
||||
});
|
||||
});
|
||||
@@ -42,10 +42,12 @@ import { graphOptionsMenu } from "../log/FilterBar";
|
||||
import {
|
||||
EMPTY_TREE,
|
||||
assignLineStats,
|
||||
canCreatePatchFromLogChanges,
|
||||
filesUnder,
|
||||
filterPatch,
|
||||
flatFileNodes,
|
||||
lineStatRanges,
|
||||
logPatchRanges,
|
||||
toLogChanges,
|
||||
useLogChanges,
|
||||
} from "../logChanges";
|
||||
@@ -122,6 +124,78 @@ describe("changed files model", () => {
|
||||
expect(rootFile!.statsFrom).toBe(EMPTY_TREE);
|
||||
});
|
||||
|
||||
it("builds path-filtered historical patch ranges, including empty trees and both rename paths", () => {
|
||||
const previous = useVcs.getState();
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
|
||||
try {
|
||||
const older: Commit = { ...commit, id: "a".repeat(40), parents: ["9".repeat(40)], timeMs: 1 };
|
||||
const newer: Commit = { ...commit, id: "b".repeat(40), parents: [older.id], timeMs: 2 };
|
||||
const changes = [
|
||||
...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"),
|
||||
...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"),
|
||||
...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"),
|
||||
...toLogChanges([{ path: "deleted.ts", kind: "deleted", oldPath: null }], newer, "/repo"),
|
||||
];
|
||||
const paths = ["edited.ts", "new.ts", "old.ts"];
|
||||
expect(canCreatePatchFromLogChanges(changes)).toBe(true);
|
||||
expect(logPatchRanges(changes)).toEqual([
|
||||
{ repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] },
|
||||
{ repo: "/repo", before: older.id, after: newer.id, paths },
|
||||
{ repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["deleted.ts"] },
|
||||
]);
|
||||
expect(logPatchRanges(changes, true)).toEqual([
|
||||
{ repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["added.ts"] },
|
||||
{ repo: "/repo", before: newer.id, after: older.id, paths },
|
||||
{ repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["deleted.ts"] },
|
||||
]);
|
||||
|
||||
const other = { ...changes[1]!, repo: "/other" };
|
||||
useVcs.setState({ roots: ["/repo", "/other"] });
|
||||
expect(canCreatePatchFromLogChanges([changes[0]!, other])).toBe(false);
|
||||
expect(logPatchRanges([changes[0]!, other])).toEqual([]);
|
||||
const ambiguous = { ...changes[0]!, repo: null };
|
||||
expect(canCreatePatchFromLogChanges([ambiguous])).toBe(false);
|
||||
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, readOnly: true }])).toBe(true);
|
||||
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, repo: "/external", readOnly: true }])).toBe(false);
|
||||
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, oldPath: 42 as unknown as string }])).toBe(false);
|
||||
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, before: newer.id, after: newer.id }])).toBe(false);
|
||||
expect(canCreatePatchFromLogChanges([])).toBe(false);
|
||||
} finally {
|
||||
useVcs.setState(previous);
|
||||
}
|
||||
});
|
||||
|
||||
it("enables changed-file patch actions and menu rows only for an applicable selection", () => {
|
||||
const previous = useVcs.getState();
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo", "/other"] });
|
||||
const files = toLogChanges(
|
||||
[
|
||||
{ path: "a.ts", kind: "modified", oldPath: null },
|
||||
{ path: "b.ts", kind: "modified", oldPath: null },
|
||||
],
|
||||
commit,
|
||||
"/repo",
|
||||
);
|
||||
const dispose = registerLogPaneActions();
|
||||
try {
|
||||
for (const id of ["vcs.log.changes.createPatch", "vcs.log.changes.copyPatch"]) {
|
||||
const action = getAction(id)!;
|
||||
expect(action.enabled!({ ctx: {}, arg: [] })).toBe(false);
|
||||
expect(action.enabled!({ ctx: {}, arg: files })).toBe(true);
|
||||
expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/other" }] })).toBe(true);
|
||||
expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/external" }] })).toBe(false);
|
||||
const item = (changes: ReturnType<typeof toLogChanges>) =>
|
||||
changesMenu(changes).find((entry) => "action" in entry && entry.action === id);
|
||||
expect(item(files)).toMatchObject({ arg: files, disabled: false });
|
||||
expect(item([])).toMatchObject({ disabled: true });
|
||||
expect(item([{ ...files[0]!, repo: "/external" }])).toMatchObject({ disabled: true });
|
||||
}
|
||||
} finally {
|
||||
dispose();
|
||||
useVcs.setState(previous);
|
||||
}
|
||||
});
|
||||
|
||||
it("asks for one numstat per revision pair and matches a rename by either name", () => {
|
||||
const files = toLogChanges(
|
||||
[
|
||||
@@ -265,6 +339,8 @@ describe("rename label", () => {
|
||||
|
||||
describe("changed files pane", () => {
|
||||
it("shows the files flat or by directory and shares the selection with its actions", async () => {
|
||||
const previous = useVcs.getState();
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
|
||||
vcsCommitFiles.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
@@ -275,10 +351,16 @@ describe("changed files pane", () => {
|
||||
useGitLog.setState({ commits: [commit], selected: commit.id, selection: [commit.id] });
|
||||
const { unmount } = render(<CommitDetails commits={[commit]} />);
|
||||
expect(await screen.findByText("src")).toBeInTheDocument();
|
||||
const createPatch = screen.getByRole("button", { name: "Create Patch…" });
|
||||
const copyPatch = screen.getByRole("button", { name: "Copy as Patch to Clipboard" });
|
||||
expect(createPatch).toBeDisabled();
|
||||
expect(copyPatch).toBeDisabled();
|
||||
fireEvent.mouseDown(screen.getByText("a.ts"));
|
||||
expect(useLogChanges.getState().selected.map((c) => c.path)).toEqual(["src/a.ts"]);
|
||||
expect(useLogChanges.getState().commits).toEqual([commit]);
|
||||
expect(screen.getByRole("button", { name: "Show Diff" })).toBeEnabled();
|
||||
expect(createPatch).toBeEnabled();
|
||||
expect(copyPatch).toBeEnabled();
|
||||
|
||||
useLogOptions.setState({ groupByDirectory: false });
|
||||
expect(await screen.findByText("b.ts")).toBeInTheDocument();
|
||||
@@ -286,6 +368,7 @@ describe("changed files pane", () => {
|
||||
expect(screen.getAllByText("src")).toHaveLength(2);
|
||||
unmount();
|
||||
expect(useLogChanges.getState().selected).toEqual([]);
|
||||
useVcs.setState(previous);
|
||||
});
|
||||
|
||||
it("shows added and deleted lines when the log option is on", async () => {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { Commit, PatchSource } from "@/bindings";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createPatch: vi.fn(),
|
||||
writeClipboardText: vi.fn(),
|
||||
openDialog: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsCreatePatch: (repo: string | null, source: PatchSource, base: string | null) =>
|
||||
mocks.createPatch(repo, source, base),
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/platform/clipboard", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/clipboard")>()),
|
||||
writeClipboardText: mocks.writeClipboardText,
|
||||
}));
|
||||
vi.mock("../dialogs", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../dialogs")>()),
|
||||
openDialog: mocks.openDialog,
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify: mocks.notify }),
|
||||
}));
|
||||
|
||||
import { EMPTY_TREE, toLogChanges } from "../logChanges";
|
||||
import { copyLogChangesAsPatch } from "../patches";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const commit = (id: string, parents: string[], timeMs: number): Commit => ({
|
||||
id: id.repeat(40),
|
||||
shortId: id.repeat(8),
|
||||
parents,
|
||||
author: "A",
|
||||
email: "[email protected]",
|
||||
timeMs,
|
||||
summary: `Commit ${id}`,
|
||||
message: `Commit ${id}`,
|
||||
refs: [],
|
||||
});
|
||||
|
||||
const originalVcs = useVcs.getState();
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.createPatch.mockReset();
|
||||
mocks.writeClipboardText.mockReset();
|
||||
mocks.openDialog.mockReset();
|
||||
mocks.notify.mockReset();
|
||||
mocks.writeClipboardText.mockResolvedValue(undefined);
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
|
||||
});
|
||||
|
||||
afterEach(() => useVcs.setState(originalVcs));
|
||||
|
||||
describe("Git Log changed-file patches", () => {
|
||||
it("copies exactly the selected revision/path ranges, with both names of a rename", async () => {
|
||||
const older = commit("a", ["9".repeat(40)], 1);
|
||||
const newer = commit("b", [older.id], 2);
|
||||
const changes = [
|
||||
...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"),
|
||||
...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"),
|
||||
...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"),
|
||||
];
|
||||
mocks.createPatch.mockImplementation(async (_repo: string, source: PatchSource) => ({
|
||||
status: "ok" as const,
|
||||
data: source.from === "revisions" ? `patch ${source.before} ${source.after} ${source.paths.join(",")}\n` : "",
|
||||
}));
|
||||
await copyLogChangesAsPatch(changes);
|
||||
|
||||
expect(mocks.createPatch.mock.calls).toEqual([
|
||||
["/repo", { from: "revisions", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] }, null],
|
||||
[
|
||||
"/repo",
|
||||
{
|
||||
from: "revisions",
|
||||
before: older.id,
|
||||
after: newer.id,
|
||||
paths: ["edited.ts", "new.ts", "old.ts"],
|
||||
},
|
||||
null,
|
||||
],
|
||||
]);
|
||||
expect(mocks.writeClipboardText).toHaveBeenCalledExactlyOnceWith(
|
||||
`patch ${EMPTY_TREE} ${older.id} added.ts\npatch ${older.id} ${newer.id} edited.ts,new.ts,old.ts\n`,
|
||||
);
|
||||
expect(mocks.openDialog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not touch the clipboard for empty, mixed-repository or external read-only selections", async () => {
|
||||
const c = commit("c", ["9".repeat(40)], 1);
|
||||
const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo");
|
||||
await copyLogChangesAsPatch([]);
|
||||
await copyLogChangesAsPatch([files[0]!, { ...files[0]!, repo: "/other" }]);
|
||||
await copyLogChangesAsPatch([{ ...files[0]!, repo: "/external", readOnly: true }]);
|
||||
expect(mocks.createPatch).not.toHaveBeenCalled();
|
||||
expect(mocks.writeClipboardText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves the clipboard untouched when Git returns an empty patch", async () => {
|
||||
const c = commit("c", ["9".repeat(40)], 1);
|
||||
const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo");
|
||||
mocks.createPatch.mockResolvedValue({ status: "ok", data: "" });
|
||||
await copyLogChangesAsPatch(files);
|
||||
expect(mocks.writeClipboardText).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ group: "vcs", level: "info", title: "No changes to create a patch from" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,7 @@ import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree";
|
||||
import styles from "../GitLog.module.css";
|
||||
import {
|
||||
canApplySelectedChanges,
|
||||
canCreatePatchFromLogChanges,
|
||||
canOpenRepositoryVersion,
|
||||
absolutePath,
|
||||
changesArg,
|
||||
@@ -412,6 +413,22 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
|
||||
actionArg={chosenChanges}
|
||||
disabled={!chosenChanges.length}
|
||||
/>
|
||||
<IconButton
|
||||
icon="patch"
|
||||
size="small"
|
||||
title="Create Patch…"
|
||||
action="vcs.log.changes.createPatch"
|
||||
actionArg={chosenChanges}
|
||||
disabled={!canCreatePatchFromLogChanges(chosenChanges)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="copy"
|
||||
size="small"
|
||||
title="Copy as Patch to Clipboard"
|
||||
action="vcs.log.changes.copyPatch"
|
||||
actionArg={chosenChanges}
|
||||
disabled={!canCreatePatchFromLogChanges(chosenChanges)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="revert"
|
||||
size="small"
|
||||
@@ -590,6 +607,19 @@ export function changesMenu(changes: LogChange[], source?: { commit: Commit; tot
|
||||
disabled: !canOpenRepositoryVersion(changes),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.createPatch",
|
||||
arg: changes,
|
||||
disabled: !canCreatePatchFromLogChanges(changes),
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.copyPatch",
|
||||
arg: changes,
|
||||
disabled: !canCreatePatchFromLogChanges(changes),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.apply",
|
||||
|
||||
@@ -23,7 +23,7 @@ import type { FileTreeNode } from "./fileTree";
|
||||
import { baseName } from "./model";
|
||||
import { readWorkingText, runOp, saveAll, writeFileText } from "./ops";
|
||||
import { reportApply } from "./shelf";
|
||||
import { currentRepoRoot } from "./store";
|
||||
import { currentRepoRoot, useVcs } from "./store";
|
||||
import { commitRepo } from "./multiRoot";
|
||||
import { repositoryPath } from "./repositoryPaths";
|
||||
import { confirmDialog } from "./dialogs";
|
||||
@@ -156,6 +156,66 @@ export async function withLineStats(files: LogChange[]): Promise<LogChange[]> {
|
||||
return assignLineStats(files, loaded);
|
||||
}
|
||||
|
||||
/** One repository's selected historical files between the same two revisions. */
|
||||
export interface LogPatchRange {
|
||||
repo: string;
|
||||
before: string;
|
||||
after: string;
|
||||
paths: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The repository a historical patch can safely use. A missing row repository is
|
||||
* unambiguous only when the project has one root; otherwise callers must retain it.
|
||||
*/
|
||||
export function logPatchRepository(changes: readonly LogChange[]): string | null {
|
||||
if (!changes.length) return null;
|
||||
const state = useVcs.getState();
|
||||
const fallback = state.roots.length === 1 ? state.roots[0]! : state.roots.length ? null : (state.repo ?? state.root);
|
||||
const repo = changes[0]!.repo ?? fallback;
|
||||
if (!repo || changes.some((change) => (change.repo ?? fallback) !== repo)) return null;
|
||||
return state.roots.length && !state.roots.includes(repo) ? null : repo;
|
||||
}
|
||||
|
||||
/** Create Patch is an export: empty, malformed, read-only external and mixed-repository selections cannot use it. */
|
||||
export function canCreatePatchFromLogChanges(changes: readonly LogChange[]): boolean {
|
||||
if (!changes.length || !logPatchRepository(changes)) return false;
|
||||
return (
|
||||
changes.every(
|
||||
(change) =>
|
||||
typeof change.path === "string" &&
|
||||
change.path.length > 0 &&
|
||||
(change.oldPath === null || (typeof change.oldPath === "string" && change.oldPath.length > 0)) &&
|
||||
(change.before === null || (typeof change.before === "string" && change.before.length > 0)) &&
|
||||
(change.after === null || (typeof change.after === "string" && change.after.length > 0)) &&
|
||||
(change.before !== null || change.after !== null),
|
||||
) && changes.some((change) => (change.before ?? EMPTY_TREE) !== (change.after ?? EMPTY_TREE))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Path-filtered revision diffs for exactly the selected rows. Added and deleted
|
||||
* files use Git's empty tree on their missing side; renames include both names.
|
||||
* Reversing swaps each range's endpoints, including the empty tree.
|
||||
*/
|
||||
export function logPatchRanges(changes: readonly LogChange[], reverse = false): LogPatchRange[] {
|
||||
if (!canCreatePatchFromLogChanges(changes)) return [];
|
||||
const repo = logPatchRepository(changes)!;
|
||||
const ranges = new Map<string, LogPatchRange>();
|
||||
for (const change of changes) {
|
||||
const before = (reverse ? change.after : change.before) ?? EMPTY_TREE;
|
||||
const after = (reverse ? change.before : change.after) ?? EMPTY_TREE;
|
||||
if (before === after) continue;
|
||||
const key = `${before}\0${after}`;
|
||||
let range = ranges.get(key);
|
||||
if (!range) ranges.set(key, (range = { repo, before, after, paths: [] }));
|
||||
for (const path of change.oldPath ? [change.path, change.oldPath] : [change.path]) {
|
||||
if (path && !range.paths.includes(path)) range.paths.push(path);
|
||||
}
|
||||
}
|
||||
return [...ranges.values()];
|
||||
}
|
||||
|
||||
/** Files without directory grouping: by name, each node's path shown next to it. */
|
||||
export function flatFileNodes<F>(files: readonly F[], relPath: (f: F) => string): FileTreeNode<F>[] {
|
||||
return files
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { isFavoriteBranch } from "./branches";
|
||||
import {
|
||||
applySelectedChanges,
|
||||
canCreatePatchFromLogChanges,
|
||||
canOpenRepositoryVersion,
|
||||
changesArg,
|
||||
compareChangesWithLocal,
|
||||
@@ -32,6 +33,7 @@ import { logOptions } from "./logOptions";
|
||||
import { goToRef, selectedCommits, toggleCherryHighlight, updateLogOptions, useGitLog } from "./logStore";
|
||||
import { commitKey, commitRepo } from "./multiRoot";
|
||||
import { dropSelectedChanges, extractSelectedChanges } from "./rebase";
|
||||
import { copyLogChangesAsPatch, showCreatePatchForLogChanges } from "./patches";
|
||||
import { openRevisionFile } from "./revisionInput";
|
||||
import { currentRepoRoot, focusRepo } from "./store";
|
||||
import { showCompareBranches, type BranchComparisonTarget, type BranchComparisonData } from "./CompareBranches";
|
||||
@@ -301,6 +303,28 @@ export function registerLogPaneActions(): () => void {
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vcs.log.changes.createPatch",
|
||||
title: "Create Patch…",
|
||||
category: "Git Log",
|
||||
icon: "patch",
|
||||
when: LOG,
|
||||
hidden: true,
|
||||
keyWhen: "vcsLogChangesFocus",
|
||||
enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)),
|
||||
run: ({ arg }) => showCreatePatchForLogChanges(changesArg(arg), useLogChanges.getState().commits),
|
||||
},
|
||||
{
|
||||
id: "vcs.log.changes.copyPatch",
|
||||
title: "Copy as Patch to Clipboard",
|
||||
category: "Git Log",
|
||||
icon: "copy",
|
||||
when: LOG,
|
||||
hidden: true,
|
||||
keyWhen: "vcsLogChangesFocus",
|
||||
enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)),
|
||||
run: ({ arg }) => copyLogChangesAsPatch(changesArg(arg)),
|
||||
},
|
||||
{
|
||||
id: "vcs.log.changes.getFromRevision",
|
||||
title: "Get from Revision",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard";
|
||||
import { commitRepo } from "./multiRoot";
|
||||
import { canCreatePatchFromLogChanges, logPatchRanges, logPatchRepository, type LogChange } from "./logChanges";
|
||||
/** Create Patch… (from local changes or commits) and Apply Patch… (file or clipboard, with a preview). */
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
import type {
|
||||
@@ -68,15 +69,20 @@ import { useDiffSource } from "./diffSource";
|
||||
export type PatchOrigin =
|
||||
| { kind: "changes"; files: FileStatus[]; staging?: readonly StagingPatchEntry[] }
|
||||
| { kind: "commits"; commits: Commit[] }
|
||||
| { kind: "logChanges"; changes: LogChange[]; commits: Commit[] }
|
||||
| { kind: "shelf"; entry: ShelvedChangeList; path?: string };
|
||||
|
||||
/** File name IDEA suggests: the change list or commit subject, sanitised. */
|
||||
export function suggestedPatchName(origin: PatchOrigin, listName: string): string {
|
||||
const base =
|
||||
origin.kind === "commits"
|
||||
origin.kind === "commits" || origin.kind === "logChanges"
|
||||
? origin.commits.length === 1
|
||||
? origin.commits[0]!.summary
|
||||
: `${origin.commits.length} commits`
|
||||
: origin.commits.length > 1
|
||||
? `${origin.commits.length} commits`
|
||||
: origin.kind === "logChanges"
|
||||
? `${origin.changes.length} files`
|
||||
: "0 commits"
|
||||
: origin.kind === "shelf"
|
||||
? origin.entry.name
|
||||
: listName;
|
||||
@@ -160,6 +166,38 @@ export function showCreatePatchForCommits(commits: Commit[]) {
|
||||
openDialog((close) => <CreatePatchDialog origin={{ kind: "commits", commits }} onClose={close} />);
|
||||
}
|
||||
|
||||
async function createLogChangesPatch(changes: readonly LogChange[], reverse: boolean, base: string | null) {
|
||||
const patches = await Promise.all(
|
||||
logPatchRanges(changes, reverse).map(({ repo, before, after, paths }) =>
|
||||
call(commands.vcsCreatePatch(repo, { from: "revisions", before, after, paths }, base)),
|
||||
),
|
||||
);
|
||||
return patches.join("");
|
||||
}
|
||||
|
||||
export function showCreatePatchForLogChanges(changes: LogChange[], commits: Commit[]) {
|
||||
if (!canCreatePatchFromLogChanges(changes)) return;
|
||||
openDialog((close) => <CreatePatchDialog origin={{ kind: "logChanges", changes, commits }} onClose={close} />);
|
||||
}
|
||||
|
||||
/** Copy the selected historical files as a patch directly, without the Create Patch dialog. */
|
||||
export async function copyLogChangesAsPatch(changes: readonly LogChange[]) {
|
||||
if (!canCreatePatchFromLogChanges(changes)) return;
|
||||
await runOp(
|
||||
tx("Create patch"),
|
||||
async () => {
|
||||
const patch = await createLogChangesPatch(changes, false, null);
|
||||
if (!patch) {
|
||||
noPatchChanges();
|
||||
return false;
|
||||
}
|
||||
await writeClipboardText(patch);
|
||||
return true;
|
||||
},
|
||||
{ success: (copied) => (copied ? "Patch copied to the clipboard" : ""), refresh: false },
|
||||
);
|
||||
}
|
||||
|
||||
export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string) {
|
||||
openDialog((close) => <CreatePatchDialog origin={{ kind: "shelf", entry, path }} onClose={close} />);
|
||||
}
|
||||
@@ -220,7 +258,11 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
|
||||
const root = useVcs((s) => s.root) ?? "";
|
||||
const roots = useVcs((s) => s.roots);
|
||||
const [repo] = useState(() =>
|
||||
origin.kind === "commits" ? (commitRepo(origin.commits[0]!) ?? currentRepoRoot()) : currentRepoRoot(),
|
||||
origin.kind === "commits"
|
||||
? (commitRepo(origin.commits[0]!) ?? currentRepoRoot())
|
||||
: origin.kind === "logChanges"
|
||||
? (logPatchRepository(origin.changes) ?? currentRepoRoot())
|
||||
: currentRepoRoot(),
|
||||
);
|
||||
const listName = useChangelists((s) => activeList(s.state).name);
|
||||
const [selected, setSelected] = useState(
|
||||
@@ -254,7 +296,7 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
|
||||
setPending(true);
|
||||
setError("");
|
||||
const source: PatchSource | null =
|
||||
origin.kind === "shelf"
|
||||
origin.kind === "shelf" || origin.kind === "logChanges"
|
||||
? null
|
||||
: origin.kind === "changes"
|
||||
? localPatchSource(origin, selected, reverse)
|
||||
@@ -273,7 +315,9 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
|
||||
? await call(
|
||||
commands.vcsShelfPatch(origin.entry.id, origin.path ?? null, baseInput === null ? null : directory),
|
||||
)
|
||||
: await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory));
|
||||
: origin.kind === "logChanges"
|
||||
? await createLogChangesPatch(origin.changes, reverse, directory)
|
||||
: await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory));
|
||||
if (!patch) {
|
||||
noPatchChanges();
|
||||
return false;
|
||||
|
||||
@@ -122,6 +122,8 @@ describe("IDEA keymap parity", () => {
|
||||
// Vcs.Log.GoToRef: Find in the Git Log table.
|
||||
["vcs.log.goToRef", ["Meta+F"], ["Ctrl+F"]],
|
||||
["vcs.log.maximizeCommitMessage", [], []],
|
||||
["vcs.log.changes.createPatch", [], []],
|
||||
["vcs.log.changes.copyPatch", [], []],
|
||||
["vcs.log.refresh", ["Meta+R"], ["Ctrl+F5"]],
|
||||
["vcs.log.focusTextFilter", ["Ctrl+L"], ["Ctrl+L"]],
|
||||
// Back / Forward also carry the mouse side buttons (`<mouse-shortcut keystroke="button4"/>`).
|
||||
|
||||
@@ -389,6 +389,8 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"vcs.addToVcs": ["Meta+Alt+A"],
|
||||
"vcs.showDiff": ["Meta+D"],
|
||||
"vcs.log.changes.showDiff": ["Meta+D"],
|
||||
"vcs.log.changes.createPatch": [],
|
||||
"vcs.log.changes.copyPatch": [],
|
||||
"vcs.showDiffInNewWindow": [],
|
||||
"vcs.nextChange": ["Ctrl+Alt+Shift+Down"],
|
||||
"vcs.prevChange": ["Ctrl+Alt+Shift+Up"],
|
||||
|
||||
@@ -383,6 +383,8 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"vcs.addToVcs": ["Ctrl+Alt+A"],
|
||||
"vcs.showDiff": ["Ctrl+D"],
|
||||
"vcs.log.changes.showDiff": ["Ctrl+D"],
|
||||
"vcs.log.changes.createPatch": [],
|
||||
"vcs.log.changes.copyPatch": [],
|
||||
"vcs.showDiffInNewWindow": [],
|
||||
"vcs.nextChange": ["Ctrl+Alt+Shift+Down"],
|
||||
"vcs.prevChange": ["Ctrl+Alt+Shift+Up"],
|
||||
|
||||
@@ -402,6 +402,8 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"vcs.addToVcs": [],
|
||||
"vcs.showDiff": [],
|
||||
"vcs.log.changes.showDiff": [],
|
||||
"vcs.log.changes.createPatch": [],
|
||||
"vcs.log.changes.copyPatch": [],
|
||||
"vcs.showDiffInNewWindow": [],
|
||||
"vcs.nextChange": ["Alt+F5"],
|
||||
"vcs.prevChange": ["Alt+Shift+F5"],
|
||||
|
||||
Reference in new issue
Заблокувати користувача