diff --git a/crates/ide-vcs/src/history.rs b/crates/ide-vcs/src/history.rs index 6e4c051971..28dae2bf47 100644 --- a/crates/ide-vcs/src/history.rs +++ b/crates/ide-vcs/src/history.rs @@ -764,7 +764,7 @@ fn log_indexed_rows( return Ok(Vec::new()); } let (decorations, _) = r.ref_decorations(&repo)?; - let paths: Vec = q + let mut paths: Vec = q .path .iter() .chain(&q.paths) @@ -773,6 +773,12 @@ fn log_indexed_rows( .into_iter() .filter(|p| !p.is_empty()) .collect(); + // A staged rename's history is under the name HEAD has. + if let [path] = paths.as_mut_slice() + && let Some(committed) = r.committed_path(path) + { + *path = committed; + } let range_ids = if let Some(range) = range { Some(range_ids(r, range, q.order, q.first_parent, cancel)?) } else if !ranges.is_empty() { diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index 00dafd0ba7..a534e8de22 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -1362,7 +1362,8 @@ impl Repo { /// Deletions have `lines == 0` and `start` = the line of the current text that now /// follows the removed block (equal to the line count when removed at the end). /// Files absent from the base yield one `Added` hunk; ignored files, binary files and - /// paths outside the worktree yield no hunks. + /// paths outside the worktree yield no hunks. A staged rename is compared with HEAD's + /// copy under the name it was committed as. pub fn line_hunks( &self, path: &Path, @@ -1377,7 +1378,14 @@ impl Repo { return Ok(Vec::new()); } let repo = self.gix()?; - let base = repo::blob_at(&repo, &rel, if against_index { ":0" } else { "HEAD" })?; + let rev = if against_index { ":0" } else { "HEAD" }; + let mut base = repo::blob_at(&repo, &rel, rev)?; + if base.is_none() + && !against_index + && let Some(committed) = self.committed_path(&rel) + { + base = repo::blob_at(&repo, &committed, rev)?; + } match base { Some(base) if text_encoding::is_binary(&base, encoding) => Ok(Vec::new()), Some(base) => Ok(diff::line_hunks(&text_encoding::decode(&base, encoding), current_text)), diff --git a/crates/ide-vcs/src/repo.rs b/crates/ide-vcs/src/repo.rs index eddb56c51d..2696bdbcc7 100644 --- a/crates/ide-vcs/src/repo.rs +++ b/crates/ide-vcs/src/repo.rs @@ -260,6 +260,40 @@ impl Repo { Ok(self.index_spelling(self.given_rel_path(path)?)) } + /// Where HEAD has the file at `rel` when it lacks `rel`: the source of a staged rename, as + /// status reports it in `renamed_from`. Only a path that the index has and HEAD lacks pays for + /// comparing HEAD's tree with the index; a failure there counts as no rename. + pub(crate) fn committed_path(&self, rel: &str) -> Option { + let lookup = || -> IdeResult> { + let repo = self.gix()?; + let index = repo.index_or_empty().map_err(gx)?; + if rel.is_empty() || index.entry_by_path(rel.as_bytes().as_bstr()).is_none() { + return Ok(None); + } + let Some(tree) = tree_of(&repo, "HEAD")? else { return Ok(None) }; + if tree.lookup_entry_by_path(Path::new(rel)).map_err(gx)?.is_some() { + return Ok(None); + } + let mut source = None; + repo.tree_index_status(&tree.id, &index, None, crate::status::staged_renames(), |change, _, _| { + use gix::diff::index::ChangeRef; + if let ChangeRef::Rewrite { source_location, location, copy: false, .. } = change + && location.as_ref() == rel.as_bytes() + { + source = Some(to_string(source_location.as_ref())); + return Ok(std::ops::ControlFlow::Break(())); + } + Ok(std::ops::ControlFlow::Continue(())) + }) + .map_err(gx)?; + Ok(source) + }; + lookup().unwrap_or_else(|e| { + tracing::debug!("no committed name for {rel}: {}", e.message); + None + }) + } + /// The blob of `path` at `rev`. A revision may spell a file differently from the index (a /// case-only rename staged or made since it): the spelling given wins when the revision has /// it, the index's spelling is the fallback. diff --git a/crates/ide-vcs/src/status.rs b/crates/ide-vcs/src/status.rs index 9ba7107095..0f8b038848 100644 --- a/crates/ide-vcs/src/status.rs +++ b/crates/ide-vcs/src/status.rs @@ -179,6 +179,11 @@ impl DiskSpelling { type Entries = (BTreeMap, HashSet); +/// How a staged deletion and addition pair up into the rename status reports as `renamed_from`. +pub(crate) fn staged_renames() -> gix::status::tree_index::TrackRenames { + gix::status::tree_index::TrackRenames::Given(gix::diff::Rewrites::default()) +} + /// Stat checks for a work tree on a network share: mtime and size only. /// /// A share's index is usually written by git on the server too, whose inode, owner and change @@ -220,7 +225,7 @@ fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult { .untracked_files(gix::status::UntrackedFiles::Files) .index_worktree_rewrites(None) .index_worktree_submodules(gix::status::Submodule::AsConfigured { check_dirty: true }) - .tree_index_track_renames(gix::status::tree_index::TrackRenames::Given(gix::diff::Rewrites::default())); + .tree_index_track_renames(staged_renames()); let mut iter = platform.into_iter(Vec::::new()).map_err(gx)?; for item in iter.by_ref() { let item = item.map_err(gx)?; diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs index 221944650f..1519a93c08 100644 --- a/crates/ide-vcs/src/write.rs +++ b/crates/ide-vcs/src/write.rs @@ -127,6 +127,11 @@ pub(crate) fn blame( Some(rev) => check_rev(rev)?, None => "HEAD", }; + // A staged rename's history is under the name HEAD has; the lines stay this file's, so their + // origin is reported against `rel`. + let committed = (revision == "HEAD").then(|| r.committed_path(&rel)).flatten(); + let history = committed.as_deref().unwrap_or(&rel); + let history_path = committed.as_deref().map_or_else(|| path.to_path_buf(), |name| r.abs_path(name)); let disk = match std::fs::read(r.abs_path(&rel)) { Ok(bytes) => bytes, Err(_) if current_text.is_some() => Vec::new(), @@ -147,9 +152,17 @@ pub(crate) fn blame( args.push("--no-textconv"); } args.extend(ignore.iter().map(String::as_str)); - let plain_args = [args.as_slice(), &[revision, "--", &rel]].concat(); + let plain_args = [args.as_slice(), &[revision, "--", history]].concat(); if encoding.has_ascii_conversion() { - return converted_blame(r, path, (&rel, revision), &text, encoding, &plain_args, options.ignore_whitespace); + return converted_blame( + r, + &history_path, + (&rel, revision), + &text, + encoding, + &plain_args, + options.ignore_whitespace, + ); } let contents = match current_text { Some(_) if crate::diff::normalize_eol(&text) == crate::diff::normalize_eol(&decode(&disk, encoding)) => disk, @@ -170,7 +183,7 @@ pub(crate) fn blame( let line_count = text.split_inclusive('\n').count(); let tracked_in_head = { let repo = r.gix()?; - crate::repo::blob_at(&repo, &rel, revision)?.is_some() + crate::repo::blob_at(&repo, history, revision)?.is_some() }; if !tracked_in_head { return Ok(uncommitted_lines(line_count)); @@ -186,7 +199,7 @@ pub(crate) fn blame( if revision != "HEAD" { args.push(revision); } - args.extend(["--", &rel]); + args.extend(["--", history]); let out = cli::run_raw(r.root(), &args, Some(&contents))?; if out.code == Some(0) { (out, true) @@ -207,7 +220,7 @@ pub(crate) fn blame( } } if !contents_blame { - let base = r.file_at(path, Some(revision), encoding)?.unwrap_or_default(); + let base = r.file_at(&history_path, Some(revision), encoding)?.unwrap_or_default(); for hunk in blame_hunks(&base, &text, options.ignore_whitespace).into_iter().rev() { let start = (hunk.old_start as usize).min(lines.len()); let end = (start + hunk.old_lines as usize).min(lines.len()); diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/repo.rs index 776595b005..104c74725c 100644 --- a/crates/ide-vcs/tests/repo.rs +++ b/crates/ide-vcs/tests/repo.rs @@ -666,6 +666,54 @@ fn blame_against_another_revision() { assert!(repo.blame(&fx.path("b.txt"), Some(text), Some("no-such-ref"), encoding_rs::UTF_8).is_err()); } +/// A staged rename (`git mv`) leaves the file's history under the name HEAD has, which status +/// reports as `renamed_from`: Annotate, the gutter and file history read it from there. +#[test] +fn a_staged_rename_keeps_the_history_of_its_committed_name() { + let fx = Fixture::new(); + fx.write("old.txt", "one\ntwo\nthree\n"); + let first = fx.commit_all("first"); + fx.write("old.txt", "one\ntwo\nthree\nfour\n"); + let second = fx.commit_all("second"); + fx.git(&["mv", "old.txt", "new.txt"]); + let edited = "one\nTWO\nthree\nfour\n"; + fx.write("new.txt", edited); + fx.write("added.txt", "one\ntwo\n"); + fx.git(&["add", "added.txt"]); + let repo = fx.repo(); + let (new, utf8) = (fx.path("new.txt"), encoding_rs::UTF_8); + assert_eq!(status_of(&repo.status().unwrap(), "new.txt").renamed_from.as_deref(), Some("old.txt")); + + let blamed: Vec<_> = + repo.blame(&new, None, None, utf8).unwrap().into_iter().map(|l| (l.commit, l.origin_path)).collect(); + let old = Some(ide_core::IpcPath(fx.path("old.txt"))); + let uncommitted = ("0".repeat(40), None); + assert_eq!( + blamed, + [(first.clone(), old.clone()), uncommitted, (first.clone(), old.clone()), (second.clone(), old)] + ); + + let hunks = repo.line_hunks(&new, edited, false, utf8).unwrap(); + let hunks: Vec<_> = hunks.iter().map(|h| (h.kind, h.start, h.lines, h.old_text.as_str())).collect(); + assert_eq!(hunks, [(HunkKind::Modified, 1, 1, "two\n")]); + let staging = repo.staging_line_hunks(&new, Some(&fx.path("old.txt")), edited, 1 << 20, |_, _| utf8.into()); + assert_eq!(staging.unwrap().map(|s| s.hunks.len()), Some(1), "the staging-area gutter is given the old name"); + + let history = |follow| { + let query = LogQuery { path: Some(new.clone().into()), follow, limit: 10, ..Default::default() }; + repo.log(&query).unwrap().into_iter().map(|c| (c.id, c.history_path)).collect::>() + }; + let old = Some("old.txt".to_owned()); + assert_eq!(history(true), [(second.clone(), old.clone()), (first.clone(), old)]); + assert_eq!(history(false).first().map(|c| &c.0), Some(&second), "Annotate's current revision"); + + // A staged addition has no committed name. + let added = fx.path("added.txt"); + let hunks = repo.line_hunks(&added, "one\ntwo\n", false, utf8).unwrap(); + assert_eq!(hunks.iter().map(|h| (h.kind, h.start, h.lines)).collect::>(), [(HunkKind::Added, 0, 2)]); + assert!(repo.blame(&added, None, None, utf8).unwrap().iter().all(|l| l.author == "Not Committed Yet")); +} + #[test] fn log_filters_pagination_and_refs() { let fx = Fixture::new(); diff --git a/src/features/vcs/__tests__/fileRevisions.test.tsx b/src/features/vcs/__tests__/fileRevisions.test.tsx index 991f27da81..65b6157edc 100644 --- a/src/features/vcs/__tests__/fileRevisions.test.tsx +++ b/src/features/vcs/__tests__/fileRevisions.test.tsx @@ -90,6 +90,20 @@ for (const id of ["vcs.compareWithRevision", "vcs.showCurrentRevision"]) { useVcs.setState({ statusLoaded: false }); expect(isActionEnabled(action, { vcsAvailable: true })).toBe(false); }); + + it("offers a staged rename, whose history HEAD has under its old name", () => { + const action = getAction(id)!; + expect(isActionEnabled(action, { vcsAvailable: true }, "/repo/moved.txt")).toBe(false); + const moved = { + path: "/repo/moved.txt", + relPath: "moved.txt", + renamedFrom: "other.txt", + staged: "renamed", + unstaged: "modified", + } as const; + useVcs.setState({ byPath: new Map([["/repo/moved.txt", moved]]) }); + expect(isActionEnabled(action, { vcsAvailable: true }, "/repo/moved.txt")).toBe(true); + }); }); } diff --git a/src/features/vcs/__tests__/inlineBlame.test.ts b/src/features/vcs/__tests__/inlineBlame.test.ts index 037a85991d..30043db7c7 100644 --- a/src/features/vcs/__tests__/inlineBlame.test.ts +++ b/src/features/vcs/__tests__/inlineBlame.test.ts @@ -363,6 +363,25 @@ describe("current line decoration", () => { expect(hint()).toBeNull(); }); + it("blames a staged rename, which HEAD has under its old name", async () => { + const moved = { + path: ctx.path, + relPath: "file.ts", + staged: "renamed", + unstaged: null, + renamedFrom: "old.ts", + } as const; + useVcs.setState({ byPath: new Map([[ctx.path, moved]]) }); + mocks.file.mockImplementation(async (path: string) => ({ + status: "ok", + data: path === "/repo/old.ts" ? "x" : null, + })); + editor(); + await tick(); + expect(mocks.file).toHaveBeenCalledWith("/repo/old.ts", "HEAD"); + expect(hint()?.textContent).toContain("Alice Smith"); + }); + it("skips paths outside repositories", async () => { editor("one", { ...ctx, path: "/elsewhere/file.ts" }); await tick(); diff --git a/src/features/vcs/changes.ts b/src/features/vcs/changes.ts index 0daef1ecb0..f10f42fcff 100644 --- a/src/features/vcs/changes.ts +++ b/src/features/vcs/changes.ts @@ -568,6 +568,11 @@ export function renamedFromPath(fs: FileStatus): string | null { return segments.length > depth ? `${segments.slice(0, -depth).join("/")}/${fs.renamedFrom}` : null; } +/** The path HEAD has the file at `path` under: the source of its staged rename, else `path`. */ +export function committedPath(fs: FileStatus | undefined, path: string): string { + return (fs?.staged === "renamed" && renamedFromPath(fs)) || path; +} + /** What the commit takes beyond the index, and what staged changes it leaves out. */ export function planCommit( status: readonly FileStatus[], diff --git a/src/features/vcs/fileRevisions.ts b/src/features/vcs/fileRevisions.ts index 095b3888e1..b6c42d1431 100644 --- a/src/features/vcs/fileRevisions.ts +++ b/src/features/vcs/fileRevisions.ts @@ -3,6 +3,7 @@ import { setContext } from "@/platform/context"; import { call, commands } from "@/platform/ipc"; import { editorService, notifications, toolWindowService } from "@/workbench/contributions"; import { isUncommitted } from "./blame"; +import { committedPath } from "./changes"; import { revealCommit } from "./logStore"; import { repoOf, statusOf, useVcs } from "./store"; import { repositoryPath } from "./repositoryPaths"; @@ -48,8 +49,8 @@ export function hasFileHistory(path: string | null | undefined): boolean { // A working copy of another system lists every file it does not have as unversioned (or added): // the others have a committed revision. const git = (useVcs.getState().kinds[repo] ?? "git") === "git"; - if (git && !historyFiles.get(repo)?.files.has(path)) return false; const status = statusOf(path); + if (git && !historyFiles.get(repo)?.files.has(committedPath(status, path))) return false; return ![status?.staged, status?.unstaged].some( (kind) => kind === "untracked" || kind === "ignored" || kind === "added" || kind === "deleted", ); diff --git a/src/features/vcs/inlineBlame.ts b/src/features/vcs/inlineBlame.ts index 8796354c2d..700206f7c1 100644 --- a/src/features/vcs/inlineBlame.ts +++ b/src/features/vcs/inlineBlame.ts @@ -16,6 +16,7 @@ import { tx, useI18n } from "@/platform/i18n"; import { call, commands, isTauri } from "@/platform/ipc"; import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings"; import { isUncommitted } from "./blame"; +import { committedPath } from "./changes"; import { repoOf, statusOf, useVcs } from "./store"; export function relativeBlameDate(timeMs: number | null, now = Date.now()): string { @@ -404,7 +405,8 @@ export function inlineBlame(ctx: EditorDocContext): Extension { try { const lines = await this.cache.get(doc, async () => { // Blame also returns synthetic entries for paths absent from HEAD (ignored / new files). - if ((await call(commands.vcsFileAt(ctx.path, "HEAD"))) === null) return []; + const head = committedPath(statusOf(ctx.path), ctx.path); + if ((await call(commands.vcsFileAt(head, "HEAD"))) === null) return []; return call(commands.vcsBlame(ctx.path, doc.toString(), null)); }); if (this.destroyed || generation !== this.generation || doc !== this.view.state.doc || !this.enabled())