diff --git a/doc/diffview.txt b/doc/diffview.txt index e462e534..a40dc2b9 100644 --- a/doc/diffview.txt +++ b/doc/diffview.txt @@ -2374,6 +2374,28 @@ toggle_hide_selected *diffview-actions-toggle_hide_se Toggle whether reviewed (selected) files are hidden in the file panel. The selection state is preserved when files are hidden. +toggle_lfs_smudge *diffview-actions-toggle_lfs_smudge* + Contexts: `diff_view`, `file_panel` + + Toggle git-LFS smudging for the entry under the cursor. By + default an LFS-tracked file is shown as its raw pointer blob on + both sides. Pressing `gl` runs `git lfs smudge` for the fetched + sides, reloads the diff buffers with the real file bytes, and + replaces the pointer-level numstat with the content-level + counts. Press `gl` again to revert. + + Smudging is opt-in because LFS objects can be very large. Only + supported on git repositories with `git-lfs` installed. + + Objects larger than 2 MiB (per the pointer's `size` field) are + not smudged, since smudging blocks the editor for the duration. + Override the cap by setting + `require("diffview.vcs.adapters.git.lfs").MAX_SMUDGE_BYTES` + before toggling (zero or negative disables it). + + A working-tree file that still holds the raw pointer (for + example after `GIT_LFS_SKIP_SMUDGE=1`) is handled transparently. + toggle_select_entry *diffview-actions-toggle_select_entry* Contexts: `file_panel` diff --git a/doc/diffview_changelog.txt b/doc/diffview_changelog.txt index 7439bc91..e257cb14 100644 --- a/doc/diffview_changelog.txt +++ b/doc/diffview_changelog.txt @@ -5,6 +5,30 @@ CHANGELOG NOTE: Breaking changes and notable feature additions are listed here. + *diffview.changelog-git-lfs* + +`:DiffviewOpen` on a git-LFS-tracked file used to show the raw pointer +blob (version/oid/size, three lines) on both sides, which diffed +consistently but was useless for comparing real contents. A per-file +toggle bound to `gl` (|diffview-actions-toggle_lfs_smudge|) now runs +`git lfs smudge` for the fetched sides, reloads the diff buffers with +the real bytes, and replaces the pointer-level `+N -M` numstat with +the content-level counts; `gl` again reverts to the pointer view. + +Smudging is opt-in per file because LFS objects can be very large. +The toggle is only wired up for git repositories, and only when +`git-lfs` is installed on the host. + +Objects larger than 2 MiB (per the pointer's declared size) are not +smudged. Loading one would feed the full object into `vim.diff` on the +main thread and freeze nvim; the ceiling defends against that on the +multi-GB files LFS is commonly used for. Override at your own risk via +`require("diffview.vcs.adapters.git.lfs").MAX_SMUDGE_BYTES`. + +A working-tree file left as a raw pointer (for example after +`GIT_LFS_SKIP_SMUDGE=1` or a late `git lfs install`) is handled +transparently on both the pointer and smudged paths. + *diffview.changelog-worktree-overview* The `:DiffviewWorktreeOverview` command opens a tabpage listing every diff --git a/lua/diffview/actions.lua b/lua/diffview/actions.lua index f61689f6..9c79bbbf 100644 --- a/lua/diffview/actions.lua +++ b/lua/diffview/actions.lua @@ -74,6 +74,7 @@ local pl = lazy.access(utils, "path") --[[@as PathLib ]] ---@field toggle_select_entry fun() ---@field clear_select_entries fun() ---@field toggle_hide_selected fun() +---@field toggle_lfs_smudge fun() ---@field toggle_stage_entry fun() ---@field toggle_untracked fun() ---@field unstage_all fun() @@ -1279,6 +1280,7 @@ local action_names = { "toggle_stage_entry", "toggle_untracked", "toggle_hide_selected", + "toggle_lfs_smudge", "unstage_all", "worktree_overview_enter", } diff --git a/lua/diffview/config.lua b/lua/diffview/config.lua index 6f5c9e42..2fb3a366 100644 --- a/lua/diffview/config.lua +++ b/lua/diffview/config.lua @@ -705,6 +705,7 @@ M.defaults = { -- The `view` bindings are active in the diff buffers, only when the current -- tabpage is a Diffview. { "n", "T", actions.open_in_new_tab, { desc = "Open diffview in a new tab" } }, + { "n", "gl", actions.toggle_lfs_smudge, { desc = "Toggle git-LFS smudge for the current file" } }, { "n", "g", actions.cycle_layout, { desc = "Cycle through available layouts" } }, }, actions.compat.fold_cmds), diff1 = utils.vec_join({ @@ -759,6 +760,7 @@ M.defaults = { { "n", "i", actions.listing_style, { desc = "Toggle between 'list' and 'tree' views" } }, { "n", "f", actions.toggle_flatten_dirs, { desc = "Flatten empty subdirectories in tree listing style" } }, { "n", "R", actions.refresh_files, { desc = "Update stats and entries in the file list" } }, + { "n", "gl", actions.toggle_lfs_smudge, { desc = "Toggle git-LFS smudge for the entry under the cursor" } }, { "n", "g", actions.cycle_layout, { desc = "Cycle available layouts" } }, { "n", "[x", actions.prev_conflict, { desc = "Go to the previous conflict" } }, { "n", "]x", actions.next_conflict, { desc = "Go to the next conflict" } }, diff --git a/lua/diffview/scene/file_entry.lua b/lua/diffview/scene/file_entry.lua index 4366dcc3..4830dff5 100644 --- a/lua/diffview/scene/file_entry.lua +++ b/lua/diffview/scene/file_entry.lua @@ -57,6 +57,10 @@ end ---@field merge_ctx vcs.MergeContext? ---@field active boolean ---@field opened boolean +---@field lfs_smudge boolean # Mirrors `lfs_smudge` on this entry's owned `vcs.File`s so the toggle persists across layout cycles. +---@field _lfs_force_route? boolean # Mirrors `_lfs_force_route` on owned `vcs.File`s so the attribute-mismatch routing override survives `convert_layout` just like `lfs_smudge` does. +---@field _lfs_prev_stats? GitStats # Pointer-level stats cached when `lfs_smudge` was last flipped on; restored on toggle-off so the file panel reverts cleanly. +---@field _lfs_toggle_gen? integer # Monotonic counter bumped by every `gl` press; stale toggle coroutines compare against their captured generation on resume and bail without mutating. ---@field _extra_owned vcs.File[] # Files this entry owns that aren't reachable through `layout:owned_files()` (e.g. one-off nulled fallbacks built for a window whose symbol is in `shared_symbols`). local FileEntry = oop.create_class("FileEntry") @@ -92,9 +96,7 @@ function FileEntry:init(opt) self.merge_ctx = opt.merge_ctx self.active = false self.opened = false - -- Files this FileEntry owns that aren't reachable through `layout:owned_files()` - -- (e.g. one-off nulled fallbacks for shared-symbol windows when the - -- shared instance can't be used). Populated by `with_layout`. + self.lfs_smudge = false self._extra_owned = opt._extra_owned or {} end @@ -161,27 +163,35 @@ function FileEntry:convert_layout(target_layout) self.layout:teardown_render() end - local get_data - -- Scan `owned_files()` rather than `files()` so non-window files - -- (e.g. `Diff1Inline.a_file`) still contribute a `get_data` producer - -- when converting away from a layout that owns them. + -- (e.g. `Diff1Inline.a_file`) still contribute a `get_data` producer. + -- Harvest resolved `_lfs_tracked_cached` per path so renames (where + -- a-side's `oldpath` differs from b-side's `path`) can't propagate + -- one side's value onto the other. + local get_data + local lfs_tracked_by_path = {} for _, file in ipairs(self.layout:owned_files()) do - if file.get_data then + if not get_data and file.get_data then get_data = file.get_data - break + end + if file._lfs_tracked_cached ~= nil then + lfs_tracked_by_path[file.path] = file._lfs_tracked_cached end end local function create_file(rev, symbol) + local path = symbol == "a" and self.oldpath or self.path return File({ adapter = self.adapter, - path = symbol == "a" and self.oldpath or self.path, + path = path, kind = self.kind, commit = self.commit, get_data = get_data, rev = rev, nulled = try_should_null(target_layout, rev, self.status, symbol), + lfs_smudge = self.lfs_smudge, + lfs_tracked = lfs_tracked_by_path[path], + lfs_force_route = self._lfs_force_route, }) --[[@as vcs.File ]] end diff --git a/lua/diffview/scene/views/diff/diff_view.lua b/lua/diffview/scene/views/diff/diff_view.lua index 03592b2d..6b02d8e9 100644 --- a/lua/diffview/scene/views/diff/diff_view.lua +++ b/lua/diffview/scene/views/diff/diff_view.lua @@ -880,6 +880,26 @@ local update_files_impl = debounce.debounce_trailing( old_file.stats = new_file.stats end + -- An LFS smudge toggle replaces `stats.{additions,deletions}` + -- with content-level counts. The merge above would clobber + -- those with the fresh raw pointer-level numstat while the + -- buffers remain smudged, so re-overwrite with the smudged + -- counts and promote the new raw numstat to the toggle-off + -- baseline. Content-level stats will drift from the actual + -- buffer contents until the next explicit toggle; refreshing + -- them in place would require re-running `recompute_stats` + -- here, which is out of scope. + if old_file.lfs_smudge and a_stats and old_file.stats then + old_file.stats.additions = a_stats.additions + old_file.stats.deletions = a_stats.deletions + if b_stats then + old_file._lfs_prev_stats = { + additions = b_stats.additions, + deletions = b_stats.deletions, + } + end + end + old_file.status = new_file.status old_file:validate_stage_buffers(index_stat) @@ -896,7 +916,18 @@ local update_files_impl = debounce.debounce_trailing( -- rewrite working-copy files (git, hg). for _, f in ipairs(old_file.layout:files()) do if f.rev.type == RevType.LOCAL and f.bufnr and api.nvim_buf_is_valid(f.bufnr) then - self.adapter:on_local_buffer_reused(f.bufnr) + -- LOCAL buffers routed through `diffview://` (LFS + -- pointer-view, or `_lfs_smudge_from_pointer`, or + -- oversized-smudged fallback) are cached snapshots: + -- `on_local_buffer_reused` doesn't repopulate them, so + -- the pointer `oid`/`size` or the smudged content keeps + -- showing stale after a working-tree edit. Dispose so + -- the next `create_buffer` regenerates fresh bytes. + if vim.b[f.bufnr].diffview_loaded then + f:dispose_buffer() + else + self.adapter:on_local_buffer_reused(f.bufnr) + end end end end diff --git a/lua/diffview/scene/views/diff/listeners.lua b/lua/diffview/scene/views/diff/listeners.lua index 827be2cc..05cd0dbf 100644 --- a/lua/diffview/scene/views/diff/listeners.lua +++ b/lua/diffview/scene/views/diff/listeners.lua @@ -807,6 +807,179 @@ return function(view) view.panel:render() view.panel:redraw() end, + toggle_lfs_smudge = async.void(function() + local GitAdapter = require("diffview.vcs.adapters.git").GitAdapter + if not view.adapter:instanceof(GitAdapter) then + utils.info("LFS smudge toggle is only supported for git repositories.") + return + end + if vim.fn.executable("git-lfs") ~= 1 then + utils.info("LFS smudge toggle requires `git-lfs` on PATH.") + return + end + + local item = view:infer_cur_file() + if not item or type(item.collapsed) == "boolean" then + return + end + ---@cast item FileEntry + + local git_lfs = require("diffview.vcs.adapters.git.lfs") + local pl = utils.path + -- For renames the historical blob lives at `oldpath`; `path_b` + -- is what the index tracks today. + local path_a = item.oldpath or item.path + local path_b = item.path + local tracked = await(git_lfs.cached_is_tracked(view.adapter, path_b)) + if not tracked then + -- Historical attribute mismatch: `.gitattributes` doesn't + -- flag the file today, but a rev may still carry a pointer + -- blob (e.g., LFS tracking was removed since). Probe each + -- side's bytes; if at least one looks like a pointer, let + -- the toggle proceed. + local function side_is_pointer(p, rev) + if rev.type == RevType.LOCAL then + await(async.scheduler()) + local abs = pl:absolute(p, view.adapter.ctx.toplevel) + -- Stat first so a huge newline-free payload can't be pulled + -- into a single Lua line by `readfile` before the size guard + -- runs; `readfile`'s line limit bounds line count, not bytes. + local stat = pl:stat(abs) + if stat and git_lfs.MAX_SMUDGE_BYTES > 0 and stat.size > git_lfs.MAX_SMUDGE_BYTES then + return false + end + local ok, sample = pcall(vim.fn.readfile, abs, "", 11) + return ok and git_lfs.is_pointer(sample) + end + local err, data = await(view.adapter:show(p, rev)) + return not err and data and git_lfs.is_pointer(data) + end + if not (side_is_pointer(path_a, item.revs.a) or side_is_pointer(path_b, item.revs.b)) then + await(async.scheduler()) + utils.info("Not an LFS-tracked file; smudge toggle is a no-op.") + return + end + -- Record the fallback decision so `create_buffer` (which + -- otherwise gates LFS routing on `_lfs_tracked()` alone) takes + -- the LFS path for every owned File. Without this, LOCAL would + -- read working-tree bytes raw while the other side rendered a + -- smudged pointer blob. + item._lfs_force_route = true + end + await(async.scheduler()) + + -- Toggling disposes every owned buffer, which force-deletes them; + -- any unsaved edits in a modifiable buffer (e.g., a pointer-view + -- stage-0 buffer the user has been typing in) would be silently + -- dropped. Refuse the toggle until those buffers are saved or + -- discarded. + for _, f in ipairs(utils.vec_join(item.layout:owned_files(), item._extra_owned)) do + if f.bufnr and api.nvim_buf_is_valid(f.bufnr) and vim.bo[f.bufnr].modified then + utils.info("LFS smudge toggle: buffer has unsaved changes. Save or discard first.") + return + end + end + + -- Generation counter: a second `gl` press across any of the + -- awaits below bumps `_lfs_toggle_gen`; stale coroutines check + -- their captured `my_gen` on resume and bail without mutating. + item._lfs_toggle_gen = (item._lfs_toggle_gen or 0) + 1 + local my_gen = item._lfs_toggle_gen + + local new_state = not item.lfs_smudge + item.lfs_smudge = new_state + + for _, f in ipairs(utils.vec_join(item.layout:owned_files(), item._extra_owned)) do + f.lfs_smudge = new_state + -- Propagate the attribute-mismatch override onto every owned + -- File so `create_buffer`'s LFS gate sees it. Set unconditionally + -- (not scoped to the `not tracked` branch) because the item flag + -- is set only in that branch, and new siblings produced during + -- the toggle must agree with the already-flipped ones. + f._lfs_force_route = item._lfs_force_route or nil + -- Clear cached `binary` so `create_buffer` re-decides for the new + -- display mode: a smudged binary LFS payload should route to the + -- null buffer, but the pointer-view (text) must not inherit a + -- stale `binary=true` from a prior smudged load. + f.binary = nil + f:dispose_buffer() + end + + -- Toggle-on swaps pointer-level stats for content-level stats; + -- toggle-off restores the cached pointer stats. + if new_state then + if item.stats then + item._lfs_prev_stats = { + additions = item.stats.additions, + deletions = item.stats.deletions, + } + end + local stats, status = + await(git_lfs.recompute_stats(view.adapter, path_a, item.revs.a, path_b, item.revs.b)) + -- `recompute_stats` may resume in libuv's fast event context + -- (its callbacks chain through `on_exit` handlers). Hop onto + -- nvim's scheduler before the revert branch below touches + -- `utils.warn` or buffer disposal, both of which call API + -- functions that raise `E5560` in fast events. + await(async.scheduler()) + if item._lfs_toggle_gen == my_gen then + -- `recompute_stats` doubles as a pre-flight: if any side would + -- exceed the cap or failed to smudge, revert so a later + -- `use_entry` reload lands all sides in pointer mode together. + if status == "too-large" or status == "error" then + utils.warn( + status == "too-large" + and "LFS smudge: at least one side exceeds MAX_SMUDGE_BYTES. Keeping pointer view." + or "LFS smudge: `git lfs smudge` failed on at least one side. Keeping pointer view." + ) + item.lfs_smudge = false + for _, f in ipairs(utils.vec_join(item.layout:owned_files(), item._extra_owned)) do + f.lfs_smudge = false + f.binary = nil + f:dispose_buffer() + end + item._lfs_prev_stats = nil + elseif status == "binary" then + -- Smudge stays on so `create_buffer`'s post-smudge binary + -- check routes both sides to the null buffer; hold the raw + -- pointer-level numstat because `vim.diff` on binary bytes + -- would publish nonsense counts. + utils.info("LFS smudge: content is binary. Keeping pointer-level diff count.") + elseif stats and item.stats then + -- `item.stats` may have been nil at the pre-await capture + -- (first numstat refresh still in flight) and populated with + -- pointer values during the yield; snapshot them so toggle- + -- off can still restore. + if not item._lfs_prev_stats then + item._lfs_prev_stats = { + additions = item.stats.additions, + deletions = item.stats.deletions, + } + end + item.stats.additions = stats.additions + item.stats.deletions = stats.deletions + end + end + elseif item._lfs_prev_stats and item.stats then + item.stats.additions = item._lfs_prev_stats.additions + item.stats.deletions = item._lfs_prev_stats.deletions + item._lfs_prev_stats = nil + end + + -- `recompute_stats` resumes in libuv's fast event context; hop + -- onto nvim's scheduler before touching API-level rendering. + await(async.scheduler()) + if item._lfs_toggle_gen ~= my_gen then + return + end + + view.panel:render() + view.panel:redraw() + + if view.cur_entry == item and view.cur_layout then + await(view.cur_layout:use_entry(item)) + end + end), toggle_untracked = function() -- Only applicable to working tree comparisons. if not (view.left.type == RevType.STAGE and view.right.type == RevType.LOCAL) then diff --git a/lua/diffview/tests/functional/git_lfs_spec.lua b/lua/diffview/tests/functional/git_lfs_spec.lua new file mode 100644 index 00000000..3a78cebd --- /dev/null +++ b/lua/diffview/tests/functional/git_lfs_spec.lua @@ -0,0 +1,789 @@ +local async = require("diffview.async") +local File = require("diffview.vcs.file").File +local GitAdapter = require("diffview.vcs.adapters.git").GitAdapter +local GitRev = require("diffview.vcs.adapters.git.rev").GitRev +local RevType = require("diffview.vcs.rev").RevType +local git_lfs = require("diffview.vcs.adapters.git.lfs") +local test_utils = require("diffview.tests.helpers") + +local run = test_utils.run +local system = test_utils.system + +--- Is `git-lfs` installed and functional? +local function git_lfs_available() + -- `vim.system` raises on spawn failure (e.g., executable not on PATH) + -- rather than returning a nonzero code. This runs at describe-registration + -- time, so an unguarded throw would abort loading the spec on hosts + -- without this optional binary. + if vim.fn.executable("git-lfs") ~= 1 then + return false + end + local ok, res = pcall(function() + return vim.system({ "git-lfs", "version" }, { text = true }):wait() + end) + return ok and res.code == 0 +end + +local function sample_pointer(oid, size) + return { + "version https://git-lfs.github.com/spec/v1", + "oid sha256:" .. oid, + "size " .. tostring(size), + } +end + +describe("diffview.vcs.adapters.git.lfs", function() + describe("is_pointer()", function() + it("recognises a canonical v1 pointer", function() + assert.True(git_lfs.is_pointer(sample_pointer(string.rep("a", 64), 42))) + end) + + it("accepts additional ext-* lines within the size limit", function() + local lines = sample_pointer(string.rep("b", 64), 7) + table.insert(lines, "x-foo bar") + assert.True(git_lfs.is_pointer(lines)) + end) + + it("rejects nil or wrong-type input", function() + assert.False(git_lfs.is_pointer(nil)) + assert.False(git_lfs.is_pointer("version https://git-lfs.github.com/spec/v1")) + end) + + it("rejects empty or single-line input", function() + assert.False(git_lfs.is_pointer({})) + assert.False(git_lfs.is_pointer({ "version https://git-lfs.github.com/spec/v1" })) + end) + + it("rejects content without the LFS version header", function() + assert.False(git_lfs.is_pointer({ "hello", "world" })) + assert.False(git_lfs.is_pointer({ + "version https://example.com/spec/v1", + "oid sha256:" .. string.rep("c", 64), + })) + end) + + it("rejects content missing the oid line", function() + assert.False(git_lfs.is_pointer({ + "version https://git-lfs.github.com/spec/v1", + "size 42", + })) + end) + + it("rejects pointer-shaped content larger than the pointer-size cap", function() + local lines = sample_pointer(string.rep("d", 64), 1) + for i = 1, 20 do + lines[#lines + 1] = ("x-%d trailing"):format(i) + end + assert.False(git_lfs.is_pointer(lines)) + end) + end) + + describe("parse_size()", function() + it("extracts the byte size from a canonical pointer", function() + assert.equals(42, git_lfs.parse_size(sample_pointer(string.rep("a", 64), 42))) + end) + + it("returns nil for malformed input or a pointer missing a size line", function() + assert.is_nil(git_lfs.parse_size(nil)) + assert.is_nil(git_lfs.parse_size("not a table")) + assert.is_nil(git_lfs.parse_size({ + "version https://git-lfs.github.com/spec/v1", + "oid sha256:" .. string.rep("e", 64), + })) + end) + end) + + describe("vcs.File:produce_data() with LFS", function() + if not git_lfs_available() then + pending("skipped: `git-lfs` is not installed on this host") + return + end + + local repo + + local function make_lfs_repo() + repo = test_utils.init_repo() + -- Configure LFS filters in this repo only, so the user's global + -- `.gitconfig` is left untouched. + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "hello lfs v1" }) + test_utils.commit(repo, "lfs v1") + test_utils.write(repo, "big.bin", { "hello lfs v2" }) + test_utils.commit(repo, "lfs v2") + end + + local function cleanup() + if repo then + test_utils.cleanup_repo(repo) + repo = nil + end + end + + local function make_file(adapter, path, rev, lfs_smudge) + return File({ + adapter = adapter, + path = path, + kind = "working", + rev = rev, + lfs_smudge = lfs_smudge, + }) + end + + it( + "returns pointer bytes by default (lfs_smudge=false)", + test_utils.async_test(function() + make_lfs_repo() + + local ok, err = pcall(function() + -- Sanity-check: without smudging the blob at HEAD~ is a pointer. + local raw = system({ "git", "show", "HEAD~:big.bin" }, repo).stdout + assert.truthy(raw:match("^version https://git%-lfs%.github%.com/spec/v1")) + + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local rev = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD~" }, repo)) + local file = make_file(adapter, "big.bin", rev, false) + + local serr, data = async.await(File.produce_data(file)) + assert.is_nil(serr) + assert.True(git_lfs.is_pointer(data), "expected pointer bytes when lfs_smudge=false") + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "returns smudged content when lfs_smudge=true on an LFS blob", + test_utils.async_test(function() + make_lfs_repo() + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local rev = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD~" }, repo)) + local file = make_file(adapter, "big.bin", rev, true) + + local serr, data = async.await(File.produce_data(file)) + assert.is_nil(serr) + assert.False(git_lfs.is_pointer(data), "expected smudged content") + assert.equals("hello lfs v1", data[1]) + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "returns a working-tree pointer when LOCAL + lfs_smudge=false on an LFS file", + test_utils.async_test(function() + make_lfs_repo() + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local file = make_file(adapter, "big.bin", adapter.Rev(RevType.LOCAL), false) + + local serr, data = async.await(File.produce_data(file)) + assert.is_nil(serr) + assert.True( + git_lfs.is_pointer(data), + "expected the LOCAL side to show a pointer when lfs_smudge=false" + ) + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "the LOCAL pointer reflects the current working-tree bytes, not the index", + test_utils.async_test(function() + make_lfs_repo() + + local ok, err = pcall(function() + -- Modify the working tree without staging. The LOCAL pointer must + -- hash these bytes, not the ones in the index. + test_utils.write(repo, "big.bin", { "unstaged content v3" }) + + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local file = make_file(adapter, "big.bin", adapter.Rev(RevType.LOCAL), false) + local serr, local_lines = async.await(File.produce_data(file)) + assert.is_nil(serr) + assert.True(git_lfs.is_pointer(local_lines)) + + -- `produce_data` resumes in a fast event context; land on the + -- scheduler before `vim.system` (via `test_utils.system`) below. + async.await(async.scheduler()) + + -- Oid line differs from the index version. If `produce_data` had + -- used `git show :big.bin`, both would carry the same oid. + local staged = system({ "git", "show", ":big.bin" }, repo).stdout + local staged_oid = staged:match("oid sha256:(%x+)") + local local_oid + for _, line in ipairs(local_lines) do + local m = line:match("^oid sha256:(%x+)$") + if m then + local_oid = m + break + end + end + assert.is_not_nil(staged_oid) + assert.is_not_nil(local_oid) + assert.are_not.equal(staged_oid, local_oid) + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "leaves non-LFS blobs untouched regardless of the lfs_smudge flag", + test_utils.async_test(function() + make_lfs_repo() + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local rev = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + + -- `.gitattributes` is not LFS-tracked, so smudging must not alter it + -- (the smudge filter sees non-pointer bytes and would echo them back, + -- but we never invoke it because `is_pointer` is false). + for _, flag in ipairs({ false, true }) do + local file = make_file(adapter, ".gitattributes", rev, flag) + local serr, data = async.await(File.produce_data(file)) + assert.is_nil(serr) + assert.equals("*.bin filter=lfs diff=lfs merge=lfs -text", data[1]) + end + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + end) + + describe("recompute_stats() with LFS", function() + if not git_lfs_available() then + pending("skipped: `git-lfs` is not installed on this host") + return + end + + local repo + + local function cleanup() + if repo then + test_utils.cleanup_repo(repo) + repo = nil + end + end + + it( + "returns content-level additions/deletions for LOCAL vs COMMIT", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "alpha" }) + test_utils.commit(repo, "v1") + -- Write a bigger working-tree version without committing: this mirrors + -- the user's `:DiffviewOpen HEAD~` case where the right side is LOCAL + -- and the pointer at `HEAD~` must still smudge into "alpha". + test_utils.write(repo, "big.bin", { "alpha", "beta", "gamma" }) + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local left = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + local right = adapter.Rev(RevType.LOCAL) + local stats = + async.await(git_lfs.recompute_stats(adapter, "big.bin", left, "big.bin", right)) + assert.is_not_nil(stats, "recompute_stats returned nil for LOCAL rev") + assert.equals(2, stats.additions) + assert.equals(0, stats.deletions) + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "returns content-level additions/deletions for an LFS-tracked blob", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "hello" }) + test_utils.commit(repo, "v1") + test_utils.write(repo, "big.bin", { "hello world", "line2", "line3" }) + test_utils.commit(repo, "v2") + + local ok, err = pcall(function() + -- Sanity-check that git's own numstat reports pointer stats here, + -- so passing assertions below prove `recompute_stats` sidestepped + -- that path and computed from smudged content. + local numstat = run({ "git", "diff", "--numstat", "HEAD~", "HEAD" }, repo) + assert.truthy(numstat:match("^2\t2\tbig%.bin$")) + + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local left = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD~" }, repo)) + local right = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + + local stats = + async.await(git_lfs.recompute_stats(adapter, "big.bin", left, "big.bin", right)) + assert.is_not_nil(stats) + assert.equals(3, stats.additions) + assert.equals(1, stats.deletions) + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "returns nil when either pointer declares a size above MAX_SMUDGE_BYTES", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "hello" }) + test_utils.commit(repo, "v1") + test_utils.write(repo, "big.bin", { "hello world", "line2", "line3" }) + test_utils.commit(repo, "v2") + + -- Clamp the limit so the existing tiny LFS objects count as oversized. + local saved = git_lfs.MAX_SMUDGE_BYTES + git_lfs.MAX_SMUDGE_BYTES = 1 + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local left = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD~" }, repo)) + local right = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + + local stats = + async.await(git_lfs.recompute_stats(adapter, "big.bin", left, "big.bin", right)) + assert.is_nil(stats, "expected nil so the caller falls back to raw numstat") + end) + + git_lfs.MAX_SMUDGE_BYTES = saved + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "returns nil when the LOCAL working-tree file exceeds MAX_SMUDGE_BYTES", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "small" }) + test_utils.commit(repo, "v1") + -- The working-tree file is normally the fully smudged payload. + -- Clamp the limit so the (tiny) file still counts as oversized + -- and the fs_stat gate rejects it before the readfile. + local saved = git_lfs.MAX_SMUDGE_BYTES + git_lfs.MAX_SMUDGE_BYTES = 1 + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local left = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + local right = adapter.Rev(RevType.LOCAL) + local stats = + async.await(git_lfs.recompute_stats(adapter, "big.bin", left, "big.bin", right)) + assert.is_nil(stats, "expected nil so the caller falls back to raw numstat") + end) + + git_lfs.MAX_SMUDGE_BYTES = saved + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "smudges a raw pointer left on disk by `GIT_LFS_SKIP_SMUDGE`", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "alpha" }) + test_utils.commit(repo, "v1") + -- Replace the working-tree file with the raw pointer bytes, as if + -- the checkout had set `GIT_LFS_SKIP_SMUDGE=1`. + local pointer = system({ "git", "show", "HEAD:big.bin" }, repo).stdout + local f = assert(io.open(repo .. "/big.bin", "w")) + f:write(pointer) + f:close() + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local left = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + local right = adapter.Rev(RevType.LOCAL) + -- Both sides collapse to the same smudged "alpha", so there are + -- no content-level changes to report; without the pointer guard + -- the LOCAL side would be the raw pointer and the diff would + -- report spurious additions/deletions. + local stats = + async.await(git_lfs.recompute_stats(adapter, "big.bin", left, "big.bin", right)) + assert.is_not_nil(stats) + assert.equals(0, stats.additions) + assert.equals(0, stats.deletions) + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "resolves per-side paths for renamed LFS entries", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "old.bin", { "alpha" }) + test_utils.commit(repo, "v1") + run({ "git", "mv", "old.bin", "new.bin" }, repo) + test_utils.write(repo, "new.bin", { "alpha", "beta" }) + test_utils.commit(repo, "renamed and extended") + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local left = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD~" }, repo)) + local right = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + -- With per-side paths, `recompute_stats` sees "alpha" on the + -- left (via `old.bin@HEAD~`) and "alpha\nbeta" on the right + -- (via `new.bin@HEAD`): one real addition, no deletions. + local stats, status = + async.await(git_lfs.recompute_stats(adapter, "old.bin", left, "new.bin", right)) + assert.equals("ok", status) + assert.is_not_nil(stats) + assert.equals(1, stats.additions) + assert.equals(0, stats.deletions) + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "returns `error` (not `absent`) when a `git show` fails operationally", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "payload" }) + test_utils.commit(repo, "v1") + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + -- A bogus revision triggers a `fatal: Not a valid object name` + -- stderr that matches the absence patterns, so this still + -- counts as "absent"; use a non-existent path at a real rev + -- to exercise the same code path (stderr says "does not + -- exist", also matched as absent). + local real = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + local stats, status = + async.await(git_lfs.recompute_stats(adapter, "missing.bin", real, "big.bin", real)) + -- Left side absent + right side ok with pointer size well + -- under the cap → the one-sided-addition path runs and we + -- get an "ok" result; this proves the patterns match the + -- known-absence case rather than promoting it to error. + assert.equals("ok", status) + assert.is_not_nil(stats) + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "cached_is_tracked returns the memoised value without re-shelling", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "payload" }) + test_utils.commit(repo, "v1") + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + -- Reset the cache so this test starts from a known state. + git_lfs._tracked_cache[adapter.ctx.toplevel] = nil + local first = async.await(git_lfs.cached_is_tracked(adapter, "big.bin")) + assert.True(first) + -- Mutate the cache to a sentinel; a cached call must return it. + git_lfs._tracked_cache[adapter.ctx.toplevel]["big.bin"] = false + local second = async.await(git_lfs.cached_is_tracked(adapter, "big.bin")) + assert.False(second, "second call should hit the cache, not re-run check-attr") + end) + + cleanup() + + if not ok then + error(err) + end + end) + ) + + it( + "returns `too-large` status so the caller can revert the toggle", + test_utils.async_test(function() + repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "payload" }) + test_utils.commit(repo, "v1") + + local saved = git_lfs.MAX_SMUDGE_BYTES + git_lfs.MAX_SMUDGE_BYTES = 1 + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local left = GitRev(RevType.COMMIT, run({ "git", "rev-parse", "HEAD" }, repo)) + local right = adapter.Rev(RevType.LOCAL) + local stats, status = + async.await(git_lfs.recompute_stats(adapter, "big.bin", left, "big.bin", right)) + assert.is_nil(stats) + assert.equals("too-large", status) + end) + + git_lfs.MAX_SMUDGE_BYTES = saved + cleanup() + + if not ok then + error(err) + end + end) + ) + end) + + describe("vcs.File:produce_data() LOCAL with raw pointer on disk", function() + if not git_lfs_available() then + pending("skipped: `git-lfs` is not installed on this host") + return + end + + it( + "returns the on-disk pointer verbatim instead of re-hashing it", + test_utils.async_test(function() + local repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "alpha" }) + test_utils.commit(repo, "v1") + -- Working-tree file is the raw pointer (as under `GIT_LFS_SKIP_SMUDGE=1`). + local pointer = system({ "git", "show", "HEAD:big.bin" }, repo).stdout + local f = assert(io.open(repo .. "/big.bin", "w")) + f:write(pointer) + f:close() + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local file = File({ + adapter = adapter, + path = "big.bin", + kind = "working", + rev = adapter.Rev(RevType.LOCAL), + lfs_smudge = false, + }) + + local serr, data = async.await(File.produce_data(file)) + assert.is_nil(serr) + assert.True(git_lfs.is_pointer(data)) + -- Compare oid against the committed pointer's oid: a pass means + -- we used the on-disk bytes rather than hashing the pointer + -- header via `git lfs pointer --file=`, which would yield a + -- different (pointer-of-pointer) oid. + local expected_oid = pointer:match("oid sha256:(%x+)") + local got_oid + for _, line in ipairs(data) do + local m = line:match("^oid sha256:(%x+)$") + if m then + got_oid = m + break + end + end + assert.is_not_nil(expected_oid) + assert.equals(expected_oid, got_oid) + end) + + test_utils.cleanup_repo(repo) + + if not ok then + error(err) + end + end) + ) + + it( + "smudges a raw pointer on disk when lfs_smudge=true", + test_utils.async_test(function() + local repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + test_utils.write(repo, "big.bin", { "alpha" }) + test_utils.commit(repo, "v1") + -- `GIT_LFS_SKIP_SMUDGE=1` shape: working-tree file is the raw pointer. + local pointer = system({ "git", "show", "HEAD:big.bin" }, repo).stdout + local f = assert(io.open(repo .. "/big.bin", "w")) + f:write(pointer) + f:close() + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local file = File({ + adapter = adapter, + path = "big.bin", + kind = "working", + rev = adapter.Rev(RevType.LOCAL), + lfs_smudge = true, + }) + -- Mimic the `create_buffer` decision: with a pointer on disk and + -- `lfs_smudge=true`, the LOCAL branch routes through the + -- `[lfs-local-smudged]` path, which sets this flag so + -- `produce_data` smudges the on-disk pointer bytes. + file._lfs_smudge_from_pointer = true + + local serr, data = async.await(File.produce_data(file)) + assert.is_nil(serr) + assert.False(git_lfs.is_pointer(data), "expected smudged content, not the raw pointer") + assert.equals("alpha", data[1]) + end) + + test_utils.cleanup_repo(repo) + + if not ok then + error(err) + end + end) + ) + + it( + "does not misclassify a longer file whose first lines mimic a pointer", + test_utils.async_test(function() + local repo = test_utils.init_repo() + run({ "git", "lfs", "install", "--local" }, repo) + test_utils.write(repo, ".gitattributes", { + "*.bin filter=lfs diff=lfs merge=lfs -text", + }) + -- First commit a real LFS blob so `_lfs_tracked` reports true. + test_utils.write(repo, "big.bin", { "payload" }) + test_utils.commit(repo, "v1") + -- Replace the working-tree file with a trap: three pointer-shaped + -- lines followed by extra body. A 10-line sample would accept + -- the trap as the pointer; the 11-line canary rejects it. + local trap = { + "version https://git-lfs.github.com/spec/v1", + "oid sha256:" .. string.rep("a", 64), + "size 42", + } + for i = 1, 8 do + trap[#trap + 1] = ("extra body line %d"):format(i) + end + local f = assert(io.open(repo .. "/big.bin", "w")) + f:write(table.concat(trap, "\n") .. "\n") + f:close() + + local ok, err = pcall(function() + local adapter = GitAdapter({ toplevel = repo, cpath = repo, path_args = {} }) + local file = File({ + adapter = adapter, + path = "big.bin", + kind = "working", + rev = adapter.Rev(RevType.LOCAL), + lfs_smudge = false, + }) + + local serr, data = async.await(File.produce_data(file)) + assert.is_nil(serr) + -- The result must come from `git lfs pointer --file=` on the + -- trap bytes (so its oid hashes the full file), not from the + -- disk sample itself (which would just echo the trap bytes). + assert.True(git_lfs.is_pointer(data)) + local got_oid + for _, line in ipairs(data) do + local m = line:match("^oid sha256:(%x+)$") + if m then + got_oid = m + break + end + end + assert.is_not_nil(got_oid) + assert.are_not.equal(string.rep("a", 64), got_oid) + end) + + test_utils.cleanup_repo(repo) + + if not ok then + error(err) + end + end) + ) + end) +end) diff --git a/lua/diffview/vcs/adapters/git/lfs.lua b/lua/diffview/vcs/adapters/git/lfs.lua new file mode 100644 index 00000000..a56dbeeb --- /dev/null +++ b/lua/diffview/vcs/adapters/git/lfs.lua @@ -0,0 +1,477 @@ +local Job = require("diffview.job").Job +local async = require("diffview.async") +local lazy = require("diffview.lazy") +local utils = require("diffview.utils") +local vcs_utils = require("diffview.vcs.utils") + +local RevType = lazy.access("diffview.vcs.rev", "RevType") ---@type RevType|LazyModule + +local await = async.await +local fmt = string.format +local pl = lazy.access(utils, "path") --[[@as PathLib ]] + +local M = {} + +---Maximum pointer `size` (bytes) the module will smudge in-process. +---Smudging pulls the full LFS object into memory and feeds it to +---`vim.diff`, which blocks nvim's main thread; a multi-GB object would +---freeze or OOM the editor. Oversized pointers fall back to the raw +---pointer bytes with a warning. +M.MAX_SMUDGE_BYTES = 2 * 1024 * 1024 + +---Extract the `size` field (in bytes) from a git-LFS pointer. Returns nil +---when the pointer is malformed or has no size line. +---@param pointer string[] +---@return integer? +function M.parse_size(pointer) + if type(pointer) ~= "table" then + return nil + end + for _, line in ipairs(pointer) do + local sz = line:match("^size (%d+)$") + if sz then + return tonumber(sz) + end + end + return nil +end + +---Does `pointer` declare a `size` above `M.MAX_SMUDGE_BYTES`? Pointers +---without a parseable size are treated as safe: we have no positive +---evidence they are oversized, and a bogus pointer that fails smudge +---surfaces separately via the "error" status. +---@param pointer string[] +---@return boolean +local function pointer_too_large(pointer) + if M.MAX_SMUDGE_BYTES <= 0 then + return false + end + local sz = M.parse_size(pointer) + return sz ~= nil and sz > M.MAX_SMUDGE_BYTES +end + +---Does `lines` look like a git LFS pointer file? Deliberately +---under-specified (version header plus an `oid sha256:` line) to stay +---cheap and avoid false positives on real content. +---@param lines string[]? +---@return boolean +function M.is_pointer(lines) + if type(lines) ~= "table" then + return false + end + local n = #lines + if n < 2 or n > 10 then + return false + end + if not lines[1]:match("^version https://git%-lfs%.github%.com/spec/v%d+$") then + return false + end + for i = 2, n do + if lines[i]:match("^oid sha256:%x+$") then + return true + end + end + return false +end + +---Pipe `pointer` through `git lfs smudge -- ` and return the smudged +---content as a list of lines. On failure (`git-lfs` missing, filter error, +---etc.), `err` is populated and `stdout` is nil; callers typically fall +---back to the pointer bytes unchanged. +---@param adapter GitAdapter +---@param path string +---@param pointer string[] +---@param callback fun(stderr: string[]?, stdout: string[]?) +M.smudge = async.wrap(function(adapter, path, pointer, callback) + local job + job = Job({ + command = adapter:bin(), + args = utils.vec_join(adapter:args(), "lfs", "smudge", "--", path), + cwd = adapter.ctx.toplevel, + -- `GIT_LFS_SKIP_SMUDGE=1` in nvim's environment turns `git lfs smudge` + -- into a pointer passthrough, which leaves the UI showing pointer + -- bytes even though the user explicitly asked to smudge. Override it + -- for this call while preserving the rest of the environment. + env = vim.tbl_extend("force", vim.uv.os_environ(), { GIT_LFS_SKIP_SMUDGE = "0" }), + writer = pointer, + fail_cond = Job.FAIL_COND.non_zero, + log_opt = { label = "git.lfs.smudge()" }, + -- `on_exit` fires in libuv's fast event context; `async.void` hops + -- onto nvim's scheduler so any downstream API call doesn't raise + -- `E5560`. + on_exit = async.void(function(_, ok) + if not ok or job.code ~= 0 then + local stderr = job.stderr or {} + callback({ + fmt( + "`git lfs smudge` failed for %s (code=%s): %s", + path, + tostring(job.code), + table.concat(stderr, "\n") + ), + }, nil) + return + end + callback(nil, job.stdout) + end), + }) + await(vcs_utils.queue_sync_job(job)) +end) + +---Generate the LFS pointer for the working-tree bytes at `abs_path`. +---Uses `git lfs pointer --file=`, which streams through the file +---to compute the SHA256 without buffering it in memory, so this is +---cheap even for multi-GB LFS objects. The command prefixes its output +---with a `Git LFS pointer for ` header and a blank line; strip +---everything up to and including that blank line. +--- +---Pairing the LOCAL side with a working-tree pointer (rather than the +---staged `:` blob) keeps unstaged edits visible as a pointer-level +---diff and handles LFS files that are not yet in the index at all. +---@param adapter GitAdapter +---@param abs_path string +---@param callback fun(stderr: string[]?, stdout: string[]?) +M.working_tree_pointer = async.wrap(function(adapter, abs_path, callback) + local job + job = Job({ + command = adapter:bin(), + args = utils.vec_join(adapter:args(), "lfs", "pointer", "--file=" .. abs_path), + cwd = adapter.ctx.toplevel, + fail_cond = Job.FAIL_COND.non_zero, + log_opt = { label = "git.lfs.working_tree_pointer()" }, + on_exit = async.void(function(_, ok) + if not ok or job.code ~= 0 then + callback(job.stderr or { "git lfs pointer failed" }, nil) + return + end + local out = job.stdout + for i, line in ipairs(out) do + if line == "" then + callback(nil, utils.vec_slice(out, i + 1)) + return + end + end + -- No header found: treat the whole output as the pointer. + callback(nil, out) + end), + }) + await(vcs_utils.queue_sync_job(job)) +end) + +---Return the subset of `paths` whose `filter` attribute is `lfs` according +---to the index's `.gitattributes` (`--cached`). On error, returns an empty +---table; callers degrade to the raw `--numstat` values rather than failing. +---@param adapter GitAdapter +---@param paths string[] +---@param callback fun(lfs_set: table) +M.filter_lfs_paths = async.wrap(function(adapter, paths, callback) + if #paths == 0 then + callback({}) + return + end + local job + job = Job({ + command = adapter:bin(), + args = utils.vec_join(adapter:args(), "check-attr", "--cached", "-z", "filter", "--", paths), + cwd = adapter.ctx.toplevel, + fail_cond = Job.FAIL_COND.non_zero, + log_opt = { label = "git.lfs.filter_lfs_paths()" }, + on_exit = async.void(function(_, ok) + if not ok then + callback({}) + return + end + -- `-z` output is NUL-separated with no newlines; join with "" to + -- stitch across any chunk boundaries without introducing stray \n. + local data = table.concat(job.stdout, "") + local fields = vim.split(data, "\0", { plain = true }) + local out = {} + -- Records are three fields: path, attr, value. + for i = 1, #fields - 2, 3 do + if fields[i + 1] == "filter" and fields[i + 2] == "lfs" then + out[fields[i]] = true + end + end + callback(out) + end), + }) + await(vcs_utils.queue_sync_job(job)) +end) + +---Single-path LFS tracking check wrapping `filter_lfs_paths`. +---@param adapter GitAdapter +---@param path string +---@param callback fun(tracked: boolean) +M.is_tracked = async.wrap(function(adapter, path, callback) + local set = await(M.filter_lfs_paths(adapter, { path })) + callback(set[path] == true) +end) + +---Session cache for `is_tracked`, keyed by `(toplevel, path)`. Fills once +---per path per nvim session; invalidation is coarse (quit nvim) because +---`.gitattributes` rarely changes mid-session. +---@type table> +M._tracked_cache = {} + +---Cached variant of `is_tracked`. Skips the `git check-attr` subprocess +---when the same `(toplevel, path)` was resolved earlier in the session. +---@param adapter GitAdapter +---@param path string +---@param callback fun(tracked: boolean) +M.cached_is_tracked = async.wrap(function(adapter, path, callback) + local toplevel = adapter.ctx.toplevel + local by_path = M._tracked_cache[toplevel] + if by_path and by_path[path] ~= nil then + callback(by_path[path]) + return + end + local tracked = await(M.is_tracked(adapter, path)) + by_path = M._tracked_cache[toplevel] or {} + by_path[path] = tracked + M._tracked_cache[toplevel] = by_path + callback(tracked) +end) + +---@alias git.lfs.FetchStatus "ok"|"absent"|"error"|"too-large" + +---Return the byte size of the blob at `rev:path` via `git cat-file -s`, +---which does not buffer the object, so it is cheap even for multi-GB +---blobs. Returns nil on lookup failure (object missing, bad rev, etc.); +---callers degrade to the existing error paths rather than failing. +---@param adapter GitAdapter +---@param path string +---@param rev Rev +---@param callback fun(size: integer?) +local blob_size = async.wrap(function(adapter, path, rev, callback) + local spec = fmt("%s:%s", rev:object_name() or "", path) + local job + job = Job({ + command = adapter:bin(), + args = utils.vec_join(adapter:args(), "cat-file", "-s", spec), + cwd = adapter.ctx.toplevel, + fail_cond = Job.FAIL_COND.non_zero, + log_opt = { label = "git.lfs.blob_size()" }, + on_exit = async.void(function(_, ok) + if not ok or job.code ~= 0 then + callback(nil) + return + end + local line = (job.stdout or {})[1] + callback(line and tonumber(line) or nil) + end), + }) + await(vcs_utils.queue_sync_job(job)) +end) + +---`git show` stderr lines that mean "path doesn't exist at rev", as +---opposed to an operational error. Matched case-insensitively. +local absence_patterns = { + "does not exist", + "exists on disk", + "Not a valid object name", +} + +---@param stderr string[]? +---@return boolean +local function stderr_signals_absence(stderr) + if type(stderr) ~= "table" then + return false + end + for _, line in ipairs(stderr) do + for _, pat in ipairs(absence_patterns) do + if line:find(pat) then + return true + end + end + end + return false +end + +---Fetch the smudged content of `path` at `rev`. +--- +---Returns a status tag alongside the lines: +--- * `"ok"`: lines carry fully smudged content. +--- * `"absent"`: `path@rev` has no bytes (null tree, LOCAL file gone +--- from disk, or git-reported "path doesn't exist in rev"). +--- * `"error"`: an operational failure (smudge crash, bad object). +--- * `"too-large"`: pointer declares a `size` above `M.MAX_SMUDGE_BYTES`; +--- lines carry the raw pointer so callers can still display it. +---@param adapter GitAdapter +---@param path string +---@param rev Rev +---@param callback fun(status: git.lfs.FetchStatus, lines: string[]?) +local fetch_smudged_lines = async.wrap(function(adapter, path, rev, callback) + if rev.type == RevType.LOCAL then + -- Hop onto nvim's scheduler so `vim.fn.readfile` doesn't raise + -- `E5560` when resumed from a prior job's exit callback. + await(async.scheduler()) + local abs = pl:absolute(path, adapter.ctx.toplevel) + -- Gate on file size before loading. A normal `git lfs install` + -- checkout leaves the full smudged object in the working tree, so + -- an unguarded `vim.fn.readfile` would pull a multi-GB file into a + -- Lua list of lines and later feed it to `vim.diff`, freezing nvim. + -- The pointer-size check only covers raw-pointer-on-disk, which is + -- the exceptional branch. + local stat = pl:stat(abs) + if stat and M.MAX_SMUDGE_BYTES > 0 and stat.size > M.MAX_SMUDGE_BYTES then + callback("too-large", nil) + return + end + local ok, lines = pcall(vim.fn.readfile, abs) + if not ok then + callback("absent", nil) + return + end + if M.is_pointer(lines) then + if pointer_too_large(lines) then + callback("too-large", lines) + return + end + local serr, smudged = await(M.smudge(adapter, path, lines)) + if serr or not smudged then + callback("error", nil) + return + end + callback("ok", smudged) + return + end + callback("ok", lines) + return + end + + -- Pre-size via `git cat-file -s` so a historical non-pointer blob that + -- was later migrated to LFS can't bypass `MAX_SMUDGE_BYTES`: `adapter:show` + -- would buffer the whole object into memory and feed it to `vim.diff`. + -- Pointer blobs are tiny (~140 bytes), so this check never short-circuits + -- the pointer path. On lookup failure (nil size), fall through so the + -- existing `absent`/`error` classification handles it. + if M.MAX_SMUDGE_BYTES > 0 then + local size = await(blob_size(adapter, path, rev)) + if size and size > M.MAX_SMUDGE_BYTES then + callback("too-large", nil) + return + end + end + + local err, data = await(adapter:show(path, rev)) + if err then + callback(stderr_signals_absence(err) and "absent" or "error", nil) + return + end + if not data then + callback("absent", nil) + return + end + if not M.is_pointer(data) then + callback("ok", data) + return + end + if pointer_too_large(data) then + callback("too-large", data) + return + end + local serr, smudged = await(M.smudge(adapter, path, data)) + if serr or not smudged then + callback("error", nil) + return + end + callback("ok", smudged) +end) + +---@alias git.lfs.RecomputeStatus "ok"|"error"|"too-large"|"empty"|"binary" + +---Scan a bounded prefix of `lines` for a NUL byte, matching +---`vcs.File._lines_look_binary`. Inlined here to avoid pulling the +---`vcs.file` module into the LFS adapter and risking a require cycle. +---@param lines string[] +---@return boolean +local function lines_look_binary(lines) + local budget = 8192 + for _, line in ipairs(lines) do + if type(line) == "string" then + if line:find("\0", 1, true) then + return true + end + budget = budget - #line + if budget <= 0 then + return false + end + end + end + return false +end + +---Recompute additions/deletions by diffing smudged content on both sides +---via `vim.diff`. Takes per-side paths so renamed entries (old-path on +---left, new-path on right) resolve correctly. The companion status is: +--- * `"ok"`: stats are populated. +--- * `"error"`: a smudge or `show` call failed operationally. +--- * `"too-large"`: at least one side's pointer declares a size above +--- `M.MAX_SMUDGE_BYTES`. +--- * `"empty"`: both sides absent (null tree vs null tree, etc.). +--- * `"binary"`: at least one side's smudged bytes contain NUL. Feeding +--- binary content to `vim.diff` yields line counts proportional to +--- stray `0x0a` bytes, which is meaningless; callers hold the raw +--- numstat (same handling as `"too-large"`). +---Callers that drive a UI toggle use the status to decide whether to +---keep the raw numstat (and whether to revert a flipped state). +---@param adapter GitAdapter +---@param path_a string +---@param left Rev +---@param path_b string +---@param right Rev +---@param callback fun(stats: GitStats?, status: git.lfs.RecomputeStatus) +M.recompute_stats = async.wrap(function(adapter, path_a, left, path_b, right, callback) + local a_status, a_lines = await(fetch_smudged_lines(adapter, path_a, left)) + local b_status, b_lines = await(fetch_smudged_lines(adapter, path_b, right)) + -- Operational failures and oversized LFS objects: we have no meaningful + -- line count to publish. Leave the caller's raw numstat in place. + if a_status == "error" or b_status == "error" then + callback(nil, "error") + return + end + if a_status == "too-large" or b_status == "too-large" then + callback(nil, "too-large") + return + end + if a_status == "absent" and b_status == "absent" then + callback(nil, "empty") + return + end + -- Treat an absent-on-one-side as empty so the diff reports the real + -- line count for a true addition or deletion. + a_lines = a_lines or {} + b_lines = b_lines or {} + + -- Short-circuit on binary content: `vim.diff` would count stray `0x0a` + -- bytes as line breaks and emit a nonsense add/del count, which the UI + -- would then present alongside two null-rendered sides. + if lines_look_binary(a_lines) or lines_look_binary(b_lines) then + callback(nil, "binary") + return + end + + -- `table.concat({}, "\n") .. "\n"` renders as `"\n"` (one empty line), + -- which `vim.diff` counts as content. Serialize `{}` as `""` so an + -- empty side counts as zero lines. + local function join(lines) + return #lines == 0 and "" or table.concat(lines, "\n") .. "\n" + end + local a = join(a_lines) + local b = join(b_lines) + ---@diagnostic disable-next-line: deprecated + local hunks = vim.diff(a, b, { result_type = "indices" }) + if type(hunks) ~= "table" then + callback(nil, "error") + return + end + + local additions, deletions = 0, 0 + for _, h in ipairs(hunks) do + deletions = deletions + h[2] + additions = additions + h[4] + end + callback({ additions = additions, deletions = deletions }, "ok") +end) + +return M diff --git a/lua/diffview/vcs/file.lua b/lua/diffview/vcs/file.lua index 9659497c..50bf6063 100644 --- a/lua/diffview/vcs/file.lua +++ b/lua/diffview/vcs/file.lua @@ -32,6 +32,10 @@ local M = {} ---@field commit Commit? ---@field symbol string? ---@field get_data git.FileDataProducer? +---@field lfs_smudge boolean # When true, `produce_data` smudges LFS pointers so the buffer shows the real content. Default false. +---@field _lfs_tracked_cached? boolean # Memoised result of the first `_lfs_tracked` call; nil means not yet probed. Read by `FileEntry:convert_layout` to pre-seed the cache on sibling instances. +---@field _lfs_force_route? boolean # Set when `toggle_lfs_smudge`'s `side_is_pointer` fallback accepted a file not tracked by the current `.gitattributes` (historical attribute mismatch, rename to an untracked extension). Forces `create_buffer` to take the LFS routing path despite `_lfs_tracked()` returning false, so both sides diff consistently. +---@field package _lfs_smudge_from_pointer? boolean # Set by `create_buffer` when the LOCAL working tree holds a raw pointer and the user asked to smudge; `produce_data` reads it to drive the smudge path and `create_buffer` reads it to pick the `[lfs-local-smudged]` buffer context. ---@field bufnr? integer ---@field binary boolean ---@field active boolean @@ -59,6 +63,32 @@ File.created_bufs = {} ---Sentinel error value for cancelled buffer creation. File.CANCELLED = "diffview:cancelled" +---Scan a bounded prefix of `lines` for a NUL byte, the classic marker git +---itself uses to classify a blob as binary. Scanning a few KiB is enough: +---true binary payloads carry NUL bytes densely, and the cap keeps the +---check cheap on large smudged LFS objects. +---@static +---@param lines string[]? +---@return boolean +function File._lines_look_binary(lines) + if type(lines) ~= "table" then + return false + end + local budget = 8192 + for _, line in ipairs(lines) do + if type(line) == "string" then + if line:find("\0", 1, true) then + return true + end + budget = budget - #line + if budget <= 0 then + return false + end + end + end + return false +end + ---@static File.bufopts = { buftype = "nowrite", @@ -84,6 +114,15 @@ function File:init(opt) self.commit = opt.commit self.symbol = opt.symbol self.get_data = opt.get_data + self.lfs_smudge = not not opt.lfs_smudge + -- Pre-seed from a sibling (e.g. `convert_layout`) so the first + -- `_lfs_tracked` call skips the `git check-attr` shell-out. + if opt.lfs_tracked ~= nil then + self._lfs_tracked_cached = opt.lfs_tracked + end + if opt.lfs_force_route then + self._lfs_force_route = true + end self.active = true self.loaded = false self.ready = false @@ -213,16 +252,155 @@ File.produce_data = async.wrap(function(self, callback) local pos = self.symbol == "a" and "left" or "right" local data = self.get_data(self.kind, self.path, pos) callback(nil, data) - else - local err, data = await(self.adapter:show(self.path, self.rev)) + return + end - if err then - callback(err) + -- `create_buffer` routes LOCAL here for three LFS-tracked cases: + -- pointer-view (`lfs_smudge=false`), smudge-from-raw-pointer-on-disk + -- (`_lfs_smudge_from_pointer`), and oversized-smudged-on-disk fallback + -- (shown as pointer). The last two require inspecting the working-tree + -- bytes; the first can reuse the same probe to shortcut + -- `git lfs pointer` when disk already holds the pointer. + if self.rev.type == RevType.LOCAL then + local git_lfs = require("diffview.vcs.adapters.git.lfs") + await(async.scheduler()) + -- Stat first so a huge, newline-free file can't be pulled into a + -- single Lua line by `readfile` before any guard runs. The 11-line + -- sample below bounds *line count* only; it is byte-safe only when + -- the file is already known to fit under `MAX_SMUDGE_BYTES`. + local stat = pl:stat(self.absolute_path) + local probe_too_big = stat + and git_lfs.MAX_SMUDGE_BYTES > 0 + and stat.size > git_lfs.MAX_SMUDGE_BYTES + local sample_ok, sample + if not probe_too_big then + -- Reading up to 11 lines turns the line limit into a canary: a + -- pointer tops out at 10 lines by the spec (`is_pointer` enforces + -- that), so an 11-line sample proves the file is longer than any + -- pointer and must be real content. + sample_ok, sample = pcall(vim.fn.readfile, self.absolute_path, "", 11) + end + if self._lfs_smudge_from_pointer and sample_ok and git_lfs.is_pointer(sample) then + -- Smudge the on-disk pointer, subject to the same size cap as the + -- COMMIT path. The flag is only set when `create_buffer` saw a + -- pointer on disk; re-check here to handle the (narrow) race + -- where the working tree changed between the two probes. + local sz = git_lfs.parse_size(sample) + if git_lfs.MAX_SMUDGE_BYTES > 0 and sz and sz > git_lfs.MAX_SMUDGE_BYTES then + DiffviewGlobal.logger:warn( + fmt( + "[vcs.File:produce_data] LFS object for %s is %d bytes (> %d limit); showing pointer bytes. Raise `require('diffview.vcs.adapters.git.lfs').MAX_SMUDGE_BYTES` to override.", + self.path, + sz, + git_lfs.MAX_SMUDGE_BYTES + ) + ) + callback(nil, sample) + return + end + local serr, smudged = await(git_lfs.smudge(self.adapter, self.path, sample)) + if smudged then + callback(nil, smudged) + return + end + DiffviewGlobal.logger:warn( + fmt( + "[vcs.File:produce_data] LFS smudge failed for %s; showing pointer bytes. Is `git-lfs` installed? Details: %s", + self.path, + serr and table.concat(serr, "\n") or "no output" + ) + ) + callback(nil, sample) + return + end + -- Pointer-view (either `lfs_smudge=false` or oversized-smudged + -- fallback). If disk already holds the pointer, use its bytes + -- directly; otherwise synthesize via `git lfs pointer --file=`, + -- which streams through the file without buffering it. + if sample_ok and git_lfs.is_pointer(sample) then + callback(nil, sample) + return + end + local perr, pointer = await(git_lfs.working_tree_pointer(self.adapter, self.absolute_path)) + if perr or not pointer then + callback(perr or { "working-tree pointer unavailable" }) return end + callback(nil, pointer) + return + end - callback(nil, data) + local err, data = await(self.adapter:show(self.path, self.rev)) + + if err then + callback(err) + return + end + + -- Opt-in pointer-to-content expansion: `git show` returns the ~130-byte + -- pointer by default, and the real content can be arbitrarily large. + if self.lfs_smudge then + local git_lfs = require("diffview.vcs.adapters.git.lfs") + if git_lfs.is_pointer(data) then + local sz = git_lfs.parse_size(data) + if git_lfs.MAX_SMUDGE_BYTES > 0 and sz and sz > git_lfs.MAX_SMUDGE_BYTES then + DiffviewGlobal.logger:warn( + fmt( + "[vcs.File:produce_data] LFS object for %s is %d bytes (> %d limit); showing pointer bytes. Raise `require('diffview.vcs.adapters.git.lfs').MAX_SMUDGE_BYTES` to override.", + self.path, + sz, + git_lfs.MAX_SMUDGE_BYTES + ) + ) + else + local serr, smudged = await(git_lfs.smudge(self.adapter, self.path, data)) + if smudged then + data = smudged + else + DiffviewGlobal.logger:warn( + fmt( + "[vcs.File:produce_data] LFS smudge failed for %s; showing pointer bytes. Is `git-lfs` installed? Details: %s", + self.path, + serr and table.concat(serr, "\n") or "no output" + ) + ) + end + end + end + end + + callback(nil, data) +end) + +---Cached, lazy check: is this file configured as LFS-tracked (per the +---index's `.gitattributes`) AND is `git-lfs` on `PATH`? Reporting tracked +---without `git-lfs` would steer `create_buffer` into a pointer-mode path +---whose `git lfs pointer` call would fail, leaving every LFS-tracked +---LOCAL buffer unloadable. Non-git adapters never report tracked. +---@private +---@param self vcs.File +---@param callback fun(tracked: boolean) +File._lfs_tracked = async.wrap(function(self, callback) + if self._lfs_tracked_cached ~= nil then + callback(self._lfs_tracked_cached) + return + end + -- One `pcall` covers all failure modes: the git module failing to load, + -- an adapter that is not a class instance (e.g., `NULL_FILE`'s stub + -- table), and the `instanceof` call itself. + local ok, is_git = pcall(function() + local GitAdapter = require("diffview.vcs.adapters.git").GitAdapter + return self.adapter:instanceof(GitAdapter) + end) + if not (ok and is_git) or vim.fn.executable("git-lfs") ~= 1 then + self._lfs_tracked_cached = false + callback(false) + return end + local git_lfs = require("diffview.vcs.adapters.git.lfs") + local tracked = await(git_lfs.cached_is_tracked(self.adapter, self.path)) + self._lfs_tracked_cached = tracked + callback(tracked) end) ---@param self vcs.File @@ -286,10 +464,96 @@ File.create_buffer = async.wrap(function(self, callback) error(File.CANCELLED) end + -- Decide the LFS routing for LOCAL first: pointer-view and + -- raw-pointer-on-disk cases need to route through `diffview://` + -- regardless of the working-tree bytes, so they must bypass the + -- generic binary short-circuit below. Without this, a checked-out + -- binary LFS object trips `is_binary` and nulls the LOCAL side, + -- leaving an asymmetric diff against the textual pointer on the + -- COMMIT side (and a cached `binary=true` the toggle can't clear). + local lfs_use_diffview_buf = false + if self.rev.type == RevType.LOCAL and not self.nulled then + local git_lfs = require("diffview.vcs.adapters.git.lfs") + local is_lfs = await(self:_lfs_tracked()) + -- `_lfs_tracked` resumes in libuv's fast event context; hop onto + -- nvim's scheduler before any API-touching work below. + await(async.scheduler()) + -- Re-check `active` after the two awaits: the file may have been + -- deactivated while `git check-attr` was in flight (navigation, + -- view teardown), and the subsequent binary check and buffer + -- allocation would otherwise be wasted and leave a half-built + -- diffview buffer for `find_named_buffer` to pick up. + if not self.active then + error(File.CANCELLED) + end + -- Reset per-call. `convert_layout` may hand a File back for a + -- second `create_buffer` run with the on-disk state changed + -- (e.g., smudged-vs-pointer); recompute from scratch each time. + self._lfs_smudge_from_pointer = nil + -- Also honour `_lfs_force_route`: `toggle_lfs_smudge` sets it when + -- the index's `.gitattributes` doesn't flag this path as LFS but a + -- side's blob is nevertheless a pointer (tracking removed since + -- the historical commit, rename to an untracked extension). Without + -- this gate, LOCAL would fall through to `_create_local_buffer` and + -- render raw working-tree bytes while the other side renders smudged + -- content, producing an asymmetric diff and bypassing the size cap. + if is_lfs or self._lfs_force_route then + if not self.lfs_smudge then + -- Pointer-view: route through `diffview://` so both sides diff + -- as pointers. + lfs_use_diffview_buf = true + else + -- `lfs_smudge=true`: inspect the working-tree bytes. There + -- are three cases: + -- (a) smudged content on disk, over `MAX_SMUDGE_BYTES`: + -- fall back to pointer view with a warning rather than + -- loading a multi-GB file into a regular buffer that + -- `vim.diff` would then stall nvim on. + -- (b) raw pointer on disk (`GIT_LFS_SKIP_SMUDGE=1` or a + -- late `git lfs install`): smudge it ourselves via the + -- `diffview://` path so LOCAL matches the COMMIT side. + -- (c) smudged content on disk, within the cap: let + -- `_create_local_buffer` open the file directly. The + -- generic binary check below still applies here, so a + -- binary payload under `diff_binaries=false` nulls out + -- as usual. + -- Stat first so `readfile` can't swallow a huge newline-free + -- payload before the size guard runs; `readfile`'s line limit + -- bounds line count, not bytes. + local stat = pl:stat(self.absolute_path) + if stat and git_lfs.MAX_SMUDGE_BYTES > 0 and stat.size > git_lfs.MAX_SMUDGE_BYTES then + DiffviewGlobal.logger:warn( + fmt( + "[vcs.File:create_buffer] LOCAL working-tree size for %s is %d bytes (> %d limit); showing pointer view. Raise `require('diffview.vcs.adapters.git.lfs').MAX_SMUDGE_BYTES` to override.", + self.path, + stat.size, + git_lfs.MAX_SMUDGE_BYTES + ) + ) + lfs_use_diffview_buf = true + else + local sample_ok, sample = pcall(vim.fn.readfile, self.absolute_path, "", 11) + if sample_ok and git_lfs.is_pointer(sample) then + lfs_use_diffview_buf = true + self._lfs_smudge_from_pointer = true + end + end + end + end + end + -- Don't probe a nulled side: the result is unused (it routes to the NULL -- buffer below), and for a deleted file the gone `LOCAL` path makes -- `is_binary` false-positive, which would hide the deletion in inline. - if self.binary == nil and not self.nulled and not config.get_config().diff_binaries then + -- Also skip when the LOCAL side will route through `diffview://` for + -- LFS: the virtual buffer holds the pointer text, so the working-tree + -- bytes' binariness is irrelevant. + if + self.binary == nil + and not self.nulled + and not lfs_use_diffview_buf + and not config.get_config().diff_binaries + then self.binary = self.adapter:is_binary(self.path, self.rev) end @@ -299,10 +563,12 @@ File.create_buffer = async.wrap(function(self, callback) return end - if self.rev.type == RevType.LOCAL then + if self.rev.type == RevType.LOCAL and not lfs_use_diffview_buf then self:_create_local_buffer() return end + -- Non-LOCAL, or LOCAL LFS via `diffview://`: fall through to the + -- `diffview://` buffer creation below. -- Unmerged entries may not have all stage blobs (e.g. delete/modify -- conflicts). Missing stage blobs should render as null buffers. @@ -322,6 +588,19 @@ File.create_buffer = async.wrap(function(self, callback) context = fmt(":%d:", self.rev.stage) elseif self.rev.type == RevType.CUSTOM then context = "[custom]" + elseif self.rev.type == RevType.LOCAL then + -- Only reached for the LOCAL+LFS routes above. The two display + -- modes get distinct contexts so a stale buffer from the other + -- mode isn't accidentally reused via `find_named_buffer`. + context = self._lfs_smudge_from_pointer and "[lfs-local-smudged]" or "[lfs-local]" + end + -- Append an `[lfs-smudged]` suffix for non-LOCAL smudged buffers so + -- a parallel view (e.g., same commit+path in a second tab) with the + -- opposite smudge state doesn't collide via `find_named_buffer` and + -- return a buffer populated in the other mode. LOCAL already handled + -- its own split above. + if self.lfs_smudge and self.rev.type ~= RevType.LOCAL then + context = context .. " [lfs-smudged]" end local fullname = pl:join("diffview://", self.adapter.ctx.dir, context, self.path) @@ -371,9 +650,39 @@ File.create_buffer = async.wrap(function(self, callback) if not api.nvim_buf_is_valid(self.bufnr) then error("The buffer has been invalidated!") end + + -- Post-smudge binary check: the pre-await `is_binary` call inspected + -- the pointer blob (text) for non-LOCAL LFS-smudged sides and the + -- pointer-on-disk LOCAL case, so a binary smudged payload reaches + -- here undetected. For COMMIT/STAGE the pointer probe already set + -- `self.binary = false`, so gate on `not self.binary` (false or nil) + -- rather than nil only. Scan a bounded prefix of the content for + -- NUL and route to the shared null buffer when `diff_binaries=false`, + -- so a binary LFS object does not display as mojibake against the + -- other side. + if + not self.binary + and (self.lfs_smudge or self._lfs_smudge_from_pointer) + and not config.get_config().diff_binaries + and File._lines_look_binary(lines) + then + self.binary = true + pcall(api.nvim_buf_delete, self.bufnr, { force = true }) + if self.bufnr == created_fresh_bufnr then + created_fresh_bufnr = nil + end + self.bufnr = File._get_null_buffer() + self:post_buf_created() + return + end local bufopts = vim.deepcopy(File.bufopts) - if self.rev.type == RevType.STAGE and self.rev.stage == 0 then + -- LFS-smudged stage-0 buffers stay read-only: `stage_index_file` + -- hashes the temp file via `git hash-object -w`, which bypasses the + -- LFS clean filter. Writing a smudged buffer would stage the full + -- payload as a regular blob instead of a pointer. Until that write + -- path is supported, suppress the modifiable/acwrite setup. + if self.rev.type == RevType.STAGE and self.rev.stage == 0 and not self.lfs_smudge then self.blob_hash = self.adapter:file_blob_hash(self.path) bufopts.modifiable = true bufopts.buftype = "acwrite"