Файли
openidea/src/features/vcs/logChanges.ts
T
l0ng-ai b16d485f35 feat(vcs): get files from the branch comparison window (#7953)
The Compare with Branch window gets a Get action (toolbar and dialog button) that replaces the selected local files with their content in the compared revision: missing files are created, files the revision lacks are deleted, and a renamed file is restored under its old path. The window can be maximized where the app draws its own title bar.

A file of the revision that is back in the working tree as an untracked file is now one change (modified, or omitted when identical) instead of a deletion plus an untracked file.

Closes #7917
2026-12-04 14:19:28 +08:00

520 рядки
20 KiB
TypeScript

/**
* Git Log changed-files pane: the selected commits' files as one model (a single
* commit's files or the combined changes of several), and what its toolbar and
* context menu do with them.
*/
import { create } from "zustand";
import type { ChangedFile, Commit, FileLineStats, LinkTarget, RevisionChange } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { editorService } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { relativePath } from "@/platform/project";
import { workflowSettings } from "@/platform/workflowSettings";
import { combinedOf } from "./allInOneDiff";
import {
commitFileDiffData,
openDiff,
openVcsDiff,
revisionChangeDiffData,
vcsDiffInFront,
withChain,
type DiffData,
} from "./diffInput";
import type { FileTreeNode } from "./fileTree";
import { baseName } from "./model";
import { readWorkingText, runOp, saveAll, writeFileText } from "./ops";
import { reportApply } from "./shelf";
import { currentRepoRoot, useVcs, vcsKindOf } from "./store";
import { commitRepo } from "./multiRoot";
import { repositoryPath } from "./repositoryPaths";
import { confirmDialog } from "./dialogs";
/** Git's empty tree: a file added in a root commit is diffed against this. */
export const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
/** A file of the pane, with the revisions holding its content before and after the change. */
export interface LogChange {
/** Repository-relative path (after the change). */
path: string;
repo?: string | null;
oldPath: string | null;
kind: ChangedFile["kind"];
/** Set for a symbolic link: what it points to in the revision holding it. */
link?: LinkTarget | null;
/** `null`: the file did not exist before. */
before: string | null;
/** `null`: the change deleted the file. */
after: string | null;
/**
* Revisions whose diff holds this file's line counts. For one commit that is its
* first parent (or the empty tree) and the commit itself, added files included.
*/
statsFrom: string;
statsTo: string;
added?: number;
removed?: number;
diff: DiffData;
readOnly?: boolean;
group?: string;
mergeParents?: Array<{ rev: string; path: string }>;
}
/** One `git diff --numstat` covering every file that shares its endpoints. */
export interface LineStatRange {
repo: string | null;
from: string;
to: string;
paths: string[];
}
/** One commit's files (`commit` given) or several commits' combined changes. */
export function toLogChanges(
files: readonly (ChangedFile | RevisionChange)[],
commit: Pick<Commit, "id" | "shortId" | "parents"> | null,
repo = currentRepoRoot(),
readOnly = false,
): LogChange[] {
return files.map((f) => {
if (commit) {
const parent = commit.parents[0] ?? null;
return {
repo,
readOnly,
path: f.path,
oldPath: f.oldPath,
kind: f.kind,
link: f.link,
before: f.kind === "added" ? null : parent,
after: f.kind === "deleted" ? null : commit.id,
statsFrom: parent ?? EMPTY_TREE,
statsTo: commit.id,
diff: commitFileDiffData({ ...commit, repo }, f),
};
}
const r = f as RevisionChange;
return {
repo,
readOnly: readOnly || (r.path.startsWith("/") && vcsKindOf(repo) === "subversion"),
path: r.path,
oldPath: r.oldPath,
kind: r.kind,
link: r.link,
before: r.before,
after: r.after,
statsFrom: r.before ?? EMPTY_TREE,
statsTo: r.after ?? EMPTY_TREE,
diff: revisionChangeDiffData(r, repo),
};
});
}
/** Groups files that share a diff, so one numstat covers a commit's additions and edits. */
export function lineStatRanges(files: readonly LogChange[]): LineStatRange[] {
const groups = new Map<string, LineStatRange>();
for (const f of files) {
if (!f.statsFrom || !f.statsTo || f.statsFrom === f.statsTo) continue;
const repo = f.repo ?? null;
const key = `${repo ?? ""}\0${f.statsFrom}\0${f.statsTo}`;
let group = groups.get(key);
if (!group) groups.set(key, (group = { repo, from: f.statsFrom, to: f.statsTo, paths: [] }));
if (!group.paths.includes(f.path)) group.paths.push(f.path);
if (f.oldPath && !group.paths.includes(f.oldPath)) group.paths.push(f.oldPath);
}
return [...groups.values()];
}
/** Writes numstat rows onto the files of the same revision pair, matching a rename by either name. */
export function assignLineStats(
files: readonly LogChange[],
loaded: readonly (LineStatRange & { stats: readonly FileLineStats[] })[],
): LogChange[] {
const byPath = new Map<string, FileLineStats>();
for (const range of loaded)
for (const stat of range.stats) {
const put = (path: string) => byPath.set(`${range.repo ?? ""}\0${range.from}\0${range.to}\0${path}`, stat);
put(stat.path);
if (stat.oldPath) put(stat.oldPath);
}
return files.map((f) => {
const repo = f.repo ?? "";
const stat =
byPath.get(`${repo}\0${f.statsFrom}\0${f.statsTo}\0${f.path}`) ??
(f.oldPath ? byPath.get(`${repo}\0${f.statsFrom}\0${f.statsTo}\0${f.oldPath}`) : undefined);
return stat ? { ...f, added: stat.added, removed: stat.removed } : f;
});
}
/** Fills `added` / `removed` from `git diff --numstat`. A failed diff leaves the files uncounted. */
export async function withLineStats(files: LogChange[]): Promise<LogChange[]> {
const ranges = lineStatRanges(files);
if (!ranges.length) return files;
const loaded = await Promise.all(
ranges.map(async (range) => ({
...range,
stats: await call(commands.vcsDiffNumstat(range.repo, range.from, range.to, range.paths)),
})),
);
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
.map((file) => {
const rel = relPath(file);
return { key: `f:${rel}`, name: baseName(rel), file, children: [], count: 1, rel };
})
.sort((a, b) => a.name.localeCompare(b.name) || a.rel.localeCompare(b.rel))
.map(({ rel: _rel, ...n }) => n);
}
/**
* Files of `nodes` in display order; with `keys`, only the selected files and the files
* under selected directories (each once).
*/
export function filesUnder<F>(nodes: readonly FileTreeNode<F>[], keys?: ReadonlySet<string>): F[] {
const out: F[] = [];
const walk = (list: readonly FileTreeNode<F>[], inSelected: boolean) => {
for (const n of list) {
const hit = inSelected || !keys || keys.has(n.key);
if (n.file) {
if (hit) out.push(n.file);
} else walk(n.children, hit);
}
};
walk(nodes, false);
return out;
}
/**
* The sections of a `git diff` patch that touch `paths` (repository-relative; a rename
* matches by either name, in either direction for a reversed patch).
*/
export function filterPatch(patch: string, paths: ReadonlySet<string>): string {
const sections = patch.split(/^(?=diff --git )/m);
const header = /^diff --git ("?)a\/(.+?)\1 ("?)b\/(.+?)\3$/;
return sections
.filter((s) => {
const first = s.slice(0, s.indexOf("\n") >>> 0);
const m = header.exec(first);
return !!m && (paths.has(m[2]!) || paths.has(m[4]!));
})
.join("");
}
/** Absolute path of a repository-relative one. */
export function absolutePath(rel: string, root = currentRepoRoot()): string {
return repositoryPath(root, rel);
}
/** Pane state the changed-files actions work on when they get no argument. */
export interface LogChangesState {
/** The selected commits, newest first. */
commits: Commit[];
/** Every file of the pane, in display order. */
all: LogChange[];
/** The selected files. */
selected: LogChange[];
}
export const useLogChanges = create<LogChangesState>(() => ({ commits: [], all: [], selected: [] }));
/** The files an action refers to: its argument, else the pane's selection. */
export function changesArg(arg: unknown): LogChange[] {
if (Array.isArray(arg)) return arg as LogChange[];
return useLogChanges.getState().selected;
}
/**
* The first file's diff with every file of the pane in the chain (F7 moves along); null without
* files, or for a merge commit's file, which shows a merge diff of its own.
*/
export function changesDiffData(
changes: readonly LogChange[],
chainChanges: readonly LogChange[] = useLogChanges.getState().all,
): DiffData | null {
const first = changes[0];
if (!first || (first.mergeParents?.length === 2 && first.after)) return null;
const chain = chainChanges.includes(first) ? chainChanges : [...changes];
return withChain(
chain.map((c) => c.diff),
Math.max(0, chain.indexOf(first)),
);
}
/**
* Show Diff: the first file, with every file of the pane in the chain (F7 moves along), in the
* 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,
chainChanges: readonly LogChange[] = useLogChanges.getState().all,
) {
const first = changes[0];
if (!first) return;
if (first.mergeParents?.length === 2 && first.after) {
const input = {
kind: "git-merge-diff",
key: `git-merge-diff:${first.repo}:${first.after}:${first.path}`,
data: {
repo: first.repo ?? currentRepoRoot(),
revision: first.after,
path: first.path,
parents: first.mergeParents,
},
};
if (!preview && vcsDiffInFront()) (await import("./diffDialog")).openMergeDiffDialog(input);
else await editorService().openInput(input, { preview: true, focus: !preview });
return;
}
const data = changesDiffData(changes, chainChanges)!;
// Selection preview stays a preview tab even under the modal interface; an explicit
// diff opens where the commit interface puts it. With "Open diff as editor tab" off
// (and no all-in-one diff) that is a separate window, so there is no tab to preview in.
if (preview) {
if (!vcsDiffInFront() && !workflowSettings().vcs.diffAsEditorTab && !combinedOf(data)) return;
await openDiff(data, { preview: true, focus: false });
} else await openVcsDiff(data, { preview: true });
}
/** Compare the selected files' saved revisions with their working copies. */
export async function compareChangesWithLocal(changes: readonly LogChange[], side: "after" | "before" = "after") {
const diffs = changes.flatMap((change): DiffData[] => {
const rev = change[side];
if (!rev || change.readOnly) return [];
const revPath = side === "before" && change.oldPath ? absolutePath(change.oldPath, change.repo) : undefined;
return [
{
path: absolutePath(change.path, change.repo),
left: { type: "rev", rev, path: revPath, label: rev.slice(0, 8) },
right: { type: "worktree" },
},
];
});
if (diffs.length) await openVcsDiff(withChain(diffs, 0));
}
/** Jump to Source: the working file. */
export async function openChangeSource(change: LogChange) {
if (change.readOnly) return;
const path = absolutePath(change.path, change.repo);
const kind = await call(commands.fsEntryKind(path)).catch(() => null);
if (kind === "file") await editorService().openFile(path, { focus: true });
}
/**
* Open Repository Version: files that exist after the change. Directory rows are flattened
* to their files before actions run; readOnly prevents working-tree edits, not revision viewing.
*/
export function canOpenRepositoryVersion(changes: readonly LogChange[]): boolean {
return changes.some((change) => !!change.after && change.link !== "dir" && !!(change.repo ?? currentRepoRoot()));
}
/** A working file and the revision content it takes; none: the file is deleted. */
export interface RevisionFile {
path: string;
from?: { path: string; rev: string };
}
/**
* Get from Revision: the working files take their content after the change; a file the
* change deleted is deleted.
*/
export async function getFromRevision(changes: readonly LogChange[]) {
if (changes.some((c) => c.readOnly)) return;
await getFilesFromRevision(
changes.map((c) => {
const path = absolutePath(c.path, c.repo);
return { path, from: c.after ? { path, rev: c.after } : undefined };
}),
);
}
/** Replaces working files with revision content after a confirmation; true when it ran. */
export async function getFilesFromRevision(files: readonly RevisionFile[]): Promise<boolean> {
if (!files.length) return false;
const ok = await confirmDialog({
title: "Get from Revision",
message:
files.length === 1
? tx`Replace '${baseName(files[0]!.path)}' with its content from the revision? Local changes to it are lost.`
: tx`Replace ${files.length} files with their content from the revision? Local changes to them are lost.`,
okLabel: "Get",
danger: true,
});
if (!ok) return false;
await saveAll();
await runOp(
tx("Get from Revision"),
async () => {
for (const f of files) {
if (!f.from) {
// oxlint-disable-next-line no-await-in-loop -- a deleted file is removed only after checking it still exists; working-tree operations stay ordered
if ((await readWorkingText(f.path)) !== null) await call(commands.fsDelete(f.path));
continue;
}
// oxlint-disable-next-line no-await-in-loop -- the file's revision text must be read before it can be written to the working tree
const text = await call(commands.vcsFileAt(f.from.path, f.from.rev));
if (text === null) continue;
// oxlint-disable-next-line no-await-in-loop -- a missing working file is created before its content is written, one file at a time
if ((await readWorkingText(f.path)) === null) await call(commands.fsCreateFile(f.path));
// oxlint-disable-next-line no-await-in-loop -- files are written in selection order so the working tree is updated deterministically
await writeFileText(f.path, text, { save: true });
}
return files.length;
},
{ success: (n) => (n === 1 ? tx("Got 1 file from revision") : tx`Got ${n} files from revision`) },
);
return true;
}
/** Revert Selected Changes: applies the reverse of the selected files' changes to the working tree. */
export async function revertSelectedChanges(changes: readonly LogChange[], commits: readonly Commit[]) {
if (changes.some((c) => c.readOnly)) return;
if (!changes.length || !commits.length) return;
const repo = changes[0]!.repo ?? currentRepoRoot();
if (changes.some((c) => (c.repo ?? currentRepoRoot()) !== repo)) return;
await saveAll();
// Oldest first; the backend reverses the order for a reversed patch.
const ids = [...commits]
.reverse()
.filter((c) => (commitRepo(c) ?? currentRepoRoot()) === repo)
.map((c) => c.id);
if (!ids.length) return;
const paths = new Set(changes.flatMap((c) => (c.oldPath ? [c.path, c.oldPath] : [c.path])));
const outcome = await runOp(
tx("Revert selected changes"),
async () => {
const patch = filterPatch(
await call(
commands.vcsCreatePatch(
changes[0]!.repo ?? currentRepoRoot(),
{ from: "commits", commits: ids, reverse: true },
null,
),
),
paths,
);
if (!patch.trim()) throw new Error(tx("Nothing to revert"));
return call(commands.vcsApplyPatch(changes[0]!.repo ?? currentRepoRoot(), patch, null));
},
{ refresh: false },
);
if (outcome) await reportApply(outcome, "Changes reverted");
}
export function canApplySelectedChanges(changes: readonly LogChange[]): boolean {
if (!changes.length || changes.some((change) => change.readOnly || change.statsFrom === change.statsTo)) return false;
const repo = changes[0]!.repo ?? currentRepoRoot();
if (!repo || changes.some((change) => (change.repo ?? currentRepoRoot()) !== repo)) return false;
const paths = new Set<string>();
for (const change of changes) {
if (paths.has(change.path) || (change.oldPath && paths.has(change.oldPath))) return false;
paths.add(change.path);
if (change.oldPath) paths.add(change.oldPath);
}
return true;
}
export async function applySelectedChanges(changes: readonly LogChange[]) {
if (!canApplySelectedChanges(changes)) return;
const repo = changes[0]!.repo ?? currentRepoRoot();
if (!repo) return;
const ranges = lineStatRanges(changes);
await saveAll();
const outcome = await runOp(
tx("Apply Selected Changes"),
async () => {
const patches = await Promise.all(
ranges.map(({ from, to, paths }) =>
call(commands.vcsCreatePatch(repo, { from: "revisions", before: from, after: to, paths }, null)),
),
);
const patch = patches.join("");
if (!patch.trim()) throw new Error(tx("Nothing to apply"));
return call(commands.vcsApplyPatch(repo, patch, null));
},
{ refresh: false },
);
if (outcome) await reportApply(outcome, tx("Changes applied"));
}
/** The changes of `commit` to the file whose history shows `target` (its name at that revision, after a rename). */
export function historyFileChanges<T extends Pick<LogChange, "path" | "oldPath">>(
commit: Commit & { repo?: string | null; historyPath?: string | null },
target: string,
changes: readonly T[],
): T[] {
const root = commitRepo(commit) ?? currentRepoRoot();
const targetPath = root ? relativePath(root, target) : target;
const historyPath = typeof commit.historyPath === "string" ? commit.historyPath : null;
return changes.filter(
(change) =>
change.path === targetPath ||
change.oldPath === targetPath ||
(historyPath !== null && (change.path === historyPath || change.oldPath === historyPath)),
);
}