Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions doc/diffview.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
24 changes: 24 additions & 0 deletions doc/diffview_changelog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions lua/diffview/actions.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -1279,6 +1280,7 @@ local action_names = {
"toggle_stage_entry",
"toggle_untracked",
"toggle_hide_selected",
"toggle_lfs_smudge",
"unstage_all",
"worktree_overview_enter",
}
Expand Down
2 changes: 2 additions & 0 deletions lua/diffview/config.lua
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,7 @@ M.defaults = {
-- The `view` bindings are active in the diff buffers, only when the current
-- tabpage is a Diffview.
{ "n", "<C-w>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<C-x>", actions.cycle_layout, { desc = "Cycle through available layouts" } },
}, actions.compat.fold_cmds),
diff1 = utils.vec_join({
Expand Down Expand Up @@ -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<C-x>", 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" } },
Expand Down
30 changes: 20 additions & 10 deletions lua/diffview/scene/file_entry.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
33 changes: 32 additions & 1 deletion lua/diffview/scene/views/diff/diff_view.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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
Expand Down
173 changes: 173 additions & 0 deletions lua/diffview/scene/views/diff/listeners.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines +886 to +906

-- 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
Comment on lines +959 to +960
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
Expand Down
Loading
Loading