perf(vcs): read only the clicked file's change for the annotate gutter's Show Diff (#7257)

Show Diff in the annotate gutter listed every change of the blamed commit, with rename detection, only to learn how one file changed; on a commit touching thousands of files that was the whole wait. A new vcs_commit_file_change reads the file off the commit's and first parent's trees, and only runs the rename search for an added file, against the commit's deletions. Backend::commit_file_change defaults to filtering commit_files, so other backends (SVN) stay correct.

Fixes #7169

Co-authored-by: Pecnikas <[email protected]>
Цей коміт міститься в:
Ivan authored and GitHub committed 2026-12-02 05:02:36 +08:00
1 джерело 6c36723a7d
коміт 878e86e10c
11 files changed
+223 -26

No files matched your search

+15
Переглянути файл
@@ -1114,6 +1114,20 @@ pub async fn vcs_commit_files(
blocking(move || project.with_log_backend_at(repo.as_deref(), |r| r.commit_files(&commit))).await
}
/// What `commit` did to one file (`path`, relative to the repository), without listing the
/// commit's other changes; `None` when it left the file as it was.
#[command(trust = always)]
pub async fn vcs_commit_file_change(
host: &Host,
window: &str,
repo: Option<PathBuf>,
commit: String,
path: String,
) -> IdeResult<Option<ChangedFile>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_backend_at(repo.as_deref(), |r| r.commit_file_change(&commit, &path))).await
}
#[command(trust = trusted)]
pub async fn vcs_preview_partial_commit(host: &Host, window: &str, file: PartialCommitFile) -> IdeResult<String> {
let project = host.project(window)?;
@@ -3600,6 +3614,7 @@ ide_command::domain!(
vcs_commit,
vcs_keep_amend_commit,
vcs_commit_crlf_paths,
vcs_commit_file_change,
vcs_commit_files,
vcs_commit_large_files,
vcs_preview_partial_commit,
+10
Переглянути файл
@@ -246,6 +246,11 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
call!("vcs_revision_files", "", vcs::vcs_revision_files(host, w, root(), project.head.clone())),
call!("vcs_revision_files", "missing tree", vcs::vcs_revision_files(host, w, root(), project.promised.clone())),
call!("vcs_commit_files", "", vcs::vcs_commit_files(host, w, root(), project.head.clone())),
call!(
"vcs_commit_file_change",
"",
vcs::vcs_commit_file_change(host, w, root(), project.head.clone(), "src/a.txt".into())
),
call!("vcs_commits_changes", "", vcs::vcs_commits_changes(host, w, root(), vec![project.head.clone()])),
call!("vcs_branches", "", vcs::vcs_branches(host, w, root())),
call!("vcs_stashes", "", vcs::vcs_stashes(host, w, root())),
@@ -326,6 +331,11 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
),
call!("vcs_revision_files", "external", vcs::vcs_revision_files(host, w, log(), external.head.clone())),
call!("vcs_commit_files", "external", vcs::vcs_commit_files(host, w, log(), external.head.clone())),
call!(
"vcs_commit_file_change",
"external",
vcs::vcs_commit_file_change(host, w, log(), external.head.clone(), "src/a.txt".into())
),
(
"vcs_review_apply_commit",
"paused cherry-pick",
+10
Переглянути файл
@@ -158,6 +158,12 @@ pub trait Backend: Send + Sync + Any {
/// Files `commit` changed.
fn commit_files(&self, commit: &str) -> IdeResult<Vec<ChangedFile>>;
/// What `commit` did to the one file `path`; `None` when it left the file as it was. Backends
/// that can read one file's change without listing the whole commit override this.
fn commit_file_change(&self, commit: &str, path: &str) -> IdeResult<Option<ChangedFile>> {
Ok(self.commit_files(commit)?.into_iter().find(|f| f.path == path))
}
/// The per-file changes a set of commits made, for a combined diff.
fn commits_changes(&self, commits: &[String]) -> IdeResult<Vec<RevisionChange>>;
@@ -422,6 +428,10 @@ impl Backend for Repo {
Repo::commit_files(self, commit)
}
fn commit_file_change(&self, commit: &str, path: &str) -> IdeResult<Option<ChangedFile>> {
Repo::commit_file_change(self, commit, path)
}
fn commits_changes(&self, commits: &[String]) -> IdeResult<Vec<RevisionChange>> {
Repo::commits_changes(self, commits)
}
+89 -2
Переглянути файл
@@ -1609,8 +1609,11 @@ struct CommitChanges {
files: Vec<ChangedFile>,
}
/// Files changed by `rev` relative to its first parent (renames detected), sorted by path.
fn first_parent_changes(repo: &gix::Repository, rev: &str) -> IdeResult<CommitChanges> {
/// A commit's id, its first parent and the trees of both (`None` for a root commit).
fn commit_trees<'r>(
repo: &'r gix::Repository,
rev: &str,
) -> IdeResult<(ObjectId, Option<ObjectId>, gix::Tree<'r>, Option<gix::Tree<'r>>)> {
let id = resolve(repo, rev)?;
let commit = repo.find_object(id).map_err(gx)?.peel_to_commit().map_err(gx)?;
let id = commit.id;
@@ -1620,6 +1623,90 @@ fn first_parent_changes(repo: &gix::Repository, rev: &str) -> IdeResult<CommitCh
Some(p) => Some(repo.find_commit(p).map_err(gx)?.tree().map_err(gx)?),
None => None,
};
Ok((id, parent, new_tree, old_tree))
}
/// What `rev` did to the one file `path` (its path after the change) relative to the first parent,
/// as `commit_files` lists it, without reading the changes of the commit's other files: a modified
/// or deleted file is read off the two trees, and only an added one is checked for a rename, against
/// the commit's deletions. `None` when the commit left the file as it was.
pub(crate) fn commit_file_change(r: &Repo, rev: &str, path: &str) -> IdeResult<Option<ChangedFile>> {
let repo = r.gix()?;
let (_, _, new_tree, old_tree) = commit_trees(&repo, rev)?;
let blob_at = |tree: Option<&gix::Tree<'_>>| -> IdeResult<Option<(gix::object::tree::EntryMode, ObjectId)>> {
let Some(tree) = tree else { return Ok(None) };
let entry = tree.lookup_entry_by_path(Path::new(path)).map_err(gx)?;
Ok(entry.filter(|e| !e.mode().is_tree()).map(|e| (e.mode(), e.oid().to_owned())))
};
let (new, old) = (blob_at(Some(&new_tree))?, blob_at(old_tree.as_ref())?);
let (kind, old_path, link_tree) = match (new, old) {
(None, None) => return Ok(None),
(Some(n), Some(o)) if n == o => return Ok(None),
(Some(_), Some(_)) => (ChangeKind::Modified, None, Some(&new_tree)),
// A deleted link is described as it was in the parent.
(None, Some(_)) => (ChangeKind::Deleted, None, old_tree.as_ref()),
(Some(_), None) => match renamed_source(&repo, old_tree.as_ref(), &new_tree, path)? {
Some(source) => (ChangeKind::Renamed, Some(source), Some(&new_tree)),
None => (ChangeKind::Added, None, Some(&new_tree)),
},
};
let is_link = new.or(old).is_some_and(|(mode, _)| mode.is_link());
let link = if is_link { link_tree.and_then(|t| link_target(&repo, t, path)) } else { None };
Ok(Some(ChangedFile { path: path.to_string(), kind, old_path, link }))
}
/// The path the added file `path` was renamed from in the commit: the rename search of
/// `first_parent_changes`, run over this file and the commit's deletions only.
fn renamed_source(
repo: &gix::Repository,
old_tree: Option<&gix::Tree<'_>>,
new_tree: &gix::Tree<'_>,
path: &str,
) -> IdeResult<Option<String>> {
use gix::diff::tree::visit::Change as V;
use gix::object::tree::diff::ChangeDetached as C;
let Some(old_tree) = old_tree else { return Ok(None) };
// Without rewrites this lists the changed entries cheaply: equal subtrees are skipped.
let mut opts = gix::diff::Options::default();
opts.track_path();
let mut tracker = gix::diff::rewrites::Tracker::new(gix::diff::Rewrites::default());
let mut deletions = false;
for change in repo.diff_tree_to_tree(Some(old_tree), Some(new_tree), Some(opts)).map_err(gx)? {
match change {
C::Deletion { location, entry_mode, id, .. } if !entry_mode.is_tree() => {
deletions = true;
tracker.try_push_change(V::Deletion { entry_mode, oid: id, relation: None }, location.as_ref());
}
C::Addition { location, entry_mode, id, .. } if !entry_mode.is_tree() && location == path.as_bytes() => {
tracker.try_push_change(V::Addition { entry_mode, oid: id, relation: None }, location.as_ref());
}
_ => {}
}
}
if !deletions {
return Ok(None);
}
let mut cache = repo.diff_resource_cache_for_tree_diff().map_err(gx)?;
let mut source = None;
tracker
.emit(
|dest, from| {
if let Some(from) = from.filter(|_| dest.location == path.as_bytes()) {
source = Some(to_string(from.location));
}
std::ops::ControlFlow::Continue(())
},
&mut cache,
&repo.objects,
|_| Ok::<(), std::convert::Infallible>(()),
)
.map_err(gx)?;
Ok(source)
}
/// Files changed by `rev` relative to its first parent (renames detected), sorted by path.
fn first_parent_changes(repo: &gix::Repository, rev: &str) -> IdeResult<CommitChanges> {
let (id, parent, new_tree, old_tree) = commit_trees(repo, rev)?;
let mut opts = gix::diff::Options::default();
opts.track_path().track_rewrites(Some(gix::diff::Rewrites::default()));
let changes = repo.diff_tree_to_tree(old_tree.as_ref(), Some(&new_tree), Some(opts)).map_err(gx)?;
+6
Переглянути файл
@@ -1643,6 +1643,12 @@ impl Repo {
let _scope = self.execution_scope();
history::commit_files(self, commit)
}
/// What `commit` did to the one file `path`, as `commit_files` lists it; `None` when it left
/// the file as it was. Does not read the commit's other changes.
pub fn commit_file_change(&self, commit: &str, path: &str) -> IdeResult<Option<ChangedFile>> {
let _scope = self.execution_scope();
history::commit_file_change(self, commit, path)
}
/// Combined changes of several commits (oldest first): per file, before the first commit
/// that touched it ↔ after the last one (IDEA's multi-commit Git Log selection).
pub fn commits_changes(&self, commits: &[String]) -> IdeResult<Vec<RevisionChange>> {
+46
Переглянути файл
@@ -769,6 +769,52 @@ fn commit_files_kinds() {
assert!(repo.commit_files("HEAD").unwrap().len() == 4);
}
/// Show Diff in the annotate gutter reads one file's change (#7169); it agrees with the commit's full list.
#[test]
fn commit_file_change_agrees_with_commit_files() {
let fx = Fixture::new();
let long = "a fairly long line of content\nanother line\nand a third\nand a fourth one\n";
fx.write("keep.txt", "k\n");
fx.write("mod.txt", "m\n");
fx.write("del.txt", "d\n");
fx.write("old_name.txt", long);
fx.write("same.txt", "s\n");
let root = fx.commit_all("root");
fx.write("mod.txt", "m2\n");
std::fs::remove_file(fx.path("del.txt")).unwrap();
fx.write("dir/added.txt", "new\n");
fx.write("dir/other_added.txt", "other\n");
fx.git(&["mv", "old_name.txt", "dir/new_name.txt"]);
fx.write("dir/new_name.txt", &format!("{long}and a fifth\n"));
let c = fx.commit_all("changes");
let repo = fx.repo();
for rev in [&root, &c] {
let files = repo.commit_files(rev).unwrap();
assert!(!files.is_empty());
for f in &files {
let one =
repo.commit_file_change(rev, &f.path).unwrap().unwrap_or_else(|| panic!("{}: {files:#?}", f.path));
assert_eq!((one.kind, one.old_path.as_deref()), (f.kind, f.old_path.as_deref()), "{}", f.path);
assert_eq!(one.path, f.path);
}
}
let change = |p: &str| repo.commit_file_change(&c, p).unwrap();
assert_eq!(change("mod.txt").unwrap().kind, ChangeKind::Modified);
assert_eq!(change("del.txt").unwrap().kind, ChangeKind::Deleted);
assert_eq!(change("dir/added.txt").unwrap().kind, ChangeKind::Added);
let renamed = change("dir/new_name.txt").unwrap();
assert_eq!((renamed.kind, renamed.old_path.as_deref()), (ChangeKind::Renamed, Some("old_name.txt")));
// The commit left these as they were, or they are not files of it at all.
for p in ["keep.txt", "same.txt", "dir", "nope.txt"] {
assert!(change(p).is_none(), "{p}");
}
// The old name of a rename is the commit's deletion of that path.
assert_eq!(change("old_name.txt").unwrap().kind, ChangeKind::Deleted);
// A root commit adds everything.
assert_eq!(repo.commit_file_change(&root, "mod.txt").unwrap().unwrap().kind, ChangeKind::Added);
}
/// Stages a symbolic link (mode 120000) to `target` without touching the working tree, so
/// the test needs no symlink support from the file system.
fn stage_link(fx: &Fixture, path: &str, target: &str) {
+1
Переглянути файл
@@ -808,6 +808,7 @@ vcs_checkout_affected_files trusted project_host bin
vcs_clone always project_host bindings async
vcs_commit trusted project_host bindings async
vcs_commit_crlf_paths trusted project_host bindings async
vcs_commit_file_change always project_host bindings async
vcs_commit_files always project_host bindings async
vcs_commit_large_files trusted project_host bindings async
vcs_commit_push_target always project_host bindings async
+11
Переглянути файл
@@ -2407,6 +2407,17 @@ export const commands = {
vcsClone: (request: RequestId, url: string, dest: string, depth: number | null, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_clone", { request, url, dest, depth, onOutput })),
vcsCommit: (repo: string | null, message: string, options: CommitOptions_Deserialize) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_commit", { repo, message, options })),
vcsCommitCrlfPaths: (repo: string, paths: string[], options: CommitOptions_Deserialize, request: RequestId) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("vcs_commit_crlf_paths", { repo, paths, options, request })),
/**
* What `commit` did to one file (`path`, relative to the repository), without listing the
* commit's other changes; `None` when it left the file as it was.
*/
vcsCommitFileChange: (repo: string | null, commit: string, path: string) => typedError<{
path: string,
kind: ChangeKind,
oldPath: string | null,
/** Set when the entry is a symbolic link (git mode `120000`); only revision diffs fill it. */
link?: LinkTarget | null,
} | null, IdeError>(__TAURI_INVOKE("vcs_commit_file_change", { repo, commit, path })),
vcsCommitFiles: (repo: string | null, commit: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_commit_files", { repo, commit })),
vcsCommitLargeFiles: (repo: string, paths: string[], options: CommitOptions_Deserialize, limit: number, request: RequestId) => typedError<LargeCommitFile[], IdeError>(__TAURI_INVOKE("vcs_commit_large_files", { repo, paths, options, limit, request })),
/** Chooses the source branch and configured destination for a single Git Log commit. */
+23 -17
Переглянути файл
@@ -18,7 +18,7 @@ const mocks = vi.hoisted(() => ({
openDiff: vi.fn(),
blame: vi.fn(),
log: vi.fn(),
commitFiles: vi.fn(),
commitFileChange: vi.fn(),
notify: vi.fn(),
}));
@@ -30,7 +30,12 @@ vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
commands: { ...actual.commands, vcsBlame: mocks.blame, vcsLog: mocks.log, vcsCommitFiles: mocks.commitFiles },
commands: {
...actual.commands,
vcsBlame: mocks.blame,
vcsLog: mocks.log,
vcsCommitFileChange: mocks.commitFileChange,
},
};
});
vi.mock("@/workbench/contributions", async (original) => ({
@@ -58,7 +63,7 @@ beforeEach(() => {
useVcs.setState({ available: true, root: "/repo", repo: "/repo", roots: ["/repo"] });
mocks.openDiff.mockResolvedValue(undefined);
mocks.log.mockResolvedValue({ status: "ok", data: [commit([parent])] });
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "a.py", kind: "modified", oldPath: null }] });
mocks.commitFileChange.mockResolvedValue({ status: "ok", data: { path: "a.py", kind: "modified", oldPath: null } });
mocks.blame.mockResolvedValue({
status: "ok",
data: [
@@ -175,7 +180,7 @@ describe("show diff from the annotate gutter", () => {
"/repo",
expect.objectContaining({ branch: sha, path: "/repo/a.py", follow: true, limit: 1 }),
);
expect(mocks.commitFiles).toHaveBeenCalledWith("/repo", sha);
expect(mocks.commitFileChange).toHaveBeenCalledWith("/repo", sha, "a.py");
expect(mocks.openDiff).toHaveBeenCalledWith(
{
path: "/repo/a.py",
@@ -194,7 +199,7 @@ describe("show diff from the annotate gutter", () => {
});
it("shows the file as added when the commit added it", async () => {
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "a.py", kind: "added", oldPath: null }] });
mocks.commitFileChange.mockResolvedValue({ status: "ok", data: { path: "a.py", kind: "added", oldPath: null } });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(
expect.objectContaining({ left: absent("(does not exist)"), right: expect.objectContaining({ rev: sha }) }),
@@ -203,12 +208,9 @@ describe("show diff from the annotate gutter", () => {
});
it("shows the old name on the left when the commit renamed the file", async () => {
mocks.commitFiles.mockResolvedValue({
mocks.commitFileChange.mockResolvedValue({
status: "ok",
data: [
{ path: "b.py", kind: "modified", oldPath: null },
{ path: "a.py", kind: "renamed", oldPath: "old/a.py" },
],
data: { path: "a.py", kind: "renamed", oldPath: "old/a.py" },
});
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(
@@ -230,13 +232,13 @@ describe("show diff from the annotate gutter", () => {
it("asks the line's repository, not the selected one", async () => {
useVcs.setState({ repo: "/repo", roots: ["/repo", "/other"] });
mocks.commitFiles.mockResolvedValue({
mocks.commitFileChange.mockResolvedValue({
status: "ok",
data: [{ path: "src/b.go", kind: "modified", oldPath: null }],
data: { path: "src/b.go", kind: "modified", oldPath: null },
});
await showRevisionDiff("/other/src/b.go", sha);
expect(mocks.log).toHaveBeenCalledWith("/other", expect.anything());
expect(mocks.commitFiles).toHaveBeenCalledWith("/other", sha);
expect(mocks.commitFileChange).toHaveBeenCalledWith("/other", sha, "src/b.go");
expect(mocks.openDiff).toHaveBeenCalledWith(expect.objectContaining({ path: "/other/src/b.go" }), {
preview: false,
});
@@ -244,9 +246,13 @@ describe("show diff from the annotate gutter", () => {
it("uses the file's name at the commit when it was renamed later", async () => {
mocks.log.mockResolvedValue({ status: "ok", data: [{ ...commit([parent]), historyPath: "old.py" }] });
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "old.py", kind: "modified", oldPath: null }] });
mocks.commitFileChange.mockResolvedValue({
status: "ok",
data: { path: "old.py", kind: "modified", oldPath: null },
});
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.log).toHaveBeenCalledTimes(1);
expect(mocks.commitFileChange).toHaveBeenCalledWith("/repo", sha, "old.py");
expect(mocks.openDiff).toHaveBeenCalledWith(
{
path: "/repo/old.py",
@@ -274,14 +280,14 @@ describe("show diff from the annotate gutter", () => {
);
});
it("falls back to the current path when the commit doesn't list the file", async () => {
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "b.py", kind: "modified", oldPath: null }] });
it("falls back to the current path when the commit doesn't change the file", async () => {
mocks.commitFileChange.mockResolvedValue({ status: "ok", data: null });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).toHaveBeenCalledWith(expect.objectContaining({ path: "/repo/a.py" }), { preview: false });
});
it("reports a failure instead of opening a diff", async () => {
mocks.commitFiles.mockResolvedValue({ status: "error", error: "bad revision" });
mocks.commitFileChange.mockResolvedValue({ status: "error", error: "bad revision" });
await showRevisionDiff("/repo/a.py", sha);
expect(mocks.openDiff).not.toHaveBeenCalled();
expect(mocks.notify).toHaveBeenCalledWith(
+5 -5
Переглянути файл
@@ -26,7 +26,7 @@ const mocks = vi.hoisted(() => ({
log: vi.fn(),
action: vi.fn(),
notify: vi.fn(),
commitFiles: vi.fn(),
commitFileChange: vi.fn(),
openDiff: vi.fn(),
menu: vi.fn(),
settingsSet: vi.fn(),
@@ -47,7 +47,7 @@ vi.mock("@/platform/ipc", async (original) => {
...actual.commands,
vcsBlame: mocks.blame,
vcsLog: mocks.log,
vcsCommitFiles: mocks.commitFiles,
vcsCommitFileChange: mocks.commitFileChange,
settingsSet: mocks.settingsSet,
},
};
@@ -165,9 +165,9 @@ describe("git blame gutter and commit popup", () => {
status: "ok",
data: lines.map((line) => ({ ...line, originPath })),
});
mocks.commitFiles.mockResolvedValue({
mocks.commitFileChange.mockResolvedValue({
status: "ok",
data: [{ path: origin.slice("/repo/".length), kind: "added", oldPath: null }],
data: { path: origin.slice("/repo/".length), kind: "added", oldPath: null },
});
view = new EditorView({
parent: document.body,
@@ -194,7 +194,7 @@ describe("git blame gutter and commit popup", () => {
items[1]!.run!();
await vi.waitFor(() => expect(mocks.openDiff).toHaveBeenCalled());
expect(mocks.commitFiles).toHaveBeenCalledWith("/repo", sha);
expect(mocks.commitFileChange).toHaveBeenCalledWith("/repo", sha, origin.slice("/repo/".length));
expect(mocks.openDiff).toHaveBeenCalledWith(
expect.objectContaining({
path: origin,
+7 -2
Переглянути файл
@@ -137,12 +137,17 @@ export async function showRevisionDiff(path: string, commit: string, line?: numb
}),
);
try {
const [[inHistory], files] = await Promise.all([log(path), call(commands.vcsCommitFiles(repo, commit))]);
const [inHistory] = await log(path);
// A line's commit is in its file's history; a merge commit may not be, so read it directly then.
const found = inHistory?.id === commit ? inHistory : (await log(null))[0];
if (!found) return;
const name = (found === inHistory && found.historyPath) || relative;
const changed = files.find((f) => f.path === name) ?? { path: name, kind: "modified", oldPath: null };
// Only this file's change: listing a large commit's changes would make Show Diff wait for all of them.
const changed = (await call(commands.vcsCommitFileChange(repo, commit, name))) ?? {
path: name,
kind: "modified",
oldPath: null,
};
const data = commitFileDiffData({ ...found, repo }, changed);
await openDiff(line == null ? data : { ...data, line, lineSide: "right" }, { preview: false });
} catch (e) {