From a3a117280e93556cd6971b2af21daf91e900bce9 Mon Sep 17 00:00:00 2001 From: Yanuo Ma <41042490+esmuellert@users.noreply.github.com> Date: Sat, 12 Sep 2026 01:39:51 -0400 Subject: [PATCH 1/8] fix(refresh): classify mutable inputs and repository events Add a dependency policy for worktree, index, HEAD, refs and buffer invalidations. Restrict the Git content cache to immutable object IDs and normalize missing merge-stage errors. This commit contains only the policy foundation and its tests; snapshot application and session scheduling remain separate changes. --- lua/codediff/core/git/content.lua | 6 +-- lua/codediff/core/git/revision.lua | 9 ++++ lua/codediff/ui/refresh/policy.lua | 76 ++++++++++++++++++++++++++++++ tests/ui/refresh/policy_spec.lua | 50 ++++++++++++++++++++ 4 files changed, 138 insertions(+), 3 deletions(-) create mode 100644 lua/codediff/ui/refresh/policy.lua create mode 100644 tests/ui/refresh/policy_spec.lua diff --git a/lua/codediff/core/git/content.lua b/lua/codediff/core/git/content.lua index 13a315d9..f9be8e67 100644 --- a/lua/codediff/core/git/content.lua +++ b/lua/codediff/core/git/content.lua @@ -83,8 +83,8 @@ end -- rel_path: relative path from git root (with forward slashes) -- callback: function(err, lines) where lines is a table of strings function M.get_file_content(revision, git_root, rel_path, callback) - -- Don't cache mutable revisions (staged index can change with git add/reset) - local is_mutable = revision:match("^:[0-3]$") + -- Branches, HEAD and index stages can change without changing the path. + local is_mutable = not require("codediff.core.git.revision").is_fixed(revision) -- Check cache first (only for immutable revisions) if not is_mutable then @@ -100,7 +100,7 @@ function M.get_file_content(revision, git_root, rel_path, callback) run_git_async({ "show", git_object }, { cwd = git_root }, function(err, output) if err then - if err:match("does not exist") or err:match("exists on disk, but not in") then + if err:match("does not exist") or err:match("exists on disk, but not in") or err:match("is in the index, but not at stage") then callback(string.format("File '%s' not found in revision '%s'", rel_path, revision), nil) else callback(err, nil) diff --git a/lua/codediff/core/git/revision.lua b/lua/codediff/core/git/revision.lua index 0b15ee2b..eeb24ad6 100644 --- a/lua/codediff/core/git/revision.lua +++ b/lua/codediff/core/git/revision.lua @@ -12,6 +12,15 @@ local run_git_sync = runner.run_sync -- see #498). local GIT_EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" +--- Only full object IDs and their ancestry expressions are immutable cache keys. +function M.is_fixed(revision) + if type(revision) ~= "string" then + return false + end + local hash, suffix = revision:match("^(%x+)(.*)$") + return hash ~= nil and (#hash == 40 or #hash == 64) and (suffix == "" or suffix:match("^[~^%d]+$") ~= nil) +end + -- Resolve a git revision to its commit hash (async, atomic) -- revision: branch name, tag, or commit reference -- git_root: absolute path to git repository root diff --git a/lua/codediff/ui/refresh/policy.lua b/lua/codediff/ui/refresh/policy.lua new file mode 100644 index 00000000..b2fc233d --- /dev/null +++ b/lua/codediff/ui/refresh/policy.lua @@ -0,0 +1,76 @@ +-- Refresh events select data to inspect; they never request a view reset. +local M = {} +local fields = { "worktree", "index", "head", "refs", "buffer", "full", "render" } + +function M.normalize(event) + if type(event) ~= "table" then + return { full = true } + end + local result, known = {}, event.type == "refresh" + for _, field in ipairs(fields) do + if event[field] ~= nil then + known = true + if event[field] then + result[field] = true + end + end + end + return known and result or { full = true } +end + +function M.merge(first, second) + local result = {} + for _, event in ipairs({ first or {}, second or {} }) do + for _, field in ipairs(fields) do + if event[field] then + result[field] = true + end + end + end + return result +end + +function M.is_working(revision) + return revision == nil or revision == "WORKING" +end + +M.is_fixed = require("codediff.core.git.revision").is_fixed + +function M.needs_read(revision, event) + if event.full then + return true + end + if M.is_working(revision) then + return event.worktree == true or event.buffer == true + end + if type(revision) == "string" and revision:match("^:[0-3]:?$") then + return event.index == true + end + if M.is_fixed(revision) then + return false + end + return event.head == true or event.refs == true +end + +function M.panel_needed(panel, event) + if not panel then + return false + end + if event.full then + return true + end + if panel.name == "history" then + return event.head == true or event.refs == true + end + local view = panel.view or {} + if not view.git_root and view.dir1 then + return event.worktree == true + end + if view.base_revision then + local refs = view.source_revisions or {} + return M.needs_read(refs.original or view.base_revision, event) or M.needs_read(refs.modified or view.target_revision or "WORKING", event) + end + return event.worktree == true or event.index == true or event.head == true or event.refs == true +end + +return M diff --git a/tests/ui/refresh/policy_spec.lua b/tests/ui/refresh/policy_spec.lua new file mode 100644 index 00000000..f880c268 --- /dev/null +++ b/tests/ui/refresh/policy_spec.lua @@ -0,0 +1,50 @@ +describe("refresh dependency policy", function() + local policy + before_each(function() + policy = require("codediff.ui.refresh.policy") + end) + + it("checks everything when the source of a change is unknown", function() + assert.same({ full = true }, policy.normalize()) + assert.is_true(policy.needs_read("HEAD", { full = true })) + assert.is_true(policy.needs_read(":1", { full = true })) + assert.is_true(policy.needs_read(nil, { full = true })) + end) + + it("never loses a change category while merging pending events", function() + assert.same({ worktree = true, index = true, refs = true }, policy.merge({ worktree = true, refs = true }, { index = true, refs = false })) + end) + + it("selects dependencies for all sixteen watcher flag combinations", function() + for mask = 0, 15 do + local event = { + worktree = mask % 2 == 1, + index = math.floor(mask / 2) % 2 == 1, + head = math.floor(mask / 4) % 2 == 1, + refs = math.floor(mask / 8) % 2 == 1, + } + assert.equals(event.worktree, policy.needs_read("WORKING", event)) + for stage = 0, 3 do + assert.equals(event.index, policy.needs_read(":" .. stage, event)) + end + assert.equals(event.head or event.refs, policy.needs_read("HEAD", event)) + assert.equals(event.head or event.refs, policy.needs_read("topic", event)) + assert.is_false(policy.needs_read(string.rep("a", 40), event)) + assert.is_false(policy.needs_read(string.rep("a", 40) .. "^", event)) + end + end) + + it("treats buffer edits independently of filesystem events", function() + assert.is_true(policy.needs_read(nil, { buffer = true })) + assert.is_false(policy.needs_read(":0", { buffer = true })) + assert.is_false(policy.needs_read("HEAD", { buffer = true })) + end) + + it("does not refresh fixed revision or history lists for worktree-only events", function() + assert.is_false(policy.panel_needed({ name = "history" }, { worktree = true })) + assert.is_true(policy.panel_needed({ name = "history" }, { refs = true })) + assert.is_false(policy.panel_needed({ name = "explorer", view = { base_revision = string.rep("a", 40), target_revision = string.rep("b", 40) } }, { worktree = true })) + assert.is_false(policy.panel_needed({ name = "explorer", view = { base_revision = "HEAD", target_revision = ":0" } }, { worktree = true })) + assert.is_true(policy.panel_needed({ name = "explorer", view = {} }, { index = true })) + end) +end) From 49b9dfe951edc7c6fb0658f0df582992095c355c Mon Sep 17 00:00:00 2001 From: Yanuo Ma <41042490+esmuellert@users.noreply.github.com> Date: Sat, 12 Sep 2026 15:53:49 -0400 Subject: [PATCH 2/8] fix(refresh): snapshot inputs and update comparisons in place Read all comparison inputs before applying changes, compare source contents, and validate working-buffer ticks. Update existing panes without reopening unchanged inputs or overwriting edited merge results. Centralize revision-buffer content population and reject stale virtual-file loads. Cover snapshot completion, dependency selection, failures, and missing sides. --- lua/codediff/core/virtual_file.lua | 71 +++++----- lua/codediff/ui/refresh/apply.lua | 181 +++++++++++++++++++++++++ lua/codediff/ui/refresh/snapshot.lua | 196 +++++++++++++++++++++++++++ tests/ui/auto_refresh_spec.lua | 171 ++++++++--------------- 4 files changed, 472 insertions(+), 147 deletions(-) create mode 100644 lua/codediff/ui/refresh/apply.lua create mode 100644 lua/codediff/ui/refresh/snapshot.lua diff --git a/lua/codediff/core/virtual_file.lua b/lua/codediff/core/virtual_file.lua index ec43deab..05e9c9b2 100644 --- a/lua/codediff/core/virtual_file.lua +++ b/lua/codediff/core/virtual_file.lua @@ -5,15 +5,45 @@ local M = {} local api = vim.api +local loads = {} + +-- Populate revision buffers consistently whether opening or refreshing a view. +function M.set_content(buf, lines, filepath) + if not api.nvim_buf_is_valid(buf) then + return false + end + local value = #lines > 0 and lines or { "" } + if not vim.deep_equal(api.nvim_buf_get_lines(buf, 0, -1, false), value) then + vim.bo[buf].modifiable = true + vim.bo[buf].readonly = false + api.nvim_buf_set_lines(buf, 0, -1, false, value) + end + vim.bo[buf].modifiable = false + vim.bo[buf].readonly = true + -- Setting filetype fires FileType and can attach LSPs to codediff:// URIs. + local ft = filepath and vim.filetype.match({ filename = filepath, buf = buf }) + if ft then + local lang = vim.treesitter.language.get_lang(ft) or ft + if pcall(vim.treesitter.start, buf, lang) then + vim.bo[buf].syntax = "" + else + vim.bo[buf].syntax = ft + end + end + vim.diagnostic.enable(false, { bufnr = buf }) + return true +end -- Helper function to load content into a virtual buffer and fire the loaded event local function load_virtual_buffer_content(buf, git_root, commit, filepath) local git = require("codediff.core.git") + loads[buf] = (loads[buf] or 0) + 1 + local generation = loads[buf] git.get_file_content(commit, git_root, filepath, function(err, lines) vim.schedule(function() -- Check buffer is still valid (might have been deleted during async fetch) - if not api.nvim_buf_is_valid(buf) then + if not api.nvim_buf_is_valid(buf) or loads[buf] ~= generation then return end @@ -39,37 +69,7 @@ local function load_virtual_buffer_content(buf, git_root, commit, filepath) return end - -- Set the content - if not api.nvim_buf_is_valid(buf) then - -- Buffer was deleted while we were fetching, skip - return - end - vim.bo[buf].modifiable = true - vim.bo[buf].readonly = false - api.nvim_buf_set_lines(buf, 0, -1, false, lines) - - -- Make it read-only - vim.bo[buf].modifiable = false - vim.bo[buf].readonly = true - - -- Start TreeSitter highlighting directly without setting filetype. - -- Setting filetype fires FileType autocmd, which triggers LSP plugins - -- to attach and send textDocument/didOpen with codediff:// URI, - -- crashing language servers that can't handle custom URI schemes. - local ft = vim.filetype.match({ filename = filepath, buf = buf }) - if ft then - local lang = vim.treesitter.language.get_lang(ft) or ft - if pcall(vim.treesitter.start, buf, lang) then - -- Keep syntax fallback disabled when Tree-sitter is active. - vim.bo[buf].syntax = "" - else - -- TreeSitter parser not available, fall back to syntax highlighting - vim.bo[buf].syntax = ft - end - end - - -- Disable diagnostics for this buffer completely - vim.diagnostic.enable(false, { bufnr = buf }) + M.set_content(buf, lines, filepath) api.nvim_exec_autocmds("User", { pattern = "CodeDiffVirtualFileLoaded", @@ -174,6 +174,13 @@ function M.setup() end, }) + api.nvim_create_autocmd("BufWipeout", { + group = group, + callback = function(event) + loads[event.buf] = nil + end, + }) + -- Prevent writing to these buffers api.nvim_create_autocmd("BufWriteCmd", { group = group, diff --git a/lua/codediff/ui/refresh/apply.lua b/lua/codediff/ui/refresh/apply.lua new file mode 100644 index 00000000..b8954bb9 --- /dev/null +++ b/lua/codediff/ui/refresh/apply.lua @@ -0,0 +1,181 @@ +-- Update an existing comparison without reopening files or resetting editor state. +local M = {} +local api = vim.api +local snapshot = require("codediff.ui.refresh.snapshot") +local policy = require("codediff.ui.refresh.policy") + +local function put(buf, value) + if vim.deep_equal(snapshot.lines(buf), value) then + return + end + local modifiable, readonly = vim.bo[buf].modifiable, vim.bo[buf].readonly + vim.bo[buf].modifiable, vim.bo[buf].readonly = true, false + api.nvim_buf_set_lines(buf, 0, -1, false, value) + vim.bo[buf].modifiable, vim.bo[buf].readonly = modifiable, readonly +end + +local function materialize(session, side, input, value) + local buf = session[side .. "_bufnr"] + if not input.path or input.path.absolute == "" then + return buf + end + if policy.is_working(input.revision) then + -- Real buffers were reloaded by checktime, never by replacing their text. + if vim.bo[buf].buftype ~= "" then + put(buf, value) + end + return buf + end + + if input.resolved ~= session[side .. "_revision"] then + local virtual = require("codediff.core.virtual_file") + local name = virtual.create_url(session.git_root, input.resolved, input.path.relative) + local existing = -1 + for _, candidate in ipairs(api.nvim_list_bufs()) do + if api.nvim_buf_get_name(candidate) == name then + existing = candidate + break + end + end + if existing ~= -1 and api.nvim_buf_is_loaded(existing) then + buf = existing + else + buf = api.nvim_create_buf(false, true) + if existing == -1 then + api.nvim_buf_set_name(buf, name) + end + vim.bo[buf].buftype = "nowrite" + vim.bo[buf].bufhidden = "hide" + vim.bo[buf].swapfile = false + vim.bo[buf].readonly = true + vim.bo[buf].modifiable = false + end + session[side .. "_bufnr"] = buf + local win = session[side .. "_win"] + local hidden = side == "original" and session.layout == "inline" and session.single_side ~= "original" + if win and api.nvim_win_is_valid(win) and not hidden then + api.nvim_win_set_buf(win, buf) + vim.bo[buf].bufhidden = "wipe" + end + end + require("codediff.core.virtual_file").set_content(buf, value, input.path.relative) + session[side .. "_revision"] = input.resolved + return buf +end + +local function options() + local config = require("codediff.config").options.diff + return { + max_computation_time_ms = config.max_computation_time_ms, + ignore_trim_whitespace = config.ignore_trim_whitespace, + compute_moves = config.compute_moves, + } +end + +function M.result(session) + if not session.result_bufnr or not api.nvim_buf_is_valid(session.result_bufnr) or not session.result_base_lines then + return + end + local value = snapshot.lines(session.result_bufnr) + local result = require("codediff.core.diff").compute_diff(session.result_base_lines, value, options()) + if result then + require("codediff.ui.core").render_single_buffer(session.result_bufnr, result, "modified") + end + require("codediff.ui.conflict").refresh(session) +end + +function M.run(session, data, previous, redraw) + local input_changed = not snapshot.same_inputs(previous, data) + local result_changed = session.result_bufnr and not vim.deep_equal(previous and previous.result, snapshot.lines(session.result_bufnr)) + local seed = session.result_base_lines or {} + -- Neovim represents an empty Result as one empty line, not an empty array. + local untouched = vim.deep_equal(snapshot.lines(session.result_bufnr), #seed > 0 and seed or { "" }) + if session.result_bufnr and input_changed and not untouched then + if not session.refresh.blocked or not snapshot.same_inputs(session.refresh.blocked, data) then + vim.notify("Conflict inputs changed; Result has unsaved edits. Reopen the conflict view to reload its inputs.", vim.log.levels.WARN) + session.refresh.blocked = data + end + if result_changed or redraw then + M.result(session) + end + return false + end + if not input_changed and not redraw then + if result_changed then + M.result(session) + end + return true + end + + local views = {} + for _, side in ipairs({ "original", "modified", "result" }) do + local win = session[side .. "_win"] + if win and api.nvim_win_is_valid(win) and not views[win] then + views[win] = { view = api.nvim_win_call(win, vim.fn.winsaveview), scrollbind = vim.wo[win].scrollbind } + vim.wo[win].scrollbind = false + end + end + local focused = api.nvim_get_current_win() + local old_original, old_modified = session.original_bufnr, session.modified_bufnr + local ok, err = xpcall(function() + if input_changed then + materialize(session, "original", data.sources.original, data.original) + materialize(session, "modified", data.sources.modified, data.modified) + end + local core = require("codediff.ui.core") + local compute = require("codediff.core.diff").compute_diff + if session.result_bufnr then + local original = assert(compute(data.base, data.original, options())) + local modified = assert(compute(data.base, data.modified, options())) + core.render_merge_view(session.original_bufnr, session.modified_bufnr, original, modified, data.base, data.original, data.modified) + if input_changed then + local result, blocks = require("codediff.ui.conflict.merge").compute_auto_merged_result(original, modified, data.base, data.original, data.modified) + put(session.result_bufnr, result) + session.result_base_lines, session.merge_base_lines, session.conflict_blocks = result, data.base, blocks + require("codediff.ui.conflict").initialize_tracking(session.result_bufnr, blocks) + end + session.stored_diff_result = modified + require("codediff.ui.conflict").attach_gutter(session.original_win, session.modified_win) + M.result(session) + elseif session.single_side then + core.render_whole_file(session[session.single_side .. "_bufnr"], session.single_side) + session.stored_diff_result = { changes = {}, moves = {} } + else + local diff = assert(compute(data.original, data.modified, options())) + if session.layout == "inline" then + require("codediff.ui.inline").render_inline_diff(session.modified_bufnr, diff, data.original, data.modified) + else + core.render_diff(session.original_bufnr, session.modified_bufnr, data.original, data.modified, diff) + end + session.stored_diff_result = diff + end + session.changedtick.original = api.nvim_buf_get_changedtick(session.original_bufnr) + session.changedtick.modified = api.nvim_buf_get_changedtick(session.modified_bufnr) + if old_original ~= session.original_bufnr or old_modified ~= session.modified_bufnr then + require("codediff.ui.lifecycle").update_buffers(session.refresh.tabpage, session.original_bufnr, session.modified_bufnr) + if session.reapply_keymaps then + session.reapply_keymaps() + end + end + require("codediff.ui.view.compact").refresh(session.refresh.tabpage) + end, debug.traceback) + for win, saved in pairs(views) do + if api.nvim_win_is_valid(win) then + api.nvim_win_call(win, function() + local cursor = require("codediff.ui.view.cursor").clamp_cursor(win, { saved.view.lnum, saved.view.col }) + saved.view.lnum, saved.view.col = cursor[1], cursor[2] + vim.fn.winrestview(saved.view) + end) + vim.wo[win].scrollbind = saved.scrollbind + end + end + if api.nvim_win_is_valid(focused) and api.nvim_get_current_win() ~= focused then + api.nvim_set_current_win(focused) + end + if not ok then + error(err) + end + return true +end + +return M diff --git a/lua/codediff/ui/refresh/snapshot.lua b/lua/codediff/ui/refresh/snapshot.lua new file mode 100644 index 00000000..1d11d096 --- /dev/null +++ b/lua/codediff/ui/refresh/snapshot.lua @@ -0,0 +1,196 @@ +local M = {} +local api = vim.api +local policy = require("codediff.ui.refresh.policy") + +local function lines(buf) + return buf and api.nvim_buf_is_valid(buf) and api.nvim_buf_get_lines(buf, 0, -1, false) or { "" } +end + +local function normalized(value) + return value and #value > 0 and value or { "" } +end + +local function source(path, revision, resolved) + return { path = path, revision = revision, resolved = resolved } +end + +-- Preserve the requested ref, not just the SHA that happened to resolve at open. +function M.describe(session) + local requested = session.source_revisions or {} + local original = requested.original or session.original_revision + local modified = requested.modified or session.modified_revision + local panel = session.panel and session.panel.view + if session.panel and session.panel.name == "explorer" and panel and panel.git_root and panel.current_file_path then + if session.merge and session.result_bufnr then + original, modified = session.original_revision, session.modified_revision + elseif panel.base_revision then + local refs = panel.source_revisions or {} + original, modified = refs.original or panel.base_revision, refs.modified or panel.target_revision or "WORKING" + if session.single_side == "original" then + modified = nil + end + elseif panel.current_file_group == "staged" then + original, modified = "HEAD", ":0" + elseif session.single_side == "original" then + original, modified = ":0", nil + else + original, modified = "HEAD", "WORKING" + for _, file in ipairs((panel.status_result or {}).staged or {}) do + if file.path == panel.current_file_path then + original = ":0" + break + end + end + end + end + local description = { + original = source(session.original, original, session.original_revision), + modified = source(session.modified, modified, session.modified_revision), + } + if session.merge and session.result_bufnr then + description.base = source(session.original, ":1", ":1") + end + return description +end + +function M.capture(session) + local data = { sources = M.describe(session), original = lines(session.original_bufnr), modified = lines(session.modified_bufnr) } + if session.result_bufnr then + data.base = vim.deepcopy(session.merge_base_lines or {}) + data.result = lines(session.result_bufnr) + end + return data +end + +local function same_source(first, second) + return first and second and first.revision == second.revision and vim.deep_equal(first.path, second.path) +end + +function M.same_inputs(first, second) + if not first or not second then + return false + end + for _, side in ipairs({ "original", "modified", "base" }) do + if not vim.deep_equal(first[side], second[side]) then + return false + end + if first.sources[side] or second.sources[side] then + if not same_source(first.sources[side], second.sources[side]) then + return false + end + end + end + return true +end + +local function real_buffer(path) + local buf = vim.fn.bufadd(path) + if api.nvim_buf_is_loaded(buf) and vim.bo[buf].buftype == "" then + return buf + end +end + +local function read_working(session, side, input, event) + local path = input.path.absolute + local buf = real_buffer(path) + if buf then + -- Never replace unsaved text. checktime follows Neovim's reload safeguards. + if (event.full or event.worktree) and not vim.bo[buf].modified then + pcall(vim.cmd, "silent! checktime " .. buf) + end + return lines(buf), buf + end + if vim.fn.filereadable(path) == 0 then + return { "" } + end + local value = vim.fn.readfile(path) + for i, text in ipairs(value) do + value[i] = text:gsub("\r$", "") + end + if value[1] then + value[1] = value[1]:gsub("^\239\187\191", "") + end + return normalized(value) +end + +-- Read all candidates before touching any displayed input buffer. +function M.read(session, event, previous, done) + local data = { sources = M.describe(session), ticks = {} } + local git = require("codediff.core.git") + local remaining, completed, first_error = 1, false, nil + local function finish(err) + first_error = first_error or err + remaining = remaining - 1 + if remaining == 0 and not completed then + completed = true + done(first_error, data) + end + end + + for _, side in ipairs({ "original", "modified", "base" }) do + local input = data.sources[side] + if input then + remaining = remaining + 1 + local old = previous and previous.sources[side] + if not input.path or input.path.absolute == "" then + data[side] = side == "base" and {} or { "" } + finish() + elseif policy.is_working(input.revision) then + local value, buf = read_working(session, side, input, event) + data[side] = value + if buf then + data.ticks[buf] = api.nvim_buf_get_changedtick(buf) + end + finish() + elseif same_source(input, old) and not policy.needs_read(input.revision, event) then + -- Buffer events may originate from a programmatic edit of a diff pane. + data[side] = event.buffer and side ~= "base" and lines(session[side .. "_bufnr"]) or vim.deepcopy(previous[side]) + input.resolved = old.resolved + finish() + else + local function load(resolved) + input.resolved = resolved + git.get_file_content(resolved, session.git_root, input.path.relative, function(err, value) + vim.schedule(function() + if err and not err:find("not found in revision", 1, true) then + finish(err) + return + end + data[side] = side == "base" and (value or {}) or normalized(value) + finish() + end) + end) + end + if input.revision:match("^:[0-3]:?$") then + load(input.revision:gsub(":$", "")) + else + git.resolve_revision(input.revision, session.git_root, function(err, resolved) + vim.schedule(function() + if err then + finish(err) + else + load(resolved) + end + end) + end) + end + end + end + end + if session.result_bufnr then + data.result = lines(session.result_bufnr) + end + finish() +end + +function M.valid(data) + for buf, tick in pairs(data.ticks or {}) do + if not api.nvim_buf_is_valid(buf) or api.nvim_buf_get_changedtick(buf) ~= tick then + return false + end + end + return true +end + +M.lines = lines +return M diff --git a/tests/ui/auto_refresh_spec.lua b/tests/ui/auto_refresh_spec.lua index 4afba9f5..94de8b5e 100644 --- a/tests/ui/auto_refresh_spec.lua +++ b/tests/ui/auto_refresh_spec.lua @@ -1,150 +1,91 @@ -describe("mutable revision synchronization", function() - local original_auto_refresh - local original_git - local original_lifecycle - local auto_refresh - local original_trigger - local current_session - local callbacks - local trigger_count - local original_bufnr - local modified_bufnr - local tabpage +local snapshot = require("codediff.ui.refresh.snapshot") - before_each(function() - original_auto_refresh = package.loaded["codediff.ui.auto_refresh"] - original_git = package.loaded["codediff.core.git"] - original_lifecycle = package.loaded["codediff.ui.lifecycle"] +describe("refresh input snapshots", function() + local git, original_get_content, session, buffers, callbacks - original_bufnr = vim.api.nvim_create_buf(false, true) - modified_bufnr = vim.api.nvim_create_buf(false, true) - vim.api.nvim_buf_set_lines(original_bufnr, 0, -1, false, { "old original" }) - vim.api.nvim_buf_set_lines(modified_bufnr, 0, -1, false, { "old modified" }) - tabpage = vim.api.nvim_get_current_tabpage() - current_session = { + before_each(function() + git = require("codediff.core.git") + original_get_content = git.get_file_content + callbacks, buffers = {}, {} + for i = 1, 2 do + buffers[i] = vim.api.nvim_create_buf(false, true) + vim.api.nvim_buf_set_lines(buffers[i], 0, -1, false, { "old " .. i }) + end + session = { git_root = "/repo", - original_bufnr = original_bufnr, - modified_bufnr = modified_bufnr, + original_bufnr = buffers[1], + modified_bufnr = buffers[2], original_revision = ":2", modified_revision = ":3", - original = { relative = "file.txt" }, - modified = { relative = "file.txt" }, + original = { absolute = "/repo/file.txt", relative = "file.txt" }, + modified = { absolute = "/repo/file.txt", relative = "file.txt" }, } - callbacks = {} - trigger_count = 0 - - package.loaded["codediff.ui.lifecycle"] = { - get_session = function(candidate) - assert.equals(tabpage, candidate) - return current_session - end, - } - package.loaded["codediff.core.git"] = { - get_file_content = function(revision, git_root, path, callback) - assert.equals("/repo", git_root) - assert.equals("file.txt", path) - callbacks[revision] = callback - end, - } - package.loaded["codediff.ui.auto_refresh"] = nil - auto_refresh = require("codediff.ui.auto_refresh") - original_trigger = auto_refresh.trigger - auto_refresh.trigger = function() - trigger_count = trigger_count + 1 + git.get_file_content = function(revision, _, _, done) + callbacks[revision] = done end end) after_each(function() - auto_refresh.trigger = original_trigger - package.loaded["codediff.ui.auto_refresh"] = original_auto_refresh - package.loaded["codediff.core.git"] = original_git - package.loaded["codediff.ui.lifecycle"] = original_lifecycle - if vim.api.nvim_buf_is_valid(original_bufnr) then - vim.api.nvim_buf_delete(original_bufnr, { force = true }) - end - if vim.api.nvim_buf_is_valid(modified_bufnr) then - vim.api.nvim_buf_delete(modified_bufnr, { force = true }) + git.get_file_content = original_get_content + for _, buf in ipairs(buffers) do + vim.api.nvim_buf_delete(buf, { force = true }) end end) - it("completes only after every mutable target settles", function() - local completed = 0 - auto_refresh.sync_mutable_buffers(tabpage, function() - completed = completed + 1 + it("settles all candidates before returning and does not mutate displayed buffers", function() + local result + snapshot.read(session, { index = true }, snapshot.capture(session), function(err, data) + assert.is_nil(err) + result = data end) - - assert.is_function(callbacks[":2"]) - assert.is_function(callbacks[":3"]) - assert.equals(0, completed) - callbacks[":2"](nil, { "new original" }) - assert.is_true(vim.wait(1000, function() - return vim.api.nvim_buf_get_lines(original_bufnr, 0, -1, false)[1] == "new original" - end, 10)) - assert.equals(0, completed) - + vim.wait(20) + assert.is_nil(result) + assert.same({ "old 1" }, vim.api.nvim_buf_get_lines(buffers[1], 0, -1, false)) callbacks[":3"](nil, { "new modified" }) assert.is_true(vim.wait(1000, function() - return completed == 1 + return result ~= nil end, 10)) - assert.equals("new modified", vim.api.nvim_buf_get_lines(modified_bufnr, 0, -1, false)[1]) - assert.equals(2, trigger_count) - end) - - it("completes immediately when the session no longer exists", function() - current_session = nil - local completed = 0 - - auto_refresh.sync_mutable_buffers(tabpage, function() - completed = completed + 1 - end) - - assert.equals(1, completed) - assert.same({}, callbacks) + assert.same({ "new original" }, result.original) + assert.same({ "new modified" }, result.modified) + assert.same({ "old 2" }, vim.api.nvim_buf_get_lines(buffers[2], 0, -1, false)) end) - it("completes immediately when neither side is mutable", function() - current_session.original_revision = "HEAD" - current_session.modified_revision = nil - local completed = 0 - - auto_refresh.sync_mutable_buffers(tabpage, function() - completed = completed + 1 + it("does not read index sources for a worktree-only event", function() + local result + snapshot.read(session, { worktree = true }, snapshot.capture(session), function(err, data) + assert.is_nil(err) + result = data end) - - assert.equals(1, completed) assert.same({}, callbacks) + assert.same({ "old 1" }, result.original) end) - it("counts errors as settled", function() - current_session.modified_revision = nil - local completed = 0 - auto_refresh.sync_mutable_buffers(tabpage, function() - completed = completed + 1 + it("reports read failures without applying a partial snapshot", function() + local failure + snapshot.read(session, { index = true }, snapshot.capture(session), function(err) + failure = err end) - callbacks[":2"]("git failed") - + callbacks[":3"](nil, { "new modified" }) assert.is_true(vim.wait(1000, function() - return completed == 1 + return failure ~= nil end, 10)) - assert.equals("old original", vim.api.nvim_buf_get_lines(original_bufnr, 0, -1, false)[1]) + assert.equals("git failed", failure) + assert.same({ "old 2" }, vim.api.nvim_buf_get_lines(buffers[2], 0, -1, false)) end) - it("does not write after the owning session is replaced", function() - current_session.modified_revision = nil - local completed = 0 - auto_refresh.sync_mutable_buffers(tabpage, function() - completed = completed + 1 + it("represents a missing side as empty content rather than a transport failure", function() + local result + snapshot.read(session, { index = true }, snapshot.capture(session), function(err, data) + assert.is_nil(err) + result = data end) - current_session = {} - - callbacks[":2"](nil, { "stale" }) - + callbacks[":2"]("File 'file.txt' not found in revision ':2'") + callbacks[":3"](nil, { "new modified" }) assert.is_true(vim.wait(1000, function() - return completed == 1 + return result ~= nil end, 10)) - assert.equals("old original", vim.api.nvim_buf_get_lines(original_bufnr, 0, -1, false)[1]) - assert.equals(0, trigger_count) + assert.same({ "" }, result.original) end) end) From 6d5673e363a22985446f9ae60187a98e9557ff4a Mon Sep 17 00:00:00 2001 From: Yanuo Ma <41042490+esmuellert@users.noreply.github.com> Date: Sat, 12 Sep 2026 15:56:05 -0400 Subject: [PATCH 3/8] fix(refresh): coordinate session invalidations and lifecycle Route watcher classifications, buffer events, panel refreshes, and the 500ms polling fallback through one session controller. Separate repository-list updates from comparison updates and merge-result initialization. Preserve symbolic source refs across commands, panels, file following, and layout changes. Retire per-view schedulers, reject stale callbacks, and clean up refresh ownership when buffers or tabs disappear. Update Explorer and History tests for coalescing, retry, fallback, and lifecycle behavior. --- lua/codediff/commands/handlers/explorer.lua | 1 + .../commands/handlers/explorer_staged.lua | 1 + lua/codediff/commands/handlers/git_diff.lua | 2 + lua/codediff/ui/auto_refresh.lua | 469 +----------------- lua/codediff/ui/conflict/view/result.lua | 4 - lua/codediff/ui/explorer/refresh/init.lua | 134 +++-- .../ui/explorer/refresh/scheduler.lua | 159 +----- lua/codediff/ui/explorer/render.lua | 18 +- lua/codediff/ui/follow_working_file.lua | 179 +++---- lua/codediff/ui/history/refresh.lua | 241 +++------ lua/codediff/ui/history/render.lua | 30 +- lua/codediff/ui/lifecycle/accessors.lua | 4 +- lua/codediff/ui/lifecycle/cleanup.lua | 8 +- lua/codediff/ui/lifecycle/session.lua | 10 + lua/codediff/ui/lifecycle/state.lua | 280 ++--------- lua/codediff/ui/refresh/init.lua | 409 +++++++++++++++ lua/codediff/ui/view/init.lua | 5 + lua/codediff/ui/view/inline_view/buffers.lua | 2 - lua/codediff/ui/view/inline_view/create.lua | 4 - lua/codediff/ui/view/inline_view/update.lua | 8 +- lua/codediff/ui/view/panel.lua | 1 + lua/codediff/ui/view/render.lua | 7 - lua/codediff/ui/view/side_by_side/create.lua | 3 - .../ui/view/side_by_side/single_file.lua | 8 +- lua/codediff/ui/view/side_by_side/update.lua | 18 +- lua/codediff/ui/view/toggle.lua | 5 + tests/ui/explorer/explorer_refresh_spec.lua | 7 +- tests/ui/explorer/native_watcher_spec.lua | 364 +++++++------- .../history/history_refresh_watcher_spec.lua | 131 ++--- 29 files changed, 998 insertions(+), 1514 deletions(-) create mode 100644 lua/codediff/ui/refresh/init.lua diff --git a/lua/codediff/commands/handlers/explorer.lua b/lua/codediff/commands/handlers/explorer.lua index a25565cf..9a7aeaae 100644 --- a/lua/codediff/commands/handlers/explorer.lua +++ b/lua/codediff/commands/handlers/explorer.lua @@ -41,6 +41,7 @@ function M.run(revision, revision2, global_opts, pathspec) status_result = status_result, focus_file = focus_file, -- Focus on current file if changed pathspec = pathspec, -- Scope (#74): preserved so refresh re-applies it + source_revisions = revision and { original = revision, modified = revision2 or "WORKING" } or nil, }, }, git_root = git_root, diff --git a/lua/codediff/commands/handlers/explorer_staged.lua b/lua/codediff/commands/handlers/explorer_staged.lua index 7a60155d..f03537c8 100644 --- a/lua/codediff/commands/handlers/explorer_staged.lua +++ b/lua/codediff/commands/handlers/explorer_staged.lua @@ -49,6 +49,7 @@ function M.run(revision, global_opts, pathspec) status_result = status_result, focus_file = focus_file, pathspec = pathspec, + source_revisions = { original = rev, modified = ":0" }, }, }, git_root = git_root, diff --git a/lua/codediff/commands/handlers/git_diff.lua b/lua/codediff/commands/handlers/git_diff.lua index 9c3dae8f..06d7a799 100644 --- a/lua/codediff/commands/handlers/git_diff.lua +++ b/lua/codediff/commands/handlers/git_diff.lua @@ -67,6 +67,7 @@ function M.run(revision, revision2, global_opts) modified = path.make_ref(modified_path, git_root), original_revision = commit_hash, modified_revision = commit_hash2, + source_revisions = { original = revision, modified = revision2 }, layout = global_opts.layout, exit_on_close = global_opts.exit_on_close, } @@ -85,6 +86,7 @@ function M.run(revision, revision2, global_opts) modified = path.make_ref(relative_path, git_root), original_revision = commit_hash, modified_revision = "WORKING", + source_revisions = { original = revision, modified = "WORKING" }, layout = global_opts.layout, exit_on_close = global_opts.exit_on_close, } diff --git a/lua/codediff/ui/auto_refresh.lua b/lua/codediff/ui/auto_refresh.lua index d1d9598c..bba8eaa2 100644 --- a/lua/codediff/ui/auto_refresh.lua +++ b/lua/codediff/ui/auto_refresh.lua @@ -1,473 +1,28 @@ --- Auto-refresh mechanism for diff views --- Watches buffer changes (internal and external) and triggers diff recomputation +-- Buffer-edit entry points for the session refresh controller. local M = {} -local diff = require("codediff.core.diff") -local core = require("codediff.ui.core") - --- Throttle delay in milliseconds -local THROTTLE_DELAY_MS = 200 - --- Track watched buffers for auto-refresh --- Structure: { bufnr = { timer } } --- Buffer pair info is retrieved from lifecycle -local watched_buffers = {} - --- Cancel pending timer for a buffer -local function cancel_timer(bufnr) - local watcher = watched_buffers[bufnr] - if watcher and watcher.timer then - vim.fn.timer_stop(watcher.timer) - watcher.timer = nil - end -end - --- Perform diff computation and update decorations --- @param bufnr number: Buffer to update --- @param skip_watcher_check boolean: If true, don't require buffer to be in watched_buffers -local function do_diff_update(bufnr, skip_watcher_check) - local watcher = watched_buffers[bufnr] - - -- Check if buffer is being watched (unless skipped for manual trigger) - if not skip_watcher_check and not watcher then - return - end - - -- Clear timer reference if watcher exists - if watcher then - watcher.timer = nil - end - - -- Validate buffers still exist - if not vim.api.nvim_buf_is_valid(bufnr) then - if watcher then - watched_buffers[bufnr] = nil - end - return - end - - -- Get buffer pair from lifecycle - local lifecycle = require("codediff.ui.lifecycle") - local tabpage = lifecycle.find_tabpage_by_buffer(bufnr) - if not tabpage then - if watcher then - watched_buffers[bufnr] = nil - end - return - end - - local original_bufnr, modified_bufnr = lifecycle.get_buffers(tabpage) - if not original_bufnr or not modified_bufnr then - if watcher then - watched_buffers[bufnr] = nil - end - return - end - - if not vim.api.nvim_buf_is_valid(original_bufnr) or not vim.api.nvim_buf_is_valid(modified_bufnr) then - if watcher then - watched_buffers[bufnr] = nil - end - return - end - - -- Get fresh buffer content - local original_lines = vim.api.nvim_buf_get_lines(original_bufnr, 0, -1, false) - local modified_lines = vim.api.nvim_buf_get_lines(modified_bufnr, 0, -1, false) - - -- Async diff computation - vim.schedule(function() - -- Double-check buffer validity after schedule - if not vim.api.nvim_buf_is_valid(original_bufnr) or not vim.api.nvim_buf_is_valid(modified_bufnr) then - if watched_buffers[bufnr] then - watched_buffers[bufnr] = nil - end - return - end - - -- Compute diff - local config = require("codediff.config") - local diff_options = { - max_computation_time_ms = config.options.diff.max_computation_time_ms, - ignore_trim_whitespace = config.options.diff.ignore_trim_whitespace, - compute_moves = config.options.diff.compute_moves, - } - local lines_diff = diff.compute_diff(original_lines, modified_lines, diff_options) - if not lines_diff then - return - end - - -- Update stored diff result in lifecycle (critical for hunk navigation and do/dp) - lifecycle.update_diff_result(tabpage, lines_diff) - - -- Refresh compact mode folds if active - require("codediff.ui.view.compact").refresh(tabpage) - - -- Check if the session still owns the tab after the asynchronous diff. - local session = lifecycle.get_session(tabpage) - if not session then - return - end - if session.layout == "inline" then - local inline_mod = require("codediff.ui.inline") - inline_mod.render_inline_diff(modified_bufnr, lines_diff, original_lines, modified_lines) - return - end - - -- Side-by-side mode: Update decorations on both buffers - core.render_diff(original_bufnr, modified_bufnr, original_lines, modified_lines, lines_diff) - - -- Re-sync scrollbind after filler changes. Use the session's windows rather - -- than searching by buffer, because a duplicated pane may show the same - -- buffer without belonging to the diff. - local original_win = session.original_win - local modified_win = session.modified_win - local _, result_win = lifecycle.get_result(tabpage) - - if original_win and modified_win and original_win ~= modified_win and vim.api.nvim_win_is_valid(original_win) and vim.api.nvim_win_is_valid(modified_win) then - local current_win = vim.api.nvim_get_current_win() - if current_win == original_win or current_win == modified_win or current_win == result_win then - local other_win = current_win == original_win and modified_win or original_win - - local saved_view = vim.fn.winsaveview() - vim.api.nvim_set_current_win(other_win) - local other_saved_view = vim.fn.winsaveview() - local result_saved_view - if result_win then - vim.api.nvim_set_current_win(result_win) - result_saved_view = vim.fn.winsaveview() - end - vim.api.nvim_set_current_win(current_win) - - vim.api.nvim_win_set_cursor(original_win, { 1, 0 }) - vim.api.nvim_win_set_cursor(modified_win, { 1, 0 }) - if result_win then - vim.api.nvim_win_set_cursor(result_win, { 1, 0 }) - end - - vim.wo[original_win].scrollbind = false - vim.wo[modified_win].scrollbind = false - if result_win then - vim.wo[result_win].scrollbind = false - end - vim.wo[original_win].scrollbind = true - vim.wo[modified_win].scrollbind = true - if result_win then - vim.wo[result_win].scrollbind = true - end - - vim.api.nvim_set_current_win(other_win) - vim.fn.winrestview(other_saved_view) - if result_win and result_saved_view then - vim.api.nvim_set_current_win(result_win) - vim.fn.winrestview(result_saved_view) - end - vim.api.nvim_set_current_win(current_win) - vim.fn.winrestview(saved_view) - end - end - end) -end - --- Trigger diff update with throttling -local function trigger_diff_update(bufnr) - local watcher = watched_buffers[bufnr] - if not watcher then - return - end - - -- Cancel existing timer - cancel_timer(bufnr) - - -- Start new timer - watcher.timer = vim.fn.timer_start(THROTTLE_DELAY_MS, function() - do_diff_update(bufnr) - end) -end - --- Setup auto-refresh for a buffer --- @param bufnr number: Buffer to watch for changes --- Note: Buffer pair info is retrieved from lifecycle when needed -function M.enable(bufnr) - -- Store watcher info (just timer) - watched_buffers[bufnr] = { - timer = nil, - } - - -- Setup autocmds for this buffer - local buf_augroup = vim.api.nvim_create_augroup("codediff_auto_refresh_" .. bufnr, { clear = true }) - - -- Internal changes (user editing) - vim.api.nvim_create_autocmd({ "TextChanged", "TextChangedI", "TextChangedP" }, { - group = buf_augroup, - buffer = bufnr, - callback = function() - trigger_diff_update(bufnr) - end, - }) - - -- External changes (file modified on disk) - vim.api.nvim_create_autocmd({ "FileChangedShellPost", "FocusGained" }, { - group = buf_augroup, - buffer = bufnr, - callback = function() - trigger_diff_update(bufnr) - end, - }) - - -- Cleanup on buffer delete/wipe - vim.api.nvim_create_autocmd({ "BufDelete", "BufWipeout" }, { - group = buf_augroup, - buffer = bufnr, - callback = function() - M.disable(bufnr) - end, - }) -end - --- Disable auto-refresh for a buffer -function M.disable(bufnr) - cancel_timer(bufnr) - watched_buffers[bufnr] = nil - - -- Clear autocmd group - pcall(vim.api.nvim_del_augroup_by_name, "codediff_auto_refresh_" .. bufnr) +function M.trigger(bufnr) + require("codediff.ui.refresh").buffer_changed(bufnr) end --- Track result buffer timers only (base_lines stored in lifecycle) -local result_timers = {} - --- Perform diff update for result buffer against BASE -local function do_result_diff_update(bufnr) - -- Clear timer reference - result_timers[bufnr] = nil - - -- Validate buffer still exists - if not vim.api.nvim_buf_is_valid(bufnr) then - return - end - - -- Get base_lines from lifecycle +-- Resolution commands need their Result highlights updated synchronously. +function M.refresh_result_now(bufnr) local lifecycle = require("codediff.ui.lifecycle") local tabpage = lifecycle.find_tabpage_by_buffer(bufnr) - if not tabpage then - return - end - - local base_lines = lifecycle.get_result_base_lines(tabpage) - if not base_lines then - return - end - - -- Get current result buffer content - local result_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) - - -- Compute diff: BASE vs result (result shows what was added/changed from BASE) - local config = require("codediff.config") - local diff_options = { - max_computation_time_ms = config.options.diff.max_computation_time_ms, - ignore_trim_whitespace = config.options.diff.ignore_trim_whitespace, - compute_moves = config.options.diff.compute_moves, - } - local lines_diff = diff.compute_diff(base_lines, result_lines, diff_options) - if not lines_diff then - return - end - - -- Render highlights on result buffer only (modified side = insertions shown as green) - core.render_single_buffer(bufnr, lines_diff, "modified") -end - --- Trigger throttled diff update for result buffer -local function trigger_result_diff_update(bufnr) - -- Cancel existing timer - if result_timers[bufnr] then - vim.fn.timer_stop(result_timers[bufnr]) - end - - -- Start new throttled timer - result_timers[bufnr] = vim.fn.timer_start(THROTTLE_DELAY_MS, function() - vim.schedule(function() - do_result_diff_update(bufnr) - end) - end) -end - --- Enable auto-refresh for result buffer (diffs against BASE stored in lifecycle) -function M.enable_for_result(bufnr) - if not vim.api.nvim_buf_is_valid(bufnr) then - return - end - - -- Disable if already enabled - M.disable_result(bufnr) - - -- Setup autocmds for this buffer - local buf_augroup = vim.api.nvim_create_augroup("codediff_result_refresh_" .. bufnr, { clear = true }) - - -- Internal changes (user editing) - vim.api.nvim_create_autocmd({ "TextChanged", "TextChangedI", "TextChangedP" }, { - group = buf_augroup, - buffer = bufnr, - callback = function() - trigger_result_diff_update(bufnr) - end, - }) - - -- Cleanup on buffer delete/wipe - vim.api.nvim_create_autocmd({ "BufDelete", "BufWipeout" }, { - group = buf_augroup, - buffer = bufnr, - callback = function() - M.disable_result(bufnr) - end, - }) - - -- Initial render - vim.schedule(function() - do_result_diff_update(bufnr) - end) -end - --- Disable auto-refresh for result buffer -function M.disable_result(bufnr) - if result_timers[bufnr] then - vim.fn.timer_stop(result_timers[bufnr]) - result_timers[bufnr] = nil - end - - -- Clear autocmd group - pcall(vim.api.nvim_del_augroup_by_name, "codediff_result_refresh_" .. bufnr) -end - --- Immediately refresh result buffer diff (call after programmatic changes) -function M.refresh_result_now(bufnr) - if not vim.api.nvim_buf_is_valid(bufnr) then - return - end - -- Cancel pending timer if any - if result_timers[bufnr] then - vim.fn.timer_stop(result_timers[bufnr]) - result_timers[bufnr] = nil + local session = tabpage and lifecycle.get_session(tabpage) + if session and session.result_bufnr == bufnr then + require("codediff.ui.refresh.apply").result(session) end - do_result_diff_update(bufnr) end --- Sync mutable revision buffers (:0-:3) with current git index content. --- Called when repository state changes. Only writes if content actually changed, --- which triggers TextChanged → auto_refresh recomputes diff automatically. --- @param tabpage number: Tabpage whose session buffers to sync --- @param done function|nil: Called after every mutable target settles function M.sync_mutable_buffers(tabpage, done) - done = done or function() end - local lifecycle = require("codediff.ui.lifecycle") - local session = lifecycle.get_session(tabpage) - if not session then - done() - return - end - - local function is_mutable(revision) - return revision and revision:match("^:[0-3]$") - end - - local targets = {} - local function add_target(side, bufnr, revision, ref) - local path = ref and ref.relative - if bufnr and vim.api.nvim_buf_is_valid(bufnr) and is_mutable(revision) and path and path ~= "" then - targets[#targets + 1] = { - side = side, - bufnr = bufnr, - revision = revision, - path = path, - } - end - end - add_target("original", session.original_bufnr, session.original_revision, session.original) - add_target("modified", session.modified_bufnr, session.modified_revision, session.modified) - - if #targets == 0 then - done() - return - end - - local remaining = #targets - local completed = false - local function finish_target() - remaining = remaining - 1 - if remaining == 0 and not completed then - completed = true - done() - end - end - - local function still_current(target) - local current = lifecycle.get_session(tabpage) - if current ~= session then - return false - end - local ref = current[target.side] - local bufnr = current[target.side .. "_bufnr"] - local revision = current[target.side .. "_revision"] - return bufnr == target.bufnr and revision == target.revision and ref and ref.relative == target.path - end - - local function lines_equal(bufnr, lines) - local current = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) - if #current ~= #lines then - return false - end - for i = 1, #lines do - if current[i] ~= lines[i] then - return false - end - end - return true - end - - local git = require("codediff.core.git") - for _, target in ipairs(targets) do - git.get_file_content(target.revision, session.git_root, target.path, function(err, lines) - vim.schedule(function() - local can_update = not err and lines and vim.api.nvim_buf_is_valid(target.bufnr) and still_current(target) - if can_update and not lines_equal(target.bufnr, lines) then - local was_modifiable = vim.bo[target.bufnr].modifiable - local was_readonly = vim.bo[target.bufnr].readonly - vim.bo[target.bufnr].readonly = false - vim.bo[target.bufnr].modifiable = true - vim.api.nvim_buf_set_lines(target.bufnr, 0, -1, false, lines) - vim.bo[target.bufnr].modifiable = was_modifiable - vim.bo[target.bufnr].readonly = was_readonly - -- TextChanged doesn't fire on nowrite/nofile buffers, trigger explicitly - M.trigger(target.bufnr) - end - finish_target() - end) - end) - end + require("codediff.ui.refresh").request(tabpage, { index = true }, done) end --- Cleanup all watched buffers function M.cleanup_all() - for bufnr, _ in pairs(watched_buffers) do - M.disable(bufnr) - end - for bufnr, _ in pairs(result_timers) do - M.disable_result(bufnr) - end -end - --- Manually trigger a diff refresh for a buffer (e.g., after programmatic changes) --- Works for any buffer in a diff session, even if auto-refresh is not enabled for it --- @param bufnr number: Buffer that was changed -function M.trigger(bufnr) - if watched_buffers[bufnr] then - -- Buffer has auto-refresh enabled, use throttled update - trigger_diff_update(bufnr) - else - -- Buffer might not have auto-refresh enabled (e.g., virtual buffer) - -- Do immediate update, skipping watcher check - do_diff_update(bufnr, true) + local refresh = require("codediff.ui.refresh") + for tabpage in pairs(require("codediff.ui.lifecycle.session").get_active_diffs()) do + refresh.dispose(tabpage) end end diff --git a/lua/codediff/ui/conflict/view/result.lua b/lua/codediff/ui/conflict/view/result.lua index 797a2c45..c831583f 100644 --- a/lua/codediff/ui/conflict/view/result.lua +++ b/lua/codediff/ui/conflict/view/result.lua @@ -2,7 +2,6 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") local config = require("codediff.config") local layout = require("codediff.ui.layout") @@ -161,9 +160,6 @@ function M.setup_conflict_result_window(tabpage, session_config, original_win, m end end - -- Enable auto-refresh for result buffer - auto_refresh.enable_for_result(result_bufnr) - -- Initialize conflict tracking (keymaps setup separately after setup_all_keymaps) local conflict = require("codediff.ui.conflict") conflict.initialize_tracking(result_bufnr, conflict_diffs.conflict_blocks) diff --git a/lua/codediff/ui/explorer/refresh/init.lua b/lua/codediff/ui/explorer/refresh/init.lua index 2924f5cb..aeb35402 100644 --- a/lua/codediff/ui/explorer/refresh/init.lua +++ b/lua/codediff/ui/explorer/refresh/init.lua @@ -181,31 +181,27 @@ local function rebuild_tree(explorer, status_result, collapsed_state) -- Restore user's collapsed state (must be after expand_all_dirs) restore_collapsed_state(explorer.tree, collapsed_state, root_nodes) - explorer.tree:render() + if not explorer.is_hidden then + explorer.tree:render() + end end -- Execute one explorer refresh. Public callers use M.refresh below. -function M._refresh_once(explorer, done, force) +function M._refresh_once(explorer, done) local git = require("codediff.core.git") local completed = false - local function complete() + local function complete(err) if completed then return end completed = true if done then - done() + done(err) end end - -- Skip refresh if explorer is hidden - if explorer.is_hidden then - complete() - return - end - - -- Verify window is still valid before accessing - if not vim.api.nvim_win_is_valid(explorer.winid) then + -- A hidden panel still supplies status and comparison definitions. + if not explorer.is_hidden and not vim.api.nvim_win_is_valid(explorer.winid) then complete() return end @@ -216,20 +212,18 @@ function M._refresh_once(explorer, done, force) local function process_result(err, status_result) vim.schedule(function() local lifecycle = require("codediff.ui.lifecycle") - if lifecycle.get_panel_view(explorer.tabpage) ~= explorer or not vim.api.nvim_win_is_valid(explorer.winid) then + if lifecycle.get_panel_view(explorer.tabpage) ~= explorer or (not explorer.is_hidden and not vim.api.nvim_win_is_valid(explorer.winid)) then complete() return end if err then - vim.notify("Failed to refresh: " .. err, vim.log.levels.ERROR) - complete() + complete(err) return end - -- Watch notifications are invalidation hints. Skip UI churn when the - -- resulting status did not actually change. - if not force and vim.deep_equal(status_result, explorer.status_result) then + -- Panel equality does not suppress the controller's input inspection. + if vim.deep_equal(status_result, explorer.status_result) then complete() return end @@ -261,15 +255,22 @@ function M._refresh_once(explorer, done, force) if explorer.current_file_path and total_files > 0 then local found_file, found_group = file_to_reselect(explorer, status_result, prev_index) if found_file then - -- on_file_select dedupes; no_jump keeps the cursor where it is, - -- since this is a refresh rather than a click. - explorer.on_file_select({ - path = found_file.path, - old_path = found_file.old_path, - status = found_file.status, - git_root = explorer.git_root, - group = found_group, - }, { no_jump = true, force = force }) + local selected = explorer.current_selection + if + not selected + or selected.path ~= found_file.path + or selected.group ~= found_group + or selected.status ~= found_file.status + or selected.old_path ~= found_file.old_path + then + explorer.on_file_select({ + path = found_file.path, + old_path = found_file.old_path, + status = found_file.status, + git_root = explorer.git_root, + group = found_group, + }, { no_jump = true }) + end else -- Committed or removed. clear_current_file(explorer) @@ -280,31 +281,72 @@ function M._refresh_once(explorer, done, force) end) end - -- Use appropriate function based on mode - if not explorer.git_root then - -- Dir mode: re-scan directories - local dir_mod = require("codediff.core.dir") - local diff = dir_mod.diff_directories(explorer.dir1, explorer.dir2) - process_result(nil, diff.status_result) - elseif explorer.target_revision == ":0" then - -- Staged-only mode (--staged): index vs base_revision. `git diff base :0` - -- isn't a valid rev-pair; use `git diff --cached base` instead. - git.get_diff_staged(explorer.base_revision, explorer.git_root, process_result, explorer.pathspec) - elseif explorer.base_revision and explorer.target_revision and explorer.target_revision ~= "WORKING" then - git.get_diff_revisions_with_line_stats(explorer.base_revision, explorer.target_revision, explorer.git_root, process_result, explorer.pathspec) - elseif explorer.base_revision then - git.get_diff_revision_with_line_stats(explorer.base_revision, explorer.git_root, process_result, explorer.pathspec) - else - git.get_status_with_line_stats(explorer.git_root, process_result, explorer.pathspec) + local function fetch_status() + -- Use appropriate function based on mode + if not explorer.git_root then + -- Dir mode: re-scan directories + local dir_mod = require("codediff.core.dir") + local diff = dir_mod.diff_directories(explorer.dir1, explorer.dir2) + process_result(nil, diff.status_result) + elseif explorer.target_revision == ":0" then + -- Staged-only mode (--staged): index vs base_revision. `git diff base :0` + -- isn't a valid rev-pair; use `git diff --cached base` instead. + git.get_diff_staged(explorer.base_revision, explorer.git_root, process_result, explorer.pathspec) + elseif explorer.base_revision and explorer.target_revision and explorer.target_revision ~= "WORKING" then + git.get_diff_revisions_with_line_stats(explorer.base_revision, explorer.target_revision, explorer.git_root, process_result, explorer.pathspec) + elseif explorer.base_revision then + git.get_diff_revision_with_line_stats(explorer.base_revision, explorer.git_root, process_result, explorer.pathspec) + else + git.get_status_with_line_stats(explorer.git_root, process_result, explorer.pathspec) + end + end + + local requested = explorer.source_revisions + if not requested then + fetch_status() + return + end + local resolved, remaining, failure = {}, 1, nil + local function settled(err) + failure = failure or err + remaining = remaining - 1 + if remaining ~= 0 then + return + end + if failure then + complete(failure) + return + end + if require("codediff.ui.lifecycle").get_panel_view(explorer.tabpage) ~= explorer then + complete() + return + end + explorer.base_revision, explorer.target_revision = resolved.original, resolved.modified + fetch_status() + end + for side, revision in pairs(requested) do + remaining = remaining + 1 + if revision == "WORKING" or revision:match("^:[0-3]$") then + resolved[side] = revision + settled() + else + git.resolve_revision(revision, explorer.git_root, function(err, hash) + vim.schedule(function() + resolved[side] = hash + settled(err) + end) + end) + end end + settled() end -- Queue every refresh source through the controller installed on the explorer. -function M.refresh(explorer, done, force) +function M.refresh(explorer, done) if explorer and explorer._request_refresh then - return explorer._request_refresh(force, done) + return explorer._request_refresh({ full = true }, done) end - return M._refresh_once(explorer, done, force) + return M._refresh_once(explorer, done) end -- Rebuild the tree synchronously from the cached status_result. Used when only diff --git a/lua/codediff/ui/explorer/refresh/scheduler.lua b/lua/codediff/ui/explorer/refresh/scheduler.lua index 75851b2c..e1da0264 100644 --- a/lua/codediff/ui/explorer/refresh/scheduler.lua +++ b/lua/codediff/ui/explorer/refresh/scheduler.lua @@ -1,161 +1,24 @@ --- Serializes complete Explorer refresh cycles across every request source. +-- Explorer is a panel of the session refresh controller, not a second scheduler. local M = {} -local config = require("codediff.config") - function M.setup(explorer, tabpage, refresh_once) - local explorer_config = config.options.explorer or {} - local uv = vim.uv or vim.loop - local poll_timer - local unsubscribe - local cleaned = false - local refresh_running = false - local refresh_pending = false - local pending_force = false - local pending_done = {} - local group - - local function stop_polling() - if not poll_timer then - return - end - pcall(function() - poll_timer:stop() - end) - pcall(function() - poll_timer:close() - end) - poll_timer = nil + local refresh = require("codediff.ui.refresh") + local unbind = refresh.bind_panel(tabpage, explorer, function(done) + refresh_once(explorer, done) + end) + explorer._request_refresh = function(event, done) + refresh.request(tabpage, event, done) + end + explorer._request_auto_refresh = function(message) + refresh.request(tabpage, message) end - local function cleanup() - if cleaned then - return - end - cleaned = true - stop_polling() - if unsubscribe then - unsubscribe() - unsubscribe = nil - end - pending_done = {} + unbind() explorer._request_refresh = nil explorer._request_auto_refresh = nil explorer._native_watcher_ready = nil - if group then - pcall(vim.api.nvim_del_augroup_by_id, group) - end end - explorer._cleanup_auto_refresh = cleanup - - local function call_done(callbacks) - for _, callback in ipairs(callbacks) do - pcall(callback) - end - end - - local request_refresh - request_refresh = function(force, done_callbacks) - done_callbacks = done_callbacks or {} - if cleaned then - return - end - if refresh_running then - refresh_pending = true - pending_force = pending_force or force == true - vim.list_extend(pending_done, done_callbacks) - return - end - refresh_running = true - refresh_once(explorer, function() - if cleaned then - return - end - require("codediff.ui.auto_refresh").sync_mutable_buffers(tabpage, function() - if cleaned then - return - end - refresh_running = false - call_done(done_callbacks) - if refresh_pending then - local force_pending = pending_force - local done_pending = pending_done - refresh_pending = false - pending_force = false - pending_done = {} - request_refresh(force_pending, done_pending) - end - end) - end, force) - end - - local function tick(force) - if not vim.api.nvim_tabpage_is_valid(tabpage) or explorer.is_hidden then - return - end - -- A queued fallback tick may outlive the tab or repository setup/teardown. - local git_root = explorer.git_root - if git_root and git_root ~= "" then - if vim.fn.isdirectory(git_root) == 0 then - return - end - -- Linked worktrees and submodules use a .git pointer file. - local dot_git = git_root .. "/.git" - if vim.fn.isdirectory(dot_git) == 0 and vim.fn.filereadable(dot_git) == 0 then - return - end - end - request_refresh(force) - end - - explorer._request_refresh = function(force, done) - request_refresh(force, done and { done } or {}) - end - explorer._request_auto_refresh = function() - tick(true) - end - - if explorer_config.auto_refresh == false then - return cleanup - end - - group = vim.api.nvim_create_augroup("CodeDiffExplorerRefresh_" .. tabpage, { clear = true }) - - local function start_polling() - if cleaned or poll_timer then - return - end - poll_timer = uv.new_timer() - if poll_timer then - poll_timer:start(500, 500, vim.schedule_wrap(tick)) - end - end - - start_polling() - if explorer.git_root and explorer.git_root ~= "" then - unsubscribe = require("codediff.core.watcher").subscribe(explorer.git_root, { - on_ready = function() - explorer._native_watcher_ready = true - stop_polling() - tick(true) - end, - on_refresh = function() - tick(true) - end, - on_error = function() - explorer._native_watcher_ready = false - start_polling() - end, - }) - end - - vim.api.nvim_create_autocmd("TabClosed", { - group = group, - pattern = tostring(tabpage), - callback = cleanup, - }) - return cleanup end diff --git a/lua/codediff/ui/explorer/render.lua b/lua/codediff/ui/explorer/render.lua index 110c5aaa..34b7079b 100644 --- a/lua/codediff/ui/explorer/render.lua +++ b/lua/codediff/ui/explorer/render.lua @@ -58,7 +58,7 @@ end --- codediff:// buffers mid-load (bufhidden=wipe), and resets single_pane. local function open_diff_when_still_selected(ctx, sides) vim.schedule(function() - if ctx.explorer.current_file_path ~= ctx.file_path then + if ctx.explorer.current_file_path ~= ctx.file_path or (ctx.selection and ctx.explorer._selection_generation ~= ctx.selection) then return end ---@type SessionConfig @@ -106,7 +106,7 @@ end --- @return boolean local function already_showing(session, explorer, file_path, abs_path, group) local same_file = (session.modified and session.modified.absolute == abs_path) or (session.original and session.original.absolute == abs_path) - if not same_file then + if not same_file or session.single_side then return false end @@ -155,8 +155,9 @@ end --- a newer one. --- @param show fun(is_inline: boolean) local function show_when_still_selected(explorer, file_path, show) + local generation = explorer._selection_generation vim.schedule(function() - if explorer.current_file_path ~= file_path then + if explorer.current_file_path ~= file_path or explorer._selection_generation ~= generation then return end local session = lifecycle.get_session(explorer.tabpage) @@ -271,6 +272,7 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target dir2 = opts.dir2, base_revision = base_revision, target_revision = target_revision, + source_revisions = opts.source_revisions, pathspec = opts.pathspec, -- Scope (#74): re-applied on every auto-refresh status_result = status_result, -- Store initial status result on_file_select = nil, -- Will be set below @@ -284,6 +286,7 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target -- File selection callback - manages its own lifecycle local function on_file_select(file_data, opts) opts = opts or {} + local base_revision, target_revision = explorer.base_revision, explorer.target_revision local git = require("codediff.core.git") local view = require("codediff.ui.view") local lifecycle = require("codediff.ui.lifecycle") @@ -316,6 +319,7 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target and session.original.absolute == original.absolute and session.modified.absolute == modified.absolute if showing_already and not opts.force then + require("codediff.ui.refresh").ready(tabpage) return end @@ -325,6 +329,7 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target git_root = nil, file_path = file_path, jump = jump, + selection = explorer._selection_generation, }, { original = original, modified = modified }) return end @@ -405,14 +410,16 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target -- Same file can have different diffs (staged vs HEAD, working vs staged) local session = lifecycle.get_session(tabpage) if session and not opts.force and already_showing(session, explorer, file_path, abs_path, group) then + require("codediff.ui.refresh").ready(tabpage) return end if base_revision and target_revision and target_revision ~= "WORKING" then -- Two revision mode: Compare base vs target + local selection = explorer._selection_generation vim.schedule(function() -- Ignore stale async: see comment on the base_revision branch below. - if explorer.current_file_path ~= file_path then + if explorer.current_file_path ~= file_path or explorer._selection_generation ~= selection then return end ---@type SessionConfig @@ -435,6 +442,7 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target git_root = git_root, file_path = file_path, jump = jump, + selection = explorer._selection_generation, } local target_revision_single = base_revision or "HEAD" @@ -493,6 +501,8 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target -- Wrap on_file_select to track current file and group explorer.on_file_select = function(file_data, opts) + explorer._selection_generation = (explorer._selection_generation or 0) + 1 + require("codediff.ui.refresh").begin(tabpage) explorer.current_file_path = file_data.path explorer.current_file_group = file_data.group explorer.current_selection = vim.deepcopy(file_data) diff --git a/lua/codediff/ui/follow_working_file.lua b/lua/codediff/ui/follow_working_file.lua index f827a583..15de2f4e 100644 --- a/lua/codediff/ui/follow_working_file.lua +++ b/lua/codediff/ui/follow_working_file.lua @@ -1,131 +1,96 @@ --- Keep a diff pointed at whatever file the working window holds. --- --- Sibling to auto_refresh, which watches buffer *content*. This watches the --- working window's *file*: with one side pinned to a git revision and the other --- showing the working file, opening a different file in that window rebuilds --- the diff around it, rather than leaving a stale pair on screen. --- --- Applies to a session with no side panel (`panel == nil`) where exactly one --- side is a git revision. Explorer and history drive their own file switching --- through view.update, and a diff of two real files has nothing to follow. --- --- Registered per tabpage; the augroup is torn down in lifecycle/cleanup. +-- Follow file navigation in a bare revision/worktree comparison. Content +-- invalidations belong to ui.refresh; this changes the comparison itself. local M = {} --- Lazy require to avoid a cycle: session -> accessors -> ... -> this module -local function get_active_diffs() - return require("codediff.ui.lifecycle.session").get_active_diffs() -end - ---- Watch the working window and re-target the diff when its file changes. ---- No-op unless exactly one side is a git revision. ---- @param tabpage number ---- @param original_is_virtual boolean Original side is a git revision ---- @param modified_is_virtual boolean Modified side is a git revision function M.enable(tabpage, original_is_virtual, modified_is_virtual) - -- Nothing to follow when both sides are revisions, or both are real files. if original_is_virtual == modified_is_virtual then return end - - local active_diffs = get_active_diffs() - local sess = active_diffs[tabpage] - if not sess then - vim.notify("[codediff] No session found for working-file follow", vim.log.levels.ERROR) + local lifecycle = require("codediff.ui.lifecycle") + local session = lifecycle.get_session(tabpage) + if not session or session.panel then return end - -- Determine which window is working - local working_win = original_is_virtual and sess.modified_win or sess.original_win local working_side = original_is_virtual and "modified" or "original" - - if not working_win or not vim.api.nvim_win_is_valid(working_win) then - vim.notify("[codediff] Working window not found for working-file follow", vim.log.levels.WARN) - return - end - - -- Session stores paths as PathRefs, so read .absolute for identity comparison. - -- (The old sess[working_side .. "_path"] field is gone and left this nil, which - -- defeated the change guard below and caused spurious re-updates.) - local working_ref = sess[working_side] - local current_path = working_ref and working_ref.absolute or nil - - -- Setup listener using BufWinEnter (fires when buffer enters window, even if existing buffer) - local sync_group = vim.api.nvim_create_augroup("codediff_working_sync_" .. tabpage, { clear = true }) - - -- Listen to BufWinEnter - fires when ANY buffer enters the window (including existing buffers) + local virtual_side = original_is_virtual and "original" or "modified" + local pending_path + local group = vim.api.nvim_create_augroup("codediff_working_sync_" .. tabpage, { clear = true }) vim.api.nvim_create_autocmd("BufWinEnter", { - group = sync_group, - callback = function(args) - -- Check if this buffer is in the working window - local buf_win = vim.fn.bufwinid(args.buf) - if buf_win ~= working_win then + group = group, + callback = function(event) + if lifecycle.get_session(tabpage) ~= session or session.refresh and session.refresh.applying then return end - - local path = require("codediff.core.path") - local new_path = vim.api.nvim_buf_get_name(args.buf) - - -- Skip virtual files - they're programmatic, not user navigation - if new_path:match("^codediff://") then + local win = session[working_side .. "_win"] + if not win or not vim.api.nvim_win_is_valid(win) or vim.api.nvim_win_get_buf(win) ~= event.buf then return end - - -- Normalize to the same absolute form used for the session PathRefs so the - -- identity comparison is reliable across platforms. - new_path = new_path ~= "" and path.make_ref(new_path, nil).absolute or "" - - -- Check if file changed - if new_path == "" or new_path == current_path then + if vim.bo[event.buf].buftype ~= "" then return end + local path = require("codediff.core.path") + local name = vim.api.nvim_buf_get_name(event.buf) + local new_path = name ~= "" and path.make_ref(name, nil).absolute or "" + if new_path == "" or new_path == pending_path or new_path == session[working_side].absolute then + return + end + pending_path = new_path + + local refresh = require("codediff.ui.refresh") + local generation = refresh.begin(tabpage) + local requested = vim.deepcopy(session.source_revisions or {}) + requested[virtual_side] = requested[virtual_side] or session[virtual_side .. "_revision"] + requested[working_side] = "WORKING" + local revision = requested[virtual_side] + local function current() + return refresh.is_current(tabpage, session, generation) and pending_path == new_path + end + local function update(root, resolved) + vim.schedule(function() + if not current() then + return + end + local target = path.make_ref(new_path, root) + local options = { + git_root = root, + original = root and target or path.empty(), + modified = root and target or path.empty(), + source_revisions = requested, + } + options[working_side] = target + options[virtual_side .. "_revision"] = resolved + require("codediff.ui.view").update(tabpage, options) + end) + end - -- Update tracked path - current_path = new_path - - -- Path changed! Need to update both sides - vim.schedule(function() - -- Get git root (might have changed if user switched to different repo) - local git = require("codediff.core.git") - local view = require("codediff.ui.view") - - git.get_git_root(new_path, function(err, new_git_root) + local git = require("codediff.core.git") + git.get_git_root(new_path, function(err, root) + vim.schedule(function() + if not current() then + return + end if err then - -- Not in git, just update paths without git context - vim.schedule(function() - -- Get relative path if possible - local relative_path = new_path - if sess.git_root then - relative_path = git.get_relative_path(new_path, sess.git_root) - end - - -- No pre-fetching needed, buffers will load content - view.update(tabpage, { - panel = sess.panel, - git_root = nil, - original = path.make_ref(working_side == "original" and new_path or relative_path, nil), - modified = path.make_ref(working_side == "modified" and new_path or relative_path, nil), - original_revision = working_side == "original" and nil or sess.original_revision, - modified_revision = working_side == "modified" and nil or sess.modified_revision, - }) + update(nil, nil) + elseif revision:match("^:[0-3]:?$") then + update(root, revision) + else + -- A requested HEAD/branch is resolved in the destination repository, + -- not replaced by the SHA from the file we just left. + git.resolve_revision(revision, root, function(resolve_error, hash) + vim.schedule(function() + if not current() then + return + end + if resolve_error then + vim.notify(resolve_error, vim.log.levels.WARN) + refresh.ready(tabpage) + else + update(root, hash) + end + end) end) - return end - - -- In git! Get relative path - local relative_path = git.get_relative_path(new_path, new_git_root) - - -- No pre-fetching needed, buffers will load content - vim.schedule(function() - view.update(tabpage, { - panel = sess.panel, - git_root = new_git_root, - original = path.make_ref(relative_path, new_git_root), - modified = path.make_ref(relative_path, new_git_root), - original_revision = sess.original_revision, - modified_revision = sess.modified_revision, - }) - end) end) end) end, diff --git a/lua/codediff/ui/history/refresh.lua b/lua/codediff/ui/history/refresh.lua index d8e350eb..9df10bd5 100644 --- a/lua/codediff/ui/history/refresh.lua +++ b/lua/codediff/ui/history/refresh.lua @@ -1,212 +1,87 @@ --- Auto-refresh and refresh logic for history panel +-- History list updates share the session controller with the selected diff. local M = {} - local git = require("codediff.core.git") -local render_module = require("codediff.ui.history.render") +local render = require("codediff.ui.history.render") --- Setup auto-refresh triggers for history panel --- Returns a cleanup function that should be called when the history is destroyed function M.setup_auto_refresh(history, tabpage) - local refresh_timer = nil - local debounce_ms = 500 - local git_watcher = nil - local group = vim.api.nvim_create_augroup("CodeDiffHistoryRefresh_" .. tabpage, { clear = true }) - - local function cleanup() - if refresh_timer then - vim.fn.timer_stop(refresh_timer) - refresh_timer = nil - end - if git_watcher then - pcall(function() - git_watcher:stop() - end) - pcall(function() - git_watcher:close() - end) - git_watcher = nil - end - pcall(vim.api.nvim_del_augroup_by_id, group) - end - - -- Store cleanup function so lifecycle cleanup can call it - history._cleanup_auto_refresh = cleanup - - local function debounced_refresh() - if refresh_timer then - vim.fn.timer_stop(refresh_timer) - end - refresh_timer = vim.fn.timer_start(debounce_ms, function() - if vim.api.nvim_tabpage_is_valid(tabpage) and not history.is_hidden then - M.refresh(history) - end - refresh_timer = nil - end) - end - - -- Watch .git directory for changes - if history.git_root then - git.get_git_dir(history.git_root, function(err, git_dir) - if err or not git_dir then - return - end - - vim.schedule(function() - if vim.fn.isdirectory(git_dir) ~= 1 then - return - end - - if not vim.api.nvim_tabpage_is_valid(tabpage) then - return - end - - local uv = vim.uv or vim.loop - git_watcher = uv.new_fs_event() - if git_watcher then - local ok = pcall(function() - git_watcher:start( - git_dir, - {}, - vim.schedule_wrap(function(watch_err, filename, events) - if watch_err then - -- A dead watch (typically the repository being deleted or - -- replaced) keeps re-delivering the same error on Windows, so - -- tear the handle down instead of spinning on it. - if git_watcher then - pcall(function() - git_watcher:stop() - end) - pcall(function() - git_watcher:close() - end) - git_watcher = nil - end - return - end - if vim.api.nvim_get_current_tabpage() == tabpage and vim.api.nvim_tabpage_is_valid(tabpage) and not history.is_hidden then - debounced_refresh() - end - end) - ) - end) - if not ok then - pcall(function() - git_watcher:close() - end) - git_watcher = nil - end - end - end) - end) - end - - -- Clean up on tab close - vim.api.nvim_create_autocmd("TabClosed", { - group = group, - pattern = tostring(tabpage), - callback = cleanup, - }) - - return cleanup + local refresh = require("codediff.ui.refresh") + history.tabpage = tabpage + local unbind = refresh.bind_panel(tabpage, history, function(done) + M._refresh_once(history, done) + end) + history._cleanup_auto_refresh = unbind + return unbind end --- Refresh history panel with updated commit list -function M.refresh(history) - if history.is_hidden then - return +function M._refresh_once(history, done) + done = done or function() end + local lifecycle = require("codediff.ui.lifecycle") + local function valid() + return lifecycle.get_panel_view(history.tabpage) == history and vim.api.nvim_buf_is_valid(history.bufnr) end - - if not vim.api.nvim_win_is_valid(history.winid) then + if not valid() then + done() return end - - -- Save current cursor position - local cursor_line = nil - local ok, pos = pcall(vim.api.nvim_win_get_cursor, history.winid) - if ok then - cursor_line = pos[1] - end - - -- Save which commits were expanded - local expanded_hashes = {} + local expanded = {} for _, node in ipairs(history.tree:get_nodes() or {}) do if node.data and node.data.type == "commit" and node:is_expanded() then - expanded_hashes[node.data.hash] = true + expanded[node.data.hash] = true end end - - -- Reconstruct git log options - local git_opts = { - no_merges = true, - path = history.opts.file_path, - } - if not history.opts.range or history.opts.range == "" then - git_opts.limit = 100 - end - + local opts = { no_merges = true, path = history.opts.file_path } local range = history.opts.range or "" - - git.get_commit_list(range, history.git_root, git_opts, function(err, commits) - if err then - vim.schedule(function() - vim.notify("Failed to refresh history: " .. err, vim.log.levels.ERROR) - end) - return - end - + if range == "" then + opts.limit = 100 + end + git.get_commit_list(range, history.git_root, opts, function(err, commits) vim.schedule(function() - if not vim.api.nvim_buf_is_valid(history.bufnr) then + if not valid() then + done() return end - - -- Update stored commits - history.commits = commits - - -- Rebuild tree nodes - local tree_nodes = render_module.build_tree_nodes(commits, history.git_root, history.opts) - - -- Set new nodes - history.tree:set_nodes(tree_nodes) - - -- Re-expand previously expanded commits and reload their files - local has_pending_expand = false - if history._load_commit_files then - for _, node in ipairs(history.tree:get_nodes() or {}) do - if node.data and node.data.type == "commit" and expanded_hashes[node.data.hash] then - has_pending_expand = true - history._load_commit_files(node) - end - end + if err then + done(err) + return end - - -- Skip render if expanded commits are being reloaded async - -- (_load_commit_files triggers its own render when files arrive) - if not has_pending_expand then - history.tree:render() + if vim.deep_equal(commits, history.commits) then + done() + return end - - -- Restore cursor position - if vim.api.nvim_win_is_valid(history.winid) then - local restored = false - -- Try to restore to same commit - if history.current_commit then - for _, node in ipairs(history.tree:get_nodes() or {}) do - if node.data and node.data.hash == history.current_commit and node._line then - pcall(vim.api.nvim_win_set_cursor, history.winid, { node._line, 0 }) - restored = true - break + history.commits = commits + history.tree:set_nodes(render.build_tree_nodes(commits, history.git_root, history.opts)) + local remaining = 1 + local function loaded() + remaining = remaining - 1 + if remaining ~= 0 then + return + end + if valid() and not history.is_hidden then + history.tree:render() + if history.winid and vim.api.nvim_win_is_valid(history.winid) then + for _, node in ipairs(history.tree:get_nodes()) do + if node.data and node.data.hash == history.current_commit and node._line then + vim.api.nvim_win_set_cursor(history.winid, { node._line, 0 }) + break + end end end end - -- Fall back to same line number - if not restored and cursor_line then - local line_count = vim.api.nvim_buf_line_count(history.bufnr) - local target_line = math.min(cursor_line, line_count) - pcall(vim.api.nvim_win_set_cursor, history.winid, { target_line, 0 }) + done() + end + for _, node in ipairs(history.tree:get_nodes()) do + if node.data and node.data.type == "commit" and expanded[node.data.hash] and history._load_commit_files then + remaining = remaining + 1 + history._load_commit_files(node, loaded) end end + loaded() end) end) end +function M.refresh(history) + require("codediff.ui.refresh").request(history.tabpage, { full = true }) +end + return M diff --git a/lua/codediff/ui/history/render.lua b/lua/codediff/ui/history/render.lua index 59ff53af..0c8d6ef3 100644 --- a/lua/codediff/ui/history/render.lua +++ b/lua/codediff/ui/history/render.lua @@ -244,14 +244,20 @@ function M.create(commits, git_root, tabpage, width, opts) end git.get_commit_files(data.hash, git_root, function(err, files) - if err then - vim.schedule(function() - vim.notify("Failed to load commit files: " .. err, vim.log.levels.ERROR) - end) - return - end - vim.schedule(function() + if not vim.api.nvim_buf_is_valid(history.bufnr) or tree:get_node(commit_node:get_id()) ~= commit_node then + if callback then + callback() + end + return + end + if err then + vim.notify("Failed to load commit files: " .. err, vim.log.levels.ERROR) + if callback then + callback() + end + return + end -- Apply file_filter.ignore patterns (same as explorer view) local filter = require("codediff.ui.explorer.filter") local explorer_config = config.options.explorer or {} @@ -304,14 +310,18 @@ function M.create(commits, git_root, tabpage, width, opts) local file_path = file_data.path local old_path = file_data.old_path local commit_hash = file_data.commit_hash + local selection = history._selection_generation + local refresh = require("codediff.ui.refresh") if not file_path or file_path == "" then vim.notify("[CodeDiff] No file path for selection", vim.log.levels.WARN) + refresh.ready(tabpage) return end if not commit_hash or commit_hash == "" then vim.notify("[CodeDiff] No commit hash for selection", vim.log.levels.WARN) + refresh.ready(tabpage) return end @@ -320,11 +330,15 @@ function M.create(commits, git_root, tabpage, width, opts) local session = lifecycle.get_session(tabpage) if not opts.force and session and session.original_revision == target_hash and session.modified_revision == commit_hash then if (session.modified and session.modified.relative == file_path) or (session.original and session.original.relative == file_path) then + refresh.ready(tabpage) return end end vim.schedule(function() + if lifecycle.get_panel_view(tabpage) ~= history or history._selection_generation ~= selection then + return + end -- Handle added/deleted files: show single file instead of empty diff local file_status = file_data.status if file_status == "A" or file_status == "D" then @@ -364,6 +378,8 @@ function M.create(commits, git_root, tabpage, width, opts) end history.on_file_select = function(file_data, opts) + history._selection_generation = (history._selection_generation or 0) + 1 + require("codediff.ui.refresh").begin(tabpage) history.current_commit = file_data.commit_hash history.current_file = file_data.path history.current_selection = vim.deepcopy(file_data) diff --git a/lua/codediff/ui/lifecycle/accessors.lua b/lua/codediff/ui/lifecycle/accessors.lua index aad75a6a..b0a0ea21 100644 --- a/lua/codediff/ui/lifecycle/accessors.lua +++ b/lua/codediff/ui/lifecycle/accessors.lua @@ -262,6 +262,9 @@ function M.update_diff_result(tabpage, diff_lines) end sess.stored_diff_result = diff_lines + if diff_lines then + require("codediff.ui.refresh").ready(tabpage) + end return true end @@ -427,7 +430,6 @@ function M.set_result(tabpage, result_bufnr, result_win) sess.keymaps:release_scope("conflict") end require("codediff.ui.conflict").teardown_gutter(tabpage) - require("codediff.ui.auto_refresh").disable_result(sess.result_bufnr) sess.conflict_blocks = nil sess.result_base_lines = nil sess.merge_base_lines = nil diff --git a/lua/codediff/ui/lifecycle/cleanup.lua b/lua/codediff/ui/lifecycle/cleanup.lua index 9984efe8..a2328471 100644 --- a/lua/codediff/ui/lifecycle/cleanup.lua +++ b/lua/codediff/ui/lifecycle/cleanup.lua @@ -34,13 +34,7 @@ local function cleanup_diff(tabpage) }, }) - -- Disable auto-refresh for both buffers - local auto_refresh = require("codediff.ui.auto_refresh") - auto_refresh.disable(diff.original_bufnr) - auto_refresh.disable(diff.modified_bufnr) - if diff.result_bufnr then - auto_refresh.disable_result(diff.result_bufnr) - end + require("codediff.ui.refresh").dispose(tabpage) -- Restore gutter options before deleting buffers can close or reuse windows. require("codediff.ui.conflict").teardown_gutter(tabpage) diff --git a/lua/codediff/ui/lifecycle/session.lua b/lua/codediff/ui/lifecycle/session.lua index ca14af9c..4dd9d9a5 100644 --- a/lua/codediff/ui/lifecycle/session.lua +++ b/lua/codediff/ui/lifecycle/session.lua @@ -72,6 +72,9 @@ M.compute_virtual_uri = compute_virtual_uri --- @param session_config SessionConfig What was asked for --- @param panes SessionPanes What the layout built for it function M.create_session(tabpage, session_config, panes) + if active_diffs[tabpage] and active_diffs[tabpage].refresh then + active_diffs[tabpage].refresh:dispose() + end local state = require("codediff.ui.lifecycle.state") local original_bufnr, modified_bufnr = panes.original_bufnr, panes.modified_bufnr -- Save buffer states @@ -91,6 +94,7 @@ function M.create_session(tabpage, session_config, panes) modified = session_config.modified, original_revision = session_config.original_revision, modified_revision = session_config.modified_revision, + source_revisions = session_config.source_revisions, -- Buffers & Windows original_bufnr = original_bufnr, @@ -127,6 +131,12 @@ function M.create_session(tabpage, session_config, panes) } welcome_window.capture_session_profiles(active_diffs[tabpage]) + local created = active_diffs[tabpage] + vim.schedule(function() + if active_diffs[tabpage] == created then + require("codediff.ui.refresh").attach(tabpage) + end + end) -- Mark windows with restore flag vim.w[panes.original_win].codediff_restore = 1 diff --git a/lua/codediff/ui/lifecycle/state.lua b/lua/codediff/ui/lifecycle/state.lua index ec929e79..6dff48f2 100644 --- a/lua/codediff/ui/lifecycle/state.lua +++ b/lua/codediff/ui/lifecycle/state.lua @@ -1,299 +1,85 @@ --- State management for diff views --- Handles save/restore, suspend/resume, and buffer state +-- State management for diff views. local M = {} - local highlights = require("codediff.ui.highlights") --- Save buffer state before modifications -local function save_buffer_state(bufnr) +function M.save_buffer_state(bufnr) if not vim.api.nvim_buf_is_valid(bufnr) then return nil end - local state = {} - - -- Save inlay hint state (Neovim 0.10+) if vim.lsp.inlay_hint then state.inlay_hints_enabled = vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }) end - return state end -M.save_buffer_state = save_buffer_state - --- Restore buffer state after cleanup -local function restore_buffer_state(bufnr, state) +function M.restore_buffer_state(bufnr, state) if not vim.api.nvim_buf_is_valid(bufnr) or not state then return end - - -- Restore inlay hint state if vim.lsp.inlay_hint and state.inlay_hints_enabled ~= nil then vim.lsp.inlay_hint.enable(state.inlay_hints_enabled, { bufnr = bufnr }) end end -M.restore_buffer_state = restore_buffer_state - --- Clear highlights and extmarks from a buffer --- @param bufnr number: Buffer number to clean -local function clear_buffer_highlights(bufnr) +function M.clear_buffer_highlights(bufnr) if not vim.api.nvim_buf_is_valid(bufnr) then return end - - -- Clear highlight, filler, conflict sign, and inline namespaces vim.api.nvim_buf_clear_namespace(bufnr, highlights.ns_highlight, 0, -1) vim.api.nvim_buf_clear_namespace(bufnr, highlights.ns_filler, 0, -1) vim.api.nvim_buf_clear_namespace(bufnr, highlights.ns_conflict, 0, -1) - local ns_inline = vim.api.nvim_create_namespace("codediff-inline") - vim.api.nvim_buf_clear_namespace(bufnr, ns_inline, 0, -1) + vim.api.nvim_buf_clear_namespace(bufnr, vim.api.nvim_create_namespace("codediff-inline"), 0, -1) require("codediff.ui.gutter_signs").clear_buffer(bufnr) end -M.clear_buffer_highlights = clear_buffer_highlights - --- Get file modification time (mtime) -local function get_file_mtime(bufnr) +function M.get_file_mtime(bufnr) if not vim.api.nvim_buf_is_valid(bufnr) then return nil end - - local bufname = vim.api.nvim_buf_get_name(bufnr) - - -- Virtual buffers don't have mtime - if bufname:match("^codediff://") or bufname == "" then + local name = vim.api.nvim_buf_get_name(bufnr) + if name == "" or name:match("^codediff://") then return nil end - - -- Get file stat - local stat = vim.loop.fs_stat(bufname) + local stat = (vim.uv or vim.loop).fs_stat(name) return stat and stat.mtime.sec or nil end -M.get_file_mtime = get_file_mtime - --- Check if a revision represents a virtual buffer -local function is_virtual_revision(revision) - return revision ~= nil and revision ~= "WORKING" -end - --- Suspend diff view (when leaving tab) --- @param tabpage number: Tab page ID -local function suspend_diff(tabpage) - local session = require("codediff.ui.lifecycle.session") - local active_diffs = session.get_active_diffs() - local diff = active_diffs[tabpage] - if not diff or diff.suspended then +function M.suspend_diff(tabpage) + local session = require("codediff.ui.lifecycle").get_session(tabpage) + if not session or session.suspended then return end - - -- Disable auto-refresh (stop watching buffer changes) - local auto_refresh = require("codediff.ui.auto_refresh") - auto_refresh.disable(diff.original_bufnr) - auto_refresh.disable(diff.modified_bufnr) - if diff.result_bufnr then - auto_refresh.disable_result(diff.result_bufnr) - end - - -- Clear highlights from both buffers - clear_buffer_highlights(diff.original_bufnr) - clear_buffer_highlights(diff.modified_bufnr) - if diff.result_bufnr then - clear_buffer_highlights(diff.result_bufnr) + session.suspended = true + M.clear_buffer_highlights(session.original_bufnr) + M.clear_buffer_highlights(session.modified_bufnr) + if session.result_bufnr then + M.clear_buffer_highlights(session.result_bufnr) end - - -- Mark as suspended - diff.suspended = true + -- Keep collecting invalidations while hidden; apply them when the tab returns. + require("codediff.ui.refresh").request(tabpage, { render = true }) end -M.suspend_diff = suspend_diff - --- Resume diff view (when entering tab) --- @param tabpage number: Tab page ID -local function resume_diff(tabpage) - local session = require("codediff.ui.lifecycle.session") - local active_diffs = session.get_active_diffs() - local diff = active_diffs[tabpage] - if not diff or not diff.suspended then +function M.resume_diff(tabpage) + local sessions = require("codediff.ui.lifecycle.session").get_active_diffs() + local session = sessions[tabpage] + if not session or not session.suspended then return end - - -- Check if buffers still exist. Dropping the session here would otherwise - -- orphan its registry, leaving codediff's mappings installed on whichever - -- pane survived and its saved user mappings unreachable. - if not vim.api.nvim_buf_is_valid(diff.original_bufnr) or not vim.api.nvim_buf_is_valid(diff.modified_bufnr) then + if not vim.api.nvim_buf_is_valid(session.original_bufnr) or not vim.api.nvim_buf_is_valid(session.modified_bufnr) then + require("codediff.ui.refresh").dispose(tabpage) require("codediff.ui.conflict").teardown_gutter(tabpage) - if diff.keymaps then - diff.keymaps:dispose() - diff.keymaps = nil + if session.keymaps then + session.keymaps:dispose() + session.keymaps = nil end - active_diffs[tabpage] = nil - return - end - - if diff.single_side then - local core = require("codediff.ui.core") - local bufnr = diff[diff.single_side .. "_bufnr"] - core.render_whole_file(bufnr, diff.single_side) - diff.suspended = false + sessions[tabpage] = nil return end - - -- Check if buffer or file changed while suspended - local original_tick_changed = vim.api.nvim_buf_get_changedtick(diff.original_bufnr) ~= diff.changedtick.original - local modified_tick_changed = vim.api.nvim_buf_get_changedtick(diff.modified_bufnr) ~= diff.changedtick.modified - - local original_mtime_changed = false - local modified_mtime_changed = false - - if diff.mtime.original then - local current_mtime = get_file_mtime(diff.original_bufnr) - original_mtime_changed = current_mtime ~= diff.mtime.original - end - - if diff.mtime.modified then - local current_mtime = get_file_mtime(diff.modified_bufnr) - modified_mtime_changed = current_mtime ~= diff.mtime.modified - end - - local need_recompute = original_tick_changed or modified_tick_changed or original_mtime_changed or modified_mtime_changed - - -- Always get fresh buffer content for rendering - local original_lines = vim.api.nvim_buf_get_lines(diff.original_bufnr, 0, -1, false) - local modified_lines = vim.api.nvim_buf_get_lines(diff.modified_bufnr, 0, -1, false) - - local lines_diff - local diff_was_recomputed = false - - if need_recompute or not diff.stored_diff_result then - -- Buffer or file changed, recompute diff - local diff_module = require("codediff.core.diff") - local config = require("codediff.config") - lines_diff = diff_module.compute_diff(original_lines, modified_lines, { - max_computation_time_ms = config.options.diff.max_computation_time_ms, - ignore_trim_whitespace = config.options.diff.ignore_trim_whitespace, - compute_moves = config.options.diff.compute_moves, - }) - diff_was_recomputed = true - - if lines_diff then - -- Store new diff result - diff.stored_diff_result = lines_diff - - -- Update changedtick and mtime - diff.changedtick.original = vim.api.nvim_buf_get_changedtick(diff.original_bufnr) - diff.changedtick.modified = vim.api.nvim_buf_get_changedtick(diff.modified_bufnr) - diff.mtime.original = get_file_mtime(diff.original_bufnr) - diff.mtime.modified = get_file_mtime(diff.modified_bufnr) - end - else - -- Nothing changed, reuse stored diff result - lines_diff = diff.stored_diff_result - end - - -- Render with fresh content and (possibly reused) diff result - if lines_diff then - if diff.result_bufnr and diff.merge_base_lines and diff.conflict_blocks then - -- Conflict inputs are two diffs against BASE, not a diff against each - -- other. Restore that same geometry without resetting Result or its - -- tracking extmarks, so accepted edits and gutter colors survive tabs. - local diff_module = require("codediff.core.diff") - local options = require("codediff.config").options.diff - local diff_options = { - max_computation_time_ms = options.max_computation_time_ms, - ignore_trim_whitespace = options.ignore_trim_whitespace, - compute_moves = options.compute_moves, - } - local original_diff = diff_module.compute_diff(diff.merge_base_lines, original_lines, diff_options) - local modified_diff = diff_module.compute_diff(diff.merge_base_lines, modified_lines, diff_options) - if original_diff and modified_diff then - require("codediff.ui.core").render_merge_view(diff.original_bufnr, diff.modified_bufnr, original_diff, modified_diff, diff.merge_base_lines, original_lines, modified_lines) - diff.stored_diff_result = modified_diff - local conflict = require("codediff.ui.conflict") - conflict.attach_gutter(diff.original_win, diff.modified_win) - conflict.refresh(diff) - end - elseif diff.layout == "inline" then - local inline_mod = require("codediff.ui.inline") - inline_mod.render_inline_diff(diff.modified_bufnr, lines_diff, original_lines, modified_lines) - else - local core = require("codediff.ui.core") - core.render_diff(diff.original_bufnr, diff.modified_bufnr, original_lines, modified_lines, lines_diff) - end - - -- Re-sync scrollbind ONLY if diff was recomputed and not inline mode. - if - diff_was_recomputed - and diff.layout ~= "inline" - and diff.original_win - and diff.modified_win - and vim.api.nvim_win_is_valid(diff.original_win) - and vim.api.nvim_win_is_valid(diff.modified_win) - then - local current_win = vim.api.nvim_get_current_win() - local result_win = diff.result_win and vim.api.nvim_win_is_valid(diff.result_win) and diff.result_win or nil - - if current_win == diff.original_win or current_win == diff.modified_win or current_win == result_win then - local saved_cursor = vim.api.nvim_win_get_cursor(current_win) - - vim.api.nvim_win_set_cursor(diff.original_win, { 1, 0 }) - vim.api.nvim_win_set_cursor(diff.modified_win, { 1, 0 }) - if result_win then - vim.api.nvim_win_set_cursor(result_win, { 1, 0 }) - end - - vim.wo[diff.original_win].scrollbind = false - vim.wo[diff.modified_win].scrollbind = false - if result_win then - vim.wo[result_win].scrollbind = false - end - vim.wo[diff.original_win].scrollbind = true - vim.wo[diff.modified_win].scrollbind = true - if result_win then - vim.wo[result_win].scrollbind = true - end - - vim.wo[diff.original_win].wrap = false - vim.wo[diff.modified_win].wrap = false - if result_win then - vim.wo[result_win].wrap = false - end - - pcall(vim.api.nvim_win_set_cursor, diff.original_win, saved_cursor) - pcall(vim.api.nvim_win_set_cursor, diff.modified_win, saved_cursor) - if result_win then - pcall(vim.api.nvim_win_set_cursor, result_win, saved_cursor) - end - end - end - end - - -- Re-enable auto-refresh for real buffers only - local auto_refresh = require("codediff.ui.auto_refresh") - - -- Check if buffers are real files (not virtual) using revision - local original_is_real = not is_virtual_revision(diff.original_revision) - local modified_is_real = not is_virtual_revision(diff.modified_revision) - - if original_is_real then - auto_refresh.enable(diff.original_bufnr) - end - - if modified_is_real then - auto_refresh.enable(diff.modified_bufnr) - end - - -- Re-enable auto-refresh for result buffer if in conflict mode - if diff.result_bufnr and vim.api.nvim_buf_is_valid(diff.result_bufnr) and diff.result_base_lines then - auto_refresh.enable_for_result(diff.result_bufnr) - end - - -- Mark as active - diff.suspended = false + session.suspended = false + local refresh = require("codediff.ui.refresh") + refresh.replay(tabpage) + refresh.request(tabpage, { full = true }) end -M.resume_diff = resume_diff - return M diff --git a/lua/codediff/ui/refresh/init.lua b/lua/codediff/ui/refresh/init.lua new file mode 100644 index 00000000..ff4cc99e --- /dev/null +++ b/lua/codediff/ui/refresh/init.lua @@ -0,0 +1,409 @@ +-- One refresh controller per session: collect invalidations, inspect data, apply changes. +local M = {} +local policy = require("codediff.ui.refresh.policy") +local snapshot = require("codediff.ui.refresh.snapshot") +local apply = require("codediff.ui.refresh.apply") +local uv = vim.uv or vim.loop +local Controller = {} +Controller.__index = Controller + +local function session_for(tabpage) + return require("codediff.ui.lifecycle").get_session(tabpage) +end + +function Controller:valid() + return not self.closed and session_for(self.tabpage) == self.session and vim.api.nvim_tabpage_is_valid(self.tabpage) +end + +function Controller:visible() + if not self:valid() or vim.api.nvim_get_current_tabpage() ~= self.tabpage or self.session.suspended then + return false + end + local root = self.session.git_root + return not root or root == "" or (vim.fn.isdirectory(root) == 1 and (vim.fn.isdirectory(root .. "/.git") == 1 or vim.fn.filereadable(root .. "/.git") == 1)) +end + +function Controller:schedule(delay) + if self.closed or self.running or self.loading or not self:visible() then + return + end + self.timer:stop() + self.timer:start( + delay or 20, + 0, + vim.schedule_wrap(function() + self:run() + end) + ) +end + +function Controller:request(event, done) + if self.closed then + if done then + done() + end + return + end + self.pending = policy.merge(self.pending, policy.normalize(event)) + if done then + self.callbacks[#self.callbacks + 1] = done + end + self:schedule() +end + +function Controller:run() + if not self:visible() or self.loading or self.running then + return + end + if not next(self.pending) and #self.callbacks == 0 then + return + end + local event, callbacks, generation = self.pending, self.callbacks, self.generation + local panel = require("codediff.ui.lifecycle").get_panel_view(self.tabpage) + local function owns_panel() + return require("codediff.ui.lifecycle").get_panel_view(self.tabpage) == panel + end + self.pending, self.callbacks, self.running = {}, {}, true + local finished = false + local function finish(err, cancelled) + if finished then + return + end + finished, self.running = true, false + if not self:valid() then + return + end + if err or cancelled then + self.pending = policy.merge(event, self.pending) + -- A completion may navigate or restore a cursor: never replay it onto + -- a different file or a replacement panel. + if self.generation == generation and owns_panel() then + vim.list_extend(self.callbacks, callbacks) + end + if err then + vim.notify_once("CodeDiff refresh: " .. tostring(err), vim.log.levels.WARN) + end + else + for _, callback in ipairs(callbacks) do + callback() + end + end + if next(self.pending) or #self.callbacks > 0 then + self:schedule(err and 500 or 20) + end + end + local function current() + return not finished and self:visible() and not self.loading and self.generation == generation and owns_panel() + end + local function inspect(panel_error) + if not current() then + finish(nil, true) + return + end + if panel_error then + finish(panel_error) + return + end + if not self.last then + self.last = snapshot.capture(self.session) + end + local read_ok, read_error = pcall(snapshot.read, self.session, event, self.last, function(err, data) + if not current() then + finish(nil, true) + return + end + if err then + finish(err) + return + end + if not snapshot.valid(data) then + self.pending = policy.merge(self.pending, { buffer = true }) + finish(nil, true) + return + end + self.applying = true + local ok, accepted = xpcall(function() + return apply.run(self.session, data, self.last, event.render) + end, debug.traceback) + self.applying = false + if not ok then + finish(accepted) + return + end + if accepted then + self.blocked = nil + data.result = self.session.result_bufnr and snapshot.lines(self.session.result_bufnr) or nil + self.last = data + elseif self.last then + self.last.result = snapshot.lines(self.session.result_bufnr) + end + finish() + end) + if not read_ok then + finish(read_error) + end + end + if self.panel_refresh and policy.panel_needed(self.session.panel, event) then + local ok, err = pcall(self.panel_refresh, inspect) + if not ok then + finish(err) + end + else + inspect() + end +end + +function Controller:start_polling() + if self.polling or self.closed then + return + end + self.polling = true + self.poll:start( + 500, + 500, + vim.schedule_wrap(function() + self:request({ full = true }) + end) + ) +end + +-- A file-follow operation may move the session to another repository. +function Controller:watch() + self.watch_generation = (self.watch_generation or 0) + 1 + local generation = self.watch_generation + if self.unsubscribe then + self.unsubscribe() + self.unsubscribe = nil + end + self.git_root = self.session.git_root + self.native, self.polling = false, false + self.poll:stop() + local panel = self.session.panel and self.session.panel.view + if panel then + panel._native_watcher_ready = false + end + local automatic = not (self.session.panel and self.session.panel.name == "explorer" and require("codediff.config").options.explorer.auto_refresh == false) + if not automatic then + return + end + self:start_polling() + if not self.git_root or self.git_root == "" then + return + end + local function current() + return self:valid() and self.watch_generation == generation + end + self.unsubscribe = require("codediff.core.watcher").subscribe(self.git_root, { + on_ready = function() + if not current() then + return + end + self.native, self.polling = true, false + self.poll:stop() + local view = self.session.panel and self.session.panel.view + if view then + view._native_watcher_ready = true + end + self:request({ full = true }) + end, + on_refresh = function(message) + if current() then + self:request(message) + end + end, + on_error = function() + if not current() then + return + end + self.native = false + local view = self.session.panel and self.session.panel.view + if view then + view._native_watcher_ready = false + end + self:start_polling() + self:request({ full = true }) + end, + }) +end + +function Controller:dispose() + if self.closed then + return + end + self.closed = true + for _, timer in ipairs({ self.timer, self.poll }) do + timer:stop() + timer:close() + end + if self.unsubscribe then + self.unsubscribe() + end + pcall(vim.api.nvim_del_augroup_by_id, self.group) + self.callbacks, self.pending = {}, {} +end + +function M.attach(tabpage) + local session = session_for(tabpage) + if not session then + return + end + if session.refresh and not session.refresh.closed then + return session.refresh + end + local self = setmetatable({ + tabpage = tabpage, + session = session, + generation = 0, + pending = {}, + callbacks = {}, + timer = assert(uv.new_timer()), + poll = assert(uv.new_timer()), + }, Controller) + session.refresh = self + self.group = vim.api.nvim_create_augroup("CodeDiffRefresh_" .. tabpage, { clear = true }) + vim.api.nvim_create_autocmd({ "TextChanged", "TextChangedI", "TextChangedP", "FileChangedShellPost" }, { + group = self.group, + callback = function(event) + if not self:valid() or self.applying then + return + end + local name = vim.api.nvim_buf_get_name(event.buf) + local belongs = event.buf == session.original_bufnr or event.buf == session.modified_bufnr or event.buf == session.result_bufnr + if not belongs then + for _, input in pairs(snapshot.describe(session)) do + if input.path and input.path.absolute ~= "" and input.path.absolute == name then + belongs = true + end + end + end + if belongs then + self:request({ buffer = true }) + end + end, + }) + vim.api.nvim_create_autocmd("BufWipeout", { + group = self.group, + callback = function(event) + if event.buf ~= session.original_bufnr and event.buf ~= session.modified_bufnr then + return + end + vim.schedule(function() + if not self:valid() or self.loading or self.applying then + return + end + if not vim.api.nvim_buf_is_valid(session.original_bufnr) or not vim.api.nvim_buf_is_valid(session.modified_bufnr) then + require("codediff.ui.lifecycle").cleanup(tabpage) + end + end) + end, + }) + vim.api.nvim_create_autocmd({ "TabEnter", "FocusGained" }, { + group = self.group, + callback = function() + if vim.api.nvim_get_current_tabpage() == tabpage then + self:request({ full = true }) + end + end, + }) + self:watch() + M.ready(tabpage) + return self +end + +-- Opening/retargeting owns the view until its complete input set is installed. +function M.begin(tabpage, request) + local self = M.attach(tabpage) + if not self then + return + end + self.generation = self.generation + 1 + self.loading = true + if request then + self.session.source_revisions = request.source_revisions + end + return self.generation +end + +function M.is_current(tabpage, session, generation) + return session_for(tabpage) == session and vim.api.nvim_tabpage_is_valid(tabpage) and (not generation or session.refresh and session.refresh.generation == generation) +end + +function M.ready(tabpage) + local session = session_for(tabpage) + local self = session and session.refresh + if not self or self.closed then + return + end + local generation = self.generation + vim.schedule(function() + if not self:valid() or generation ~= self.generation then + return + end + self.loading = false + if self.git_root ~= session.git_root then + self:watch() + end + self.last = snapshot.capture(session) + self.blocked = nil + if next(self.pending) or #self.callbacks > 0 then + self:schedule() + end + end) +end + +function M.replay(tabpage) + local self = M.attach(tabpage) + if not self or self.loading then + return + end + local data = snapshot.capture(self.session) + self.applying = true + local ok, err = xpcall(function() + apply.run(self.session, data, self.last, true) + end, debug.traceback) + self.applying = false + if not ok then + error(err) + end +end + +function M.request(tabpage, event, done) + local self = M.attach(tabpage) + if self then + self:request(event, done) + elseif done then + done() + end +end + +function M.bind_panel(tabpage, panel, refresh) + local self = M.attach(tabpage) + if not self then + return function() end + end + self.panel_refresh = refresh + panel._native_watcher_ready = self.native == true + return function() + if self.panel_refresh == refresh then + self.panel_refresh = nil + end + end +end + +function M.dispose(tabpage) + local session = session_for(tabpage) + if session and session.refresh then + session.refresh:dispose() + session.refresh = nil + end +end + +function M.buffer_changed(buf) + for tabpage, session in pairs(require("codediff.ui.lifecycle.session").get_active_diffs()) do + if buf == session.original_bufnr or buf == session.modified_bufnr or buf == session.result_bufnr then + M.request(tabpage, { buffer = true }) + end + end +end + +return M diff --git a/lua/codediff/ui/view/init.lua b/lua/codediff/ui/view/init.lua index fad8d727..63e365c0 100644 --- a/lua/codediff/ui/view/init.lua +++ b/lua/codediff/ui/view/init.lua @@ -29,6 +29,7 @@ end ---@field modified Path ---@field original_revision string? ---@field modified_revision string? +---@field source_revisions { original: string?, modified: string? }? Requested refs before resolution; retained for refresh ---@field conflict boolean? For merge conflict mode: render both sides against base ---@field layout "side-by-side"|"inline"? Optional per-invocation layout override ---@field exit_on_close boolean? Exit Neovim when this session closes @@ -58,6 +59,10 @@ end ---@param auto_scroll_to_first_hunk boolean? Whether to auto-scroll to first hunk (default: false) ---@return boolean success Whether update succeeded function M.update(tabpage, session_config, auto_scroll_to_first_hunk) + if not lifecycle.get_session(tabpage) then + return false + end + require("codediff.ui.refresh").begin(tabpage, session_config) if get_layout(session_config, tabpage) == "inline" then return require("codediff.ui.view.inline_view").update(tabpage, session_config, auto_scroll_to_first_hunk) end diff --git a/lua/codediff/ui/view/inline_view/buffers.lua b/lua/codediff/ui/view/inline_view/buffers.lua index a13ed559..1a57d026 100644 --- a/lua/codediff/ui/view/inline_view/buffers.lua +++ b/lua/codediff/ui/view/inline_view/buffers.lua @@ -2,12 +2,10 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") function M.disable_refresh_and_clear_highlights(session) for _, bufnr in pairs({ session.original_bufnr, session.modified_bufnr }) do if vim.api.nvim_buf_is_valid(bufnr) then - auto_refresh.disable(bufnr) lifecycle.clear_highlights(bufnr) end end diff --git a/lua/codediff/ui/view/inline_view/create.lua b/lua/codediff/ui/view/inline_view/create.lua index 07043c81..17882a85 100644 --- a/lua/codediff/ui/view/inline_view/create.lua +++ b/lua/codediff/ui/view/inline_view/create.lua @@ -2,7 +2,6 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") local config = require("codediff.config") local layout = require("codediff.ui.layout") local welcome_window = require("codediff.ui.view.welcome_window") @@ -258,9 +257,6 @@ function M.create(session_config, filetype, on_ready) mark_inline(tabpage) - auto_refresh.enable(original_info.bufnr) - auto_refresh.enable(modified_info.bufnr) - setup_keymaps(tabpage, original_info.bufnr, modified_info.bufnr) -- Keep the diff pointed at the working window's file if it changes. Same diff --git a/lua/codediff/ui/view/inline_view/update.lua b/lua/codediff/ui/view/inline_view/update.lua index a2c0c6da..55eeaf43 100644 --- a/lua/codediff/ui/view/inline_view/update.lua +++ b/lua/codediff/ui/view/inline_view/update.lua @@ -2,7 +2,6 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") local layout = require("codediff.ui.layout") local welcome_window = require("codediff.ui.view.welcome_window") local helpers = require("codediff.ui.view.helpers") @@ -104,9 +103,6 @@ local function commit_update(tabpage, session_config, orig_buf, mod_buf, lines_d lifecycle.update_changedtick(tabpage, vim.api.nvim_buf_get_changedtick(orig_buf), vim.api.nvim_buf_get_changedtick(mod_buf)) lifecycle.update_paths(tabpage, session_config.original, session_config.modified) - auto_refresh.enable(orig_buf) - auto_refresh.enable(mod_buf) - setup_keymaps(tabpage, orig_buf, mod_buf) layout.arrange(tabpage) @@ -127,6 +123,7 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) return false end + local generation = session.refresh and session.refresh.generation local modified_win = session.modified_win if not modified_win or not vim.api.nvim_win_is_valid(modified_win) then return false @@ -152,6 +149,9 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) local should_auto_scroll = auto_scroll_to_first_hunk == true local render = function() + if not require("codediff.ui.refresh").is_current(tabpage, session, generation) then + return + end if not vim.api.nvim_win_is_valid(modified_win) then return end diff --git a/lua/codediff/ui/view/panel.lua b/lua/codediff/ui/view/panel.lua index 306ed6d0..d3cbfe39 100644 --- a/lua/codediff/ui/view/panel.lua +++ b/lua/codediff/ui/view/panel.lua @@ -35,6 +35,7 @@ function M.setup_explorer(tabpage, session_config, original_win, modified_win) end -- Scope (#74): carry the pathspec so auto-refresh re-applies it (see refresh.lua). explorer_opts.pathspec = panel.data.pathspec + explorer_opts.source_revisions = panel.data.source_revisions local explorer_obj = explorer_module.create(status_result, session_config.git_root, tabpage, nil, session_config.original_revision, session_config.modified_revision, explorer_opts) diff --git a/lua/codediff/ui/view/render.lua b/lua/codediff/ui/view/render.lua index 0b2d0d7e..61932cb1 100644 --- a/lua/codediff/ui/view/render.lua +++ b/lua/codediff/ui/view/render.lua @@ -168,11 +168,4 @@ function M.compute_and_render( return lines_diff end --- Common logic: Setup auto-refresh for all diff buffers (real and virtual) -function M.setup_auto_refresh(original_buf, modified_buf, original_is_virtual, modified_is_virtual) - local auto_refresh = require("codediff.ui.auto_refresh") - auto_refresh.enable(original_buf) - auto_refresh.enable(modified_buf) -end - return M diff --git a/lua/codediff/ui/view/side_by_side/create.lua b/lua/codediff/ui/view/side_by_side/create.lua index bb4552ec..4e77c21f 100644 --- a/lua/codediff/ui/view/side_by_side/create.lua +++ b/lua/codediff/ui/view/side_by_side/create.lua @@ -18,7 +18,6 @@ local show_real_file_buffer = helpers.show_real_file_buffer local open_real_file = helpers.open_real_file local compute_and_render = render.compute_and_render local compute_and_render_conflict = conflict_view.compute_and_render_conflict -local setup_auto_refresh = render.setup_auto_refresh local setup_conflict_result_window = conflict_view.setup_conflict_result_window local setup_all_keymaps = view_keymaps.setup_all_keymaps @@ -247,8 +246,6 @@ local function render_diff_view(ctx) reapply_keymaps = make_reapply_keymaps(tabpage), }) - -- Real file buffers only; virtual ones never change under us. - setup_auto_refresh(original_info.bufnr, modified_info.bufnr, ctx.original_is_virtual, ctx.modified_is_virtual) setup_all_keymaps(tabpage, original_info.bufnr, modified_info.bufnr, false) require("codediff.ui.follow_working_file").enable(tabpage, ctx.original_is_virtual, ctx.modified_is_virtual) diff --git a/lua/codediff/ui/view/side_by_side/single_file.lua b/lua/codediff/ui/view/side_by_side/single_file.lua index 81a51923..a743e49f 100644 --- a/lua/codediff/ui/view/side_by_side/single_file.lua +++ b/lua/codediff/ui/view/side_by_side/single_file.lua @@ -2,7 +2,6 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") local core = require("codediff.ui.core") local path = require("codediff.core.path") local layout = require("codediff.ui.layout") @@ -50,6 +49,7 @@ local function show_single_file(tabpage, opts) end if single_file_unchanged(session, opts) then + require("codediff.ui.refresh").ready(tabpage) return end @@ -59,11 +59,9 @@ local function show_single_file(tabpage, opts) -- Clear highlights from current session buffers local old_orig_buf, old_mod_buf = lifecycle.get_buffers(tabpage) if old_orig_buf then - auto_refresh.disable(old_orig_buf) lifecycle.clear_highlights(old_orig_buf) end if old_mod_buf then - auto_refresh.disable(old_mod_buf) lifecycle.clear_highlights(old_mod_buf) end @@ -154,7 +152,11 @@ end -- Load a real file from disk, return bufnr local function load_real_file(file_path) local bufnr = vim.fn.bufadd(file_path) + local loaded = vim.api.nvim_buf_is_loaded(bufnr) vim.fn.bufload(bufnr) + if not loaded then + vim.bo[bufnr].modified = false + end return bufnr end diff --git a/lua/codediff/ui/view/side_by_side/update.lua b/lua/codediff/ui/view/side_by_side/update.lua index 2ba676ad..73f667ae 100644 --- a/lua/codediff/ui/view/side_by_side/update.lua +++ b/lua/codediff/ui/view/side_by_side/update.lua @@ -3,7 +3,6 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") local virtual_file = require("codediff.core.virtual_file") -local auto_refresh = require("codediff.ui.auto_refresh") local config = require("codediff.config") local layout = require("codediff.ui.layout") local helpers = require("codediff.ui.view.helpers") @@ -19,7 +18,6 @@ local show_real_file_buffer = helpers.show_real_file_buffer local open_real_file = helpers.open_real_file local compute_and_render = render.compute_and_render local compute_and_render_conflict = conflict_view.compute_and_render_conflict -local setup_auto_refresh = render.setup_auto_refresh local setup_conflict_result_window = conflict_view.setup_conflict_result_window local setup_all_keymaps = view_keymaps.setup_all_keymaps @@ -120,6 +118,10 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) if not session then return false end + local generation = session.refresh and session.refresh.generation + local function current() + return require("codediff.ui.refresh").is_current(tabpage, session, generation) + end session.single_side = nil -- Get existing buffers and windows @@ -136,13 +138,8 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) -- Retire the old conflict renderer before asynchronous buffer loading starts. if session.result_bufnr then require("codediff.ui.conflict").teardown_gutter(tabpage) - auto_refresh.disable_result(session.result_bufnr) end - -- Disable auto-refresh temporarily - auto_refresh.disable(old_original_buf) - auto_refresh.disable(old_modified_buf) - -- Clear highlights from old buffers (before they're replaced/deleted) lifecycle.clear_highlights(old_original_buf) lifecycle.clear_highlights(old_modified_buf) @@ -201,6 +198,9 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) } local render_everything = function() + if not current() then + return + end -- Guard: Check if windows are still valid if not vim.api.nvim_win_is_valid(original_win) or not vim.api.nvim_win_is_valid(modified_win) then return @@ -229,6 +229,9 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) end vim.schedule(function() + if not current() or not vim.api.nvim_buf_is_valid(original_info.bufnr) or not vim.api.nvim_buf_is_valid(modified_info.bufnr) then + return + end local conflict_diffs = compute_and_render_conflict(original_info.bufnr, modified_info.bufnr, base_lines, original_lines, modified_lines, original_win, modified_win, should_auto_scroll) @@ -269,7 +272,6 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) lifecycle.update_revisions(tabpage, session_config.original_revision, session_config.modified_revision) lifecycle.update_diff_result(tabpage, lines_diff) lifecycle.update_changedtick(tabpage, vim.api.nvim_buf_get_changedtick(original_info.bufnr), vim.api.nvim_buf_get_changedtick(modified_info.bufnr)) - setup_auto_refresh(original_info.bufnr, modified_info.bufnr, original_is_virtual, modified_is_virtual) local is_explorer_mode = session.panel and session.panel.name == "explorer" setup_all_keymaps(tabpage, original_info.bufnr, modified_info.bufnr, is_explorer_mode) diff --git a/lua/codediff/ui/view/toggle.lua b/lua/codediff/ui/view/toggle.lua index 3b21b6da..ecbe67ba 100644 --- a/lua/codediff/ui/view/toggle.lua +++ b/lua/codediff/ui/view/toggle.lua @@ -89,6 +89,7 @@ local function rerender_current_file(tabpage) modified = session.modified, original_revision = session.original_revision, modified_revision = session.modified_revision, + source_revisions = session.source_revisions, } return require("codediff.ui.view").update(tabpage, session_config, false) end @@ -120,8 +121,12 @@ function M.toggle(tabpage) return false end + local refresh = require("codediff.ui.refresh") + refresh.begin(tabpage) if rerender_current_file(tabpage) then layout.arrange(tabpage) + else + refresh.ready(tabpage) end -- Re-enable compact mode in new layout diff --git a/tests/ui/explorer/explorer_refresh_spec.lua b/tests/ui/explorer/explorer_refresh_spec.lua index 7ceed530..814a904d 100644 --- a/tests/ui/explorer/explorer_refresh_spec.lua +++ b/tests/ui/explorer/explorer_refresh_spec.lua @@ -131,7 +131,9 @@ describe("Explorer refresh and single-file stability", function() refresh.refresh(explorer, function() completed = completed + 1 end) - assert.is_function(git_callback) + assert.is_true(vim.wait(1000, function() + return type(git_callback) == "function" + end, 10)) original_get_panel_view = lifecycle.get_panel_view lifecycle.get_panel_view = function(candidate) @@ -148,8 +150,9 @@ describe("Explorer refresh and single-file stability", function() }) assert.is_true(vim.wait(1000, function() - return completed == 1 + return not lifecycle.get_session(tabpage).refresh.running end, 10)) + assert.equals(0, completed, "a retired panel must not replay navigation callbacks") assert.same(status_before, explorer.status_result) end) diff --git a/tests/ui/explorer/native_watcher_spec.lua b/tests/ui/explorer/native_watcher_spec.lua index 77d8f928..f138c7ec 100644 --- a/tests/ui/explorer/native_watcher_spec.lua +++ b/tests/ui/explorer/native_watcher_spec.lua @@ -1,241 +1,231 @@ -describe("explorer native watcher", function() +local refresh = require("codediff.ui.refresh") +local snapshot = require("codediff.ui.refresh.snapshot") +local apply = require("codediff.ui.refresh.apply") +local lifecycle = require("codediff.ui.lifecycle") +local path = require("codediff.core.path") + +describe("session refresh scheduling", function() + local old_timer, old_watcher, old_read, old_apply, old_auto + local timers, handlers, reads, applied, unsubscribed, controller, session, tab, root local uv = vim.uv or vim.loop - local config - local original_auto_refresh_enabled - local original_new_timer - local original_watcher - local original_auto_refresh - local refresh_module - local original_refresh - local cleanup - local repository - local watcher_handlers - local unsubscribed - local timers - local refresh_completions - local refresh_forces - local refresh_count - local sync_count - local sync_completions before_each(function() - config = require("codediff.config") - original_auto_refresh_enabled = config.options.explorer.auto_refresh - watcher_handlers = nil - repository = vim.fn.tempname() - vim.fn.mkdir(repository .. "/.git", "p") - timers = {} - refresh_completions = {} - refresh_forces = {} - refresh_count = 0 - sync_count = 0 - sync_completions = {} + vim.cmd("tabnew") + tab = vim.api.nvim_get_current_tabpage() + root = vim.fn.tempname() + vim.fn.mkdir(root .. "/.git", "p") + timers, reads, applied = {}, {}, 0 + handlers = nil unsubscribed = false - - original_new_timer = uv.new_timer + old_timer = uv.new_timer uv.new_timer = function() - local timer = { started = false, stopped = false, closed = false } - function timer:start(_, _, callback) + local timer = {} + function timer:start(_, repeat_ms, callback) self.started = true + self.repeat_ms = repeat_ms self.callback = callback end function timer:stop() - self.stopped = true + self.started = false end function timer:close() self.closed = true end function timer:is_closing() - return self.closed + return self.closed == true end timers[#timers + 1] = timer return timer end - - original_watcher = package.loaded["codediff.core.watcher"] + old_watcher = package.loaded["codediff.core.watcher"] package.loaded["codediff.core.watcher"] = { - subscribe = function(root, handlers) - assert.equals(repository, root) - watcher_handlers = handlers + subscribe = function(_, callbacks) + handlers = callbacks return function() unsubscribed = true end end, } - - original_auto_refresh = package.loaded["codediff.ui.auto_refresh"] - package.loaded["codediff.ui.auto_refresh"] = { - sync_mutable_buffers = function(_, done) - sync_count = sync_count + 1 - sync_completions[#sync_completions + 1] = done - end, - } - - refresh_module = require("codediff.ui.explorer.refresh") - original_refresh = refresh_module._refresh_once - refresh_module._refresh_once = function(_, done, force) - refresh_count = refresh_count + 1 - refresh_completions[#refresh_completions + 1] = done - refresh_forces[#refresh_forces + 1] = force == true + old_read, old_apply = snapshot.read, apply.run + snapshot.read = function(_, event, _, done) + reads[#reads + 1] = { event = event, done = done } end + apply.run = function() + applied = applied + 1 + return true + end + old_auto = require("codediff.config").options.explorer.auto_refresh + require("codediff.config").options.explorer.auto_refresh = true end) after_each(function() - if cleanup then - cleanup() - cleanup = nil - end - refresh_module._refresh_once = original_refresh - package.loaded["codediff.core.watcher"] = original_watcher - package.loaded["codediff.ui.auto_refresh"] = original_auto_refresh - uv.new_timer = original_new_timer - config.options.explorer.auto_refresh = original_auto_refresh_enabled - vim.fn.delete(repository, "rf") + refresh.dispose(tab) + snapshot.read, apply.run = old_read, old_apply + package.loaded["codediff.core.watcher"] = old_watcher + uv.new_timer = old_timer + require("codediff.config").options.explorer.auto_refresh = old_auto + lifecycle.cleanup(tab) + pcall(vim.cmd, "tabclose!") + vim.fn.delete(root, "rf") end) local function setup() - local tabpage = vim.api.nvim_get_current_tabpage() - local explorer = { - git_root = repository, - is_hidden = false, - winid = vim.api.nvim_get_current_win(), - } - cleanup = refresh_module.setup_auto_refresh(explorer, tabpage) - return explorer + local a = vim.api.nvim_create_buf(false, true) + local b = vim.api.nvim_create_buf(false, true) + vim.api.nvim_buf_set_lines(a, 0, -1, false, { "a" }) + vim.api.nvim_buf_set_lines(b, 0, -1, false, { "b" }) + local win = vim.api.nvim_get_current_win() + lifecycle.create_session(tab, { + git_root = root, + original = path.make_ref("a.txt", root), + modified = path.make_ref("a.txt", root), + original_revision = ":0", + modified_revision = "WORKING", + panel = { name = "explorer" }, + }, { original_bufnr = a, modified_bufnr = b, original_win = win, modified_win = win, lines_diff = { changes = {} } }) + session = lifecycle.get_session(tab) + controller = refresh.attach(tab) + uv.new_timer = old_timer + vim.wait(10) end - it("stops polling after ready and serializes refreshes", function() - local explorer = setup() - assert.equals(1, #timers) - assert.is_true(timers[1].started) + local function fire() + timers[1].callback() + vim.wait(10) + end - watcher_handlers.on_ready() - assert.is_true(explorer._native_watcher_ready) - assert.is_true(timers[1].stopped) - assert.is_true(timers[1].closed) - assert.equals(1, refresh_count) - assert.is_true(refresh_forces[1]) + it("stops fallback after ready and preserves every queued event category", function() + setup() + assert.is_true(timers[2].started) + handlers.on_ready() + assert.is_false(timers[2].started) + fire() + assert.equals(1, #reads) + assert.is_true(reads[1].event.full) + handlers.on_refresh({ worktree = true }) + handlers.on_refresh({ index = true, refs = true }) + assert.equals(1, #reads) + reads[1].done(nil, snapshot.capture(session)) + fire() + assert.same({ worktree = true, index = true, refs = true }, reads[2].event) + end) - local direct_completed = 0 - watcher_handlers.on_refresh() - watcher_handlers.on_refresh() - refresh_module.refresh(explorer, function() - direct_completed = direct_completed + 1 + it("completes callbacks only after applying a settled snapshot", function() + setup() + local completed = 0 + controller:request({ index = true }, function() + completed = completed + 1 end) - watcher_handlers.on_refresh() - assert.equals(1, refresh_count) - assert.is_true(refresh_forces[1]) - - refresh_completions[1]() - assert.equals(1, sync_count) - assert.equals(1, refresh_count) - - sync_completions[1]() - assert.equals(2, refresh_count) - assert.equals(0, direct_completed) - assert.is_true(refresh_forces[2]) - - refresh_completions[2]() - assert.equals(2, sync_count) - assert.equals(2, refresh_count) - sync_completions[2]() - assert.equals(1, direct_completed) + fire() + assert.equals(0, completed) + reads[1].done(nil, snapshot.capture(session)) + assert.equals(1, applied) + assert.equals(1, completed) end) - it("keeps status-equality shortcuts for fallback polling", function() + it("uses full data checks rather than forced reinitialization for fallback", function() setup() - timers[1].callback() - assert.is_true(vim.wait(1000, function() - return refresh_count == 1 - end, 10)) - assert.is_false(refresh_forces[1]) - refresh_completions[1]() - sync_completions[1]() + handlers.on_error("watcher exited") + assert.is_true(timers[2].started) + timers[2].callback() + vim.wait(10) + fire() + assert.same({ full = true }, reads[1].event) end) - it("serializes direct refreshes when automatic refresh is disabled", function() - config.options.explorer.auto_refresh = false - local explorer = setup() - - assert.equals(0, #timers) - assert.is_nil(watcher_handlers) - - local forced_completed = 0 - local ordinary_completed = 0 - refresh_module.refresh(explorer) - refresh_module.refresh(explorer, function() - forced_completed = forced_completed + 1 - end, true) - refresh_module.refresh(explorer, function() - ordinary_completed = ordinary_completed + 1 - end, false) - - assert.equals(1, refresh_count) - assert.is_false(refresh_forces[1]) - assert.equals(0, forced_completed) - assert.equals(0, ordinary_completed) - - refresh_completions[1]() - assert.equals(1, sync_count) - assert.equals(1, refresh_count) - - sync_completions[1]() - assert.equals(2, refresh_count) - assert.is_true(refresh_forces[2]) - assert.equals(0, forced_completed) - assert.equals(0, ordinary_completed) - - refresh_completions[2]() - assert.equals(2, sync_count) - assert.equals(0, forced_completed) - assert.equals(0, ordinary_completed) - - sync_completions[2]() - assert.equals(1, forced_completed) - assert.equals(1, ordinary_completed) + it("discards an in-flight snapshot after retargeting", function() + setup() + controller:request({ index = true }) + fire() + refresh.begin(tab) + reads[1].done(nil, snapshot.capture(session)) + assert.equals(0, applied) + assert.is_true(controller.pending.index) end) - it("drops a trailing refresh when cleanup happens during mutable sync", function() + it("does not replay completion callbacks onto a newer selection", function() setup() - watcher_handlers.on_ready() - watcher_handlers.on_refresh() - refresh_completions[1]() - - assert.equals(1, sync_count) - cleanup() - cleanup = nil - sync_completions[1]() + local completed = 0 + controller:request({ index = true }, function() + completed = completed + 1 + end) + fire() + refresh.begin(tab) + reads[1].done(nil, snapshot.capture(session)) + refresh.ready(tab) + vim.wait(10) + fire() + reads[2].done(nil, snapshot.capture(session)) + assert.equals(0, completed) + end) - assert.equals(1, refresh_count) + it("tears down timers and the subscription even with a read in flight", function() + setup() + controller:request({ full = true }) + fire() + refresh.dispose(tab) + reads[1].done(nil, snapshot.capture(session)) + assert.equals(0, applied) assert.is_true(unsubscribed) + for _, timer in ipairs(timers) do + assert.is_true(timer.closed) + end end) - it("returns to polling after a running watcher fails", function() - local explorer = setup() - watcher_handlers.on_ready() - watcher_handlers.on_error("process exited") - - assert.is_false(explorer._native_watcher_ready) - - assert.equals(2, #timers) - assert.is_true(timers[2].started) + it("defers hidden-tab work, but does not drop its invalidations", function() + setup() + session.suspended = true + handlers.on_refresh({ index = true }) + assert.equals(0, #reads) + assert.is_true(controller.pending.index) + session.suspended = false + controller:request({ render = true }) + fire() + assert.is_true(reads[1].event.index) + assert.is_true(reads[1].event.render) + end) - cleanup() - cleanup = nil - assert.is_true(timers[2].stopped) - assert.is_true(timers[2].closed) - assert.is_true(unsubscribed) + it("retries a synchronous source error instead of leaving the queue running forever", function() + setup() + local reader = snapshot.read + snapshot.read = function() + error("temporary source failure") + end + controller:request({ index = true }) + local ok = pcall(controller.run, controller) + assert.is_true(ok) + assert.is_false(controller.running) + snapshot.read = reader + fire() + reads[1].done(nil, snapshot.capture(session)) + assert.equals(1, applied) end) - it("requests a refresh when a hidden explorer is shown again", function() - local explorer = setup() - explorer.is_hidden = true - watcher_handlers.on_ready() - watcher_handlers.on_refresh() - assert.equals(0, refresh_count) + it("rejects snapshots whose working buffers changed during the read", function() + setup() + controller:request({ index = true }) + fire() + local data = snapshot.capture(session) + data.ticks = { [session.modified_bufnr] = vim.api.nvim_buf_get_changedtick(session.modified_bufnr) } + vim.api.nvim_buf_set_lines(session.modified_bufnr, 0, -1, false, { "edited while reading" }) + reads[1].done(nil, data) + assert.equals(0, applied) + fire() + assert.is_true(reads[2].event.buffer) + reads[2].done(nil, snapshot.capture(session)) + assert.equals(1, applied) + end) - explorer.is_hidden = false - explorer._request_auto_refresh() - assert.equals(1, refresh_count) + it("still accepts manual requests when automatic refresh is disabled", function() + require("codediff.config").options.explorer.auto_refresh = false + setup() + assert.is_nil(handlers) + local completed = 0 + controller:request({ full = true }, function() + completed = completed + 1 + end) + fire() + reads[1].done(nil, snapshot.capture(session)) + assert.equals(1, completed) end) end) diff --git a/tests/ui/history/history_refresh_watcher_spec.lua b/tests/ui/history/history_refresh_watcher_spec.lua index bdf4bb71..b8c485dc 100644 --- a/tests/ui/history/history_refresh_watcher_spec.lua +++ b/tests/ui/history/history_refresh_watcher_spec.lua @@ -1,93 +1,58 @@ --- Regression test for c43b1f9: the history .git fs_event handle must be torn --- down when its callback fires with an error, so a dead watcher (typically the --- repository being deleted or replaced) does not keep re-delivering errors --- forever on Windows. --- --- The watcher lives inside a local closure in `setup_auto_refresh`, so the --- test stubs `vim.uv.new_fs_event()` with a spy handle, drives the callback --- with a synthetic error, and asserts that `:stop()` + `:close()` were both --- invoked on the handle. - -local h = dofile("tests/helpers.lua") - -describe("History .git watcher teardown on error (c43b1f9)", function() - local uv = vim.uv or vim.loop - local original_new_fs_event - local repo +local h = require("tests.helpers") +local lifecycle = require("codediff.ui.lifecycle") +local refresh = require("codediff.ui.refresh") +local path = require("codediff.core.path") +describe("history refresh transport lifecycle", function() + local repo, tab, original_watcher, handlers, unsubscribed before_each(function() - original_new_fs_event = uv.new_fs_event repo = h.create_temp_git_repo() + vim.cmd("tabnew") + tab = vim.api.nvim_get_current_tabpage() + original_watcher = package.loaded["codediff.core.watcher"] + unsubscribed = 0 + package.loaded["codediff.core.watcher"] = { + subscribe = function(root, callbacks) + assert.equals(repo.dir, root) + handlers = callbacks + return function() + unsubscribed = unsubscribed + 1 + end + end, + } end) - after_each(function() - uv.new_fs_event = original_new_fs_event - if repo then - repo.cleanup() - repo = nil - end + lifecycle.cleanup(tab) + package.loaded["codediff.core.watcher"] = original_watcher + pcall(vim.cmd, "tabclose!") + repo.cleanup() end) - it("stops and closes the fs_event handle when the watcher callback receives an error", function() - local calls = { start = 0, stop = 0, close = 0 } - local captured_callback - - local handle = {} - function handle:start(_dir, _flags, cb) - calls.start = calls.start + 1 - captured_callback = cb - return 0 - end - function handle:stop() - calls.stop = calls.stop + 1 - return 0 - end - function handle:close() - calls.close = calls.close + 1 - end - - uv.new_fs_event = function() - return handle - end - - -- setup_auto_refresh reads history.git_root and history.is_hidden; a - -- valid tabpage handle is enough for the augroup + tabpage_is_valid check. - local history = { + it("shares the native transport and falls back once after repeated errors", function() + local a, b = vim.api.nvim_create_buf(false, true), vim.api.nvim_create_buf(false, true) + local win = vim.api.nvim_get_current_win() + lifecycle.create_session(tab, { + panel = { name = "history" }, git_root = repo.dir, - is_hidden = false, - } - local tabpage = vim.api.nvim_get_current_tabpage() - - local refresh = require("codediff.ui.history.refresh") - refresh.setup_auto_refresh(history, tabpage) - - -- The watcher setup is chained through git.get_git_dir + vim.schedule; - -- wait for the start() to be recorded on the spy before invoking its - -- callback. - local started = vim.wait(2000, function() - return calls.start > 0 and type(captured_callback) == "function" - end, 20) - assert.is_true(started, "watcher :start() should have been called") - assert.equals(1, calls.start) - - -- Fire the callback with a watch error, then let vim.schedule_wrap flush. - captured_callback("EPERM", nil, nil) - vim.wait(200) - - assert.equals(1, calls.stop, ":stop() should have been called exactly once on error") - assert.equals(1, calls.close, ":close() should have been called exactly once on error") - - -- A second callback firing (real Windows symptom: the same error re-fires - -- forever) must NOT re-trigger stop/close, because the git_watcher local - -- was nilled by the first error. - captured_callback("EPERM", nil, nil) - vim.wait(100) - assert.equals(1, calls.stop, ":stop() must not be called again after the handle was nilled") - assert.equals(1, calls.close, ":close() must not be called again after the handle was nilled") - - -- Cleanup the augroup that setup_auto_refresh created. - if history._cleanup_auto_refresh then - history._cleanup_auto_refresh() - end + original = path.empty(), + modified = path.empty(), + }, { original_bufnr = a, modified_bufnr = b, original_win = win, modified_win = win, lines_diff = {} }) + local history = { git_root = repo.dir, bufnr = a, winid = win, opts = {}, commits = {}, is_hidden = false } + lifecycle.set_panel_view(tab, history) + require("codediff.ui.history.refresh").setup_auto_refresh(history, tab) + local controller = lifecycle.get_session(tab).refresh + assert.is_function(handlers.on_ready) + handlers.on_ready() + assert.is_true(history._native_watcher_ready) + assert.is_false(controller.polling) + handlers.on_error("EPERM") + local timer = controller.poll + assert.is_true(controller.polling) + assert.is_false(history._native_watcher_ready) + handlers.on_error("EPERM") + assert.equals(timer, controller.poll) + refresh.dispose(tab) + assert.is_true(timer:is_closing()) + assert.equals(1, unsubscribed) end) end) From 6543a5ef9fe42e12ef34801482e8a8a598688abf Mon Sep 17 00:00:00 2001 From: Yanuo Ma <41042490+esmuellert@users.noreply.github.com> Date: Sat, 12 Sep 2026 15:59:58 -0400 Subject: [PATCH 4/8] test(refresh): cover native and polling refresh end to end Add 124 real file/Git and embedded screen-grid cases across layouts, Explorer, History, standalone comparisons, merge Results, file following, and session lifecycle transitions. Require native watcher readiness, exercise the 500ms polling fallback and real process-exit failover, and verify stable panes throughout unrelated repository changes. Document the coverage and extend the screen harness for flushed-frame assertions. --- tests/README.md | 23 ++ tests/framework/screen.lua | 14 + .../ui/refresh/conflict_refresh_e2e_spec.lua | 187 +++++++++ tests/ui/refresh/file_refresh_e2e_spec.lua | 57 +++ tests/ui/refresh/helpers.lua | 367 ++++++++++++++++++ tests/ui/refresh/lifecycle_e2e_spec.lua | 214 ++++++++++ tests/ui/refresh/refresh_e2e_spec.lua | 244 ++++++++++++ 7 files changed, 1106 insertions(+) create mode 100644 tests/ui/refresh/conflict_refresh_e2e_spec.lua create mode 100644 tests/ui/refresh/file_refresh_e2e_spec.lua create mode 100644 tests/ui/refresh/helpers.lua create mode 100644 tests/ui/refresh/lifecycle_e2e_spec.lua create mode 100644 tests/ui/refresh/refresh_e2e_spec.lua diff --git a/tests/README.md b/tests/README.md index 74fa66bd..671bee57 100644 --- a/tests/README.md +++ b/tests/README.md @@ -129,6 +129,29 @@ Always close the embedded UI in `after_each`, including when an assertion fails. A grid failure reports the pane/focus context, display row, expected text and actual text. These are cell-level checks, not font or pixel snapshots. +## Refresh regressions + +`ui/refresh/*_e2e_spec.lua` exercises the session refresh controller through real +file writes, Git index/ref changes and rendered screen cells. It covers both +layouts, Explorer and bare comparisons, history, single-file previews, +directory comparisons, and editable merge Results. Lifecycle cases hold actual +Git responses to test file switches, buffer deletion, tab closure and edits +made while reads are pending. Unrelated changes must preserve pane identities, +cursors, viewports, folds and every observed diff-grid frame. + +Git cases run twice: once with the native watcher, and once with its 500 ms +polling fallback. Native tests require the real `codediff-watcher` binary and +assert that it became ready; silently falling back is not a native-test pass. +The normal installer supplies the binary, or set `CODEDIFF_WATCHER_PATH` to an +existing executable for offline runs. Android has no native release and skips +only the native cases. A process-exit case verifies actual watcher-to-polling +failover. Plain file/directory comparisons use polling without Git metadata. + +`ui/refresh/policy_spec.lua`, `ui/auto_refresh_spec.lua` and +`ui/explorer/native_watcher_spec.lua` cover dependency selection, settled input +snapshots, event coalescing, retries and stale callback rejection independently +of the screen tests. + ## Test Philosophy Focus on **integration points** that C tests cannot validate: diff --git a/tests/framework/screen.lua b/tests/framework/screen.lua index ca69ca2c..72843650 100644 --- a/tests/framework/screen.lua +++ b/tests/framework/screen.lua @@ -56,6 +56,9 @@ function Screen:_redraw(events) self.highlights[args[1]] = args[2] elseif name == "flush" then self.flushes = self.flushes + 1 + if self.on_flush then + self.on_flush(self) + end end end end @@ -167,6 +170,17 @@ function Screen:flush() ) end +-- Wait for naturally delivered UI events; unlike flush(), this does not redraw. +function Screen:await(predicate, message, timeout) + assert( + vim.wait(timeout or 10000, function() + return self.error ~= nil or predicate() + end, 10), + (message or "Embedded Neovim did not become ready") .. "\n" .. self.stderr + ) + assert(not self.error, tostring(self.error)) +end + function Screen:wait_for(predicate, message) assert(vim.wait(10000, predicate, 10), (message or "Embedded Neovim did not become ready") .. "\n" .. self.stderr) self:flush() diff --git a/tests/ui/refresh/conflict_refresh_e2e_spec.lua b/tests/ui/refresh/conflict_refresh_e2e_spec.lua new file mode 100644 index 00000000..7cf8811a --- /dev/null +++ b/tests/ui/refresh/conflict_refresh_e2e_spec.lua @@ -0,0 +1,187 @@ +local h = require("tests.ui.refresh.helpers") + +local function merge_repo() + local repo = h.repo() + repo.git("checkout -b incoming") + repo.write_file("a.txt", { "start", "incoming-A", "context", "end", "tail" }) + repo.git("commit -am incoming") + repo.git("checkout main") + repo.write_file("a.txt", { "start", "current-A", "context", "end", "tail" }) + repo.git("commit -am current") + local _, code = repo.git("merge incoming --no-edit") + assert.equals(1, code, "fixture must conflict") + return repo +end + +local function replace_current_stage(repo, stage) + stage = stage or 2 + repo.write_file("replacement.txt", { "start", "current-B", "context", "end", "tail" }) + local oid = vim.trim(repo.git("hash-object -w replacement.txt")) + local entries = repo.git("ls-files --stage -- a.txt") + entries = entries:gsub("(%d+) (%x+) " .. stage .. "\ta.txt", "%1 " .. oid .. " " .. stage .. "\ta.txt") + local result = vim.system({ "git", "-C", repo.dir, "update-index", "--index-info" }, { stdin = entries, text = true }):wait() + assert.equals(0, result.code, result.stderr) +end + +for _, backend in ipairs({ "native", "polling" }) do + describe("merge refresh E2E / " .. backend, function() + local repo, screen + before_each(function() + repo = merge_repo() + screen = h.screen(backend, "side-by-side") + h.open(screen, repo) + screen:await(function() + return screen:exec("return refresh_session().result_bufnr ~= nil") + end) + end) + after_each(function() + if screen then + screen:close() + screen = nil + end + if repo then + repo.cleanup() + repo = nil + end + end) + + local function edit_result() + screen:exec("vim.api.nvim_set_current_win(refresh_session().result_win); vim.api.nvim_win_set_cursor(0, { 4, 0 })") + h.feed(screen, "ccUSER_EDIT_KEEP") + h.expect_text(screen, "result", "USER_EDIT_KEEP") + return h.panes(screen) + end + + it("#558: unrelated same-status changes preserve Result, focus, cursors and windows", function() + local expected = edit_result() + local before = h.checkpoint(screen) + repo.write_file("background.txt", { "different" }) + h.wait_event(screen, before) + h.preserved(screen, expected) + end) + + it("keeps all rendered merge cells stable during a burst of unrelated writes", function() + local expected = edit_result() + h.idle(screen) + local unchanged = h.watch_grid(screen) + for i = 1, 6 do + local before = h.checkpoint(screen) + repo.write_file("background.txt", { "background-" .. i }) + h.wait_event(screen, before) + end + h.preserved(screen, expected, 200) + unchanged() + end) + + it("preserves merge work when another file is staged", function() + local expected = edit_result() + local before = h.checkpoint(screen) + repo.write_file("b.txt", { "start", "staged-B", "end" }) + repo.git("add b.txt") + h.wait_event(screen, before) + h.preserved(screen, expected) + end) + + it("refreshes actual conflict inputs when the Result is still untouched", function() + replace_current_stage(repo) + h.expect_text(screen, "modified", "current-B") + assert.equals("base-A", h.panes(screen).result.lines[2]) + end) + + it("does not overwrite user work when the conflict inputs change", function() + edit_result() + replace_current_stage(repo) + screen:await(function() + return screen:exec([[ + for _, message in ipairs(refresh_test.notifications) do + if message.message:lower():find('conflict inputs changed', 1, true) then return true end + end + return false + ]]) + end, "changed merge inputs were not reported") + assert.equals("USER_EDIT_KEEP", h.panes(screen).result.lines[4]) + end) + + it("retains pending changes across tab suspension without stealing focus", function() + local expected = edit_result() + screen:command("tabnew") + local other = screen:exec("return vim.api.nvim_get_current_tabpage()") + repo.write_file("background.txt", { "while-away" }) + vim.wait(700) + assert.equals(other, screen:exec("return vim.api.nvim_get_current_tabpage()")) + screen:exec("vim.api.nvim_set_current_tabpage(refresh_test.tab)") + h.expect_text(screen, "result", "USER_EDIT_KEEP") + assert.same(expected.result.lines, h.panes(screen).result.lines) + end) + + it("does not leave work running after its tab closes", function() + local before = h.checkpoint(screen) + repo.write_file("background.txt", { "closing" }) + if backend == "native" then + h.wait_event(screen, before) + end + screen:command("tabclose!") + repo.write_file("background.txt", { "after-close" }) + vim.wait(700) + h.assert_no_errors(screen) + assert.is_nil(screen:exec("return refresh_session()")) + end) + end) +end + +for _, backend in ipairs({ "native", "polling" }) do + describe("missing merge stage refresh / " .. backend, function() + local repo, screen + after_each(function() + if screen then + screen:close() + screen = nil + end + if repo then + repo.cleanup() + repo = nil + end + end) + + for _, shape in ipairs({ "add/add", "deleted by us", "deleted by them" }) do + it("settles and refreshes " .. shape .. " conflicts", function() + repo = h.repo() + if shape == "add/add" then + repo.git("rm a.txt") + repo.git("commit -m remove-base") + end + repo.git("checkout -b incoming") + if shape == "deleted by them" then + repo.git("rm a.txt") + else + repo.write_file("a.txt", { "start", "incoming", "context", "end", "tail" }) + end + repo.git("add -A") + repo.git("commit -m incoming") + repo.git("checkout main") + if shape == "deleted by us" then + repo.git("rm a.txt") + else + repo.write_file("a.txt", { "start", "current", "context", "end", "tail" }) + end + repo.git("add -A") + repo.git("commit -m current") + local _, code = repo.git("merge incoming --no-edit") + assert.equals(1, code) + screen = h.screen(backend, "side-by-side") + h.open(screen, repo) + local side = shape == "deleted by us" and "original" or "modified" + screen:exec("vim.api.nvim_set_current_win(refresh_session()[(...) .. '_win'])", { side }) + h.feed(screen, "ggzt") + local expected = h.panes(screen) + local before = h.checkpoint(screen) + repo.write_file("background.txt", { "changed" }) + h.wait_event(screen, before) + h.preserved(screen, expected, 200) + replace_current_stage(repo, shape == "deleted by us" and 3 or 2) + h.expect_text(screen, side, "current-B") + h.idle(screen) + end) + end + end) +end diff --git a/tests/ui/refresh/file_refresh_e2e_spec.lua b/tests/ui/refresh/file_refresh_e2e_spec.lua new file mode 100644 index 00000000..190d5085 --- /dev/null +++ b/tests/ui/refresh/file_refresh_e2e_spec.lua @@ -0,0 +1,57 @@ +local h = require("tests.ui.refresh.helpers") + +for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("file-source refresh E2E / " .. layout, function() + local repo, screen + before_each(function() + repo = h.repo() + screen = h.screen("files", layout) + end) + after_each(function() + if screen then + screen:close() + screen = nil + end + if repo then + repo.cleanup() + repo = nil + end + end) + + it("refreshes a plain two-file comparison after external writes", function() + h.open(screen, repo, "CodeDiff file a.txt b.txt", "b.txt") + repo.write_file("b.txt", { "start", "external-B", "end" }) + h.expect_text(screen, "modified", "external-B") + end) + + it("refreshes a directory comparison without relying on Git metadata", function() + repo.write_file("left/a.txt", { "start", "left-A", "end" }) + repo.write_file("right/a.txt", { "start", "right-A", "end" }) + h.open(screen, repo, "CodeDiff dir left right") + repo.write_file("right/a.txt", { "start", "right-B", "end" }) + h.expect_text(screen, "modified", "right-B") + repo.write_file("right/new.txt", { "new file" }) + screen:await(function() + return screen:exec([[ + local s = refresh_session() + local text = table.concat(vim.api.nvim_buf_get_lines(s.panel.view.bufnr, 0, -1, false), '\n') + return text:find('new.txt', 1, true) ~= nil + ]]) + end, "directory listing did not update") + end) + + it("updates unsaved text in a plain comparison through buffer events", function() + repo.write_file("b.txt", { "start", "base-A", "context", "end", "tail" }) + h.open(screen, repo, "CodeDiff file a.txt b.txt", "b.txt") + screen:exec("vim.api.nvim_set_current_win(refresh_session().modified_win); vim.api.nvim_win_set_cursor(0, { 2, 0 })") + h.feed(screen, "ccBUFFER_EDIT") + h.expect_text(screen, "modified", "BUFFER_EDIT") + screen:await(function() + return screen:exec([[ + local s = refresh_session() + return s.stored_diff_result and #s.stored_diff_result.changes > 0 + ]]) + end, "buffer edit was not consumed by the diff") + end) + end) +end diff --git a/tests/ui/refresh/helpers.lua b/tests/ui/refresh/helpers.lua new file mode 100644 index 00000000..becc4424 --- /dev/null +++ b/tests/ui/refresh/helpers.lua @@ -0,0 +1,367 @@ +local M = {} +local Screen = require("tests.framework.screen") +local helpers = require("tests.helpers") +local watcher_path + +function M.native_watcher() + if require("codediff.core.installer.common").detect_os() == "android" then + pending("No native watcher release for Android; polling E2Es run separately") + end + if not watcher_path then + local saved = vim.env.CODEDIFF_WATCHER_NO_AUTO_INSTALL + vim.env.CODEDIFF_WATCHER_NO_AUTO_INSTALL = nil + local install_error + require("codediff.core.installer.watcher").ensure(function(path, err) + watcher_path, install_error = path, err + end) + vim.env.CODEDIFF_WATCHER_NO_AUTO_INSTALL = saved + assert(watcher_path and vim.fn.filereadable(watcher_path) == 1, "Native E2Es require codediff-watcher: " .. tostring(install_error)) + end + return watcher_path +end + +function M.repo() + local repo = helpers.create_temp_git_repo() + repo.write_file("a.txt", { "start", "base-A", "context", "end", "tail" }) + repo.write_file("b.txt", { "start", "base-B", "end" }) + repo.write_file("background.txt", { "unchanged" }) + repo.git("add -A") + repo.git("commit -m base") + repo.base = vim.trim(repo.git("rev-parse HEAD")) + return repo +end + +function M.screen(backend, layout) + local binary = backend == "native" and M.native_watcher() or "" + local screen = Screen.new(120, 40) + screen.backend = backend + screen:exec( + [[ + local backend, layout, binary = ... + require('codediff').setup({ + diff = { layout = layout, jump_to_first_change = false, compute_moves = false }, + explorer = { width = 28 }, + }) + vim.o.hidden = true + vim.o.autoread = true + vim.o.number = false + vim.o.relativenumber = false + vim.o.foldcolumn = '0' + vim.o.scrolloff = 0 + _G.refresh_test = { received = 0, reads = 0, pending = 0, scheduled = 0, errors = {}, notifications = {} } + local test = refresh_test + if backend == 'native' then + vim.env.CODEDIFF_WATCHER_PATH = binary + local uv = vim.uv or vim.loop + local spawn = uv.spawn + uv.spawn = function(command, options, done) + local handle, pid = spawn(command, options, done) + if command == binary then test.watcher_pid = pid end + return handle, pid + end + else + require('codediff.core.installer.watcher').ensure = function(done) + done(nil, 'native transport disabled for polling E2E') + end + end + -- Observe the real transport and Git requests, without replacing their work. + local watcher = require('codediff.core.watcher') + local subscribe = watcher.subscribe + watcher.subscribe = function(root, handlers) + local ready, refresh, failed = handlers.on_ready, handlers.on_refresh, handlers.on_error + handlers.on_ready = function(message) + test.native_ready = true + if ready then ready(message) end + end + handlers.on_refresh = function(message) + test.received = test.received + 1 + test.last_message = message + if refresh then refresh(message) end + end + handlers.on_error = function(message) + test.fallback = true + if failed then failed(message) end + end + return subscribe(root, handlers) + end + local runner = require('codediff.core.git.runner') + local run = runner.run_async + runner.run_async = function(args, options, done) + test.pending = test.pending + 1 + test.reads = test.reads + 1 + return run(args, options, function(...) + test.pending = test.pending - 1 + done(...) + end) + end + local git = require('codediff.core.git') + for _, name in ipairs({ 'get_status_with_line_stats', 'get_diff_staged', 'get_diff_revision_with_line_stats', 'get_diff_revisions_with_line_stats', 'get_file_content', 'get_commit_list' }) do + local original = git[name] + git[name] = function(...) + local args, count = { ... }, select('#', ...) + for i = 1, count do + if type(args[i]) == 'function' then + local callback = args[i] + test.reads = test.reads + 1 + test.pending = test.pending + 1 + args[i] = function(...) + test.pending = test.pending - 1 + return callback(...) + end + break + end + end + return original(unpack(args, 1, count)) + end + end + local schedule = vim.schedule + vim.schedule = function(fn) + test.scheduled = test.scheduled + 1 + schedule(function() + local ok, err = xpcall(fn, debug.traceback) + test.scheduled = test.scheduled - 1 + if not ok then test.errors[#test.errors + 1] = tostring(err) end + end) + end + vim.notify = function(message, level) + local record = { message = tostring(message), level = level } + test.notifications[#test.notifications + 1] = record + if level == vim.log.levels.ERROR then test.errors[#test.errors + 1] = tostring(message) end + end + _G.refresh_session = function() + return require('codediff.ui.lifecycle').get_session(refresh_test.tab or vim.api.nvim_get_current_tabpage()) + end + ]], + { backend, layout or "side-by-side", binary } + ) + return screen +end + +function M.open(screen, repo, command, expected) + screen:exec( + [[ + local root, command = ... + refresh_test.tab = nil + vim.cmd('cd ' .. vim.fn.fnameescape(root)) + vim.cmd('edit ' .. vim.fn.fnameescape(root .. '/a.txt')) + vim.cmd(command) + ]], + { repo.dir, command or "CodeDiff" } + ) + screen:await(function() + M.assert_no_errors(screen) + return screen:exec( + [[ + local expected = ... + local s = refresh_session() + if not s or not s.stored_diff_result then return false end + if expected and not ((s.modified and s.modified.absolute:sub(-#expected) == expected) + or (s.original and s.original.absolute:sub(-#expected) == expected)) then return false end + refresh_test.tab = vim.api.nvim_get_current_tabpage() + return true + ]], + { expected or "a.txt" } + ) + end, "CodeDiff did not open the requested file") + if screen.backend == "native" then + screen:await(function() + return screen:exec("return refresh_test.native_ready == true") + end, "Native watcher never became ready; fallback is not a native E2E pass") + end + M.idle(screen) +end + +function M.idle(screen) + screen:await(function() + M.assert_no_errors(screen) + return screen:exec([[ + local s = refresh_session() + local controller = s and s.refresh + return refresh_test.pending == 0 and refresh_test.scheduled == 0 + and (not s or s.stored_diff_result ~= nil) + and (not controller or controller.closed or not controller.running and not controller.loading + and not next(controller.pending) and not controller.timer:is_active()) + ]]) + end, "refresh did not settle") +end + +function M.assert_no_errors(screen) + local errors = screen:exec("return refresh_test.errors") + assert.same({}, errors, "unhandled error in embedded Neovim") +end + +function M.checkpoint(screen) + return screen:exec("return { received = refresh_test.received, reads = refresh_test.reads }") +end + +function M.wait_event(screen, before) + screen:await(function() + M.assert_no_errors(screen) + return screen:exec( + [[ + local before, native = ... + return native and refresh_test.received > before.received or not native and refresh_test.reads > before.reads + ]], + { before, screen.backend == "native" } + ) + end, "the external change was not observed") + M.idle(screen) +end + +function M.panes(screen) + return screen:exec([[ + local s = refresh_session() + local result = { tab = refresh_test.tab, focused = vim.api.nvim_get_current_win(), layout = s.layout } + for _, side in ipairs({ 'original', 'modified', 'result' }) do + local buf, win = s[side .. '_bufnr'], s[side .. '_win'] + if buf and vim.api.nvim_buf_is_valid(buf) then + local pane = { buf = buf, lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false), win = win } + if win and vim.api.nvim_win_is_valid(win) then + local v = vim.api.nvim_win_call(win, vim.fn.winsaveview) + pane.view = { v.topline, v.topfill, v.leftcol, v.lnum, v.col } + pane.width = vim.api.nvim_win_get_width(win) + pane.height = vim.api.nvim_win_get_height(win) + end + result[side] = pane + end + end + return result + ]]) +end + +function M.contains(screen, side, text) + local rect = screen:exec( + [[ + local s = refresh_session() + local win = s and s[(...) .. '_win'] + if not win or not vim.api.nvim_win_is_valid(win) then return nil end + local p = vim.api.nvim_win_get_position(win) + return { p[1] + 1, p[2] + 1, vim.api.nvim_win_get_height(win), vim.api.nvim_win_get_width(win) } + ]], + { side } + ) + if not rect then + return false + end + for row = rect[1], math.min(screen.height, rect[1] + rect[3] - 1) do + if screen:text(row, rect[2], rect[4]):find(text, 1, true) then + return true + end + end + return false +end + +function M.expect_text(screen, side, text) + screen:await(function() + M.assert_no_errors(screen) + return M.contains(screen, side, text) + end, side .. " grid never showed " .. text) +end + +-- Check stability throughout an observation window, not just at its last frame. +function M.preserved(screen, expected, duration) + local finish = (vim.uv or vim.loop).hrtime() + (duration or 800) * 1e6 + repeat + M.assert_no_errors(screen) + assert.same(expected, M.panes(screen), "unrelated refresh changed the active view") + vim.wait(20) + until (vim.uv or vim.loop).hrtime() >= finish + M.idle(screen) + assert.same(expected, M.panes(screen)) +end + +-- Freeze the visible pane rectangles and compare every naturally flushed frame. +-- Only the panel may change during a repository-list-only update. +function M.watch_grid(screen) + local rectangles = screen:exec([[ + local s, rectangles, seen = refresh_session(), {}, {} + for _, side in ipairs({ 'original', 'modified', 'result' }) do + local win = s[side .. '_win'] + if win and vim.api.nvim_win_is_valid(win) and not seen[win] then + seen[win] = true + local pos = vim.api.nvim_win_get_position(win) + rectangles[#rectangles + 1] = { pos[1] + 1, pos[2] + 1, vim.api.nvim_win_get_height(win), vim.api.nvim_win_get_width(win) } + end + end + return rectangles + ]]) + local function cells() + local result = {} + for _, rect in ipairs(rectangles) do + for row = rect[1], rect[1] + rect[3] - 1 do + for col = rect[2], rect[2] + rect[4] - 1 do + result[#result + 1] = { screen.grid[row][col][1], screen:highlight(row, col) } + end + end + end + return result + end + local expected, changed = vim.deepcopy(cells()), false + screen.on_flush = function() + changed = changed or not vim.deep_equal(expected, cells()) + end + return function() + screen.on_flush = nil + assert.is_false(changed, "a repository-only refresh changed rendered diff cells") + assert.same(expected, cells()) + end +end + +function M.select(screen, filename) + screen:exec( + [[ + local panel = refresh_session().panel.view + vim.api.nvim_set_current_win(panel.winid) + for row, text in ipairs(vim.api.nvim_buf_get_lines(panel.bufnr, 0, -1, false)) do + if text:find((...), 1, true) then + vim.api.nvim_win_set_cursor(panel.winid, { row, 0 }) + return + end + end + error('file is absent from the rendered panel') + ]], + { filename } + ) + M.feed(screen, "") +end + +-- Delay delivery, not the actual Git read, to put user actions between request +-- and response. Repository notifications still come from the real transport. +function M.hold_content(screen, path) + screen:exec( + [[ + local path = ... + local git = require('codediff.core.git') + local get = git.get_file_content + refresh_test.held = {} + refresh_test.hold = true + git.get_file_content = function(revision, root, filename, done) + return get(revision, root, filename, function(err, value) + if refresh_test.hold and filename == path then + refresh_test.held[#refresh_test.held + 1] = function() done(err, value) end + else done(err, value) end + end) + end + ]], + { path } + ) +end + +function M.release_content(screen) + screen:exec([[ + refresh_test.hold = false + local held = refresh_test.held + refresh_test.held = {} + for _, done in ipairs(held) do done() end + ]]) +end + +function M.feed(screen, keys) + screen:exec("refresh_test.keys_done = false") + screen:input(keys .. "lua refresh_test.keys_done = true") + screen:await(function() + return screen:exec("return refresh_test.keys_done") + end, "keys did not finish") +end + +return M diff --git a/tests/ui/refresh/lifecycle_e2e_spec.lua b/tests/ui/refresh/lifecycle_e2e_spec.lua new file mode 100644 index 00000000..1151cee0 --- /dev/null +++ b/tests/ui/refresh/lifecycle_e2e_spec.lua @@ -0,0 +1,214 @@ +local h = require("tests.ui.refresh.helpers") + +for _, backend in ipairs({ "native", "polling" }) do + for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("refresh lifecycle E2E " .. backend .. " / " .. layout, function() + local repo, other_repo, screen + before_each(function() + repo = h.repo() + screen = h.screen(backend, layout) + end) + after_each(function() + if screen then + screen:close() + screen = nil + end + if repo then + repo.cleanup() + repo = nil + end + if other_repo then + other_repo.cleanup() + other_repo = nil + end + end) + + local function write_a(text) + repo.write_file("a.txt", { "start", text, "context", "end", "tail" }) + end + local function open_staged() + write_a("staged-A") + repo.write_file("b.txt", { "start", "staged-B", "end" }) + repo.git("add a.txt b.txt") + h.open(screen, repo, "CodeDiff --staged") + end + local function wait_held() + screen:await(function() + return screen:exec("return #refresh_test.held > 0") + end, "no real Git response was held") + end + + it("discards a late refresh after selecting another file, then keeps refreshing", function() + open_staged() + h.hold_content(screen, "a.txt") + write_a("late-A") + repo.git("add a.txt") + wait_held() + h.select(screen, "b.txt") + h.expect_text(screen, "modified", "staged-B") + h.release_content(screen) + h.idle(screen) + assert.equals("base-B", h.panes(screen).original.lines[2]) + assert.equals("staged-B", h.panes(screen).modified.lines[2]) + repo.write_file("b.txt", { "start", "latest-B", "end" }) + repo.git("add b.txt") + h.expect_text(screen, "modified", "latest-B") + end) + + it("ignores delayed Git responses after closing their tab", function() + open_staged() + h.hold_content(screen, "a.txt") + write_a("late-A") + repo.git("add a.txt") + wait_held() + screen:command("tabclose!") + h.release_content(screen) + vim.wait(700) + h.assert_no_errors(screen) + assert.is_nil(screen:exec("return refresh_session()")) + end) + + it("retires a pending refresh after a pane buffer is wiped and can open another file", function() + open_staged() + h.hold_content(screen, "a.txt") + write_a("late-A") + repo.git("add a.txt") + wait_held() + screen:exec([[ + local s = refresh_session() + refresh_test.retired = s.refresh + vim.api.nvim_buf_delete(s.original_bufnr, { force = true }) + ]]) + h.release_content(screen) + screen:await(function() + return screen:exec("return refresh_test.retired.closed == true") + end, "wiped-buffer refresh was not retired") + h.assert_no_errors(screen) + assert.is_nil(screen:exec("return refresh_session()")) + h.open(screen, repo, "CodeDiff --staged -- b.txt", "b.txt") + h.expect_text(screen, "modified", "staged-B") + h.idle(screen) + repo.write_file("b.txt", { "start", "recovered-B", "end" }) + repo.git("add b.txt") + h.expect_text(screen, "modified", "recovered-B") + end) + + it("keeps buffer edits made while new index inputs are in flight", function() + write_a("index-A") + repo.git("add a.txt") + write_a("working-B") + h.open(screen, repo) + h.hold_content(screen, "a.txt") + write_a("index-C") + repo.git("add a.txt") + write_a("working-B") + wait_held() + screen:exec("vim.api.nvim_set_current_win(refresh_session().modified_win); vim.api.nvim_win_set_cursor(0, { 2, 0 })") + h.feed(screen, "ccUSER_LATEUSER_LATE_TWO") + h.release_content(screen) + h.idle(screen) + h.expect_text(screen, "modified", "USER_LATE_TWO") + assert.equals("index-C", h.panes(screen).original.lines[2]) + assert.same({ "start", "USER_LATE", "USER_LATE_TWO", "context", "end", "tail" }, h.panes(screen).modified.lines) + assert.equals(4, screen:exec("return refresh_session().stored_diff_result.changes[1].modified.end_line")) + end) + + it("keeps the requested HEAD dependency when following a different working file", function() + write_a("working-A") + repo.write_file("b.txt", { "start", "working-B", "end" }) + h.open(screen, repo, "CodeDiff file HEAD") + screen:exec( + [[ + vim.api.nvim_set_current_win(refresh_session().modified_win) + vim.cmd('edit ' .. vim.fn.fnameescape((...) .. '/b.txt')) + ]], + { repo.dir } + ) + screen:await(function() + return screen:exec("return refresh_session().modified.relative == 'b.txt' and refresh_session().stored_diff_result ~= nil") + end, "working-file follow did not settle") + repo.git("add b.txt") + repo.git("commit -m next-B") + screen:await(function() + return h.panes(screen).original.lines[2] == "working-B" + end, "file follow pinned HEAD to the opening SHA") + end) + + it("watches the new repository after following a file across repository roots", function() + other_repo = h.repo() + other_repo.write_file("b.txt", { "start", "other-base", "end" }) + other_repo.git("commit -am other-base") + other_repo.write_file("b.txt", { "start", "other-working", "end" }) + write_a("working-A") + h.open(screen, repo, "CodeDiff file HEAD") + screen:exec( + [[ + vim.api.nvim_set_current_win(refresh_session().modified_win) + vim.cmd('edit ' .. vim.fn.fnameescape((...) .. '/b.txt')) + ]], + { other_repo.dir } + ) + screen:await(function() + return screen:exec("return refresh_session().git_root == (...) and refresh_session().stored_diff_result ~= nil", { other_repo.dir }) + end, "working-file follow did not switch repositories") + h.idle(screen) + assert.equals("other-base", h.panes(screen).original.lines[2]) + other_repo.write_file("b.txt", { "start", "other-next", "end" }) + h.expect_text(screen, "modified", "other-next") + end) + + it("updates diff content while its Explorer panel is hidden", function() + write_a("working-A") + h.open(screen, repo) + screen:exec("require('codediff.ui.view.actions.panes').toggle_explorer({ tabpage = refresh_test.tab })") + assert.is_true(screen:exec("return refresh_session().panel.view.is_hidden")) + write_a("working-B") + repo.write_file("added.txt", { "new" }) + h.expect_text(screen, "modified", "working-B") + screen:exec("require('codediff.ui.view.actions.panes').toggle_explorer({ tabpage = refresh_test.tab })") + screen:await(function() + return screen:exec([[ + local panel = refresh_session().panel.view + return table.concat(vim.api.nvim_buf_get_lines(panel.bufnr, 0, -1, false), '\n'):find('added.txt', 1, true) ~= nil + ]]) + end, "hidden-panel changes were lost") + end) + + it("shares repository events across tabs and survives closing one subscriber", function() + write_a("working-A") + repo.write_file("b.txt", { "start", "working-B", "end" }) + h.open(screen, repo) + local first = h.panes(screen).tab + screen:command("tabnew") + h.open(screen, repo, "CodeDiff -- b.txt", "b.txt") + local expected = h.panes(screen) + local before = h.checkpoint(screen) + write_a("next-A") + h.wait_event(screen, before) + h.preserved(screen, expected, 200) + screen:exec("refresh_test.tab = ...; vim.api.nvim_set_current_tabpage(refresh_test.tab)", { first }) + h.expect_text(screen, "modified", "next-A") + screen:command("tabclose!") + screen:exec("refresh_test.tab = ...; vim.api.nvim_set_current_tabpage(refresh_test.tab)", { expected.tab }) + repo.write_file("b.txt", { "start", "next-B", "end" }) + h.expect_text(screen, "modified", "next-B") + end) + + if backend == "native" then + it("continues from the real watcher into polling after the process exits", function() + write_a("working-A") + h.open(screen, repo) + screen:exec([[ + assert(refresh_test.watcher_pid, 'watcher PID was not observed') + assert((vim.uv or vim.loop).kill(refresh_test.watcher_pid, 'sigterm')) + ]]) + screen:await(function() + return screen:exec("return refresh_test.fallback == true") + end, "watcher failure did not enable fallback") + write_a("after-watcher-exit") + h.expect_text(screen, "modified", "after-watcher-exit") + end) + end + end) + end +end diff --git a/tests/ui/refresh/refresh_e2e_spec.lua b/tests/ui/refresh/refresh_e2e_spec.lua new file mode 100644 index 00000000..a4bdb03c --- /dev/null +++ b/tests/ui/refresh/refresh_e2e_spec.lua @@ -0,0 +1,244 @@ +local h = require("tests.ui.refresh.helpers") + +for _, backend in ipairs({ "native", "polling" }) do + for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("refresh E2E " .. backend .. " / " .. layout, function() + local repo, screen + before_each(function() + repo = h.repo() + screen = h.screen(backend, layout) + end) + after_each(function() + if screen then + screen:close() + screen = nil + end + if repo then + repo.cleanup() + repo = nil + end + end) + + local function edit(text) + repo.write_file("a.txt", { "start", text, "context", "end", "tail" }) + end + local function open(command) + h.open(screen, repo, command) + end + local function unrelated() + local before = h.checkpoint(screen) + repo.write_file("background.txt", { "different" }) + h.wait_event(screen, before) + end + + it("updates unstaged contents even when status and line statistics stay the same", function() + edit("working-A") + open() + h.expect_text(screen, "modified", "working-A") + edit("working-B") + h.expect_text(screen, "modified", "working-B") + assert.equals("working-B", h.panes(screen).modified.lines[2]) + end) + + it("does not replace buffers or move the cursor for an unrelated worktree event", function() + edit("working-A") + open() + screen:exec("vim.api.nvim_win_set_cursor(refresh_session().modified_win, { 4, 0 })") + local expected = h.panes(screen) + unrelated() + h.preserved(screen, expected) + end) + + it("preserves unsaved working-buffer edits during unrelated notifications", function() + edit("working-A") + open() + screen:exec("vim.api.nvim_set_current_win(refresh_session().modified_win); vim.api.nvim_win_set_cursor(0, { 2, 0 })") + h.feed(screen, "ccUNSAVED") + h.expect_text(screen, "modified", "UNSAVED") + unrelated() + h.expect_text(screen, "modified", "UNSAVED") + assert.equals("UNSAVED", h.panes(screen).modified.lines[2]) + end) + + it("updates a staged view when the index blob changes", function() + edit("staged-A") + repo.git("add a.txt") + open("CodeDiff --staged") + h.expect_text(screen, "modified", "staged-A") + edit("staged-B") + repo.git("add a.txt") + h.expect_text(screen, "modified", "staged-B") + end) + + it("does not redraw a staged view for working-tree-only changes", function() + edit("staged-A") + repo.git("add a.txt") + open("CodeDiff --staged") + local expected = h.panes(screen) + local before = h.checkpoint(screen) + edit("not-staged") + h.wait_event(screen, before) + h.preserved(screen, expected) + end) + + it("switches an unstaged comparison's baseline after staging changes", function() + edit("index-A") + repo.git("add a.txt") + edit("working-B") + open() + assert.equals("index-A", h.panes(screen).original.lines[2]) + repo.git("reset HEAD -- a.txt") + screen:await(function() + local original = h.panes(screen).original + return original and original.lines[2] == "base-A" + end, "unstaged baseline did not return to HEAD") + h.expect_text(screen, "modified", "working-B") + end) + + it("refreshes a symbolic revision comparison when only its ref moves", function() + edit("branch-A") + repo.git("commit -am branch-A") + repo.git("branch review-base") + edit("branch-B") + repo.git("commit -am branch-B") + local next_revision = vim.trim(repo.git("rev-parse HEAD")) + repo.git("reset --hard " .. repo.base) + edit("working-C") + open("CodeDiff review-base") + assert.equals("branch-A", h.panes(screen).original.lines[2]) + repo.git("update-ref refs/heads/review-base " .. next_revision) + screen:await(function() + local original = h.panes(screen).original + return original and original.lines[2] == "branch-B" + end, "symbolic revision was treated as a fixed SHA") + end) + + it("keeps following a bare file comparison's symbolic ref after a layout toggle", function() + repo.git("branch review/topic") + edit("committed-next") + repo.git("commit -am next") + local next_revision = vim.trim(repo.git("rev-parse HEAD")) + repo.git("reset --hard " .. repo.base) + edit("working-A") + open("CodeDiff file review/topic") + screen:exec("require('codediff.ui.view').toggle_layout(refresh_test.tab)") + h.idle(screen) + repo.git("update-ref refs/heads/review/topic " .. next_revision) + h.expect_text(screen, "original", "committed-next") + end) + + it("follows HEAD in a bare file comparison after a new commit", function() + edit("working-A") + open("CodeDiff file HEAD") + repo.git("commit -am next") + screen:await(function() + return h.panes(screen).original.lines[2] == "working-A" + end, "bare HEAD comparison stayed pinned") + h.expect_text(screen, "modified", "working-A") + assert.equals(0, screen:exec("return #refresh_session().stored_diff_result.changes")) + end) + + it("refreshes two symbolic revisions without changing the selected file", function() + repo.git("branch left-ref") + edit("right-A") + repo.git("commit -am right-A") + repo.git("branch right-ref") + open("CodeDiff left-ref right-ref") + h.expect_text(screen, "modified", "right-A") + edit("right-B") + repo.git("commit -am right-B") + repo.git("update-ref refs/heads/right-ref HEAD") + h.expect_text(screen, "modified", "right-B") + end) + + it("keeps fixed revision comparisons untouched by worktree, index and HEAD changes", function() + edit("committed-A") + repo.git("commit -am change-A") + local changed = vim.trim(repo.git("rev-parse HEAD")) + open("CodeDiff " .. repo.base .. " " .. changed) + local expected = h.panes(screen) + local before = h.checkpoint(screen) + edit("committed-B") + repo.git("add a.txt") + repo.git("commit -m change-B") + h.wait_event(screen, before) + h.preserved(screen, expected) + end) + + it("updates untracked previews without replacing their windows or losing sizes", function() + repo.write_file("new.txt", { "start", "new-A", "end" }) + h.open(screen, repo, "CodeDiff -- new.txt", "new.txt") + local before = h.panes(screen) + repo.write_file("new.txt", { "start", "new-B", "end" }) + h.expect_text(screen, "modified", "new-B") + local after = h.panes(screen) + assert.equals(before.modified.buf, after.modified.buf) + assert.equals(before.modified.win, after.modified.win) + end) + + it("refreshes the visible deleted-file preview after HEAD moves", function() + edit("next-base") + repo.git("commit -am next") + local next_revision = vim.trim(repo.git("rev-parse HEAD")) + repo.git("reset --hard " .. repo.base) + repo.git("rm a.txt") + open("CodeDiff --staged") + h.expect_text(screen, "original", "base-A") + repo.git("update-ref refs/heads/main " .. next_revision) + h.expect_text(screen, "original", "next-base") + end) + + it("preserves manual folds and scrolled viewports on unrelated events", function() + local lines = {} + for i = 1, 100 do + lines[i] = "line " .. i + end + repo.write_file("a.txt", lines) + repo.git("commit -am long-file") + lines[40] = "working-A" + repo.write_file("a.txt", lines) + open() + screen:exec([[ + local win = refresh_session().modified_win + vim.api.nvim_set_current_win(win) + vim.wo[win].foldmethod = 'manual' + vim.cmd('10,20fold') + vim.api.nvim_win_set_cursor(win, { 40, 0 }) + ]]) + h.feed(screen, "zz") + h.idle(screen) + local expected = h.panes(screen) + local unchanged = h.watch_grid(screen) + unrelated() + h.preserved(screen, expected, 200) + assert.equals(10, screen:exec("return vim.api.nvim_win_call(refresh_session().modified_win, function() return vim.fn.foldclosed(10) end)")) + unchanged() + end) + + it("refreshes staged added-file previews when their index content changes", function() + repo.write_file("new.txt", { "start", "added-A", "end" }) + repo.git("add new.txt") + h.open(screen, repo, "CodeDiff --staged -- new.txt", "new.txt") + repo.write_file("new.txt", { "start", "added-B", "end" }) + repo.git("add new.txt") + h.expect_text(screen, "modified", "added-B") + end) + + it("refreshes history lists without reopening the selected historical diff", function() + edit("history-A") + repo.git("commit -am history-A") + open("CodeDiff history") + local expected = h.panes(screen) + edit("history-B") + repo.git("commit -am history-B") + screen:await(function() + return screen:exec([[ + local s = refresh_session() + return s.panel and s.panel.view.commits[1].subject == 'history-B' + ]]) + end, "new commit did not reach history") + h.preserved(screen, expected) + end) + end) + end +end From b8b1aebcc19219faab27d81b86f7d09ab140e88b Mon Sep 17 00:00:00 2001 From: Yanuo Ma <41042490+esmuellert@users.noreply.github.com> Date: Mon, 14 Sep 2026 01:34:37 -0400 Subject: [PATCH 5/8] refactor(refresh): centralize session data and view updates Move panel data, comparison definitions, Git reads, and selection ownership into the session refresh controller. Explorer and History consume data notifications instead of managing refresh and file-loading workflows. Remove legacy refresh adapters and reuse the existing view renderers for in-place comparison updates. Preserve watcher classifications, the 500ms polling fallback, and edited merge Results. Add six architecture regression cases, migrate existing tests to session-owned data, and document the shared refresh flow. Verified all 114 spec files on Neovim 0.13-dev, 124 refresh E2Es on Neovim 0.12.3, the native build, and all 10 C tests. --- .../05-architecture/auto-refresh-strategy.md | 37 +- lua/codediff/ui/auto_refresh.lua | 29 - lua/codediff/ui/conflict/resolution/block.lua | 10 +- .../ui/conflict/resolution/diffget.lua | 6 +- lua/codediff/ui/conflict/resolution/file.lua | 10 +- lua/codediff/ui/conflict/view/inputs.lua | 7 +- lua/codediff/ui/conflict/view/result.lua | 61 +- lua/codediff/ui/explorer/actions.lua | 69 +- lua/codediff/ui/explorer/init.lua | 8 +- lua/codediff/ui/explorer/keymaps.lua | 10 +- lua/codediff/ui/explorer/refresh/init.lua | 410 --------- .../ui/explorer/refresh/scheduler.lua | 25 - lua/codediff/ui/explorer/render.lua | 572 ++---------- lua/codediff/ui/explorer/tree.lua | 67 ++ lua/codediff/ui/history/init.lua | 6 - lua/codediff/ui/history/keymaps.lua | 3 +- lua/codediff/ui/history/refresh.lua | 87 -- lua/codediff/ui/history/render.lua | 788 ++++------------- lua/codediff/ui/lifecycle/cleanup.lua | 6 - lua/codediff/ui/lifecycle/session.lua | 8 +- lua/codediff/ui/refresh/apply.lua | 181 ---- lua/codediff/ui/refresh/init.lua | 310 ++++--- .../ui/refresh/{snapshot.lua => inputs.lua} | 82 +- lua/codediff/ui/refresh/panel.lua | 240 ++++++ lua/codediff/ui/refresh/policy.lua | 10 +- lua/codediff/ui/view/actions/diffget.lua | 8 +- lua/codediff/ui/view/actions/hunk.lua | 4 +- lua/codediff/ui/view/actions/stage.lua | 8 +- lua/codediff/ui/view/helpers.lua | 49 ++ lua/codediff/ui/view/init.lua | 50 ++ lua/codediff/ui/view/inline_view/buffers.lua | 2 +- lua/codediff/ui/view/inline_view/render.lua | 26 +- .../ui/view/inline_view/single_file.lua | 9 +- lua/codediff/ui/view/inline_view/update.lua | 4 +- lua/codediff/ui/view/panel.lua | 28 +- lua/codediff/ui/view/render.lua | 107 ++- lua/codediff/ui/view/toggle.lua | 13 +- tests/README.md | 5 +- tests/command_e2e_spec.lua | 10 +- tests/core/pull_request_spec.lua | 2 +- tests/module_loading_spec.lua | 33 +- tests/ui/auto_refresh_spec.lua | 16 +- .../ui/conflict/inline_tab_conflict_spec.lua | 29 +- tests/ui/explorer/explorer_refresh_spec.lua | 35 +- tests/ui/explorer/explorer_spec.lua | 24 +- tests/ui/explorer/explorer_staging_spec.lua | 812 +++++++++--------- .../ui/explorer/explorer_tree_render_spec.lua | 17 +- .../ui/explorer/file_select_branches_spec.lua | 2 - tests/ui/explorer/hunk_operations_spec.lua | 16 +- tests/ui/explorer/native_watcher_spec.lua | 60 +- tests/ui/explorer/refresh_keeps_view_spec.lua | 8 +- tests/ui/explorer/reselect_spec.lua | 5 +- tests/ui/explorer/stale_buffer_spec.lua | 21 +- tests/ui/explorer/toggle_staged_view_spec.lua | 22 +- .../ui/history/history_commit_files_spec.lua | 31 +- .../history/history_refresh_watcher_spec.lua | 9 +- tests/ui/refresh/policy_spec.lua | 6 +- tests/ui/refresh/refresh_e2e_spec.lua | 2 +- .../ui/view/cycle_hunks_across_files_spec.lua | 38 +- tests/ui/view/inline_interaction_spec.lua | 3 +- tests/ui/view/layout_toggle_spec.lua | 16 +- tests/ui/welcome_spec.lua | 8 +- 62 files changed, 1788 insertions(+), 2792 deletions(-) delete mode 100644 lua/codediff/ui/auto_refresh.lua delete mode 100644 lua/codediff/ui/explorer/refresh/init.lua delete mode 100644 lua/codediff/ui/explorer/refresh/scheduler.lua delete mode 100644 lua/codediff/ui/history/refresh.lua delete mode 100644 lua/codediff/ui/refresh/apply.lua rename lua/codediff/ui/refresh/{snapshot.lua => inputs.lua} (60%) create mode 100644 lua/codediff/ui/refresh/panel.lua diff --git a/docs/development/05-architecture/auto-refresh-strategy.md b/docs/development/05-architecture/auto-refresh-strategy.md index 4a542cfa..beff914b 100644 --- a/docs/development/05-architecture/auto-refresh-strategy.md +++ b/docs/development/05-architecture/auto-refresh-strategy.md @@ -1,6 +1,37 @@ -# VSCode Diff Highlighting Refresh Strategy - Investigation Report - -## Overview +# Refresh Strategy + +## Session-data refactor (#558) + +Repository watching, polling, invalidation coalescing and stale-result checks now +belong to `lua/codediff/ui/refresh/init.lua`. Explorer, History and diff views +consume data changes rather than managing independent refresh loops. + +- `session.panel.data` owns list data, query parameters and the selected file. + Panel views hold a reference to that data and receive `on_data(data, changes)` + notifications. They retain tree expansion, cursor and layout state locally. +- `refresh/panel.lua` reads status, commit lists and commit files, and derives + comparison definitions from selections. User selection goes through + `refresh.select`; a list update never asks the view to reselect an unchanged + comparison. +- `refresh/inputs.lua` reads the session's explicit input definitions, waits for + every candidate and validates working-buffer ticks. It does not inspect panels. +- The controller publishes only actual input changes to `view/render.lua`. + Initial rendering and in-place updates share diff rendering; merge input and + Result rendering remain in `conflict/view/`. Working and Result buffers stay + authoritative for user edits. + +Removed the `auto_refresh` entry point, Explorer scheduler and per-panel refresh +modules. The former `refresh/apply.lua` responsibilities now live in the existing +view helpers and renderers; there is no separate refresh rendering pipeline. +Watcher categories remain intact, with a 500 ms polling fallback. Unchanged +inputs do not disturb the comparison, and changed merge inputs cannot overwrite +an edited Result. + +Regression coverage includes native watcher and polling screen-grid E2Es, data +ownership, presentation-only list updates, navigation, hunk actions and stale +callbacks. The investigation below records the earlier VSCode design reference. + +## Earlier investigation: VSCode Quick Diff VSCode uses a sophisticated system called "Quick Diff" (also known as "Dirty Diff") to display real-time diff decorations in the gutter and overview ruler. The implementation is found primarily in two files: - `quickDiffModel.ts` - Manages diff computation and change tracking - `quickDiffDecorator.ts` - Handles visual decorations in the editor diff --git a/lua/codediff/ui/auto_refresh.lua b/lua/codediff/ui/auto_refresh.lua deleted file mode 100644 index bba8eaa2..00000000 --- a/lua/codediff/ui/auto_refresh.lua +++ /dev/null @@ -1,29 +0,0 @@ --- Buffer-edit entry points for the session refresh controller. -local M = {} - -function M.trigger(bufnr) - require("codediff.ui.refresh").buffer_changed(bufnr) -end - --- Resolution commands need their Result highlights updated synchronously. -function M.refresh_result_now(bufnr) - local lifecycle = require("codediff.ui.lifecycle") - local tabpage = lifecycle.find_tabpage_by_buffer(bufnr) - local session = tabpage and lifecycle.get_session(tabpage) - if session and session.result_bufnr == bufnr then - require("codediff.ui.refresh.apply").result(session) - end -end - -function M.sync_mutable_buffers(tabpage, done) - require("codediff.ui.refresh").request(tabpage, { index = true }, done) -end - -function M.cleanup_all() - local refresh = require("codediff.ui.refresh") - for tabpage in pairs(require("codediff.ui.lifecycle.session").get_active_diffs()) do - refresh.dispose(tabpage) - end -end - -return M diff --git a/lua/codediff/ui/conflict/resolution/block.lua b/lua/codediff/ui/conflict/resolution/block.lua index ad494020..3a57d9eb 100644 --- a/lua/codediff/ui/conflict/resolution/block.lua +++ b/lua/codediff/ui/conflict/resolution/block.lua @@ -2,7 +2,7 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") +local refresh = require("codediff.ui.refresh") local tracking = require("codediff.ui.conflict.tracking") local gutter = require("codediff.ui.conflict.gutter") local apply_to_result = require("codediff.ui.conflict.resolution.replace").apply_to_result @@ -58,7 +58,7 @@ function M.accept_incoming(tabpage) apply_to_result(result_bufnr, block, incoming_lines, base_lines) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) return true end @@ -108,7 +108,7 @@ function M.accept_current(tabpage) apply_to_result(result_bufnr, block, current_lines, base_lines) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) return true end @@ -170,7 +170,7 @@ function M.accept_both(tabpage) apply_to_result(result_bufnr, block, combined, base_lines) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) return true end @@ -232,7 +232,7 @@ function M.discard(tabpage) -- content-search fallback, so pass the Result seed (auto-merged content). apply_to_result(result_bufnr, block, base_content, session.result_base_lines or base_lines) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) return true end diff --git a/lua/codediff/ui/conflict/resolution/diffget.lua b/lua/codediff/ui/conflict/resolution/diffget.lua index 8b92d413..d7056ac2 100644 --- a/lua/codediff/ui/conflict/resolution/diffget.lua +++ b/lua/codediff/ui/conflict/resolution/diffget.lua @@ -2,7 +2,7 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") +local refresh = require("codediff.ui.refresh") local tracking = require("codediff.ui.conflict.tracking") local gutter = require("codediff.ui.conflict.gutter") @@ -106,7 +106,7 @@ function M.diffget_incoming(tabpage) apply_to_result(result_bufnr, block, incoming_lines, base_lines) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) return true end @@ -154,7 +154,7 @@ function M.diffget_current(tabpage) apply_to_result(result_bufnr, block, current_lines, base_lines) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) return true end diff --git a/lua/codediff/ui/conflict/resolution/file.lua b/lua/codediff/ui/conflict/resolution/file.lua index 84885faa..f14259c4 100644 --- a/lua/codediff/ui/conflict/resolution/file.lua +++ b/lua/codediff/ui/conflict/resolution/file.lua @@ -2,7 +2,7 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") +local refresh = require("codediff.ui.refresh") local tracking = require("codediff.ui.conflict.tracking") local gutter = require("codediff.ui.conflict.gutter") local apply_to_result = require("codediff.ui.conflict.resolution.replace").apply_to_result @@ -48,7 +48,7 @@ function M.accept_all_incoming(tabpage) end) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) vim.notify(string.format("[codediff] Accepted %d incoming change(s)", count), vim.log.levels.INFO) return count > 0 end @@ -92,7 +92,7 @@ function M.accept_all_current(tabpage) end) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) vim.notify(string.format("[codediff] Accepted %d current change(s)", count), vim.log.levels.INFO) return count > 0 end @@ -150,7 +150,7 @@ function M.accept_all_both(tabpage, first_input) end) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) vim.notify(string.format("[codediff] Accepted %d combined change(s)", count), vim.log.levels.INFO) return count > 0 end @@ -201,7 +201,7 @@ function M.discard_all(tabpage) end) gutter.refresh(session) - auto_refresh.refresh_result_now(result_bufnr) + refresh.refresh_result_now(result_bufnr) vim.notify(string.format("[codediff] Reset %d conflict(s) to base", count), vim.log.levels.INFO) return count > 0 end diff --git a/lua/codediff/ui/conflict/view/inputs.lua b/lua/codediff/ui/conflict/view/inputs.lua index 53acc212..4139b077 100644 --- a/lua/codediff/ui/conflict/view/inputs.lua +++ b/lua/codediff/ui/conflict/view/inputs.lua @@ -2,7 +2,6 @@ local M = {} local core = require("codediff.ui.core") -local config = require("codediff.config") local diff_module = require("codediff.core.diff") -- Conflict mode rendering: Both buffers show diff against base with alignment @@ -19,11 +18,7 @@ local diff_module = require("codediff.core.diff") -- @param auto_scroll_to_first_hunk boolean: Whether to scroll to first change -- @return table: { base_to_original_diff, base_to_modified_diff } function M.compute_and_render_conflict(original_buf, modified_buf, base_lines, original_lines, modified_lines, original_win, modified_win, auto_scroll_to_first_hunk) - local diff_options = { - max_computation_time_ms = config.options.diff.max_computation_time_ms, - ignore_trim_whitespace = config.options.diff.ignore_trim_whitespace, - compute_moves = config.options.diff.compute_moves, - } + local diff_options = require("codediff.ui.view.render").diff_options() -- Compute base -> original (incoming) diff local base_to_original_diff = diff_module.compute_diff(base_lines, original_lines, diff_options) diff --git a/lua/codediff/ui/conflict/view/result.lua b/lua/codediff/ui/conflict/view/result.lua index c831583f..da564ffb 100644 --- a/lua/codediff/ui/conflict/view/result.lua +++ b/lua/codediff/ui/conflict/view/result.lua @@ -35,6 +35,33 @@ local function create_center_layout(modified_win, original_win) return result_win end +-- Shared by initial construction and accepted changes to untouched merge inputs. +function M.set_inputs(session, base_lines, diffs) + local lines, blocks = require("codediff.ui.conflict.merge").compute_auto_merged_result( + diffs.base_to_original_diff, + diffs.base_to_modified_diff, + base_lines, + diffs.original_lines, + diffs.modified_lines + ) + require("codediff.ui.view.helpers").set_lines(session.result_bufnr, lines) + session.result_base_lines, session.merge_base_lines, session.conflict_blocks = lines, base_lines, blocks + require("codediff.ui.conflict").initialize_tracking(session.result_bufnr, blocks) +end + +function M.render(session) + if not session.result_bufnr or not vim.api.nvim_buf_is_valid(session.result_bufnr) or not session.result_base_lines then + return + end + local lines = vim.api.nvim_buf_get_lines(session.result_bufnr, 0, -1, false) + local options = require("codediff.ui.view.render").diff_options() + local result = require("codediff.core.diff").compute_diff(session.result_base_lines, lines, options) + if result then + require("codediff.ui.core").render_single_buffer(session.result_bufnr, result, "modified") + end + require("codediff.ui.conflict").refresh(session) +end + -- Common logic: Setup conflict result window -- Creates the result window layout and loads the real file with BASE content -- @param tabpage number: Current tabpage @@ -95,28 +122,6 @@ function M.setup_conflict_result_window(tabpage, session_config, original_win, m result_bufnr = vim.api.nvim_get_current_buf() - -- Compute the auto-merged result: BASE + every non-conflicting change from - -- both sides applied. Only true two-sided conflicts remain as BASE for the - -- user to resolve. This matches VSCode's MergeEditorModel.computeAutoMergedResult. - -- conflict_diffs.conflict_blocks (from compute_merge_fillers_and_conflicts) is - -- the visual filler list for the side panes; the Result-buffer-oriented blocks - -- (with result_range) come from compute_auto_merged_result. - local merge_alignment = require("codediff.ui.conflict.merge") - local result_lines, result_conflict_blocks = merge_alignment.compute_auto_merged_result( - conflict_diffs.base_to_original_diff, - conflict_diffs.base_to_modified_diff, - base_lines, - conflict_diffs.original_lines, - conflict_diffs.modified_lines - ) - - -- Replace the result buffer (which currently contains the raw file with - -- `<<<<<<<`/`=======`/`>>>>>>>` markers) with the auto-merged content. - -- We always replace in the conflict path so the markers never persist into - -- a manual save. - vim.api.nvim_buf_set_lines(result_bufnr, 0, -1, false, result_lines) - vim.bo[result_bufnr].modified = true - -- Set window options for result vim.wo[result_win].wrap = false vim.wo[result_win].cursorline = true @@ -128,14 +133,8 @@ function M.setup_conflict_result_window(tabpage, session_config, original_win, m -- Update lifecycle with result buffer/window FIRST -- (This must happen before setting winbar so ensure_no_winbar knows we're in conflict mode) lifecycle.set_result(tabpage, result_bufnr, result_win) - -- result_base_lines is the seed of the Result buffer (the auto-merged - -- content), used by is_block_active to decide whether a conflict region is - -- still in its initial unresolved state. merge_base_lines keeps the true - -- merge base (stage :1) for operations that need merge-base coordinates - -- such as accept_both's smart-combine and discard. - lifecycle.set_result_base_lines(tabpage, result_lines) - lifecycle.set_merge_base_lines(tabpage, base_lines) - lifecycle.set_conflict_blocks(tabpage, result_conflict_blocks) + M.set_inputs(lifecycle.get_session(tabpage), base_lines, conflict_diffs) + vim.bo[result_bufnr].modified = true lifecycle.track_conflict_file(tabpage, abs_path) -- Arrange all windows now that lifecycle knows about result_win @@ -160,9 +159,7 @@ function M.setup_conflict_result_window(tabpage, session_config, original_win, m end end - -- Initialize conflict tracking (keymaps setup separately after setup_all_keymaps) local conflict = require("codediff.ui.conflict") - conflict.initialize_tracking(result_bufnr, conflict_diffs.conflict_blocks) conflict.attach_gutter(original_win, modified_win) -- Setup autocmd to refresh markers when the result buffer changes. diff --git a/lua/codediff/ui/explorer/actions.lua b/lua/codediff/ui/explorer/actions.lua index e4fbadc2..f06175d5 100644 --- a/lua/codediff/ui/explorer/actions.lua +++ b/lua/codediff/ui/explorer/actions.lua @@ -3,7 +3,7 @@ local M = {} local config = require("codediff.config") local git = require("codediff.core.git") -local refresh_module = require("codediff.ui.explorer.refresh") +local tree_module = require("codediff.ui.explorer.tree") local layout = require("codediff.ui.layout") -- Find line number for a file node by scanning the tree @@ -21,15 +21,14 @@ end -- Navigate to next file in explorer function M.navigate_next(explorer) - local all_files = refresh_module.get_all_files(explorer.tree) + local all_files = tree_module.get_all_files(explorer.tree) if #all_files == 0 then vim.notify("No files in explorer", vim.log.levels.WARN) return end - -- Use tracked current file path and group - local current_path = explorer.current_file_path - local current_group = explorer.current_file_group + local current_path = explorer.data.current_file_path + local current_group = explorer.data.current_file_group -- If no current path, select first file if not current_path then @@ -74,15 +73,14 @@ end -- Navigate to previous file in explorer function M.navigate_prev(explorer) - local all_files = refresh_module.get_all_files(explorer.tree) + local all_files = tree_module.get_all_files(explorer.tree) if #all_files == 0 then vim.notify("No files in explorer", vim.log.levels.WARN) return end - -- Use tracked current file path and group - local current_path = explorer.current_file_path - local current_group = explorer.current_file_group + local current_path = explorer.data.current_file_path + local current_group = explorer.data.current_file_group -- If no current path, select last file if not current_path then @@ -141,9 +139,7 @@ function M.toggle_visibility(explorer) explorer.split:show() explorer.is_hidden = false explorer.winid = explorer.split.winid - if explorer._request_auto_refresh then - explorer._request_auto_refresh() - end + require("codediff.ui.refresh").request(explorer.tabpage, { full = true }) vim.schedule(function() layout.arrange(tabpage) @@ -171,11 +167,8 @@ function M.toggle_view_mode(explorer) -- Update config config.options.explorer.view_mode = new_mode - -- View-mode change is client-only: git status is unchanged, so the async - -- refresh() path would hit the deep_equal skip introduced in #486 and - -- silently no-op. Rebuild synchronously from the cached status instead - -- (same pattern as toggle_group) so the new mode takes effect immediately. - refresh_module.rebuild_from_cache(explorer) + -- Presentation changes render the current data without requesting Git. + tree_module.rebuild(explorer) vim.notify("Explorer view: " .. new_mode, vim.log.levels.INFO) end @@ -197,18 +190,18 @@ function M.toggle_staged_view(explorer) if not explorer then return false end - if not explorer.git_root then + if not explorer.data.git_root then vim.notify("Toggle staged view only available in git mode", vim.log.levels.WARN) return false end -- Status Mode is the only mode with distinct staged/unstaged groups. - if explorer.base_revision or explorer.target_revision then + if explorer.data.base_revision or explorer.data.target_revision then vim.notify("Toggle staged view only available in Status Mode (:CodeDiff with no revision)", vim.log.levels.WARN) return false end - local current_path = explorer.current_file_path - local current_group = explorer.current_file_group + local current_path = explorer.data.current_file_path + local current_group = explorer.data.current_file_group if not current_path or not current_group then vim.notify("No file selected", vim.log.levels.WARN) @@ -220,7 +213,7 @@ function M.toggle_staged_view(explorer) end local target_group = (current_group == "staged") and "unstaged" or "staged" - local status_result = explorer.status_result or {} + local status_result = explorer.data.status_result or {} local target_list = status_result[target_group] or {} local target_file @@ -255,7 +248,7 @@ function M.toggle_staged_view(explorer) path = target_file.path, old_path = target_file.old_path, status = target_file.status, - git_root = explorer.git_root, + git_root = explorer.data.git_root, group = target_group, }) return true @@ -268,10 +261,8 @@ function M.toggle_group(explorer, group_name) end explorer.visible_groups[group_name] = not explorer.visible_groups[group_name] - -- Group visibility changed but git status did not: rebuild the tree - -- synchronously from the cached status so the hidden/shown group takes effect - -- immediately (navigation reads the tree, so this also keeps ]f/[f correct). - refresh_module.rebuild_from_cache(explorer) + -- Keep the tree and navigation in sync without refreshing repository data. + tree_module.rebuild(explorer) local state = explorer.visible_groups[group_name] and "shown" or "hidden" local label = ({ staged = "Staged Changes", unstaged = "Changes", conflicts = "Merge Changes" })[group_name] or group_name @@ -359,7 +350,7 @@ end -- Stage/unstage toggle for the selected entry in explorer (file or directory) function M.toggle_stage_entry(explorer, tree) - if not explorer or not explorer.git_root then + if not explorer or not explorer.data.git_root then vim.notify("Stage/unstage only available in git mode", vim.log.levels.WARN) return end @@ -376,25 +367,25 @@ function M.toggle_stage_entry(explorer, tree) -- Directory uses dir_path, not path local dir_path = node.data.dir_path if dir_path then - toggle_stage_directory(explorer.git_root, dir_path, group) + toggle_stage_directory(explorer.data.git_root, dir_path, group) end else -- File uses path local path = node.data.path if path then - M.toggle_stage_file(explorer.git_root, path, group) + M.toggle_stage_file(explorer.data.git_root, path, group) end end end -- Stage all files function M.stage_all(explorer) - if not explorer or not explorer.git_root then + if not explorer or not explorer.data.git_root then vim.notify("Stage all only available in git mode", vim.log.levels.WARN) return end - git.stage_all(explorer.git_root, function(err) + git.stage_all(explorer.data.git_root, function(err) if err then vim.schedule(function() vim.notify(err, vim.log.levels.ERROR) @@ -405,12 +396,12 @@ end -- Unstage all files function M.unstage_all(explorer) - if not explorer or not explorer.git_root then + if not explorer or not explorer.data.git_root then vim.notify("Unstage all only available in git mode", vim.log.levels.WARN) return end - git.unstage_all(explorer.git_root, function(err) + git.unstage_all(explorer.data.git_root, function(err) if err then vim.schedule(function() vim.notify(err, vim.log.levels.ERROR) @@ -421,7 +412,7 @@ end -- Restore/discard changes to the selected file or directory function M.restore_entry(explorer, tree) - if not explorer or not explorer.git_root then + if not explorer or not explorer.data.git_root then vim.notify("Restore only available in git mode", vim.log.levels.WARN) return end @@ -460,7 +451,7 @@ function M.restore_entry(explorer, tree) if choice == 1 then if is_untracked then -- Delete untracked file/directory - git.delete_untracked(explorer.git_root, entry_path, function(err) + git.delete_untracked(explorer.data.git_root, entry_path, function(err) if err then vim.schedule(function() vim.notify(err, vim.log.levels.ERROR) @@ -470,8 +461,8 @@ function M.restore_entry(explorer, tree) elseif is_directory then -- Directory may contain both tracked and untracked files -- Run git restore for tracked changes, then git clean for untracked - git.restore_file(explorer.git_root, entry_path, explorer.base_revision, function(restore_err) - git.delete_untracked(explorer.git_root, entry_path, function(clean_err) + git.restore_file(explorer.data.git_root, entry_path, explorer.data.base_revision, function(restore_err) + git.delete_untracked(explorer.data.git_root, entry_path, function(clean_err) if restore_err and clean_err then vim.schedule(function() vim.notify("Failed to restore: " .. restore_err, vim.log.levels.ERROR) @@ -481,7 +472,7 @@ function M.restore_entry(explorer, tree) end) else -- Restore tracked file - git.restore_file(explorer.git_root, entry_path, explorer.base_revision, function(err) + git.restore_file(explorer.data.git_root, entry_path, explorer.data.base_revision, function(err) if err then vim.schedule(function() vim.notify(err, vim.log.levels.ERROR) diff --git a/lua/codediff/ui/explorer/init.lua b/lua/codediff/ui/explorer/init.lua index 871c2a97..1c37d330 100644 --- a/lua/codediff/ui/explorer/init.lua +++ b/lua/codediff/ui/explorer/init.lua @@ -4,17 +4,11 @@ local M = {} -- Import submodules local render = require("codediff.ui.explorer.render") -local refresh = require("codediff.ui.explorer.refresh") local actions = require("codediff.ui.explorer.actions") -- Delegate to render module M.create = render.create -M.rerender_current = render.rerender_current -M.show_welcome_page = render.show_welcome_page - --- Delegate to refresh module -M.setup_auto_refresh = refresh.setup_auto_refresh -M.refresh = refresh.refresh +M.get_all_files = require("codediff.ui.explorer.tree").get_all_files -- Delegate to actions module M.navigate_next = actions.navigate_next diff --git a/lua/codediff/ui/explorer/keymaps.lua b/lua/codediff/ui/explorer/keymaps.lua index d3730d2f..6fb1a285 100644 --- a/lua/codediff/ui/explorer/keymaps.lua +++ b/lua/codediff/ui/explorer/keymaps.lua @@ -2,7 +2,7 @@ local config = require("codediff.config") local resolve = require("codediff.keymap.resolve") local actions_module = require("codediff.ui.explorer.actions") -local refresh_module = require("codediff.ui.explorer.refresh") +local refresh = require("codediff.ui.refresh") local tree_utils = require("codediff.ui.lib.tree_utils") local M = {} @@ -12,7 +12,7 @@ local M = {} function M.setup(explorer) local tree = explorer.tree local split = explorer.split - local git_root = explorer.git_root + local git_root = explorer.data.git_root local map_options = { noremap = true, silent = true, nowait = true } local explorer_keymaps = resolve.keymaps_for("explorer") @@ -135,11 +135,7 @@ function M.setup(explorer) -- Refresh explorer (R key) if explorer_keymaps.refresh then panel_map(explorer_keymaps.refresh, function() - if explorer._request_auto_refresh then - explorer._request_auto_refresh() - else - refresh_module.refresh(explorer) - end + refresh.request(explorer.tabpage, { full = true }) end, "Refresh explorer") end diff --git a/lua/codediff/ui/explorer/refresh/init.lua b/lua/codediff/ui/explorer/refresh/init.lua deleted file mode 100644 index aeb35402..00000000 --- a/lua/codediff/ui/explorer/refresh/init.lua +++ /dev/null @@ -1,410 +0,0 @@ --- Auto-refresh and refresh logic for explorer -local M = {} - -local config = require("codediff.config") -local tree_module = require("codediff.ui.explorer.tree") -local welcome = require("codediff.ui.welcome") -local scheduler = require("codediff.ui.explorer.refresh.scheduler") - --- Setup native repository watching with polling as startup/runtime fallback. -function M.setup_auto_refresh(explorer, tabpage) - return scheduler.setup(explorer, tabpage, M._refresh_once) -end - ---- Walk every group and directory node beneath `root_nodes`, calling `visit` ---- with the node and the key it is remembered by. ---- @param visit fun(node: table, key: string) -local function walk_collapsible(tree, root_nodes, visit) - local function walk(node) - if not node.data then - return - end - local node_type = node.data.type - if node_type ~= "group" and node_type ~= "directory" then - return - end - -- Directories are keyed by path, groups by name. - local key = node.data.path or node.data.name - if key then - visit(node, key) - end - if node:has_children() then - for _, child_id in ipairs(node:get_child_ids()) do - local child = tree:get_node(child_id) - if child then - walk(child) - end - end - end - end - - for _, node in ipairs(root_nodes) do - walk(node) - end -end - ---- Which collapsible nodes are collapsed, keyed for restoring later. -local function collect_collapsed_state(tree) - local collapsed = {} - walk_collapsible(tree, tree:get_nodes(), function(node, key) - if not node:is_expanded() then - collapsed[key] = true - end - end) - return collapsed -end - ---- Re-collapse whatever was collapsed before the tree was rebuilt. -local function restore_collapsed_state(tree, collapsed, root_nodes) - walk_collapsible(tree, root_nodes, function(node, key) - if collapsed[key] then - node:collapse() - end - end) -end - ---- The reviewed file's slot in its group, read off the status from before the ---- refresh. file_to_reselect needs it to find whatever takes that slot. ---- @param explorer table ---- @return number|nil -local function reviewed_file_index(explorer) - local group = explorer.current_file_group - if not group then - return nil - end - for i, f in ipairs((explorer.status_result or {})[group] or {}) do - if f.path == explorer.current_file_path then - return i - end - end - return nil -end - ---- Forget which file was being reviewed, panel selection included. ---- @param explorer table -local function clear_current_file(explorer) - explorer.current_file_path = nil - explorer.current_file_group = nil - explorer.current_selection = nil - if explorer.clear_selection then - explorer.clear_selection() - end -end - ---- Which file the explorer should show after a refresh, and in which group. ---- ---- Prefer the same group the reviewer was in: hunk staging leaves the file ---- where it was. When the file left that group entirely -- fully staged or ---- unstaged -- take whatever now occupies its slot there, so staging walks ---- down the unstaged list instead of chasing the file into the staged one ---- (#347). Only if the group has nothing left does the search follow the file. ---- ---- @param explorer table ---- @param status_result table ---- @param prev_index number? The file's slot in its group before the refresh ---- @return table|nil file, string|nil group -local function file_to_reselect(explorer, status_result, prev_index) - local group_lists = { - unstaged = status_result.unstaged, - staged = status_result.staged, - conflicts = status_result.conflicts, - } - local current_group = explorer.current_file_group - - local function search(files, group_name) - for _, f in ipairs(files or {}) do - if f.path == explorer.current_file_path then - return f, group_name - end - end - return nil, nil - end - - if current_group then - local found, group = search(group_lists[current_group], current_group) - if found then - return found, group - end - end - - if current_group and prev_index then - local same_group = group_lists[current_group] - if same_group and #same_group > 0 then - return same_group[math.min(prev_index, #same_group)], current_group - end - end - - for _, group_name in ipairs({ "conflicts", "unstaged", "staged" }) do - local found, group = search(status_result[group_name], group_name) - if found then - return found, group - end - end - - return nil, nil -end - --- Rebuild the explorer tree from a status_result and re-render, honoring the --- current group visibility. Runs synchronously (no vim.schedule), so callers in --- a normal context — e.g. toggling a group — get an immediately consistent tree. -local function rebuild_tree(explorer, status_result, collapsed_state) - local root_nodes = tree_module.create_tree_data(status_result, explorer.git_root, explorer.base_revision, not explorer.git_root, explorer.visible_groups) - - -- Expand all groups - for _, node in ipairs(root_nodes) do - node:expand() - end - - -- Update tree - explorer.tree:set_nodes(root_nodes) - - -- For tree mode, expand directories after setting nodes - local explorer_config = config.options.explorer or {} - if explorer_config.view_mode == "tree" then - local function expand_all_dirs(parent_node) - if not parent_node:has_children() then - return - end - for _, child_id in ipairs(parent_node:get_child_ids()) do - local child = explorer.tree:get_node(child_id) - if child and child.data and child.data.type == "directory" then - child:expand() - expand_all_dirs(child) - end - end - end - for _, node in ipairs(root_nodes) do - expand_all_dirs(node) - end - end - - -- Restore user's collapsed state (must be after expand_all_dirs) - restore_collapsed_state(explorer.tree, collapsed_state, root_nodes) - - if not explorer.is_hidden then - explorer.tree:render() - end -end - --- Execute one explorer refresh. Public callers use M.refresh below. -function M._refresh_once(explorer, done) - local git = require("codediff.core.git") - local completed = false - local function complete(err) - if completed then - return - end - completed = true - if done then - done(err) - end - end - - -- A hidden panel still supplies status and comparison definitions. - if not explorer.is_hidden and not vim.api.nvim_win_is_valid(explorer.winid) then - complete() - return - end - - -- Collect collapsed state before async operation - local collapsed_state = collect_collapsed_state(explorer.tree) - - local function process_result(err, status_result) - vim.schedule(function() - local lifecycle = require("codediff.ui.lifecycle") - if lifecycle.get_panel_view(explorer.tabpage) ~= explorer or (not explorer.is_hidden and not vim.api.nvim_win_is_valid(explorer.winid)) then - complete() - return - end - - if err then - complete(err) - return - end - - -- Panel equality does not suppress the controller's input inspection. - if vim.deep_equal(status_result, explorer.status_result) then - complete() - return - end - - -- Rebuild tree nodes (honors group visibility) and re-render. - rebuild_tree(explorer, status_result, collapsed_state) - - -- Read before status_result is replaced below. - local prev_index = reviewed_file_index(explorer) - explorer.status_result = status_result - - local show_welcome_page = require("codediff.ui.explorer.render").show_welcome_page - - -- Show welcome page when all files are clean (skip if already showing) - local total_files = #(status_result.unstaged or {}) + #(status_result.staged or {}) + #(status_result.conflicts or {}) - if total_files == 0 then - local session = lifecycle.get_session(explorer.tabpage) - local already_welcome = session and welcome.is_welcome_buffer(session.modified_bufnr) - clear_current_file(explorer) - if not already_welcome then - show_welcome_page(explorer) - end - end - - -- Re-select the currently viewed file after refresh. - -- Search all file children across all groups for the current file. - -- If found (possibly in a new group), call on_file_select to update diff panes. - -- If not found (committed/removed), show welcome page. - if explorer.current_file_path and total_files > 0 then - local found_file, found_group = file_to_reselect(explorer, status_result, prev_index) - if found_file then - local selected = explorer.current_selection - if - not selected - or selected.path ~= found_file.path - or selected.group ~= found_group - or selected.status ~= found_file.status - or selected.old_path ~= found_file.old_path - then - explorer.on_file_select({ - path = found_file.path, - old_path = found_file.old_path, - status = found_file.status, - git_root = explorer.git_root, - group = found_group, - }, { no_jump = true }) - end - else - -- Committed or removed. - clear_current_file(explorer) - show_welcome_page(explorer) - end - end - complete() - end) - end - - local function fetch_status() - -- Use appropriate function based on mode - if not explorer.git_root then - -- Dir mode: re-scan directories - local dir_mod = require("codediff.core.dir") - local diff = dir_mod.diff_directories(explorer.dir1, explorer.dir2) - process_result(nil, diff.status_result) - elseif explorer.target_revision == ":0" then - -- Staged-only mode (--staged): index vs base_revision. `git diff base :0` - -- isn't a valid rev-pair; use `git diff --cached base` instead. - git.get_diff_staged(explorer.base_revision, explorer.git_root, process_result, explorer.pathspec) - elseif explorer.base_revision and explorer.target_revision and explorer.target_revision ~= "WORKING" then - git.get_diff_revisions_with_line_stats(explorer.base_revision, explorer.target_revision, explorer.git_root, process_result, explorer.pathspec) - elseif explorer.base_revision then - git.get_diff_revision_with_line_stats(explorer.base_revision, explorer.git_root, process_result, explorer.pathspec) - else - git.get_status_with_line_stats(explorer.git_root, process_result, explorer.pathspec) - end - end - - local requested = explorer.source_revisions - if not requested then - fetch_status() - return - end - local resolved, remaining, failure = {}, 1, nil - local function settled(err) - failure = failure or err - remaining = remaining - 1 - if remaining ~= 0 then - return - end - if failure then - complete(failure) - return - end - if require("codediff.ui.lifecycle").get_panel_view(explorer.tabpage) ~= explorer then - complete() - return - end - explorer.base_revision, explorer.target_revision = resolved.original, resolved.modified - fetch_status() - end - for side, revision in pairs(requested) do - remaining = remaining + 1 - if revision == "WORKING" or revision:match("^:[0-3]$") then - resolved[side] = revision - settled() - else - git.resolve_revision(revision, explorer.git_root, function(err, hash) - vim.schedule(function() - resolved[side] = hash - settled(err) - end) - end) - end - end - settled() -end - --- Queue every refresh source through the controller installed on the explorer. -function M.refresh(explorer, done) - if explorer and explorer._request_refresh then - return explorer._request_refresh({ full = true }, done) - end - return M._refresh_once(explorer, done) -end - --- Rebuild the tree synchronously from the cached status_result. Used when only --- group visibility changed (gs/gu): hiding or showing a group needs no new git --- data, so we re-render immediately from the last known status instead of --- waiting for an async git refresh. This keeps the tree — and navigation, which --- reads it — consistent the moment visibility toggles. -function M.rebuild_from_cache(explorer) - if not explorer or not explorer.winid or not vim.api.nvim_win_is_valid(explorer.winid) then - return - end - local status_result = explorer.status_result - if not status_result then - -- No cached status yet; fall back to a full (async) refresh. - M.refresh(explorer) - return - end - local collapsed_state = collect_collapsed_state(explorer.tree) - rebuild_tree(explorer, status_result, collapsed_state) -end - --- Get flat list of all files from tree (unstaged + staged) --- Handles both list mode (flat) and tree mode (nested directories) -function M.get_all_files(tree) - local files = {} - - -- Recursively collect files from a node and its children - local function collect_files(parent_node) - if not parent_node:has_children() then - return - end - if not parent_node:is_expanded() then - return - end - - for _, child_id in ipairs(parent_node:get_child_ids()) do - local node = tree:get_node(child_id) - if node and node.data then - if node.data.type == "directory" then - -- Recurse into directory (tree mode) - collect_files(node) - elseif not node.data.type then - -- It's a file (no type means file node) - table.insert(files, { - node = node, - data = node.data, - }) - end - end - end - end - - local nodes = tree:get_nodes() - for _, group_node in ipairs(nodes) do - collect_files(group_node) - end - - return files -end - -return M diff --git a/lua/codediff/ui/explorer/refresh/scheduler.lua b/lua/codediff/ui/explorer/refresh/scheduler.lua deleted file mode 100644 index e1da0264..00000000 --- a/lua/codediff/ui/explorer/refresh/scheduler.lua +++ /dev/null @@ -1,25 +0,0 @@ --- Explorer is a panel of the session refresh controller, not a second scheduler. -local M = {} - -function M.setup(explorer, tabpage, refresh_once) - local refresh = require("codediff.ui.refresh") - local unbind = refresh.bind_panel(tabpage, explorer, function(done) - refresh_once(explorer, done) - end) - explorer._request_refresh = function(event, done) - refresh.request(tabpage, event, done) - end - explorer._request_auto_refresh = function(message) - refresh.request(tabpage, message) - end - local function cleanup() - unbind() - explorer._request_refresh = nil - explorer._request_auto_refresh = nil - explorer._native_watcher_ready = nil - end - explorer._cleanup_auto_refresh = cleanup - return cleanup -end - -return M diff --git a/lua/codediff/ui/explorer/render.lua b/lua/codediff/ui/explorer/render.lua index 34b7079b..f38129d1 100644 --- a/lua/codediff/ui/explorer/render.lua +++ b/lua/codediff/ui/explorer/render.lua @@ -1,147 +1,15 @@ --- UI rendering for explorer (create split, tree, keymaps) +-- Explorer presentation. Repository data and file selection belong to the session. local M = {} - local Tree = require("codediff.ui.lib.tree") local Split = require("codediff.ui.lib.split") local config = require("codediff.config") -local path = require("codediff.core.path") local lifecycle = require("codediff.ui.lifecycle") local nodes_module = require("codediff.ui.explorer.nodes") local tree_module = require("codediff.ui.explorer.tree") local keymaps_module = require("codediff.ui.explorer.keymaps") -local refresh_module = require("codediff.ui.explorer.refresh") -local welcome = require("codediff.ui.welcome") - -local function should_show_welcome(explorer) - if not explorer or not explorer.git_root or explorer.dir1 or explorer.dir2 then - return false - end - - local status = explorer.status_result or {} - local total_files = #(status.unstaged or {}) + #(status.staged or {}) + #(status.conflicts or {}) - return total_files == 0 -end - -local function show_welcome_page(explorer) - local lifecycle = require("codediff.ui.lifecycle") - local session = lifecycle.get_session(explorer.tabpage) - if not session then - return false - end - - local mod_win = session.modified_win - if not mod_win or not vim.api.nvim_win_is_valid(mod_win) then - return false - end - - if session.layout == "inline" then - local welcome_buf = welcome.create_buffer(vim.api.nvim_win_get_width(mod_win), vim.api.nvim_win_get_height(mod_win)) - require("codediff.ui.view.inline_view").show_welcome(explorer.tabpage, welcome_buf) - return true - end - - local orig_win = session.original_win - local width = vim.api.nvim_win_get_width(mod_win) - local height = vim.api.nvim_win_get_height(mod_win) - if orig_win and vim.api.nvim_win_is_valid(orig_win) then - width = vim.api.nvim_win_get_width(orig_win) + width + 1 - height = vim.api.nvim_win_get_height(orig_win) - end - - local welcome_buf = welcome.create_buffer(width, height) - require("codediff.ui.view.side_by_side").show_welcome(explorer.tabpage, welcome_buf) - return true -end - ---- Open a two-sided diff on the next tick, unless the user has moved on. ---- view.update on a stale target swaps buffers under the newer one, destroys ---- codediff:// buffers mid-load (bufhidden=wipe), and resets single_pane. -local function open_diff_when_still_selected(ctx, sides) - vim.schedule(function() - if ctx.explorer.current_file_path ~= ctx.file_path or (ctx.selection and ctx.explorer._selection_generation ~= ctx.selection) then - return - end - ---@type SessionConfig - local session_config = { - git_root = ctx.git_root, - original = sides.original, - modified = sides.modified, - original_revision = sides.original_revision, - modified_revision = sides.modified_revision, - conflict = sides.conflict, - } - require("codediff.ui.view").update(ctx.tabpage, session_config, ctx.jump) - end) -end - ---- conflict_ours_position names where OURS sits on screen; original_win is on ---- the left after the conflict view's win_splitmove(rightbelow=false). ---- @return string original_rev, string modified_rev -local function conflict_revisions() - if (config.options.diff.conflict_ours_position or "right") == "right" then - return ":3", ":2" -- THEIRS left, OURS right - end - return ":2", ":3" -- OURS left, THEIRS right -end - ---- Whether `file_path` is staged, per the explorer's last status. ---- nil when there is no status to consult. ---- @return boolean|nil -local function has_staged_changes(explorer, file_path) - local status = explorer.status_result - if not status then - return nil - end - for _, staged_file in ipairs(status.staged or {}) do - if staged_file.path == file_path then - return true - end - end - return false -end - ---- True when the session already shows exactly this comparison. Opening it ---- again only repaints, and the repaint fires the next refresh: #317, #401. ---- @param group string "staged" | "unstaged" | "conflicts" ---- @return boolean -local function already_showing(session, explorer, file_path, abs_path, group) - local same_file = (session.modified and session.modified.absolute == abs_path) or (session.original and session.original.absolute == abs_path) - if not same_file or session.single_side then - return false - end - - -- :2/:3 are mutable, so the staged-base check below would see a change on - -- every refresh and rebuild forever. - if group == "conflicts" then - return session.result_win ~= nil and vim.api.nvim_win_is_valid(session.result_win) - end - - -- The two views compare against different things, so the same path is not - -- the same diff. - if (group == "staged") ~= (session.modified_revision == ":0") then - return false - end - if group == "staged" then - return true - end - - -- Unstaged compares against :0 once the file has staged content, HEAD before - -- that. No status to consult means nothing says the base moved. - local staged = has_staged_changes(explorer, file_path) - if staged == nil then - return true - end - local base_is_index = session.original_revision ~= nil and session.original_revision:match("^:[0-3]$") ~= nil - return staged == base_is_index -end - ---- Expand every directory node beneath `node`, recursively. local function expand_directories(tree, node) - if not node:has_children() then - return - end - for _, child_id in ipairs(node:get_child_ids()) do + for _, child_id in ipairs(node:get_child_ids() or {}) do local child = tree:get_node(child_id) if child and child.data and child.data.type == "directory" then child:expand() @@ -150,51 +18,16 @@ local function expand_directories(tree, node) end end ---- Run `show` on the next tick, unless the user has moved on. The explorer ---- fires a selection per cursor movement, so a slow open must not paint over ---- a newer one. ---- @param show fun(is_inline: boolean) -local function show_when_still_selected(explorer, file_path, show) - local generation = explorer._selection_generation - vim.schedule(function() - if explorer.current_file_path ~= file_path or explorer._selection_generation ~= generation then - return - end - local session = lifecycle.get_session(explorer.tabpage) - show(session ~= nil and session.layout == "inline") - end) -end - -function M.create(status_result, git_root, tabpage, width, base_revision, target_revision, opts) - opts = opts or {} - local is_dir_mode = not git_root -- nil git_root signals directory comparison mode - - -- Get explorer position and size from config - local explorer_config = config.options.explorer or {} - local position = explorer_config.position or "left" - local size - local text_width -- Width for text rendering (always horizontal width) - - if position == "bottom" then - size = explorer_config.height or 15 - -- For bottom position, use full window width for text - text_width = vim.o.columns - else - -- Use provided width or config width or default to 40 columns - size = width or explorer_config.width or 40 - text_width = size - end - - -- Create split window for explorer +function M.create(data, tabpage, width) + local options = config.options.explorer or {} + local position = options.position or "left" + local size = position == "bottom" and (options.height or 15) or (width or options.width or 40) + local text_width = position == "bottom" and vim.o.columns or size local split = Split({ relative = "editor", position = position, size = size, - buf_options = { - modifiable = false, - readonly = true, - filetype = "codediff-explorer", - }, + buf_options = { modifiable = false, readonly = true, filetype = "codediff-explorer" }, win_options = { number = false, relativenumber = false, @@ -208,366 +41,95 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target winfixheight = true, }, }) - - -- Mount split first to get bufnr split:mount() pcall(vim.api.nvim_buf_set_name, split.bufnr, "CodeDiff Explorer [" .. tabpage .. "]") - - -- Honor the initial-visibility config: hide the split immediately if requested. - -- toggle_explorer (actions.lua) uses split:hide/show to flip this at runtime; - -- using split:hide() here matches that lifecycle so the user's toggle keymap - -- continues to work correctly. - if explorer_config.hidden then + if options.hidden then split:hide() end - -- Track selected path and group for highlighting - local selected_path = nil - local selected_group = nil - - -- Create tree with buffer number - local tree_data = tree_module.create_tree_data(status_result, git_root, base_revision, is_dir_mode, explorer_config.visible_groups) + local explorer = { + data = data, + tabpage = tabpage, + split = split, + bufnr = split.bufnr, + winid = split.winid, + is_hidden = options.hidden, + visible_groups = vim.deepcopy(options.visible_groups or { staged = true, unstaged = true, conflicts = true }), + } + local tree_data = tree_module.create_tree_data(data.status_result, data.git_root, data.base_revision, not data.git_root, explorer.visible_groups) local tree = Tree({ bufnr = split.bufnr, nodes = tree_data, prepare_node = function(node) - -- Dynamically get current window width for responsive layout - local current_width = text_width - if split.winid and vim.api.nvim_win_is_valid(split.winid) then - current_width = vim.api.nvim_win_get_width(split.winid) - end - return nodes_module.prepare_node(node, current_width, selected_path, selected_group) + local current_width = split.winid and vim.api.nvim_win_is_valid(split.winid) and vim.api.nvim_win_get_width(split.winid) or text_width + local selected = explorer.data.current_selection or {} + return nodes_module.prepare_node(node, current_width, selected.path, selected.group) end, }) - - -- Expand all groups by default before first render - -- In tree mode, also expand all directories - -- get_child_ids returns IDs, need to get actual nodes + explorer.tree = tree for _, node in ipairs(tree_data) do if node.data and node.data.type == "group" then node:expand() end - end - - -- For tree mode, expand directories after initial render when we have node IDs - if explorer_config.view_mode == "tree" then - -- Directory nodes hang off the group nodes expanded above. - for _, node in ipairs(tree_data) do + if options.view_mode == "tree" then expand_directories(tree, node) end end - - -- Render tree tree:render() - -- Create explorer object early so we can reference it in keymaps - local explorer = { - split = split, - tree = tree, - bufnr = split.bufnr, - winid = split.winid, - git_root = git_root, - tabpage = tabpage, - dir1 = opts.dir1, - dir2 = opts.dir2, - base_revision = base_revision, - target_revision = target_revision, - source_revisions = opts.source_revisions, - pathspec = opts.pathspec, -- Scope (#74): re-applied on every auto-refresh - status_result = status_result, -- Store initial status result - on_file_select = nil, -- Will be set below - current_file_path = nil, -- Track currently selected file - current_file_group = nil, -- Track currently selected file's group (staged/unstaged) - current_selection = nil, -- Full file selection used to replay current state - is_hidden = explorer_config.hidden, -- Track visibility state - visible_groups = vim.deepcopy(explorer_config.visible_groups or { staged = true, unstaged = true, conflicts = true }), - } - - -- File selection callback - manages its own lifecycle - local function on_file_select(file_data, opts) - opts = opts or {} - local base_revision, target_revision = explorer.base_revision, explorer.target_revision - local git = require("codediff.core.git") - local view = require("codediff.ui.view") - local lifecycle = require("codediff.ui.lifecycle") - - local file_path = file_data.path - local old_path = file_data.old_path -- For renames: path in original revision - local group = file_data.group or "unstaged" - local jump = not opts.no_jump and config.options.diff.jump_to_first_change - - -- Emit CodeDiffFileSelect User autocmd - vim.api.nvim_exec_autocmds("User", { - pattern = "CodeDiffFileSelect", - modeline = false, - data = { - tabpage = tabpage, - path = file_path, - status = file_data.status, - }, - }) - - -- Dir mode: Compare files from dir1 vs dir2 (no git) - if is_dir_mode then - local original = path.make_ref(file_path, explorer.dir1) - local modified = path.make_ref(file_path, explorer.dir2) - - local session = lifecycle.get_session(tabpage) - local showing_already = session - and session.original - and session.modified - and session.original.absolute == original.absolute - and session.modified.absolute == modified.absolute - if showing_already and not opts.force then - require("codediff.ui.refresh").ready(tabpage) - return - end - - open_diff_when_still_selected({ - explorer = explorer, - tabpage = tabpage, - git_root = nil, - file_path = file_path, - jump = jump, - selection = explorer._selection_generation, - }, { original = original, modified = modified }) - return - end - - local abs_path = path.make_ref(file_path, git_root).absolute - - -- Handle untracked files: show file without diff - if file_data.status == "??" then - show_when_still_selected(explorer, file_data.path, function(is_inline) - if is_inline then - require("codediff.ui.view.inline_view").show_single_file(tabpage, abs_path, { side = "modified" }) - else - require("codediff.ui.view.side_by_side").show_untracked_file(tabpage, abs_path) - end - end) + explorer.on_data = function(value, changes) + explorer.data = value + if not vim.api.nvim_buf_is_valid(explorer.bufnr) then return end - - -- Handle added files: only one side has the file - if file_data.status == "A" then - -- Which revision holds an added file depends on where it was added. - local revision - if base_revision and target_revision and target_revision ~= "WORKING" then - revision = target_revision - elseif group == "staged" then - revision = ":0" - end - - show_when_still_selected(explorer, file_data.path, function(is_inline) - if not revision then - -- Added in the working tree: read it off disk. - if is_inline then - require("codediff.ui.view.inline_view").show_single_file(tabpage, abs_path, { side = "modified" }) - else - require("codediff.ui.view.side_by_side").show_untracked_file(tabpage, abs_path) - end - return - end - if is_inline then - require("codediff.ui.view.inline_view").show_single_file(tabpage, file_path, { - revision = revision, - git_root = git_root, - rel_path = file_path, - side = "modified", - }) - else - require("codediff.ui.view.side_by_side").show_added_virtual_file(tabpage, git_root, file_path, revision) - end - end) - return - end - - -- Handle deleted files: show old content without diff - if file_data.status == "D" then - -- With a base_revision (`:CodeDiff HEAD~5` or `:CodeDiff A B`) the - -- content lives there; HEAD and :0 yield nothing, the file is already - -- gone. HEAD/:0 is only right for a plain explorer. Fixes #390. - local revision = base_revision or ((group == "staged") and "HEAD" or ":0") - - show_when_still_selected(explorer, file_data.path, function(is_inline) - if is_inline then - require("codediff.ui.view.inline_view").show_single_file(tabpage, file_path, { - revision = revision, - git_root = git_root, - rel_path = file_path, - side = "original", - }) - elseif base_revision then - require("codediff.ui.view.side_by_side").show_deleted_virtual_file(tabpage, git_root, file_path, base_revision) - else - require("codediff.ui.view.side_by_side").show_deleted_file(tabpage, git_root, file_path, abs_path, group) - end - end) - return - end - - -- Check if this exact diff is already being displayed - -- Same file can have different diffs (staged vs HEAD, working vs staged) - local session = lifecycle.get_session(tabpage) - if session and not opts.force and already_showing(session, explorer, file_path, abs_path, group) then - require("codediff.ui.refresh").ready(tabpage) - return - end - - if base_revision and target_revision and target_revision ~= "WORKING" then - -- Two revision mode: Compare base vs target - local selection = explorer._selection_generation - vim.schedule(function() - -- Ignore stale async: see comment on the base_revision branch below. - if explorer.current_file_path ~= file_path or explorer._selection_generation ~= selection then - return - end - ---@type SessionConfig - local session_config = { - git_root = git_root, - original = path.make_ref(old_path or file_path, git_root), - modified = path.make_ref(file_path, git_root), - original_revision = base_revision, - modified_revision = target_revision, - } - view.update(tabpage, session_config, jump) - end) - return + if changes.list then + tree_module.rebuild(explorer) + elseif changes.selection and not explorer.is_hidden then + tree:render() end - - -- Use base_revision if provided, otherwise default to HEAD - local ctx = { - explorer = explorer, - tabpage = tabpage, - git_root = git_root, - file_path = file_path, - jump = jump, - selection = explorer._selection_generation, - } - - local target_revision_single = base_revision or "HEAD" - git.resolve_revision(target_revision_single, git_root, function(err_resolve, commit_hash) - if err_resolve then - vim.schedule(function() - vim.notify(err_resolve, vim.log.levels.ERROR) - end) - return - end - - if base_revision then - -- A renamed file is read from its old name, which is what it was - -- called at that revision. - open_diff_when_still_selected(ctx, { - original = path.make_ref(old_path or file_path, git_root), - modified = path.make_ref(abs_path, git_root), - original_revision = commit_hash, - }) - elseif group == "conflicts" then - local original_rev, modified_rev = conflict_revisions() - open_diff_when_still_selected(ctx, { - original = path.make_ref(file_path, git_root), - modified = path.make_ref(file_path, git_root), - original_revision = original_rev, - modified_revision = modified_rev, - conflict = true, - }) - elseif group == "staged" then - -- Index against HEAD. On a rename the two sides have different names. - open_diff_when_still_selected(ctx, { - original = path.make_ref(old_path or file_path, git_root), - modified = path.make_ref(file_path, git_root), - original_revision = commit_hash, - modified_revision = ":0", - }) - else - -- Working tree against the index when the file has staged content, - -- against HEAD when it does not. - local is_staged = false - for _, staged_file in ipairs((explorer.status_result or status_result).staged) do - if staged_file.path == file_path then - is_staged = true - break - end - end - - open_diff_when_still_selected(ctx, { - original = path.make_ref(file_path, git_root), - modified = path.make_ref(abs_path, git_root), - original_revision = is_staged and ":0" or commit_hash, - }) - end - end) end - - -- Wrap on_file_select to track current file and group - explorer.on_file_select = function(file_data, opts) - explorer._selection_generation = (explorer._selection_generation or 0) + 1 - require("codediff.ui.refresh").begin(tabpage) - explorer.current_file_path = file_data.path - explorer.current_file_group = file_data.group - explorer.current_selection = vim.deepcopy(file_data) - selected_path = file_data.path - selected_group = file_data.group - tree:render() - on_file_select(file_data, opts) - end - - -- Clear selection highlight (used when showing welcome page) - explorer.clear_selection = function() - selected_path = nil - selected_group = nil - tree:render() + explorer.on_file_select = function(file, opts) + return require("codediff.ui.refresh").select(tabpage, file, opts) end - - -- Setup keymaps (delegated to keymaps module) keymaps_module.setup(explorer) - -- Auto-open diff for the node under cursor after j/k (or arrow keys). - -- Hooks j/k// instead of CursorMoved so mouse clicks, :N jumps, - -- and scrolls don't trigger an open. Buffer-local keymaps die with the - -- buffer, so no manual cleanup needed. - if explorer_config.auto_open_on_cursor then + if options.auto_open_on_cursor then local function open_under_cursor() if not vim.api.nvim_buf_is_valid(split.bufnr) then return end local node = tree:get_node() - if not node or not node.data then + if not node or not node.data or node.data.type == "group" or node.data.type == "directory" then return end - local node_type = node.data.type - if node_type == "group" or node_type == "directory" then - return - end - if explorer.current_file_path == node.data.path and explorer.current_file_group == node.data.group then - return + local selected = explorer.data.current_selection or {} + if selected.path ~= node.data.path or selected.group ~= node.data.group then + explorer.on_file_select(node.data) end - explorer.on_file_select(node.data) end - local lifecycle = require("codediff.ui.lifecycle") for _, key in ipairs({ "j", "k", "", "" }) do - lifecycle.set_buf_keymap(explorer.tabpage, split.bufnr, "n", key, function() - local motion = key == "" and "j" or key == "" and "k" or key - vim.cmd("normal! " .. motion) + lifecycle.set_buf_keymap(tabpage, split.bufnr, "n", key, function() + vim.cmd("normal! " .. (key == "" and "j" or key == "" and "k" or key)) open_under_cursor() end, { silent = true, desc = "codediff: move and auto-open file" }, { suspendable = false }) end end - local visible_files = refresh_module.get_all_files(tree) - local initial_file - if opts.focus_file then - for _, file in ipairs(visible_files) do - if file.data.path == opts.focus_file then + local files = tree_module.get_all_files(tree) + local initial_file = files[1] + if data.focus_file then + for _, file in ipairs(files) do + if file.data.path == data.focus_file then initial_file = file break end end end - initial_file = initial_file or visible_files[1] - if initial_file then vim.schedule(function() + if lifecycle.get_panel_view(tabpage) ~= explorer then + return + end if explorer.winid and vim.api.nvim_win_is_valid(explorer.winid) and initial_file.node._line then vim.api.nvim_win_set_cursor(explorer.winid, { initial_file.node._line, 0 }) end @@ -575,51 +137,17 @@ function M.create(status_result, git_root, tabpage, width, base_revision, target end) end - -- Setup auto-refresh - refresh_module.setup_auto_refresh(explorer, tabpage) - - -- Re-render on window resize for dynamic width vim.api.nvim_create_autocmd("WinResized", { callback = function() - -- Check if explorer window was resized - local resized_wins = vim.v.event.windows or {} - for _, win in ipairs(resized_wins) do + for _, win in ipairs(vim.v.event.windows or {}) do if win == explorer.winid and vim.api.nvim_win_is_valid(win) then - explorer.tree:render() + tree:render() break end end end, }) - return explorer end -function M.rerender_current(explorer) - if not explorer then - return false - end - - if explorer.current_selection then - explorer.on_file_select(vim.deepcopy(explorer.current_selection), { force = true }) - return true - end - - local lifecycle = require("codediff.ui.lifecycle") - local session = lifecycle.get_session(explorer.tabpage) - if not session then - return false - end - - if should_show_welcome(explorer) and show_welcome_page(explorer) then - return true - end - - return false -end - -M.show_welcome_page = show_welcome_page - --- Setup auto-refresh on file save and focus - return M diff --git a/lua/codediff/ui/explorer/tree.lua b/lua/codediff/ui/explorer/tree.lua index e3ef7958..14f45a70 100644 --- a/lua/codediff/ui/explorer/tree.lua +++ b/lua/codediff/ui/explorer/tree.lua @@ -84,4 +84,71 @@ function M.create_tree_data(status_result, git_root, base_revision, is_dir_mode, end end +local function walk_collapsible(tree, visit) + local function walk(node) + if not node.data or node.data.type ~= "group" and node.data.type ~= "directory" then + return + end + local key = node.data.path or node.data.name + if key then + visit(node, key) + end + for _, id in ipairs(node:get_child_ids() or {}) do + local child = tree:get_node(id) + if child then + walk(child) + end + end + end + for _, node in ipairs(tree:get_nodes()) do + walk(node) + end +end + +-- Rebuild from supplied data, retaining the user's tree presentation state. +function M.rebuild(explorer) + local data, tree = explorer.data, explorer.tree + if not data.status_result then + return + end + local collapsed = {} + walk_collapsible(tree, function(node, key) + collapsed[key] = not node:is_expanded() + end) + tree:set_nodes(M.create_tree_data(data.status_result, data.git_root, data.base_revision, not data.git_root, explorer.visible_groups)) + walk_collapsible(tree, function(node, key) + if collapsed[key] then + node:collapse() + else + node:expand() + end + end) + if not explorer.is_hidden then + tree:render() + end +end + +function M.get_all_files(tree) + local files = {} + local function collect(parent) + if not parent:is_expanded() then + return + end + for _, id in ipairs(parent:get_child_ids() or {}) do + local node = tree:get_node(id) + if node and node.data then + if node.data.type == "directory" then + collect(node) + elseif not node.data.type then + files[#files + 1] = { node = node, data = node.data } + end + end + end + end + for _, node in ipairs(tree:get_nodes()) do + collect(node) + end + return files +end + return M diff --git a/lua/codediff/ui/history/init.lua b/lua/codediff/ui/history/init.lua index 9d71dc3c..75cbb346 100644 --- a/lua/codediff/ui/history/init.lua +++ b/lua/codediff/ui/history/init.lua @@ -11,7 +11,6 @@ local render = require("codediff.ui.history.render") -- width: optional width override -- opts: { range, path, ... } original options M.create = render.create -M.rerender_current = render.rerender_current -- Navigation (files within expanded commits) M.navigate_next = render.navigate_next @@ -27,9 +26,4 @@ M.toggle_visibility = render.toggle_visibility -- Get all files (for external navigation) M.get_all_files = render.get_all_files --- Refresh -local refresh = require("codediff.ui.history.refresh") -M.refresh = refresh.refresh -M.setup_auto_refresh = refresh.setup_auto_refresh - return M diff --git a/lua/codediff/ui/history/keymaps.lua b/lua/codediff/ui/history/keymaps.lua index 78d3390a..547c9fba 100644 --- a/lua/codediff/ui/history/keymaps.lua +++ b/lua/codediff/ui/history/keymaps.lua @@ -126,8 +126,7 @@ function M.setup(history, opts) -- Refresh (R key) - re-fetch commits if history_keymaps.refresh then panel_map(history_keymaps.refresh, function() - local refresh_module = require("codediff.ui.history.refresh") - refresh_module.refresh(history) + require("codediff.ui.refresh").request(history.tabpage, { full = true }) end, "Refresh history") end diff --git a/lua/codediff/ui/history/refresh.lua b/lua/codediff/ui/history/refresh.lua deleted file mode 100644 index 9df10bd5..00000000 --- a/lua/codediff/ui/history/refresh.lua +++ /dev/null @@ -1,87 +0,0 @@ --- History list updates share the session controller with the selected diff. -local M = {} -local git = require("codediff.core.git") -local render = require("codediff.ui.history.render") - -function M.setup_auto_refresh(history, tabpage) - local refresh = require("codediff.ui.refresh") - history.tabpage = tabpage - local unbind = refresh.bind_panel(tabpage, history, function(done) - M._refresh_once(history, done) - end) - history._cleanup_auto_refresh = unbind - return unbind -end - -function M._refresh_once(history, done) - done = done or function() end - local lifecycle = require("codediff.ui.lifecycle") - local function valid() - return lifecycle.get_panel_view(history.tabpage) == history and vim.api.nvim_buf_is_valid(history.bufnr) - end - if not valid() then - done() - return - end - local expanded = {} - for _, node in ipairs(history.tree:get_nodes() or {}) do - if node.data and node.data.type == "commit" and node:is_expanded() then - expanded[node.data.hash] = true - end - end - local opts = { no_merges = true, path = history.opts.file_path } - local range = history.opts.range or "" - if range == "" then - opts.limit = 100 - end - git.get_commit_list(range, history.git_root, opts, function(err, commits) - vim.schedule(function() - if not valid() then - done() - return - end - if err then - done(err) - return - end - if vim.deep_equal(commits, history.commits) then - done() - return - end - history.commits = commits - history.tree:set_nodes(render.build_tree_nodes(commits, history.git_root, history.opts)) - local remaining = 1 - local function loaded() - remaining = remaining - 1 - if remaining ~= 0 then - return - end - if valid() and not history.is_hidden then - history.tree:render() - if history.winid and vim.api.nvim_win_is_valid(history.winid) then - for _, node in ipairs(history.tree:get_nodes()) do - if node.data and node.data.hash == history.current_commit and node._line then - vim.api.nvim_win_set_cursor(history.winid, { node._line, 0 }) - break - end - end - end - end - done() - end - for _, node in ipairs(history.tree:get_nodes()) do - if node.data and node.data.type == "commit" and expanded[node.data.hash] and history._load_commit_files then - remaining = remaining + 1 - history._load_commit_files(node, loaded) - end - end - loaded() - end) - end) -end - -function M.refresh(history) - require("codediff.ui.refresh").request(history.tabpage, { full = true }) -end - -return M diff --git a/lua/codediff/ui/history/render.lua b/lua/codediff/ui/history/render.lua index 0c8d6ef3..41099085 100644 --- a/lua/codediff/ui/history/render.lua +++ b/lua/codediff/ui/history/render.lua @@ -1,66 +1,34 @@ --- UI rendering for file history panel (create split, tree, keymaps) +-- History presentation. Commit data is supplied by the session refresh controller. local M = {} - local Tree = require("codediff.ui.lib.tree") local Split = require("codediff.ui.lib.split") local config = require("codediff.config") -local git = require("codediff.core.git") -local path = require("codediff.core.path") local nodes_module = require("codediff.ui.history.nodes") local keymaps_module = require("codediff.ui.history.keymaps") local layout = require("codediff.ui.layout") --- Build tree nodes from commits list (shared between create and refresh) function M.build_tree_nodes(commits, git_root, opts) - local base_revision = opts and opts.base_revision - - -- Calculate max widths for alignment - local max_files = 0 - local max_insertions = 0 - local max_deletions = 0 + opts = opts or {} + local max_files, max_insertions, max_deletions = 0, 0, 0 for _, commit in ipairs(commits) do - if commit.files_changed > max_files then - max_files = commit.files_changed - end - if commit.insertions > max_insertions then - max_insertions = commit.insertions - end - if commit.deletions > max_deletions then - max_deletions = commit.deletions - end - end - local max_files_width = #tostring(max_files) - local max_ins_width = #tostring(max_insertions) - local max_del_width = #tostring(max_deletions) - - local tree_nodes = {} - - -- Build title based on context - local title_text - if opts and opts.file_path and opts.file_path ~= "" then - local filename = opts.file_path:match("([^/]+)$") or opts.file_path - title_text = "File History: " .. filename .. " (" .. #commits .. ")" - elseif opts and opts.range and opts.range ~= "" then - title_text = "Commit History: " .. opts.range .. " (" .. #commits .. ")" + max_files = math.max(max_files, commit.files_changed) + max_insertions = math.max(max_insertions, commit.insertions) + max_deletions = math.max(max_deletions, commit.deletions) + end + local title + if opts.file_path and opts.file_path ~= "" then + title = "File History: " .. (opts.file_path:match("([^/]+)$") or opts.file_path) .. " (" .. #commits .. ")" + elseif opts.range and opts.range ~= "" then + title = "Commit History: " .. opts.range .. " (" .. #commits .. ")" else - title_text = "Commit History (" .. #commits .. ")" + title = "Commit History (" .. #commits .. ")" end - - if base_revision then - title_text = title_text .. " [base: " .. base_revision .. "]" + if opts.base_revision then + title = title .. " [base: " .. opts.base_revision .. "]" end - - tree_nodes[#tree_nodes + 1] = Tree.Node({ - id = "title", - text = title_text, - data = { - type = "title", - title = title_text, - }, - }) - + local result = { Tree.Node({ id = "title", text = title, data = { type = "title", title = title } }) } for _, commit in ipairs(commits) do - tree_nodes[#tree_nodes + 1] = Tree.Node({ + result[#result + 1] = Tree.Node({ id = "commit:" .. commit.hash, text = commit.subject, data = { @@ -79,22 +47,18 @@ function M.build_tree_nodes(commits, git_root, opts) git_root = git_root, files_loaded = false, file_path = commit.file_path, - max_files_width = max_files_width, - max_ins_width = max_ins_width, - max_del_width = max_del_width, + max_files_width = #tostring(max_files), + max_ins_width = #tostring(max_insertions), + max_del_width = #tostring(max_deletions), }, }) end - - return tree_nodes + return result end ---- Expand every directory node under `node_ids`, recursively. ---- @param tree table ---- @param node_ids table -local function expand_directories(tree, node_ids) - for _, node_id in ipairs(node_ids) do - local node = tree:get_node(node_id) +local function expand_directories(tree, ids) + for _, id in ipairs(ids) do + local node = tree:get_node(id) if node and node.data and node.data.type == "directory" then node:expand() expand_directories(tree, node:get_child_ids() or {}) @@ -102,651 +66,269 @@ local function expand_directories(tree, node_ids) end end ---- First file node under `node_ids`, expanding directories on the way down. ---- @param tree table ---- @param node_ids table ---- @return table|nil -local function find_first_file(tree, node_ids) - for _, node_id in ipairs(node_ids) do - local node = tree:get_node(node_id) +local function find_first_file(tree, ids) + for _, id in ipairs(ids) do + local node = tree:get_node(id) if node and node.data then if node.data.type == "file" then return node elseif node.data.type == "directory" then node:expand() - local child_file = find_first_file(tree, node:get_child_ids() or {}) - if child_file then - return child_file + local first = find_first_file(tree, node:get_child_ids() or {}) + if first then + return first end end end end - return nil end --- Create file history panel --- commits: array of commit objects from git.get_commit_list --- git_root: absolute path to git repository root --- tabpage: tabpage handle --- width: optional width override --- opts: { range, path, ... } original options -function M.create(commits, git_root, tabpage, width, opts) - opts = opts or {} - local base_revision = opts.base_revision - local line_range = opts.line_range - - -- Get history panel position and size from config (separate from explorer) - local history_config = config.options.history or {} - local position = history_config.position or "bottom" - local size - local text_width - - if position == "bottom" then - size = history_config.height or 15 - text_width = vim.o.columns - else - size = width or history_config.width or 40 - text_width = size +-- Turn cached commit files into children; this function never fetches data. +local function render_files(history, node) + local files = history.data.files[node.data.hash] + if not files then + return + end + local tree = history.tree + for _, id in ipairs(node:get_child_ids() or {}) do + tree:remove_node(id) + end + local tree_mode = config.options.history.view_mode == "tree" + local create = tree_mode and nodes_module.create_tree_file_nodes or nodes_module.create_list_file_nodes + for _, child in ipairs(create(files, node.data.hash, history.data.git_root)) do + tree:add_node(child, node:get_id()) end + node.data.files_loaded, node.data.file_count = true, #files + if tree_mode then + expand_directories(tree, node:get_child_ids() or {}) + end +end - -- Create split window for history panel +function M.create(data, tabpage, width) + local opts = data.opts + local options = config.options.history or {} + local position = options.position or "bottom" + local size = position == "bottom" and (options.height or 15) or (width or options.width or 40) + local text_width = position == "bottom" and vim.o.columns or size local split = Split({ relative = "editor", position = position, size = size, - buf_options = { - modifiable = false, - readonly = true, - filetype = "codediff-history", - }, - win_options = { - number = false, - relativenumber = false, - cursorline = true, - wrap = false, - signcolumn = "no", - foldcolumn = "0", - statuscolumn = "", - spell = false, - }, + buf_options = { modifiable = false, readonly = true, filetype = "codediff-history" }, + win_options = { number = false, relativenumber = false, cursorline = true, wrap = false, signcolumn = "no", foldcolumn = "0", statuscolumn = "", spell = false }, }) - split:mount() pcall(vim.api.nvim_buf_set_name, split.bufnr, "CodeDiff History [" .. tabpage .. "]") - - -- Track selected commit and file - local selected_commit = nil - local selected_file = nil - - -- Check if single file mode - local is_single_file_mode = opts.file_path and opts.file_path ~= "" - - -- Build initial tree with commit nodes (files will be loaded on expand) - local tree_nodes = M.build_tree_nodes(commits, git_root, opts) - local first_commit_node = nil -- Track first commit for auto-expand - for _, node in ipairs(tree_nodes) do - if node.data and node.data.type == "commit" and not first_commit_node then - first_commit_node = node - end - end - - local tree = Tree({ - bufnr = split.bufnr, - nodes = tree_nodes, - prepare_node = function(node) - local current_width = text_width - if split.winid and vim.api.nvim_win_is_valid(split.winid) then - current_width = vim.api.nvim_win_get_width(split.winid) - end - return nodes_module.prepare_node(node, current_width, selected_commit, selected_file, is_single_file_mode) - end, - }) - - tree:render() - - -- Create history panel object local history = { + data = data, + tabpage = tabpage, split = split, - tree = tree, bufnr = split.bufnr, winid = split.winid, - git_root = git_root, - commits = commits, - opts = opts, - on_file_select = nil, - current_commit = nil, - current_file = nil, - current_selection = nil, is_hidden = false, - is_single_file_mode = is_single_file_mode, + is_single_file_mode = opts.file_path and opts.file_path ~= "", } + local tree = Tree({ + bufnr = split.bufnr, + nodes = M.build_tree_nodes(data.commits, data.git_root, opts), + prepare_node = function(node) + local current_width = split.winid and vim.api.nvim_win_is_valid(split.winid) and vim.api.nvim_win_get_width(split.winid) or text_width + local selected = history.data.current_selection or {} + return nodes_module.prepare_node(node, current_width, selected.commit_hash, selected.path, history.is_single_file_mode) + end, + }) + history.tree = tree + tree:render() - -- Load files for a commit and update its children - local function load_commit_files(commit_node, callback) - local data = commit_node.data - - -- Skip non-commit nodes (e.g., title node) - if not data or data.type ~= "commit" then - if callback then - callback() - end - return - end - - if data.files_loaded then - -- Files already loaded, just expand - commit_node:expand() - tree:render() - if callback then - callback() - end + history.on_data = function(value, changes) + history.data = value + if not vim.api.nvim_buf_is_valid(history.bufnr) then return end - - git.get_commit_files(data.hash, git_root, function(err, files) - vim.schedule(function() - if not vim.api.nvim_buf_is_valid(history.bufnr) or tree:get_node(commit_node:get_id()) ~= commit_node then - if callback then - callback() - end - return - end - if err then - vim.notify("Failed to load commit files: " .. err, vim.log.levels.ERROR) - if callback then - callback() - end - return - end - -- Apply file_filter.ignore patterns (same as explorer view) - local filter = require("codediff.ui.explorer.filter") - local explorer_config = config.options.explorer or {} - local file_filter = explorer_config.file_filter or {} - local ignore_patterns = file_filter.ignore or {} - files = filter.apply(files, ignore_patterns) - - -- Create file nodes based on view_mode - local history_config = config.options.history or {} - local view_mode = history_config.view_mode or "list" - - local file_nodes - if view_mode == "tree" then - file_nodes = nodes_module.create_tree_file_nodes(files, data.hash, git_root) - else - file_nodes = nodes_module.create_list_file_nodes(files, data.hash, git_root) + if changes.list then + local expanded = {} + for _, node in ipairs(tree:get_nodes()) do + if node.data and node.data.type == "commit" and node:is_expanded() then + expanded[node.data.hash] = true end - - -- Update node with children - data.files_loaded = true - data.file_count = #files - - -- Tree doesn't have a direct "add children" API, so we need to rebuild - -- For now, we'll use set_nodes on the commit node - for _, file_node in ipairs(file_nodes) do - tree:add_node(file_node, commit_node:get_id()) - end - - -- Auto-expand all directory nodes in tree mode - if view_mode == "tree" then - expand_directories(tree, commit_node:get_child_ids() or {}) + end + tree:set_nodes(M.build_tree_nodes(value.commits, value.git_root, value.opts)) + for _, node in ipairs(tree:get_nodes()) do + if node.data and node.data.type == "commit" and expanded[node.data.hash] then + node:expand() + render_files(history, node) end - - commit_node:expand() - tree:render() - - if callback then - callback() + end + elseif changes.files then + local node = tree:get_node("commit:" .. changes.files) + if node then + render_files(history, node) + end + end + if not history.is_hidden then + tree:render() + if changes.list and history.winid and vim.api.nvim_win_is_valid(history.winid) then + local selected = value.current_commit and tree:get_node("commit:" .. value.current_commit) + if selected and selected._line then + vim.api.nvim_win_set_cursor(history.winid, { selected._line, 0 }) end - end) - end) - end - - -- File selection callback - local function on_file_select(file_data, opts) - opts = opts or {} - local view = require("codediff.ui.view") - local lifecycle = require("codediff.ui.lifecycle") - - local file_path = file_data.path - local old_path = file_data.old_path - local commit_hash = file_data.commit_hash - local selection = history._selection_generation - local refresh = require("codediff.ui.refresh") - - if not file_path or file_path == "" then - vim.notify("[CodeDiff] No file path for selection", vim.log.levels.WARN) - refresh.ready(tabpage) - return + end end - - if not commit_hash or commit_hash == "" then - vim.notify("[CodeDiff] No commit hash for selection", vim.log.levels.WARN) - refresh.ready(tabpage) + end + history.on_file_select = function(file, selection_opts) + return require("codediff.ui.refresh").select(tabpage, file, selection_opts) + end + history.load_commit_files = function(node, done) + if not node.data or node.data.type ~= "commit" then + if done then + done() + end return end - - -- Check if already displaying same file - local target_hash = base_revision or (commit_hash .. "^") - local session = lifecycle.get_session(tabpage) - if not opts.force and session and session.original_revision == target_hash and session.modified_revision == commit_hash then - if (session.modified and session.modified.relative == file_path) or (session.original and session.original.relative == file_path) then - refresh.ready(tabpage) - return + node:expand() + if history.data.files[node.data.hash] then + render_files(history, node) + tree:render() + if done then + done() end + else + require("codediff.ui.refresh").load_commit_files(tabpage, node.data.hash, done) end - - vim.schedule(function() - if lifecycle.get_panel_view(tabpage) ~= history or history._selection_generation ~= selection then - return - end - -- Handle added/deleted files: show single file instead of empty diff - local file_status = file_data.status - if file_status == "A" or file_status == "D" then - local sess = lifecycle.get_session(tabpage) - local is_inline = sess and sess.layout == "inline" - - if is_inline then - local rev = file_status == "A" and commit_hash or target_hash - local single_path = file_status == "D" and (old_path or file_path) or file_path - require("codediff.ui.view.inline_view").show_single_file(tabpage, single_path, { - revision = rev, - git_root = git_root, - rel_path = single_path, - side = file_status == "D" and "original" or "modified", - }) - else - if file_status == "A" then - require("codediff.ui.view.side_by_side").show_added_virtual_file(tabpage, git_root, file_path, commit_hash) - else - require("codediff.ui.view.side_by_side").show_deleted_virtual_file(tabpage, git_root, old_path or file_path, target_hash) - end - end - return - end - - ---@type SessionConfig - local session_config = { - git_root = git_root, - original = path.make_ref(base_revision and file_path or (old_path or file_path), git_root), - modified = path.make_ref(file_path, git_root), - original_revision = target_hash, - modified_revision = commit_hash, - line_range = line_range, - } - view.update(tabpage, session_config, config.options.diff.jump_to_first_change) - end) end - - history.on_file_select = function(file_data, opts) - history._selection_generation = (history._selection_generation or 0) + 1 - require("codediff.ui.refresh").begin(tabpage) - history.current_commit = file_data.commit_hash - history.current_file = file_data.path - history.current_selection = vim.deepcopy(file_data) - selected_commit = file_data.commit_hash - selected_file = file_data.path - tree:render() - on_file_select(file_data, opts) - end - - -- Store load_commit_files for refresh to re-expand commits - history._load_commit_files = load_commit_files - - -- Setup keymaps keymaps_module.setup(history, { - is_single_file_mode = is_single_file_mode, + is_single_file_mode = history.is_single_file_mode, file_path = opts.file_path, - git_root = git_root, + git_root = data.git_root, tabpage = tabpage, - load_commit_files = load_commit_files, - navigate_next = M.navigate_next, - navigate_prev = M.navigate_prev, - nodes_module = nodes_module, + load_commit_files = history.load_commit_files, }) - -- Auto-expand first commit and select first file - if first_commit_node then + local first = data.commits[1] + if first then vim.schedule(function() - if is_single_file_mode then - -- file_path from the commit rather than opts, so a rename resolves to - -- the name the file had at that commit. - history.on_file_select({ - path = first_commit_node.data.file_path or opts.file_path, - commit_hash = first_commit_node.data.hash, - git_root = git_root, - }) + if require("codediff.ui.lifecycle").get_panel_view(tabpage) ~= history then return end - - load_commit_files(first_commit_node, function() - if not first_commit_node:has_children() then - return - end - local first_file = find_first_file(tree, first_commit_node:get_child_ids() or {}) - if first_file and first_file.data then - tree:render() - history.on_file_select(first_file.data) - end - end) + if history.is_single_file_mode then + history.on_file_select({ path = first.file_path or opts.file_path, commit_hash = first.hash, git_root = data.git_root }) + else + local node = tree:get_node("commit:" .. first.hash) + history.load_commit_files(node, function(err) + local current = tree:get_node("commit:" .. first.hash) + local file = not err and current and find_first_file(tree, current:get_child_ids() or {}) + if file then + tree:render() + history.on_file_select(file.data) + end + end) + end end) end - - -- Setup auto-refresh (git watcher + BufEnter) - local refresh_module = require("codediff.ui.history.refresh") - refresh_module.setup_auto_refresh(history, tabpage) - - -- Re-render on window resize vim.api.nvim_create_autocmd("WinResized", { callback = function() - local resized_wins = vim.v.event.windows or {} - for _, win in ipairs(resized_wins) do + for _, win in ipairs(vim.v.event.windows or {}) do if win == history.winid and vim.api.nvim_win_is_valid(win) then - history.tree:render() + tree:render() break end end end, }) - return history end -function M.rerender_current(history) - if not history then - return false - end - - if history.current_selection then - history.on_file_select(vim.deepcopy(history.current_selection), { force = true }) - return true - end - - return false -end - --- Get all file nodes from tree (for navigation) function M.get_all_files(tree) local files = {} - - local function collect_files(parent_node) - if not parent_node:has_children() then - return - end - if not parent_node:is_expanded() then - return - end - - for _, child_id in ipairs(parent_node:get_child_ids()) do - local node = tree:get_node(child_id) - if node and node.data and node.data.type == "file" then - table.insert(files, { - node = node, - data = node.data, - }) + for _, commit in ipairs(tree:get_nodes()) do + if commit:is_expanded() then + for _, id in ipairs(commit:get_child_ids() or {}) do + local node = tree:get_node(id) + if node and node.data and node.data.type == "file" then + files[#files + 1] = { node = node, data = node.data } + end end end end - - local nodes = tree:get_nodes() - for _, commit_node in ipairs(nodes) do - collect_files(commit_node) - end - return files end --- Navigate to next file -function M.navigate_next(history) - local all_files = M.get_all_files(history.tree) - if #all_files == 0 then - vim.notify("No files in history", vim.log.levels.WARN) - return - end - - local current_commit = history.current_commit - local current_file = history.current_file - - if not current_commit or not current_file then - local first_file = all_files[1] - history.on_file_select(first_file.data) - return - end - - -- Find current index - local current_index = 0 - for i, file in ipairs(all_files) do - if file.data.commit_hash == current_commit and file.data.path == current_file then - current_index = i - break +function M.get_all_commits(tree) + local commits = {} + for _, node in ipairs(tree:get_nodes()) do + if node.data and node.data.type == "commit" then + commits[#commits + 1] = { node = node, data = node.data } end end - - if current_index >= #all_files and not config.options.diff.cycle_next_file then - vim.api.nvim_echo({ { string.format("Last file (%d of %d)", #all_files, #all_files), "WarningMsg" } }, false, {}) - return - else - vim.api.nvim_echo({}, false, {}) - end - - local next_index = current_index % #all_files + 1 - local next_file = all_files[next_index] - - -- Update cursor position - local current_win = vim.api.nvim_get_current_win() - if vim.api.nvim_win_is_valid(history.winid) then - vim.api.nvim_set_current_win(history.winid) - vim.api.nvim_win_set_cursor(history.winid, { next_file.node._line or 1, 0 }) - vim.api.nvim_set_current_win(current_win) - end - - history.on_file_select(next_file.data) + return commits end --- Navigate to previous file -function M.navigate_prev(history) - local all_files = M.get_all_files(history.tree) - if #all_files == 0 then - vim.notify("No files in history", vim.log.levels.WARN) +local function navigate(history, direction, commits) + local entries = commits and M.get_all_commits(history.tree) or M.get_all_files(history.tree) + local kind = commits and "commit" or "file" + if #entries == 0 then + vim.notify(commits and "No commits in history" or "No files in history", vim.log.levels.WARN) return end - - local current_commit = history.current_commit - local current_file = history.current_file - - if not current_commit or not current_file then - local last_file = all_files[#all_files] - history.on_file_select(last_file.data) - return - end - - local current_index = 0 - for i, file in ipairs(all_files) do - if file.data.commit_hash == current_commit and file.data.path == current_file then - current_index = i + local data = history.data + local index = 0 + for i, entry in ipairs(entries) do + if commits and entry.data.hash == data.current_commit or not commits and entry.data.commit_hash == data.current_commit and entry.data.path == data.current_file then + index = i break end end - - if current_index <= 1 and not config.options.diff.cycle_next_file then - vim.api.nvim_echo({ { string.format("First file (1 of %d)", #all_files), "WarningMsg" } }, false, {}) + local selected = data.current_commit and (commits or data.current_file) + if selected and not config.options.diff.cycle_next_file and (direction > 0 and index >= #entries or direction < 0 and index <= 1) then + local message = direction > 0 and string.format("Last %s (%d of %d)", kind, #entries, #entries) or string.format("First %s (1 of %d)", kind, #entries) + vim.api.nvim_echo({ { message, "WarningMsg" } }, false, {}) return - else + end + if not commits then vim.api.nvim_echo({}, false, {}) end - - local prev_index = current_index - 2 - if prev_index < 0 then - prev_index = #all_files + prev_index + local next_index = selected and ((index - 1 + direction) % #entries + 1) or (direction > 0 and 1 or #entries) + local entry = entries[next_index] + if selected and history.winid and vim.api.nvim_win_is_valid(history.winid) then + vim.api.nvim_win_set_cursor(history.winid, { entry.node._line or 1, 0 }) end - prev_index = prev_index % #all_files + 1 - local prev_file = all_files[prev_index] - - local current_win = vim.api.nvim_get_current_win() - if vim.api.nvim_win_is_valid(history.winid) then - vim.api.nvim_set_current_win(history.winid) - vim.api.nvim_win_set_cursor(history.winid, { prev_file.node._line or 1, 0 }) - vim.api.nvim_set_current_win(current_win) + local file = entry.data + if commits then + file = { path = entry.data.file_path or data.opts.file_path, commit_hash = entry.data.hash, git_root = data.git_root } end + history.on_file_select(file) +end - history.on_file_select(prev_file.data) +function M.navigate_next(history) + navigate(history, 1, false) end --- Get all commit nodes from tree (for navigation in single-file mode) -function M.get_all_commits(tree) - local commits = {} - local nodes = tree:get_nodes() - for _, node in ipairs(nodes) do - if node.data and node.data.type == "commit" then - table.insert(commits, { - node = node, - data = node.data, - }) - end - end - return commits +function M.navigate_prev(history) + navigate(history, -1, false) end --- Navigate to next commit (single-file history mode) function M.navigate_next_commit(history) - local all_commits = M.get_all_commits(history.tree) - if #all_commits == 0 then - vim.notify("No commits in history", vim.log.levels.WARN) - return - end - - local current_commit = history.current_commit - - if not current_commit then - -- Select first commit - local first_commit = all_commits[1] - local file_path = first_commit.data.file_path or history.opts.file_path - local file_data = { - path = file_path, - commit_hash = first_commit.data.hash, - git_root = history.git_root, - } - history.on_file_select(file_data) - return - end - - -- Find current index - local current_index = 0 - for i, commit in ipairs(all_commits) do - if commit.data.hash == current_commit then - current_index = i - break - end - end - - if current_index >= #all_commits and not config.options.diff.cycle_next_file then - vim.api.nvim_echo({ { string.format("Last commit (%d of %d)", #all_commits, #all_commits), "WarningMsg" } }, false, {}) - return - end - - local next_index = current_index % #all_commits + 1 - local next_commit = all_commits[next_index] - - -- Update cursor position in history panel - local current_win = vim.api.nvim_get_current_win() - if vim.api.nvim_win_is_valid(history.winid) then - vim.api.nvim_set_current_win(history.winid) - vim.api.nvim_win_set_cursor(history.winid, { next_commit.node._line or 1, 0 }) - vim.api.nvim_set_current_win(current_win) - end - - -- Select file at this commit - local file_path = next_commit.data.file_path or history.opts.file_path - local file_data = { - path = file_path, - commit_hash = next_commit.data.hash, - git_root = history.git_root, - } - history.on_file_select(file_data) + navigate(history, 1, true) end --- Navigate to previous commit (single-file history mode) function M.navigate_prev_commit(history) - local all_commits = M.get_all_commits(history.tree) - if #all_commits == 0 then - vim.notify("No commits in history", vim.log.levels.WARN) - return - end - - local current_commit = history.current_commit - - if not current_commit then - -- Select last commit - local last_commit = all_commits[#all_commits] - local file_path = last_commit.data.file_path or history.opts.file_path - local file_data = { - path = file_path, - commit_hash = last_commit.data.hash, - git_root = history.git_root, - } - history.on_file_select(file_data) - return - end - - local current_index = 0 - for i, commit in ipairs(all_commits) do - if commit.data.hash == current_commit then - current_index = i - break - end - end - - if current_index <= 1 and not config.options.diff.cycle_next_file then - vim.api.nvim_echo({ { string.format("First commit (1 of %d)", #all_commits), "WarningMsg" } }, false, {}) - return - end - - local prev_index = current_index - 2 - if prev_index < 0 then - prev_index = #all_commits + prev_index - end - prev_index = prev_index % #all_commits + 1 - local prev_commit = all_commits[prev_index] - - -- Update cursor position in history panel - local current_win = vim.api.nvim_get_current_win() - if vim.api.nvim_win_is_valid(history.winid) then - vim.api.nvim_set_current_win(history.winid) - vim.api.nvim_win_set_cursor(history.winid, { prev_commit.node._line or 1, 0 }) - vim.api.nvim_set_current_win(current_win) - end - - -- Select file at this commit - local file_path = prev_commit.data.file_path or history.opts.file_path - local file_data = { - path = file_path, - commit_hash = prev_commit.data.hash, - git_root = history.git_root, - } - history.on_file_select(file_data) + navigate(history, -1, true) end --- Toggle visibility function M.toggle_visibility(history) if not history or not history.split then return end - - local tabpage = vim.api.nvim_get_current_tabpage() - if history.is_hidden then history.split:show() - history.is_hidden = false history.winid = history.split.winid - vim.schedule(function() - layout.arrange(tabpage) - end) else history.split:hide() - history.is_hidden = true - vim.schedule(function() - layout.arrange(tabpage) - end) end + history.is_hidden = not history.is_hidden + vim.schedule(function() + layout.arrange(history.tabpage) + end) end return M diff --git a/lua/codediff/ui/lifecycle/cleanup.lua b/lua/codediff/ui/lifecycle/cleanup.lua index a2328471..5fe5e034 100644 --- a/lua/codediff/ui/lifecycle/cleanup.lua +++ b/lua/codediff/ui/lifecycle/cleanup.lua @@ -50,12 +50,6 @@ local function cleanup_diff(tabpage) -- Hand every mapped key back to whatever owned it before codediff keymaps.dispose_keymaps(tabpage) - -- Call the panel's cleanup function to stop file watchers - local panel_view = diff.panel and diff.panel.view - if panel_view and panel_view._cleanup_auto_refresh then - pcall(panel_view._cleanup_auto_refresh) - end - -- Delete virtual buffers if they're still valid if vim.api.nvim_buf_is_valid(diff.original_bufnr) then if is_virtual_revision(diff.original_revision) then diff --git a/lua/codediff/ui/lifecycle/session.lua b/lua/codediff/ui/lifecycle/session.lua index 4dd9d9a5..703abc06 100644 --- a/lua/codediff/ui/lifecycle/session.lua +++ b/lua/codediff/ui/lifecycle/session.lua @@ -83,11 +83,9 @@ function M.create_session(tabpage, session_config, panes) -- Create complete session in one step active_diffs[tabpage] = { - -- Panel & Git Context (immutable) - -- `panel.data` is construction material: panel.lua consumes it to build the - -- panel, which copies forward whatever it still needs (pathspec, - -- status_result). Keeping it on the session would be a second, stale copy. - panel = session_config.panel and { name = session_config.panel.name } or nil, + tabpage = tabpage, + -- Panel data belongs to the session; the sidebar only renders it. + panel = session_config.panel and { name = session_config.panel.name, data = require("codediff.ui.refresh.panel").new(session_config) } or nil, merge = session_config.conflict or nil, git_root = session_config.git_root, original = session_config.original, diff --git a/lua/codediff/ui/refresh/apply.lua b/lua/codediff/ui/refresh/apply.lua deleted file mode 100644 index b8954bb9..00000000 --- a/lua/codediff/ui/refresh/apply.lua +++ /dev/null @@ -1,181 +0,0 @@ --- Update an existing comparison without reopening files or resetting editor state. -local M = {} -local api = vim.api -local snapshot = require("codediff.ui.refresh.snapshot") -local policy = require("codediff.ui.refresh.policy") - -local function put(buf, value) - if vim.deep_equal(snapshot.lines(buf), value) then - return - end - local modifiable, readonly = vim.bo[buf].modifiable, vim.bo[buf].readonly - vim.bo[buf].modifiable, vim.bo[buf].readonly = true, false - api.nvim_buf_set_lines(buf, 0, -1, false, value) - vim.bo[buf].modifiable, vim.bo[buf].readonly = modifiable, readonly -end - -local function materialize(session, side, input, value) - local buf = session[side .. "_bufnr"] - if not input.path or input.path.absolute == "" then - return buf - end - if policy.is_working(input.revision) then - -- Real buffers were reloaded by checktime, never by replacing their text. - if vim.bo[buf].buftype ~= "" then - put(buf, value) - end - return buf - end - - if input.resolved ~= session[side .. "_revision"] then - local virtual = require("codediff.core.virtual_file") - local name = virtual.create_url(session.git_root, input.resolved, input.path.relative) - local existing = -1 - for _, candidate in ipairs(api.nvim_list_bufs()) do - if api.nvim_buf_get_name(candidate) == name then - existing = candidate - break - end - end - if existing ~= -1 and api.nvim_buf_is_loaded(existing) then - buf = existing - else - buf = api.nvim_create_buf(false, true) - if existing == -1 then - api.nvim_buf_set_name(buf, name) - end - vim.bo[buf].buftype = "nowrite" - vim.bo[buf].bufhidden = "hide" - vim.bo[buf].swapfile = false - vim.bo[buf].readonly = true - vim.bo[buf].modifiable = false - end - session[side .. "_bufnr"] = buf - local win = session[side .. "_win"] - local hidden = side == "original" and session.layout == "inline" and session.single_side ~= "original" - if win and api.nvim_win_is_valid(win) and not hidden then - api.nvim_win_set_buf(win, buf) - vim.bo[buf].bufhidden = "wipe" - end - end - require("codediff.core.virtual_file").set_content(buf, value, input.path.relative) - session[side .. "_revision"] = input.resolved - return buf -end - -local function options() - local config = require("codediff.config").options.diff - return { - max_computation_time_ms = config.max_computation_time_ms, - ignore_trim_whitespace = config.ignore_trim_whitespace, - compute_moves = config.compute_moves, - } -end - -function M.result(session) - if not session.result_bufnr or not api.nvim_buf_is_valid(session.result_bufnr) or not session.result_base_lines then - return - end - local value = snapshot.lines(session.result_bufnr) - local result = require("codediff.core.diff").compute_diff(session.result_base_lines, value, options()) - if result then - require("codediff.ui.core").render_single_buffer(session.result_bufnr, result, "modified") - end - require("codediff.ui.conflict").refresh(session) -end - -function M.run(session, data, previous, redraw) - local input_changed = not snapshot.same_inputs(previous, data) - local result_changed = session.result_bufnr and not vim.deep_equal(previous and previous.result, snapshot.lines(session.result_bufnr)) - local seed = session.result_base_lines or {} - -- Neovim represents an empty Result as one empty line, not an empty array. - local untouched = vim.deep_equal(snapshot.lines(session.result_bufnr), #seed > 0 and seed or { "" }) - if session.result_bufnr and input_changed and not untouched then - if not session.refresh.blocked or not snapshot.same_inputs(session.refresh.blocked, data) then - vim.notify("Conflict inputs changed; Result has unsaved edits. Reopen the conflict view to reload its inputs.", vim.log.levels.WARN) - session.refresh.blocked = data - end - if result_changed or redraw then - M.result(session) - end - return false - end - if not input_changed and not redraw then - if result_changed then - M.result(session) - end - return true - end - - local views = {} - for _, side in ipairs({ "original", "modified", "result" }) do - local win = session[side .. "_win"] - if win and api.nvim_win_is_valid(win) and not views[win] then - views[win] = { view = api.nvim_win_call(win, vim.fn.winsaveview), scrollbind = vim.wo[win].scrollbind } - vim.wo[win].scrollbind = false - end - end - local focused = api.nvim_get_current_win() - local old_original, old_modified = session.original_bufnr, session.modified_bufnr - local ok, err = xpcall(function() - if input_changed then - materialize(session, "original", data.sources.original, data.original) - materialize(session, "modified", data.sources.modified, data.modified) - end - local core = require("codediff.ui.core") - local compute = require("codediff.core.diff").compute_diff - if session.result_bufnr then - local original = assert(compute(data.base, data.original, options())) - local modified = assert(compute(data.base, data.modified, options())) - core.render_merge_view(session.original_bufnr, session.modified_bufnr, original, modified, data.base, data.original, data.modified) - if input_changed then - local result, blocks = require("codediff.ui.conflict.merge").compute_auto_merged_result(original, modified, data.base, data.original, data.modified) - put(session.result_bufnr, result) - session.result_base_lines, session.merge_base_lines, session.conflict_blocks = result, data.base, blocks - require("codediff.ui.conflict").initialize_tracking(session.result_bufnr, blocks) - end - session.stored_diff_result = modified - require("codediff.ui.conflict").attach_gutter(session.original_win, session.modified_win) - M.result(session) - elseif session.single_side then - core.render_whole_file(session[session.single_side .. "_bufnr"], session.single_side) - session.stored_diff_result = { changes = {}, moves = {} } - else - local diff = assert(compute(data.original, data.modified, options())) - if session.layout == "inline" then - require("codediff.ui.inline").render_inline_diff(session.modified_bufnr, diff, data.original, data.modified) - else - core.render_diff(session.original_bufnr, session.modified_bufnr, data.original, data.modified, diff) - end - session.stored_diff_result = diff - end - session.changedtick.original = api.nvim_buf_get_changedtick(session.original_bufnr) - session.changedtick.modified = api.nvim_buf_get_changedtick(session.modified_bufnr) - if old_original ~= session.original_bufnr or old_modified ~= session.modified_bufnr then - require("codediff.ui.lifecycle").update_buffers(session.refresh.tabpage, session.original_bufnr, session.modified_bufnr) - if session.reapply_keymaps then - session.reapply_keymaps() - end - end - require("codediff.ui.view.compact").refresh(session.refresh.tabpage) - end, debug.traceback) - for win, saved in pairs(views) do - if api.nvim_win_is_valid(win) then - api.nvim_win_call(win, function() - local cursor = require("codediff.ui.view.cursor").clamp_cursor(win, { saved.view.lnum, saved.view.col }) - saved.view.lnum, saved.view.col = cursor[1], cursor[2] - vim.fn.winrestview(saved.view) - end) - vim.wo[win].scrollbind = saved.scrollbind - end - end - if api.nvim_win_is_valid(focused) and api.nvim_get_current_win() ~= focused then - api.nvim_set_current_win(focused) - end - if not ok then - error(err) - end - return true -end - -return M diff --git a/lua/codediff/ui/refresh/init.lua b/lua/codediff/ui/refresh/init.lua index ff4cc99e..b47d9456 100644 --- a/lua/codediff/ui/refresh/init.lua +++ b/lua/codediff/ui/refresh/init.lua @@ -1,8 +1,8 @@ --- One refresh controller per session: collect invalidations, inspect data, apply changes. +-- Session data owns refresh. Views consume changes and submit user selections. local M = {} local policy = require("codediff.ui.refresh.policy") -local snapshot = require("codediff.ui.refresh.snapshot") -local apply = require("codediff.ui.refresh.apply") +local inputs = require("codediff.ui.refresh.inputs") +local panels = require("codediff.ui.refresh.panel") local uv = vim.uv or vim.loop local Controller = {} Controller.__index = Controller @@ -39,9 +39,6 @@ end function Controller:request(event, done) if self.closed then - if done then - done() - end return end self.pending = policy.merge(self.pending, policy.normalize(event)) @@ -51,11 +48,82 @@ function Controller:request(event, done) self:schedule() end -function Controller:run() - if not self:visible() or self.loading or self.running then - return +local function notify_panel(panel, changes) + if panel.view and panel.view.on_data then + panel.view.on_data(panel.data, changes) + end +end + +function Controller:publish_panel(data) + local panel = self.session.panel + local previous = panel.data + local key = panel.name == "history" and "commits" or "status_result" + local list_changed = not vim.deep_equal(previous[key], data[key]) + if vim.deep_equal(previous, data) then + data = previous + end + panel.data = data + if panel.name == "explorer" and list_changed then + panels.set_selection(panel, panels.reselect(previous, data.status_result)) + end + local selection_changed = not panels.same_selection(previous.current_selection, data.current_selection) + if not vim.deep_equal(previous, data) then + notify_panel(panel, { list = list_changed, selection = selection_changed }) + end + if selection_changed then + M.select(self.tabpage, data.current_selection, { no_jump = true }) + elseif data.current_selection then + local comparison = panels.comparison(panel) + if + comparison + and self.session.single_side == comparison.single_side + and self.session.merge == comparison.conflict + and vim.deep_equal(self.session.original, comparison.original) + and vim.deep_equal(self.session.modified, comparison.modified) + then + self.session.source_revisions = comparison.source_revisions + end + end +end + +-- Publish only actual data changes. Edited Result buffers are never reseeded. +function Controller:publish(data, redraw) + local session = self.session + local changed = not inputs.same(self.last, data) + local result_changed = session.result_bufnr and not vim.deep_equal(self.last and self.last.result, inputs.lines(session.result_bufnr)) + if session.result_bufnr and changed then + local seed = session.result_base_lines or {} + if not vim.deep_equal(inputs.lines(session.result_bufnr), #seed > 0 and seed or { "" }) then + if not self.blocked or not inputs.same(self.blocked, data) then + vim.notify("Conflict inputs changed; Result has unsaved edits. Reopen the conflict view to reload its inputs.", vim.log.levels.WARN) + self.blocked = data + end + if result_changed or redraw then + require("codediff.ui.conflict.view.result").render(session) + end + if self.last then + self.last.result = inputs.lines(session.result_bufnr) + end + return + end + end + if changed or result_changed or redraw then + self.applying = true + local ok, err = xpcall(function() + require("codediff.ui.view.render").update(session, data, { inputs = changed, result = result_changed, redraw = redraw }) + end, debug.traceback) + self.applying = false + if not ok then + error(err) + end end - if not next(self.pending) and #self.callbacks == 0 then + self.blocked = nil + data.result = session.result_bufnr and inputs.lines(session.result_bufnr) or nil + self.last = data +end + +function Controller:run() + if not self:visible() or self.loading or self.running or not next(self.pending) and #self.callbacks == 0 then return end local event, callbacks, generation = self.pending, self.callbacks, self.generation @@ -75,8 +143,6 @@ function Controller:run() end if err or cancelled then self.pending = policy.merge(event, self.pending) - -- A completion may navigate or restore a cursor: never replay it onto - -- a different file or a replacement panel. if self.generation == generation and owns_panel() then vim.list_extend(self.callbacks, callbacks) end @@ -95,56 +161,46 @@ function Controller:run() local function current() return not finished and self:visible() and not self.loading and self.generation == generation and owns_panel() end - local function inspect(panel_error) + local function inspect(err, panel_data) if not current() then finish(nil, true) return end - if panel_error then - finish(panel_error) + if err then + finish(err) return end - if not self.last then - self.last = snapshot.capture(self.session) - end - local read_ok, read_error = pcall(snapshot.read, self.session, event, self.last, function(err, data) - if not current() then - finish(nil, true) + if panel_data then + local ok, failure = pcall(self.publish_panel, self, panel_data) + if not ok then + finish(failure) return end - if err then - finish(err) + if not current() then + finish(nil, true) return end - if not snapshot.valid(data) then + end + self.last = self.last or inputs.capture(self.session) + local read_ok, read_error = pcall(inputs.read, self.session, event, self.last, function(read_error, data) + if not current() then + finish(nil, true) + elseif read_error then + finish(read_error) + elseif not inputs.valid(data) then self.pending = policy.merge(self.pending, { buffer = true }) finish(nil, true) - return + else + local ok, failure = pcall(self.publish, self, data, event.render) + finish(not ok and failure or nil) end - self.applying = true - local ok, accepted = xpcall(function() - return apply.run(self.session, data, self.last, event.render) - end, debug.traceback) - self.applying = false - if not ok then - finish(accepted) - return - end - if accepted then - self.blocked = nil - data.result = self.session.result_bufnr and snapshot.lines(self.session.result_bufnr) or nil - self.last = data - elseif self.last then - self.last.result = snapshot.lines(self.session.result_bufnr) - end - finish() end) if not read_ok then finish(read_error) end end - if self.panel_refresh and policy.panel_needed(self.session.panel, event) then - local ok, err = pcall(self.panel_refresh, inspect) + if panel and panel.on_data and policy.panel_needed(self.session.panel, event) then + local ok, err = pcall(panels.read, self.session, inspect) if not ok then finish(err) end @@ -167,7 +223,6 @@ function Controller:start_polling() ) end --- A file-follow operation may move the session to another repository. function Controller:watch() self.watch_generation = (self.watch_generation or 0) + 1 local generation = self.watch_generation @@ -178,12 +233,7 @@ function Controller:watch() self.git_root = self.session.git_root self.native, self.polling = false, false self.poll:stop() - local panel = self.session.panel and self.session.panel.view - if panel then - panel._native_watcher_ready = false - end - local automatic = not (self.session.panel and self.session.panel.name == "explorer" and require("codediff.config").options.explorer.auto_refresh == false) - if not automatic then + if self.session.panel and self.session.panel.name == "explorer" and require("codediff.config").options.explorer.auto_refresh == false then return end self:start_polling() @@ -195,16 +245,11 @@ function Controller:watch() end self.unsubscribe = require("codediff.core.watcher").subscribe(self.git_root, { on_ready = function() - if not current() then - return - end - self.native, self.polling = true, false - self.poll:stop() - local view = self.session.panel and self.session.panel.view - if view then - view._native_watcher_ready = true + if current() then + self.native, self.polling = true, false + self.poll:stop() + self:request({ full = true }) end - self:request({ full = true }) end, on_refresh = function(message) if current() then @@ -212,16 +257,11 @@ function Controller:watch() end end, on_error = function() - if not current() then - return - end - self.native = false - local view = self.session.panel and self.session.panel.view - if view then - view._native_watcher_ready = false + if current() then + self.native = false + self:start_polling() + self:request({ full = true }) end - self:start_polling() - self:request({ full = true }) end, }) end @@ -269,12 +309,8 @@ function M.attach(tabpage) end local name = vim.api.nvim_buf_get_name(event.buf) local belongs = event.buf == session.original_bufnr or event.buf == session.modified_bufnr or event.buf == session.result_bufnr - if not belongs then - for _, input in pairs(snapshot.describe(session)) do - if input.path and input.path.absolute ~= "" and input.path.absolute == name then - belongs = true - end - end + for _, input in pairs(inputs.describe(session)) do + belongs = belongs or input.path and input.path.absolute ~= "" and input.path.absolute == name end if belongs then self:request({ buffer = true }) @@ -310,7 +346,6 @@ function M.attach(tabpage) return self end --- Opening/retargeting owns the view until its complete input set is installed. function M.begin(tabpage, request) local self = M.attach(tabpage) if not self then @@ -343,7 +378,7 @@ function M.ready(tabpage) if self.git_root ~= session.git_root then self:watch() end - self.last = snapshot.capture(session) + self.last = inputs.capture(session) self.blocked = nil if next(self.pending) or #self.callbacks > 0 then self:schedule() @@ -351,42 +386,104 @@ function M.ready(tabpage) end) end -function M.replay(tabpage) +function M.select(tabpage, file, opts) local self = M.attach(tabpage) - if not self or self.loading then - return + local session = self and self.session + local panel = session and session.panel + if not panel then + return false + end + opts = opts or {} + local changed = not panels.same_selection(panel.data.current_selection, file) + panels.set_selection(panel, file) + if changed then + notify_panel(panel, { selection = true }) end - local data = snapshot.capture(self.session) - self.applying = true - local ok, err = xpcall(function() - apply.run(self.session, data, self.last, true) - end, debug.traceback) - self.applying = false - if not ok then - error(err) + if not file then + M.begin(tabpage, {}) + require("codediff.ui.view").show_welcome(tabpage) + return true end + local comparison = panels.comparison(panel, file) + if not comparison then + return false + end + if panel.name == "explorer" then + vim.api.nvim_exec_autocmds("User", { + pattern = "CodeDiffFileSelect", + modeline = false, + data = { tabpage = tabpage, path = file.path, status = file.status }, + }) + end + local same = session.single_side == comparison.single_side + and session.merge == comparison.conflict + and vim.deep_equal(session.original, comparison.original) + and vim.deep_equal(session.modified, comparison.modified) + and vim.deep_equal(session.source_revisions, comparison.source_revisions) + if same and not opts.force then + return true + end + local generation = M.begin(tabpage, comparison) + local view = panel.view + panels.resolve(comparison, function(err, resolved) + vim.schedule(function() + if not M.is_current(tabpage, session, generation) or session.panel ~= panel or panel.view ~= view then + return + end + if err then + vim.notify(err, vim.log.levels.ERROR) + M.ready(tabpage) + return + end + local jump = not opts.no_jump and require("codediff.config").options.diff.jump_to_first_change + require("codediff.ui.view").show(tabpage, resolved, jump) + end) + end) + return true end -function M.request(tabpage, event, done) +function M.load_commit_files(tabpage, hash, done) local self = M.attach(tabpage) - if self then - self:request(event, done) - elseif done then - done() + local panel = self and self.session.panel + if not panel or panel.name ~= "history" then + return + end + local view = panel.view + panels.load_files(panel.data, hash, function(err, files) + if not self:valid() or self.session.panel ~= panel or panel.view ~= view then + return + end + if not err then + panel.data.files[hash] = files + notify_panel(panel, { files = hash }) + else + vim.notify("Failed to load commit files: " .. err, vim.log.levels.ERROR) + end + if done then + done(err) + end + end) +end + +function M.reopen(tabpage) + local session = session_for(tabpage) + if session and session.panel then + return M.select(tabpage, session.panel.data.current_selection, { force = true, no_jump = true }) end + return false end -function M.bind_panel(tabpage, panel, refresh) +function M.replay(tabpage) local self = M.attach(tabpage) - if not self then - return function() end + if self and not self.loading then + self:publish(inputs.capture(self.session), true) end - self.panel_refresh = refresh - panel._native_watcher_ready = self.native == true - return function() - if self.panel_refresh == refresh then - self.panel_refresh = nil - end +end + +function M.request(tabpage, event, done) + local self = M.attach(tabpage) + if self then + self:request(event, done) end end @@ -406,4 +503,13 @@ function M.buffer_changed(buf) end end +-- Resolution commands render their local edits synchronously, without reading Git. +function M.refresh_result_now(buf) + for _, session in pairs(require("codediff.ui.lifecycle.session").get_active_diffs()) do + if buf == session.result_bufnr then + require("codediff.ui.conflict.view.result").render(session) + end + end +end + return M diff --git a/lua/codediff/ui/refresh/snapshot.lua b/lua/codediff/ui/refresh/inputs.lua similarity index 60% rename from lua/codediff/ui/refresh/snapshot.lua rename to lua/codediff/ui/refresh/inputs.lua index 1d11d096..877fabcb 100644 --- a/lua/codediff/ui/refresh/snapshot.lua +++ b/lua/codediff/ui/refresh/inputs.lua @@ -1,8 +1,9 @@ +-- Read comparison inputs from the session, without consulting a panel or view. local M = {} local api = vim.api local policy = require("codediff.ui.refresh.policy") -local function lines(buf) +function M.lines(buf) return buf and api.nvim_buf_is_valid(buf) and api.nvim_buf_get_lines(buf, 0, -1, false) or { "" } end @@ -10,54 +11,27 @@ local function normalized(value) return value and #value > 0 and value or { "" } end -local function source(path, revision, resolved) - return { path = path, revision = revision, resolved = resolved } -end - --- Preserve the requested ref, not just the SHA that happened to resolve at open. function M.describe(session) local requested = session.source_revisions or {} - local original = requested.original or session.original_revision - local modified = requested.modified or session.modified_revision - local panel = session.panel and session.panel.view - if session.panel and session.panel.name == "explorer" and panel and panel.git_root and panel.current_file_path then - if session.merge and session.result_bufnr then - original, modified = session.original_revision, session.modified_revision - elseif panel.base_revision then - local refs = panel.source_revisions or {} - original, modified = refs.original or panel.base_revision, refs.modified or panel.target_revision or "WORKING" - if session.single_side == "original" then - modified = nil - end - elseif panel.current_file_group == "staged" then - original, modified = "HEAD", ":0" - elseif session.single_side == "original" then - original, modified = ":0", nil - else - original, modified = "HEAD", "WORKING" - for _, file in ipairs((panel.status_result or {}).staged or {}) do - if file.path == panel.current_file_path then - original = ":0" - break - end - end - end + local sources = {} + for _, side in ipairs({ "original", "modified" }) do + sources[side] = { + path = session[side], + revision = requested[side] or session[side .. "_revision"], + resolved = session[side .. "_revision"], + } end - local description = { - original = source(session.original, original, session.original_revision), - modified = source(session.modified, modified, session.modified_revision), - } if session.merge and session.result_bufnr then - description.base = source(session.original, ":1", ":1") + sources.base = { path = session.original, revision = ":1", resolved = ":1" } end - return description + return sources end function M.capture(session) - local data = { sources = M.describe(session), original = lines(session.original_bufnr), modified = lines(session.modified_bufnr) } + local data = { sources = M.describe(session), original = M.lines(session.original_bufnr), modified = M.lines(session.modified_bufnr) } if session.result_bufnr then data.base = vim.deepcopy(session.merge_base_lines or {}) - data.result = lines(session.result_bufnr) + data.result = M.lines(session.result_bufnr) end return data end @@ -66,7 +40,7 @@ local function same_source(first, second) return first and second and first.revision == second.revision and vim.deep_equal(first.path, second.path) end -function M.same_inputs(first, second) +function M.same(first, second) if not first or not second then return false end @@ -83,22 +57,15 @@ function M.same_inputs(first, second) return true end -local function real_buffer(path) +local function read_working(input, event) + local path = input.path.absolute local buf = vim.fn.bufadd(path) if api.nvim_buf_is_loaded(buf) and vim.bo[buf].buftype == "" then - return buf - end -end - -local function read_working(session, side, input, event) - local path = input.path.absolute - local buf = real_buffer(path) - if buf then -- Never replace unsaved text. checktime follows Neovim's reload safeguards. if (event.full or event.worktree) and not vim.bo[buf].modified then pcall(vim.cmd, "silent! checktime " .. buf) end - return lines(buf), buf + return M.lines(buf), buf end if vim.fn.filereadable(path) == 0 then return { "" } @@ -113,16 +80,15 @@ local function read_working(session, side, input, event) return normalized(value) end --- Read all candidates before touching any displayed input buffer. +-- Settle every candidate before publishing a new comparison. function M.read(session, event, previous, done) local data = { sources = M.describe(session), ticks = {} } local git = require("codediff.core.git") - local remaining, completed, first_error = 1, false, nil + local remaining, first_error = 1, nil local function finish(err) first_error = first_error or err remaining = remaining - 1 - if remaining == 0 and not completed then - completed = true + if remaining == 0 then done(first_error, data) end end @@ -136,15 +102,14 @@ function M.read(session, event, previous, done) data[side] = side == "base" and {} or { "" } finish() elseif policy.is_working(input.revision) then - local value, buf = read_working(session, side, input, event) + local value, buf = read_working(input, event) data[side] = value if buf then data.ticks[buf] = api.nvim_buf_get_changedtick(buf) end finish() elseif same_source(input, old) and not policy.needs_read(input.revision, event) then - -- Buffer events may originate from a programmatic edit of a diff pane. - data[side] = event.buffer and side ~= "base" and lines(session[side .. "_bufnr"]) or vim.deepcopy(previous[side]) + data[side] = event.buffer and side ~= "base" and M.lines(session[side .. "_bufnr"]) or vim.deepcopy(previous[side]) input.resolved = old.resolved finish() else @@ -178,7 +143,7 @@ function M.read(session, event, previous, done) end end if session.result_bufnr then - data.result = lines(session.result_bufnr) + data.result = M.lines(session.result_bufnr) end finish() end @@ -192,5 +157,4 @@ function M.valid(data) return true end -M.lines = lines return M diff --git a/lua/codediff/ui/refresh/panel.lua b/lua/codediff/ui/refresh/panel.lua new file mode 100644 index 00000000..5819a97a --- /dev/null +++ b/lua/codediff/ui/refresh/panel.lua @@ -0,0 +1,240 @@ +-- Session-owned panel data and comparison definitions. No windows or tree nodes. +local M = {} +local git = require("codediff.core.git") +local path = require("codediff.core.path") +local policy = require("codediff.ui.refresh.policy") + +function M.new(session_config) + local panel = session_config.panel + local data = vim.deepcopy(panel.data or {}) + data.git_root = session_config.git_root + if panel.name == "explorer" then + data.base_revision = session_config.original_revision + data.target_revision = session_config.modified_revision + data.status_result = data.status_result or { unstaged = {}, staged = {}, conflicts = {} } + if not data.git_root then + data.dir1, data.dir2 = session_config.original.absolute, session_config.modified.absolute + end + else + data.opts = { range = data.range, file_path = data.file_path, base_revision = data.base_revision, line_range = data.line_range } + data.commits, data.files = data.commits or {}, {} + end + return data +end + +-- Resolve requested refs without replacing their symbolic dependency identities. +function M.resolve(config, done) + local remaining, failure = 1, nil + local function settled(err) + failure = failure or err + remaining = remaining - 1 + if remaining == 0 then + done(failure, config) + end + end + for _, side in ipairs({ "original", "modified" }) do + local revision = config[side .. "_revision"] + if revision and not policy.is_working(revision) and not revision:match("^:[0-3]:?$") then + remaining = remaining + 1 + git.resolve_revision(revision, config.git_root, function(err, hash) + vim.schedule(function() + config[side .. "_revision"] = hash + settled(err) + end) + end) + end + end + settled() +end + +function M.read(session, done) + local panel, data = session.panel, session.panel.data + local next_data = vim.tbl_extend("force", {}, data) + local function status_result(err, status) + vim.schedule(function() + next_data.status_result = status + done(err, next_data) + end) + end + if panel.name == "history" then + local opts = { no_merges = true, path = data.opts.file_path } + local range = data.opts.range or "" + if range == "" then + opts.limit = 100 + end + git.get_commit_list(range, data.git_root, opts, function(err, commits) + vim.schedule(function() + next_data.commits = commits + done(err, next_data) + end) + end) + return + end + + local function fetch_status() + if not data.git_root then + status_result(nil, require("codediff.core.dir").diff_directories(data.dir1, data.dir2).status_result) + elseif next_data.target_revision == ":0" then + git.get_diff_staged(next_data.base_revision, data.git_root, status_result, data.pathspec) + elseif next_data.base_revision and next_data.target_revision and next_data.target_revision ~= "WORKING" then + git.get_diff_revisions_with_line_stats(next_data.base_revision, next_data.target_revision, data.git_root, status_result, data.pathspec) + elseif next_data.base_revision then + git.get_diff_revision_with_line_stats(next_data.base_revision, data.git_root, status_result, data.pathspec) + else + git.get_status_with_line_stats(data.git_root, status_result, data.pathspec) + end + end + if not data.source_revisions then + fetch_status() + return + end + M.resolve({ + git_root = data.git_root, + original_revision = data.source_revisions.original, + modified_revision = data.source_revisions.modified, + }, function(err, resolved) + if err then + done(err) + return + end + next_data.base_revision, next_data.target_revision = resolved.original_revision, resolved.modified_revision + fetch_status() + end) +end + +-- Keep the old group's slot when staging removes its selected entry (#347). +function M.reselect(previous, status) + local selected = previous.current_selection + if not selected then + return + end + local function find(group) + for _, file in ipairs(status[group] or {}) do + if file.path == selected.path then + return vim.tbl_extend("force", file, { group = group, git_root = previous.git_root }) + end + end + end + local group = selected.group + if group then + local same = find(group) + if same then + return same + end + for i, file in ipairs((previous.status_result or {})[group] or {}) do + if file.path == selected.path and #(status[group] or {}) > 0 then + return vim.tbl_extend("force", status[group][math.min(i, #status[group])], { group = group, git_root = previous.git_root }) + end + end + end + for _, candidate in ipairs({ "conflicts", "unstaged", "staged" }) do + local file = find(candidate) + if file then + return file + end + end +end + +function M.same_selection(first, second) + if not first or not second then + return first == second + end + for _, key in ipairs({ "path", "group", "status", "old_path", "commit_hash" }) do + if first[key] ~= second[key] then + return false + end + end + return true +end + +function M.set_selection(panel, file) + local data = panel.data + data.current_selection = file and vim.deepcopy(file) or nil + if panel.name == "explorer" then + data.current_file_path, data.current_file_group = file and file.path, file and file.group + else + data.current_file, data.current_commit = file and file.path, file and file.commit_hash + end +end + +-- A selection defines its sources here; input refresh never infers them from UI state. +function M.comparison(panel, file) + local data = panel.data + file = file or data.current_selection + if not file or not file.path or file.path == "" then + return + end + local original, modified = file.old_path or file.path, file.path + local original_revision, modified_revision, conflict, line_range + if panel.name == "history" then + if not file.commit_hash or file.commit_hash == "" then + return + end + original_revision = data.opts.base_revision or (file.commit_hash .. "^") + modified_revision = file.commit_hash + original = data.opts.base_revision and file.path or original + line_range = data.opts.line_range + elseif data.git_root then + local refs = data.source_revisions or {} + if file.group == "conflicts" then + local ours_right = require("codediff.config").options.diff.conflict_ours_position ~= "left" + original_revision, modified_revision = ours_right and ":3" or ":2", ours_right and ":2" or ":3" + conflict = true + elseif data.base_revision then + original_revision = refs.original or data.base_revision + modified_revision = refs.modified or data.target_revision or "WORKING" + elseif file.group == "staged" then + original_revision, modified_revision = "HEAD", ":0" + else + original_revision, modified_revision = "HEAD", "WORKING" + for _, staged in ipairs(data.status_result.staged or {}) do + if staged.path == file.path then + original_revision = ":0" + break + end + end + if file.status == "D" then + original_revision = ":0" + end + end + end + local single_side + if data.git_root then + if file.status == "??" or file.status == "A" then + single_side, original_revision = "modified", nil + elseif file.status == "D" then + single_side, modified_revision = "original", nil + end + end + return { + git_root = data.git_root, + original = single_side == "modified" and path.empty() or path.make_ref(original, data.git_root or data.dir1), + modified = single_side == "original" and path.empty() or path.make_ref(modified, data.git_root or data.dir2), + original_revision = original_revision ~= "WORKING" and original_revision or nil, + modified_revision = modified_revision ~= "WORKING" and modified_revision or nil, + source_revisions = { original = original_revision, modified = modified_revision }, + conflict = conflict, + single_side = single_side, + line_range = line_range, + } +end + +function M.load_files(data, hash, done) + if data.files[hash] then + done(nil, data.files[hash]) + return + end + git.get_commit_files(hash, data.git_root, function(err, files) + vim.schedule(function() + if err then + done(err) + return + end + local filter = require("codediff.ui.explorer.filter") + local options = require("codediff.config").options.explorer.file_filter or {} + done(nil, filter.apply(files, options.ignore or {})) + end) + end) +end + +return M diff --git a/lua/codediff/ui/refresh/policy.lua b/lua/codediff/ui/refresh/policy.lua index b2fc233d..677edbf9 100644 --- a/lua/codediff/ui/refresh/policy.lua +++ b/lua/codediff/ui/refresh/policy.lua @@ -62,13 +62,13 @@ function M.panel_needed(panel, event) if panel.name == "history" then return event.head == true or event.refs == true end - local view = panel.view or {} - if not view.git_root and view.dir1 then + local data = panel.data or {} + if not data.git_root and data.dir1 then return event.worktree == true end - if view.base_revision then - local refs = view.source_revisions or {} - return M.needs_read(refs.original or view.base_revision, event) or M.needs_read(refs.modified or view.target_revision or "WORKING", event) + if data.base_revision then + local refs = data.source_revisions or {} + return M.needs_read(refs.original or data.base_revision, event) or M.needs_read(refs.modified or data.target_revision or "WORKING", event) end return event.worktree == true or event.index == true or event.head == true or event.refs == true end diff --git a/lua/codediff/ui/view/actions/diffget.lua b/lua/codediff/ui/view/actions/diffget.lua index 1f7c9466..06b727ac 100644 --- a/lua/codediff/ui/view/actions/diffget.lua +++ b/lua/codediff/ui/view/actions/diffget.lua @@ -6,7 +6,7 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") +local refresh = require("codediff.ui.refresh") local hunk_actions = require("codediff.ui.view.actions.hunk") function M.diff_get(ctx) @@ -30,7 +30,7 @@ function M.diff_get(ctx) local orig_lines = vim.api.nvim_buf_get_lines(ctx.original_bufnr, hunk.original.start_line - 1, hunk.original.end_line - 1, false) vim.api.nvim_buf_set_lines(ctx.modified_bufnr, hunk.modified.start_line - 1, hunk.modified.end_line - 1, false, orig_lines) - auto_refresh.trigger(ctx.modified_bufnr) + refresh.buffer_changed(ctx.modified_bufnr) vim.api.nvim_echo({ { string.format("Reverted hunk %d", hunk_idx), "None" } }, false, {}) return end @@ -64,7 +64,7 @@ function M.diff_get(ctx) vim.api.nvim_buf_set_lines(target_buf, target_range.start_line - 1, target_range.end_line - 1, false, source_lines) -- Trigger diff refresh to update highlights - auto_refresh.trigger(target_buf) + refresh.buffer_changed(target_buf) vim.api.nvim_echo({ { string.format("Obtained hunk %d", hunk_idx), "None" } }, false, {}) end @@ -110,7 +110,7 @@ function M.diff_put(ctx) vim.api.nvim_buf_set_lines(target_buf, target_range.start_line - 1, target_range.end_line - 1, false, source_lines) -- Trigger diff refresh to update highlights - auto_refresh.trigger(target_buf) + refresh.buffer_changed(target_buf) vim.api.nvim_echo({ { string.format("Put hunk %d", hunk_idx), "None" } }, false, {}) end diff --git a/lua/codediff/ui/view/actions/hunk.lua b/lua/codediff/ui/view/actions/hunk.lua index 69de9ff5..a8deabc9 100644 --- a/lua/codediff/ui/view/actions/hunk.lua +++ b/lua/codediff/ui/view/actions/hunk.lua @@ -8,7 +8,7 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local auto_refresh = require("codediff.ui.auto_refresh") +local refresh = require("codediff.ui.refresh") function M.find_hunk_at_cursor(ctx) local session = lifecycle.get_session(ctx.tabpage) @@ -224,7 +224,7 @@ function M.discard_hunk(ctx) return end - auto_refresh.trigger(discard_mod_buf) + refresh.buffer_changed(discard_mod_buf) vim.notify(string.format("Discarded hunk %d", hunk_idx), vim.log.levels.INFO) end diff --git a/lua/codediff/ui/view/actions/stage.lua b/lua/codediff/ui/view/actions/stage.lua index aaf26d85..fec1c623 100644 --- a/lua/codediff/ui/view/actions/stage.lua +++ b/lua/codediff/ui/view/actions/stage.lua @@ -19,7 +19,7 @@ function M.toggle_stage(ctx) return end - if not explorer or not explorer.git_root then + if not explorer or not explorer.data.git_root then vim.notify("Stage/unstage only available in git mode", vim.log.levels.WARN) return end @@ -34,8 +34,8 @@ function M.toggle_stage(ctx) -- Case 2: Cursor in diff buffers (original or modified) if current_buf == ctx.original_bufnr or current_buf == ctx.modified_bufnr then - local file_path = explorer.current_file_path - local group = explorer.current_file_group + local file_path = explorer.data.current_file_path + local group = explorer.data.current_file_group -- Guard: must have a current file selected if not file_path then @@ -50,7 +50,7 @@ function M.toggle_stage(ctx) end local explorer_module = require("codediff.ui.explorer") - explorer_module.toggle_stage_file(explorer.git_root, file_path, group) + explorer_module.toggle_stage_file(explorer.data.git_root, file_path, group) return end diff --git a/lua/codediff/ui/view/helpers.lua b/lua/codediff/ui/view/helpers.lua index 3e2e75e7..5ca22f8c 100644 --- a/lua/codediff/ui/view/helpers.lua +++ b/lua/codediff/ui/view/helpers.lua @@ -148,4 +148,53 @@ function M.open_real_file(win, target) return vim.api.nvim_get_current_buf() end +-- Replace generated content without changing the buffer's editing permissions. +function M.set_lines(buf, lines) + if vim.deep_equal(vim.api.nvim_buf_get_lines(buf, 0, -1, false), lines) then + return + end + local modifiable, readonly = vim.bo[buf].modifiable, vim.bo[buf].readonly + vim.bo[buf].modifiable, vim.bo[buf].readonly = true, false + vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines) + vim.bo[buf].modifiable, vim.bo[buf].readonly = modifiable, readonly +end + +-- Install a resolved input in the existing pane, without reopening the view. +function M.update_content(session, side, input, lines) + local buf = session[side .. "_bufnr"] + if not input.path or input.path.absolute == "" then + return + end + if not M.is_virtual_revision(input.revision) then + if vim.bo[buf].buftype ~= "" then + M.set_lines(buf, lines) + end + return + end + if input.resolved ~= session[side .. "_revision"] then + local name = virtual_file.create_url(session.git_root, input.resolved, input.path.relative) + local existing = bufnr_exact(name) + if existing ~= -1 and vim.api.nvim_buf_is_loaded(existing) then + buf = existing + else + buf = vim.api.nvim_create_buf(false, true) + if existing == -1 then + vim.api.nvim_buf_set_name(buf, name) + end + vim.bo[buf].buftype = "nowrite" + vim.bo[buf].bufhidden = "hide" + vim.bo[buf].swapfile = false + end + session[side .. "_bufnr"] = buf + local win = session[side .. "_win"] + local hidden = side == "original" and session.layout == "inline" and session.single_side ~= "original" + if win and vim.api.nvim_win_is_valid(win) and not hidden then + vim.api.nvim_win_set_buf(win, buf) + vim.bo[buf].bufhidden = "wipe" + end + end + virtual_file.set_content(buf, lines, input.path.relative) + session[side .. "_revision"] = input.resolved +end + return M diff --git a/lua/codediff/ui/view/init.lua b/lua/codediff/ui/view/init.lua index 63e365c0..ff47c8d7 100644 --- a/lua/codediff/ui/view/init.lua +++ b/lua/codediff/ui/view/init.lua @@ -78,6 +78,56 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) return side_by_side.update(tabpage, session_config, auto_scroll_to_first_hunk) end +-- Display a resolved comparison selected by the session controller. +function M.show(tabpage, session_config, jump) + local side = session_config.single_side + if not side then + return M.update(tabpage, session_config, jump) + end + lifecycle.update_merge(tabpage, session_config.conflict) + local ref = session_config[side] + local revision = session_config[side .. "_revision"] + if get_layout(session_config, tabpage) == "inline" then + require("codediff.ui.view.inline_view").show_single_file(tabpage, ref.absolute, { + revision = revision ~= "WORKING" and revision or nil, + git_root = session_config.git_root, + rel_path = ref.relative, + side = side, + }) + elseif revision and revision ~= "WORKING" then + local show = side == "original" and side_by_side.show_deleted_virtual_file or side_by_side.show_added_virtual_file + show(tabpage, session_config.git_root, ref.relative, revision) + else + side_by_side.show_untracked_file(tabpage, ref.absolute) + end + return true +end + +function M.show_welcome(tabpage) + local session = lifecycle.get_session(tabpage) + local win = session and session.modified_win + if not win or not vim.api.nvim_win_is_valid(win) then + return false + end + local welcome = require("codediff.ui.welcome") + if welcome.is_welcome_buffer(session.modified_bufnr) then + require("codediff.ui.refresh").ready(tabpage) + return true + end + local width, height = vim.api.nvim_win_get_width(win), vim.api.nvim_win_get_height(win) + local original = session.original_win + if session.layout ~= "inline" and original and vim.api.nvim_win_is_valid(original) then + width, height = width + vim.api.nvim_win_get_width(original) + 1, vim.api.nvim_win_get_height(original) + end + local buf = welcome.create_buffer(width, height) + if session.layout == "inline" then + require("codediff.ui.view.inline_view").show_welcome(tabpage, buf) + else + side_by_side.show_welcome(tabpage, buf) + end + return true +end + function M.toggle_layout(tabpage) return require("codediff.ui.view.toggle").toggle(tabpage) end diff --git a/lua/codediff/ui/view/inline_view/buffers.lua b/lua/codediff/ui/view/inline_view/buffers.lua index 1a57d026..b5715afd 100644 --- a/lua/codediff/ui/view/inline_view/buffers.lua +++ b/lua/codediff/ui/view/inline_view/buffers.lua @@ -3,7 +3,7 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -function M.disable_refresh_and_clear_highlights(session) +function M.clear_highlights(session) for _, bufnr in pairs({ session.original_bufnr, session.modified_bufnr }) do if vim.api.nvim_buf_is_valid(bufnr) then lifecycle.clear_highlights(bufnr) diff --git a/lua/codediff/ui/view/inline_view/render.lua b/lua/codediff/ui/view/inline_view/render.lua index e3a99625..f2fd7fa2 100644 --- a/lua/codediff/ui/view/inline_view/render.lua +++ b/lua/codediff/ui/view/inline_view/render.lua @@ -2,26 +2,15 @@ local M = {} local lifecycle = require("codediff.ui.lifecycle") -local config = require("codediff.config") -local diff_module = require("codediff.core.diff") -local inline = require("codediff.ui.inline") +local render = require("codediff.ui.view.render") local cursor_util = require("codediff.ui.view.cursor") function M.compute_and_render_inline(modified_buf, original_buf, original_lines, modified_lines, original_is_virtual, modified_is_virtual, modified_win, auto_scroll_to_first_hunk) - local diff_options = { - max_computation_time_ms = config.options.diff.max_computation_time_ms, - ignore_trim_whitespace = config.options.diff.ignore_trim_whitespace, - compute_moves = config.options.diff.compute_moves, - } - - local lines_diff = diff_module.compute_diff(original_lines, modified_lines, diff_options) + local lines_diff = render.render_diff(original_buf, modified_buf, original_lines, modified_lines, "inline") if not lines_diff then - vim.notify("Failed to compute diff", vim.log.levels.ERROR) - return nil + return end - inline.render_inline_diff(modified_buf, lines_diff, original_lines, modified_lines) - if modified_win and vim.api.nvim_win_is_valid(modified_win) then vim.wo[modified_win].wrap = false if auto_scroll_to_first_hunk and lines_diff.changes and #lines_diff.changes > 0 then @@ -64,15 +53,8 @@ function M.rerender(tabpage) local original_lines = vim.api.nvim_buf_get_lines(original_bufnr, 0, -1, false) local modified_lines = vim.api.nvim_buf_get_lines(modified_bufnr, 0, -1, false) - local diff_options = { - max_computation_time_ms = config.options.diff.max_computation_time_ms, - ignore_trim_whitespace = config.options.diff.ignore_trim_whitespace, - compute_moves = config.options.diff.compute_moves, - } - - local lines_diff = diff_module.compute_diff(original_lines, modified_lines, diff_options) + local lines_diff = render.render_diff(original_bufnr, modified_bufnr, original_lines, modified_lines, "inline") if lines_diff then - inline.render_inline_diff(modified_bufnr, lines_diff, original_lines, modified_lines) lifecycle.update_diff_result(tabpage, lines_diff) end end diff --git a/lua/codediff/ui/view/inline_view/single_file.lua b/lua/codediff/ui/view/inline_view/single_file.lua index 20d3130a..8d94808d 100644 --- a/lua/codediff/ui/view/inline_view/single_file.lua +++ b/lua/codediff/ui/view/inline_view/single_file.lua @@ -10,7 +10,7 @@ local helpers = require("codediff.ui.view.helpers") local buffers = require("codediff.ui.view.inline_view.buffers") local open_real_file = helpers.open_real_file -local disable_refresh_and_clear_highlights = buffers.disable_refresh_and_clear_highlights +local clear_highlights = buffers.clear_highlights --- Display a single file in the inline diff window without any diff decorations. --- Used for untracked (??), added (A), and deleted (D) files in explorer/history. @@ -31,9 +31,8 @@ function M.show_single_file(tabpage, file_path, opts) return end - -- Clear old inline decorations - -- Disable old auto-refresh - disable_refresh_and_clear_highlights(session) + -- Clear old inline decorations. + clear_highlights(session) -- Load the file local file_bufnr @@ -96,7 +95,7 @@ function M.show_welcome(tabpage, load_bufnr) return end - disable_refresh_and_clear_highlights(session) + clear_highlights(session) session.single_side = nil vim.api.nvim_win_set_buf(mod_win, load_bufnr) diff --git a/lua/codediff/ui/view/inline_view/update.lua b/lua/codediff/ui/view/inline_view/update.lua index 55eeaf43..38b7c2b2 100644 --- a/lua/codediff/ui/view/inline_view/update.lua +++ b/lua/codediff/ui/view/inline_view/update.lua @@ -14,7 +14,7 @@ local is_virtual_revision = helpers.is_virtual_revision local prepare_buffer = helpers.prepare_buffer local show_real_file_buffer = helpers.show_real_file_buffer local open_real_file = helpers.open_real_file -local disable_refresh_and_clear_highlights = buffers.disable_refresh_and_clear_highlights +local clear_highlights = buffers.clear_highlights local set_scratch_lines = buffers.set_scratch_lines local new_scratch = buffers.new_scratch local compute_and_render_inline = inline_render.compute_and_render_inline @@ -130,7 +130,7 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) end -- ns_highlight/ns_filler may linger after toggling from side-by-side. - disable_refresh_and_clear_highlights(session) + clear_highlights(session) session.single_side = nil lifecycle.update_diff_result(tabpage, nil) diff --git a/lua/codediff/ui/view/panel.lua b/lua/codediff/ui/view/panel.lua index d3cbfe39..cd51d609 100644 --- a/lua/codediff/ui/view/panel.lua +++ b/lua/codediff/ui/view/panel.lua @@ -23,22 +23,8 @@ function M.setup_explorer(tabpage, session_config, original_win, modified_win) end local explorer_config = config.options.explorer or {} - local status_result = panel.data.status_result - - local explorer_opts = {} - if not session_config.git_root then - explorer_opts.dir1 = session_config.original.absolute - explorer_opts.dir2 = session_config.modified.absolute - end - if panel.data.focus_file then - explorer_opts.focus_file = panel.data.focus_file - end - -- Scope (#74): carry the pathspec so auto-refresh re-applies it (see refresh.lua). - explorer_opts.pathspec = panel.data.pathspec - explorer_opts.source_revisions = panel.data.source_revisions - - local explorer_obj = - explorer_module.create(status_result, session_config.git_root, tabpage, nil, session_config.original_revision, session_config.modified_revision, explorer_opts) + local data = lifecycle.get_panel(tabpage).data + local explorer_obj = explorer_module.create(data, tabpage) lifecycle.set_panel_view(tabpage, explorer_obj) @@ -66,14 +52,8 @@ function M.setup_history(tabpage, session_config, original_win, modified_win) end local history_config = config.options.history or {} - local commits = panel.data.commits - - local history_obj = history_module.create(commits, session_config.git_root, tabpage, nil, { - range = panel.data.range, - file_path = panel.data.file_path, - base_revision = panel.data.base_revision, - line_range = panel.data.line_range, - }) + local data = lifecycle.get_panel(tabpage).data + local history_obj = history_module.create(data, tabpage) lifecycle.set_panel_view(tabpage, history_obj) diff --git a/lua/codediff/ui/view/render.lua b/lua/codediff/ui/view/render.lua index 61932cb1..fdb2de76 100644 --- a/lua/codediff/ui/view/render.lua +++ b/lua/codediff/ui/view/render.lua @@ -55,6 +55,29 @@ function M.establish_scrollbind(orig_win, mod_win, orig_buf, mod_buf, lines_diff set_cursor(mod_win, mod_cursor) end +function M.diff_options() + return { + max_computation_time_ms = config.options.diff.max_computation_time_ms, + ignore_trim_whitespace = config.options.diff.ignore_trim_whitespace, + compute_moves = config.options.diff.compute_moves, + } +end + +-- Initial opens and data updates share computation and decoration rendering. +function M.render_diff(original_buf, modified_buf, original_lines, modified_lines, layout) + local result = diff_module.compute_diff(original_lines, modified_lines, M.diff_options()) + if not result then + vim.notify("Failed to compute diff", vim.log.levels.ERROR) + return + end + if layout == "inline" then + require("codediff.ui.inline").render_inline_diff(modified_buf, result, original_lines, modified_lines) + else + core.render_diff(original_buf, modified_buf, original_lines, modified_lines, result) + end + return result +end + -- Common logic: Compute diff and render highlights -- @param auto_scroll_to_first_hunk boolean: Whether to auto-scroll to first change (default true) -- @param line_range table?: Optional {start_line, end_line} to scroll to instead of first hunk @@ -70,21 +93,11 @@ function M.compute_and_render( auto_scroll_to_first_hunk, line_range ) - -- Compute diff - local diff_options = { - max_computation_time_ms = config.options.diff.max_computation_time_ms, - ignore_trim_whitespace = config.options.diff.ignore_trim_whitespace, - compute_moves = config.options.diff.compute_moves, - } - local lines_diff = diff_module.compute_diff(original_lines, modified_lines, diff_options) + local lines_diff = M.render_diff(original_buf, modified_buf, original_lines, modified_lines) if not lines_diff then - vim.notify("Failed to compute diff", vim.log.levels.ERROR) - return nil + return end - -- Render diff highlights - core.render_diff(original_buf, modified_buf, original_lines, modified_lines, lines_diff) - -- Setup scroll synchronization (only if windows provided) if original_win and modified_win and vim.api.nvim_win_is_valid(original_win) and vim.api.nvim_win_is_valid(modified_win) then -- Save cursor position if we need to preserve it (on update) @@ -168,4 +181,74 @@ function M.compute_and_render( return lines_diff end +-- Consume a session data change without re-running file selection or window setup. +function M.update(session, data, changes) + local api = vim.api + local result_view = require("codediff.ui.conflict.view.result") + if not changes.inputs and not changes.redraw then + if changes.result then + result_view.render(session) + end + return + end + + local helpers = require("codediff.ui.view.helpers") + local views = {} + for _, side in ipairs({ "original", "modified", "result" }) do + local win = session[side .. "_win"] + if win and api.nvim_win_is_valid(win) and not views[win] then + views[win] = { view = api.nvim_win_call(win, vim.fn.winsaveview), scrollbind = vim.wo[win].scrollbind } + vim.wo[win].scrollbind = false + end + end + local focused = api.nvim_get_current_win() + local old_original, old_modified = session.original_bufnr, session.modified_bufnr + local ok, err = xpcall(function() + if changes.inputs then + helpers.update_content(session, "original", data.sources.original, data.original) + helpers.update_content(session, "modified", data.sources.modified, data.modified) + end + if session.result_bufnr then + local diffs = + assert(require("codediff.ui.conflict.view.inputs").compute_and_render_conflict(session.original_bufnr, session.modified_bufnr, data.base, data.original, data.modified)) + if changes.inputs then + result_view.set_inputs(session, data.base, diffs) + end + session.stored_diff_result = diffs.base_to_modified_diff + require("codediff.ui.conflict").attach_gutter(session.original_win, session.modified_win) + result_view.render(session) + elseif session.single_side then + core.render_whole_file(session[session.single_side .. "_bufnr"], session.single_side) + session.stored_diff_result = { changes = {}, moves = {} } + else + session.stored_diff_result = assert(M.render_diff(session.original_bufnr, session.modified_bufnr, data.original, data.modified, session.layout)) + end + session.changedtick.original = api.nvim_buf_get_changedtick(session.original_bufnr) + session.changedtick.modified = api.nvim_buf_get_changedtick(session.modified_bufnr) + if old_original ~= session.original_bufnr or old_modified ~= session.modified_bufnr then + require("codediff.ui.lifecycle").update_buffers(session.tabpage, session.original_bufnr, session.modified_bufnr) + if session.reapply_keymaps then + session.reapply_keymaps() + end + end + require("codediff.ui.view.compact").refresh(session.tabpage) + end, debug.traceback) + for win, saved in pairs(views) do + if api.nvim_win_is_valid(win) then + api.nvim_win_call(win, function() + local cursor = cursor_util.clamp_cursor(win, { saved.view.lnum, saved.view.col }) + saved.view.lnum, saved.view.col = cursor[1], cursor[2] + vim.fn.winrestview(saved.view) + end) + vim.wo[win].scrollbind = saved.scrollbind + end + end + if api.nvim_win_is_valid(focused) and api.nvim_get_current_win() ~= focused then + api.nvim_set_current_win(focused) + end + if not ok then + error(err) + end +end + return M diff --git a/lua/codediff/ui/view/toggle.lua b/lua/codediff/ui/view/toggle.lua index ecbe67ba..a1b4d76b 100644 --- a/lua/codediff/ui/view/toggle.lua +++ b/lua/codediff/ui/view/toggle.lua @@ -62,7 +62,7 @@ function M.normalize_side_by_side_layout(tabpage) end -- Re-render the current file in the new layout. --- For explorer/history: call rerender_current which re-triggers on_file_select. +-- Panels replay the session's selected comparison through the data controller. -- For a bare diff (no panel): rebuild session_config from existing session fields. local function rerender_current_file(tabpage) local session = lifecycle.get_session(tabpage) @@ -70,15 +70,8 @@ local function rerender_current_file(tabpage) return false end - local panel = session.panel - local panel_name = panel and panel.name - - if panel_name == "explorer" then - return panel.view and require("codediff.ui.explorer").rerender_current(panel.view) or false - end - - if panel_name == "history" then - return panel.view and require("codediff.ui.history").rerender_current(panel.view) or false + if session.panel then + return require("codediff.ui.refresh").reopen(tabpage) end -- No panel: rebuild from session fields diff --git a/tests/README.md b/tests/README.md index 671bee57..06ef379d 100644 --- a/tests/README.md +++ b/tests/README.md @@ -150,7 +150,10 @@ failover. Plain file/directory comparisons use polling without Git metadata. `ui/refresh/policy_spec.lua`, `ui/auto_refresh_spec.lua` and `ui/explorer/native_watcher_spec.lua` cover dependency selection, settled input snapshots, event coalescing, retries and stale callback rejection independently -of the screen tests. +of the screen tests. Controller tests also check that unchanged inputs do not +notify the diff renderer and list-only updates do not invoke file selection. +Explorer and History specs verify that their `on_data` handlers render supplied +session data without fetching Git data from the view. ## Test Philosophy diff --git a/tests/command_e2e_spec.lua b/tests/command_e2e_spec.lua index 77c9d083..db041bf0 100644 --- a/tests/command_e2e_spec.lua +++ b/tests/command_e2e_spec.lua @@ -208,8 +208,8 @@ describe("Command E2E (real dispatch + render)", function() assert.is_not_nil(session) local explorer = (session.panel or {}).view assert.is_not_nil(explorer) - assert.equals(":0", explorer.target_revision, "explorer.target_revision is the index (:0)") - assert.is_not_nil(explorer.base_revision, "explorer.base_revision resolves to HEAD~1") + assert.equals(":0", explorer.data.target_revision, "the comparison target is the index (:0)") + assert.is_not_nil(explorer.data.base_revision, "the comparison base resolves to HEAD~1") end) it(":CodeDiff --staged with no staged changes — notifies gracefully", function() @@ -298,8 +298,8 @@ describe("Command E2E (real dispatch + render)", function() local history_session = lifecycle.get_session(history_tab) assert.is_not_nil(history_session.panel.view) - assert.are.same({ 1, 2 }, history_session.panel.view.opts.line_range) - assert.equals("file.txt", history_session.panel.view.opts.file_path) + assert.are.same({ 1, 2 }, history_session.panel.data.opts.line_range) + assert.equals("file.txt", history_session.panel.data.opts.file_path) assert.is_true(wait_for_visible("c1"), "history should show commits for the selected lines") end) @@ -439,7 +439,7 @@ describe("Command E2E (real dispatch + render)", function() repo.write_file("modules/store/s2.txt", { "s2" }) repo.write_file("modules/net/n2.txt", { "n2" }) local explorer = lifecycle.get_panel_view(find_explorer_tab()) - require("codediff.ui.explorer.refresh").refresh(explorer) + require("codediff.ui.refresh").request(explorer.tabpage, { full = true }) local refreshed = vim.wait(10000, function() local buf = find_explorer_buf() diff --git a/tests/core/pull_request_spec.lua b/tests/core/pull_request_spec.lua index c80dbc47..e8bf58b2 100644 --- a/tests/core/pull_request_spec.lua +++ b/tests/core/pull_request_spec.lua @@ -220,7 +220,7 @@ describe("pull request fetching", function() "pull request review did not open" ) assert.is_not_nil(session) - local files = require("codediff.ui.explorer.refresh").get_all_files(session.panel.view.tree) + local files = require("codediff.ui.explorer.tree").get_all_files(session.panel.view.tree) assert.equals(1, #files) assert.equals("review.txt", files[1].data.path) assert.equals("main", run(repo.dir, { "branch", "--show-current" })) diff --git a/tests/module_loading_spec.lua b/tests/module_loading_spec.lua index 84ce167f..ae7ae08b 100644 --- a/tests/module_loading_spec.lua +++ b/tests/module_loading_spec.lua @@ -81,9 +81,9 @@ describe("Explorer submodules", function() assert.is_not_nil(mod) end) - it("loads refresh module", function() - local ok, mod = pcall(require, "codediff.ui.explorer.refresh") - assert.is_true(ok, "Failed to require codediff.ui.explorer.refresh") + it("loads the shared session refresh module", function() + local ok, mod = pcall(require, "codediff.ui.refresh") + assert.is_true(ok, "Failed to require codediff.ui.refresh") assert.is_not_nil(mod) end) @@ -139,11 +139,13 @@ describe("Explorer submodules", function() assert.is_function(mod.create) end) - it("refresh exports expected functions", function() - local mod = require("codediff.ui.explorer.refresh") - assert.is_function(mod.setup_auto_refresh) - assert.is_function(mod.refresh) - assert.is_function(mod.get_all_files) + it("session refresh exports data and lifecycle entry points", function() + local mod = require("codediff.ui.refresh") + assert.is_function(mod.attach) + assert.is_function(mod.request) + assert.is_function(mod.select) + assert.is_function(mod.dispose) + assert.is_function(require("codediff.ui.explorer.tree").get_all_files) end) it("tree exports create_tree_data", function() @@ -472,9 +474,9 @@ end) -- ── history ───────────────────────────────────────────────────────────── describe("History submodules", function() describe("module loading", function() - it("loads refresh module", function() - local ok, mod = pcall(require, "codediff.ui.history.refresh") - assert.is_true(ok, "Failed to require codediff.ui.history.refresh") + it("loads the session panel data module", function() + local ok, mod = pcall(require, "codediff.ui.refresh.panel") + assert.is_true(ok, "Failed to require codediff.ui.refresh.panel") assert.is_not_nil(mod) end) @@ -492,10 +494,11 @@ describe("History submodules", function() end) describe("public API", function() - it("refresh exports expected functions", function() - local mod = require("codediff.ui.history.refresh") - assert.is_function(mod.setup_auto_refresh) - assert.is_function(mod.refresh) + it("panel data exports reads and comparison definitions", function() + local mod = require("codediff.ui.refresh.panel") + assert.is_function(mod.read) + assert.is_function(mod.comparison) + assert.is_function(mod.load_files) end) it("render exports expected functions", function() diff --git a/tests/ui/auto_refresh_spec.lua b/tests/ui/auto_refresh_spec.lua index 94de8b5e..9c814dbf 100644 --- a/tests/ui/auto_refresh_spec.lua +++ b/tests/ui/auto_refresh_spec.lua @@ -1,4 +1,4 @@ -local snapshot = require("codediff.ui.refresh.snapshot") +local snapshot = require("codediff.ui.refresh.inputs") describe("refresh input snapshots", function() local git, original_get_content, session, buffers, callbacks @@ -32,6 +32,20 @@ describe("refresh input snapshots", function() end end) + it("reads source definitions from the session without inspecting a panel", function() + session.source_revisions = { original = "review/topic", modified = ":0" } + session.panel = setmetatable({}, { + __index = function() + error("input reading must not inspect panel state") + end, + }) + local sources = snapshot.describe(session) + assert.equals("review/topic", sources.original.revision) + assert.equals(":0", sources.modified.revision) + assert.equals(":2", sources.original.resolved) + assert.same(session.original, sources.original.path) + end) + it("settles all candidates before returning and does not mutate displayed buffers", function() local result snapshot.read(session, { index = true }, snapshot.capture(session), function(err, data) diff --git a/tests/ui/conflict/inline_tab_conflict_spec.lua b/tests/ui/conflict/inline_tab_conflict_spec.lua index 2b3a48f6..a1eb57a3 100644 --- a/tests/ui/conflict/inline_tab_conflict_spec.lua +++ b/tests/ui/conflict/inline_tab_conflict_spec.lua @@ -16,6 +16,7 @@ describe("conflicted file in an inline tab", function() repo = h.create_temp_git_repo() repo.write_file("conf.txt", { "base1", "base2", "base3" }) + repo.write_file("ordinary.txt", { "unchanged" }) repo.git("add -A") repo.git("commit -m base") repo.git("checkout -b feature") @@ -26,6 +27,7 @@ describe("conflicted file in an inline tab", function() repo.git("commit -am main") local merge_out = repo.git("merge feature --no-edit") assert.is_true(merge_out:find("CONFLICT", 1, true) ~= nil, "merge must conflict") + repo.write_file("ordinary.txt", { "ordinary change" }) end) after_each(function() @@ -40,37 +42,34 @@ describe("conflicted file in an inline tab", function() it("opens the three-pane merge view, not a single pane", function() local lifecycle = require("codediff.ui.lifecycle") - local path = require("codediff.core.path") - vim.cmd("edit " .. repo.path("conf.txt")) + vim.cmd("edit " .. repo.path("ordinary.txt")) vim.cmd("CodeDiff --inline") assert.is_true( vim.wait(15000, function() - return h.find_window_by_filetype("codediff-explorer") ~= nil + local session = lifecycle.get_session(vim.api.nvim_get_current_tabpage()) + return session and session.modified.relative == "ordinary.txt" and session.stored_diff_result ~= nil end, 50), - "inline explorer never opened" + "ordinary file never settled in the inline explorer" ) local tabpage = vim.api.nvim_get_current_tabpage() assert.equals("inline", lifecycle.get_session(tabpage).layout, "tab should start out inline") - -- Same config the explorer builds for a file in the Merge Changes group, - -- including which side lands on the left: conflict_ours_position decides, - -- and it defaults to putting OURS on the right. + -- Select through the session controller from a settled inline comparison. + -- conflict_ours_position defaults to putting OURS on the right. local ours_position = require("codediff.config").options.diff.conflict_ours_position or "right" local left_rev = ours_position == "right" and ":3" or ":2" local right_rev = ours_position == "right" and ":2" or ":3" local left_text = ours_position == "right" and "FEATURE1" or "MAIN1" local right_text = ours_position == "right" and "MAIN1" or "FEATURE1" - require("codediff.ui.view").update(tabpage, { + require("codediff.ui.refresh").select(tabpage, { + path = "conf.txt", + status = "UU", + group = "conflicts", git_root = repo.dir, - original = path.make_ref("conf.txt", repo.dir), - modified = path.make_ref("conf.txt", repo.dir), - original_revision = left_rev, - modified_revision = right_rev, - conflict = true, - }, false) + }, { no_jump = true }) -- The result pane appears before the two sides finish loading, so wait for -- content rather than for the window. @@ -91,6 +90,8 @@ describe("conflicted file in an inline tab", function() ) local session = lifecycle.get_session(tabpage) + assert.equals(left_rev, session.original_revision) + assert.equals(right_rev, session.modified_revision) -- Both sides need their own window, or one overwrites the other. assert.is_not_nil(session.original_win, "OURS needs a window") diff --git a/tests/ui/explorer/explorer_refresh_spec.lua b/tests/ui/explorer/explorer_refresh_spec.lua index 814a904d..54366a97 100644 --- a/tests/ui/explorer/explorer_refresh_spec.lua +++ b/tests/ui/explorer/explorer_refresh_spec.lua @@ -119,8 +119,8 @@ describe("Explorer refresh and single-file stability", function() local tabpage, explorer = open("file1.txt") local lifecycle = require("codediff.ui.lifecycle") local git = require("codediff.core.git") - local refresh = require("codediff.ui.explorer.refresh") - local status_before = vim.deepcopy(explorer.status_result) + local refresh = require("codediff.ui.refresh") + local status_before = vim.deepcopy(explorer.data.status_result) local git_callback local completed = 0 @@ -128,7 +128,7 @@ describe("Explorer refresh and single-file stability", function() git.get_status_with_line_stats = function(_, callback) git_callback = callback end - refresh.refresh(explorer, function() + refresh.request(explorer.tabpage, { full = true }, function() completed = completed + 1 end) assert.is_true(vim.wait(1000, function() @@ -153,7 +153,26 @@ describe("Explorer refresh and single-file stability", function() return not lifecycle.get_session(tabpage).refresh.running end, 10)) assert.equals(0, completed, "a retired panel must not replay navigation callbacks") - assert.same(status_before, explorer.status_result) + assert.same(status_before, explorer.data.status_result) + end) + + it("renders supplied list data without reading Git or reopening the comparison", function() + config.options.explorer.auto_refresh = false + local tabpage, explorer = open("file1.txt") + select_and_settle(explorer, "file1.txt", "M", "unstaged") + local session = require("codediff.ui.lifecycle").get_session(tabpage) + local before = { session.original_bufnr, session.modified_bufnr, session.original_win, session.modified_win } + local git = require("codediff.core.git") + original_get_status_with_line_stats = git.get_status_with_line_stats + git.get_status_with_line_stats = function() + error("rendering supplied data must not read Git") + end + local data = vim.deepcopy(session.panel.data) + data.status_result.unstaged[#data.status_result.unstaged + 1] = { path = "supplied.txt", status = "??" } + session.refresh:publish_panel(data) + assert.is_true(explorer.data == session.panel.data) + assert.is_not_nil(table.concat(vim.api.nvim_buf_get_lines(explorer.bufnr, 0, -1, false), "\n"):find("supplied.txt", 1, true)) + assert.same(before, { session.original_bufnr, session.modified_bufnr, session.original_win, session.modified_win }) end) it("picks up an externally-created untracked file automatically", function() @@ -166,7 +185,7 @@ describe("Explorer refresh and single-file stability", function() -- Wait for automatic refresh to observe the new working-tree state. local picked_up = vim.wait(3000, function() - for _, f in ipairs((explorer.status_result or {}).unstaged or {}) do + for _, f in ipairs((explorer.data.status_result or {}).unstaged or {}) do if f.path == "brand_new.txt" then return true end @@ -188,10 +207,10 @@ describe("Explorer refresh and single-file stability", function() return vim.api.nvim_buf_get_lines(session.modified_bufnr, 0, -1, false)[2] == "line 2 modified" end, 50) assert.is_true(selected, "the initial working-tree buffer should load") - local before_status = vim.deepcopy(explorer.status_result) + local before_status = vim.deepcopy(explorer.data.status_result) vim.fn.writefile({ "line 1", "changed again" }, temp_dir .. "/file1.txt") - explorer._request_auto_refresh() + require("codediff.ui.refresh").request(explorer.tabpage, { full = true }) local updated = vim.wait(5000, function() local session = lifecycle.get_session(tabpage) @@ -201,7 +220,7 @@ describe("Explorer refresh and single-file stability", function() return vim.api.nvim_buf_get_lines(session.modified_bufnr, 0, -1, false)[2] == "changed again" end, 50) assert.is_true(updated, "the visible working-tree buffer should reload") - assert.same(before_status, explorer.status_result, "the Git status remained unchanged") + assert.same(before_status, explorer.data.status_result, "the Git status remained unchanged") end) it("keeps a manually resized single-file pane across a refresh", function() diff --git a/tests/ui/explorer/explorer_spec.lua b/tests/ui/explorer/explorer_spec.lua index 2e621400..e984443c 100644 --- a/tests/ui/explorer/explorer_spec.lua +++ b/tests/ui/explorer/explorer_spec.lua @@ -38,7 +38,7 @@ local function open_explorer(temp_dir, focus_file) local e = lifecycle.get_panel_view(tp) if e and e.winid and vim.api.nvim_win_is_valid(e.winid) and e.bufnr and vim.api.nvim_buf_is_valid(e.bufnr) - and e.current_file_path ~= nil then + and e.data.current_file_path ~= nil then -- Pick the explorer wired with the auto-open j/k keymap; leftover -- explorers from prior tests (default config) lack it. local maps = vim.api.nvim_buf_get_keymap(e.bufnr, "n") @@ -75,7 +75,7 @@ local function open_initial_explorer(temp_dir, view_mode, ignore_patterns) local explorer, session local ready = vim.wait(6000, function() explorer = lifecycle.get_panel_view(vim.api.nvim_get_current_tabpage()) - if not explorer or not explorer.current_file_path then + if not explorer or not explorer.data.current_file_path then return false end session = lifecycle.get_session(explorer.tabpage) @@ -101,7 +101,7 @@ local function assert_first_visible_file_selected(explorer, session, expected_pa local cursor_line = vim.api.nvim_win_get_cursor(explorer.winid)[1] local cursor_node = explorer.tree:get_node(cursor_line) assert.equals(expected_path, first_path) - assert.equals(first_path, explorer.current_file_path) + assert.equals(first_path, explorer.data.current_file_path) assert.equals(first_path, cursor_node.data.path) assert.equals(first_path, session.original.relative) assert.equals(first_path, session.modified.relative) @@ -558,7 +558,7 @@ describe("Explorer Mode", function() vim.api.nvim_set_current_tabpage(tabpage) local target_line, target_path = find_file_node(explorer, function(data) - return data.path ~= explorer.current_file_path + return data.path ~= explorer.data.current_file_path end) assert.is_not_nil(target_line, "Should find a different file node") @@ -587,8 +587,8 @@ describe("Explorer Mode", function() assert.is_true(ready, "Explorer should be ready with an initial selection") vim.api.nvim_set_current_tabpage(tabpage) - local initial_path = explorer.current_file_path - local initial_group = explorer.current_file_group + local initial_path = explorer.data.current_file_path + local initial_group = explorer.data.current_file_group -- Find a file node and its delta from the current cursor line. local cur_line = vim.api.nvim_win_get_cursor(explorer.winid)[1] @@ -605,8 +605,8 @@ describe("Explorer Mode", function() vim.api.nvim_feedkeys(string.rep(motion, count), "tx", false) local opened = vim.wait(2000, function() - return explorer.current_file_path == target_path - and explorer.current_file_group == target_group + return explorer.data.current_file_path == target_path + and explorer.data.current_file_group == target_group end, 20) assert.is_true(opened, "j/k on a file node should auto-open its diff") end) @@ -647,8 +647,8 @@ describe("Explorer Mode", function() -- Capture state *after* manual cursor placement (which itself doesn't -- trigger our keymap, only j/k do). - local before_path = explorer.current_file_path - local before_group = explorer.current_file_group + local before_path = explorer.data.current_file_path + local before_group = explorer.data.current_file_group -- One j: lands on the skip_line (which is a group/dir). vim.api.nvim_feedkeys("j", "tx", false) @@ -656,9 +656,9 @@ describe("Explorer Mode", function() vim.wait(150) -- After landing on a group/dir, current_file_path must not have changed -- from before the j keypress. - assert.equals(before_path, explorer.current_file_path, + assert.equals(before_path, explorer.data.current_file_path, "Group/directory nodes should not trigger auto-open") - assert.equals(before_group, explorer.current_file_group, + assert.equals(before_group, explorer.data.current_file_group, "Group/directory nodes should not change current group") end) diff --git a/tests/ui/explorer/explorer_staging_spec.lua b/tests/ui/explorer/explorer_staging_spec.lua index 13ec4944..5bc999b5 100644 --- a/tests/ui/explorer/explorer_staging_spec.lua +++ b/tests/ui/explorer/explorer_staging_spec.lua @@ -1,395 +1,417 @@ --- Test explorer staging/unstaging workflow with virtual files --- This tests buffer management during file switching in explorer mode - -local h = dofile('tests/helpers.lua') -local path = require("codediff.core.path") - --- Ensure plugin is loaded (needed when the test framework isolates specs) -h.ensure_plugin_loaded() - -describe("Explorer Buffer Management", function() - local repo - - before_each(function() - -- Create a temp git repo using helper - repo = h.create_temp_git_repo() - - -- Create initial file and commit - repo.write_file('test.txt', {'line 1', 'line 2', 'line 3'}) - repo.git('add test.txt') - repo.git('commit -m initial') - end) - - after_each(function() - -- Close all extra tabs before cleanup - h.close_extra_tabs() - - -- Cleanup temp directory - if repo then - repo.cleanup() - end - end) - - it("should parse virtual file URLs correctly", function() - local virtual_file = require('codediff.core.virtual_file') - - -- Use the actual repo.dir for cross-platform compatibility - local normalized_dir = h.normalize_path(repo.dir) - - -- Test HEAD revision - local url1 = virtual_file.create_url(repo.dir, "HEAD", "file.txt") - local g1, c1, f1 = virtual_file.parse_url(url1) - assert.equals(normalized_dir, g1) - assert.equals("HEAD", c1) - assert.equals("file.txt", f1) - - -- Test :0 (staged) revision - local url2 = virtual_file.create_url(repo.dir, ":0", "file.txt") - local g2, c2, f2 = virtual_file.parse_url(url2) - assert.equals(normalized_dir, g2) - assert.equals(":0", c2) - assert.equals("file.txt", f2) - - -- Test SHA hash - local url3 = virtual_file.create_url(repo.dir, "abc123def456", "file.txt") - local g3, c3, f3 = virtual_file.parse_url(url3) - assert.equals(normalized_dir, g3) - assert.equals("abc123def456", c3) - assert.equals("file.txt", f3) - end) - - it("should load virtual file content via BufReadCmd", function() - local virtual_file = require('codediff.core.virtual_file') - - -- Listen for the loaded event - local event_fired = false - local event_buf = nil - vim.api.nvim_create_autocmd('User', { - pattern = 'CodeDiffVirtualFileLoaded', - callback = function(args) - event_fired = true - event_buf = args.data and args.data.buf - end - }) - - -- Create and edit a virtual file URL - local url = virtual_file.create_url(repo.dir, ':0', 'test.txt') - vim.cmd('edit! ' .. vim.fn.fnameescape(url)) - local buf = vim.api.nvim_get_current_buf() - - -- Wait for async loading to complete - local ok = vim.wait(5000, function() return event_fired end, 50) - - assert.is_true(ok, "Event should fire within timeout") - assert.is_true(event_fired, "CodeDiffVirtualFileLoaded should fire") - assert.equals(buf, event_buf, "Event should report correct buffer") - - -- Verify buffer content matches git content - local content = h.get_buffer_content(buf) - assert.is_not_nil(content, "Buffer should have content") - h.assert_contains(content, "line 1", "Should contain file content") - end) - - it("should refresh staged content when index changes", function() - -- This tests the full staging workflow: - -- 1. Make change A -> validate in Changes - -- 2. Stage change A -> validate in Staged Changes - -- 3. Make change B -> validate Changes has B, Staged has A - -- 4. Stage change B -> validate Staged has A+B - -- 5. Unstage file -> validate Changes has A+B - - local view = require('codediff.ui.view') - local lifecycle = require('codediff.ui.lifecycle') - - -- Step 1: Make change A - repo.write_file('test.txt', {'line 1', 'line 2', 'line 3', 'change A'}) - - -- Create diff view for unstaged changes (index vs working) - local config_changes = { - git_root = repo.dir, - original = path.make_ref('test.txt', repo.dir), - modified = path.make_ref(repo.path('test.txt'), repo.dir), - original_revision = ":0", - modified_revision = "WORKING", - } - - local result = view.create(config_changes, "text") - assert.is_not_nil(result, "Should create diff view") - - local tabpage = vim.api.nvim_get_current_tabpage() - - -- Wait for session to be ready - local ready = h.wait_for_session_ready(tabpage) - assert.is_true(ready, "Diff session should be ready") - - -- Validate: Changes should show "change A" in modified buffer - local _, modified_buf = lifecycle.get_buffers(tabpage) - assert.is_not_nil(modified_buf, "Modified buffer should exist") - local content = h.get_buffer_content(modified_buf) - assert.is_not_nil(content, "Content should not be nil") - h.assert_contains(content, "change A", "Changes should show change A") - - -- Step 2: Stage change A - repo.git("add test.txt") - - -- Switch to staged view (HEAD vs index) - local config_staged = { - git_root = repo.dir, - original = path.make_ref('test.txt', repo.dir), - modified = path.make_ref('test.txt', repo.dir), - original_revision = "HEAD", - modified_revision = ":0", - } - - view.update(tabpage, config_staged, false) - ready = h.wait_for_session_ready(tabpage) - assert.is_true(ready, "Session should be ready after update") - - -- Validate: Staged should show "change A" - _, modified_buf = lifecycle.get_buffers(tabpage) - content = h.get_buffer_content(modified_buf) - h.assert_contains(content, "change A", "Staged should show change A after staging") - - -- Step 3: Make change B (while A is staged) - repo.write_file('test.txt', {'line 1', 'line 2', 'line 3', 'change A', 'change B'}) - - -- Switch back to Changes view (index vs working) - view.update(tabpage, config_changes, false) - ready = h.wait_for_session_ready(tabpage) - - -- Validate: Changes should show "change B" (the new unstaged change). - -- Poll the current modified buffer (view.update swaps it) until the async - -- re-render lands, so this doesn't race on slow CI runners. - h.wait_for_modified_content(tabpage, "change B", 5000) - _, modified_buf = lifecycle.get_buffers(tabpage) - content = h.get_buffer_content(modified_buf) - assert.is_not_nil(content, "Step 3 content should not be nil") - h.assert_contains(content, "change B", "Changes should show change B") - - -- Switch to Staged view - should still show only "change A" - view.update(tabpage, config_staged, false) - ready = h.wait_for_session_ready(tabpage) - assert.is_true(ready, "Session should be ready after switching to staged view") - - _, modified_buf = lifecycle.get_buffers(tabpage) - -- Wait for buffer content to actually contain expected text - local content_ready = h.wait_for_buffer_content(modified_buf, "change A", 5000) - assert.is_true(content_ready, "Staged buffer should contain 'change A'") - content = h.get_buffer_content(modified_buf) - h.assert_contains(content, "change A", "Staged should still show change A") - - -- Step 4: Stage change B - repo.git("add test.txt") - - -- Refresh staged view - view.update(tabpage, config_staged, false) - ready = h.wait_for_session_ready(tabpage) - assert.is_true(ready, "Session should be ready after step 4 update") - - -- Wait for the staged view to reflect the newly staged change B. - h.wait_for_modified_content(tabpage, "change B", 5000) - _, modified_buf = lifecycle.get_buffers(tabpage) - content = h.get_buffer_content(modified_buf) - h.assert_contains(content, "change A", "Staged should show change A after staging B") - h.assert_contains(content, "change B", "Staged should show change B after staging B") - - -- Step 5: Unstage file - repo.git("reset HEAD test.txt") - - -- Switch to Changes view - should now show both A and B - view.update(tabpage, config_changes, false) - ready = h.wait_for_session_ready(tabpage) - - -- Wait for the changes view to reflect both A and B after unstaging. - h.wait_for_modified_content(tabpage, "change B", 5000) - _, modified_buf = lifecycle.get_buffers(tabpage) - content = h.get_buffer_content(modified_buf) - h.assert_contains(content, "change A", "Changes should show change A after unstage") - h.assert_contains(content, "change B", "Changes should show change B after unstage") - end) -end) - --- Regression tests for https://github.com/esmuellert/codediff.nvim/issues/347 --- --- Reviewing files one group at a time: after a full stage/unstage of the file --- being reviewed, the explorer's post-refresh re-selection advances to the --- next file in the SAME group — staging jumps to the next unstaged file, --- unstaging to the next staged file — instead of chasing the toggled file into --- another group. ]f/[f navigate only files whose group is visible. -describe("Explorer review-flow re-selection (issue #347)", function() - local repo - local lifecycle = require("codediff.ui.lifecycle") - local refresh_module = require("codediff.ui.explorer.refresh") - local explorer_actions = require("codediff.ui.explorer.actions") - - before_each(function() - require("codediff").setup({ diff = { layout = "side-by-side" } }) - lifecycle.cleanup_all() - - repo = h.create_temp_git_repo() - for _, name in ipairs({ "a.txt", "b.txt", "c.txt", "d.txt" }) do - repo.write_file(name, { "original " .. name }) - end - repo.git("add .") - repo.git("commit -m initial") - -- Modify all four files - for _, name in ipairs({ "a.txt", "b.txt", "c.txt", "d.txt" }) do - repo.write_file(name, { "modified " .. name }) - end - -- Pre-stage c and d, leaving a and b unstaged - repo.git("add c.txt d.txt") - end) - - after_each(function() - h.close_extra_tabs() - lifecycle.cleanup_all() - if repo then repo.cleanup() end - end) - - -- Open a fresh explorer focused on `focus_rel` and return its explorer object. - local function open_explorer(focus_rel) - vim.cmd("edit " .. repo.path(focus_rel)) - local commands = require("codediff.commands") - commands.vscode_diff({ fargs = {} }) - - local explorer - local ready = vim.wait(8000, function() - for _, tp in ipairs(vim.api.nvim_list_tabpages()) do - local sess = lifecycle.get_session(tp) - if sess and (sess.panel or {}).view and (sess.panel or {}).view.current_file_path ~= nil then - explorer = (sess.panel or {}).view - return true - end - end - return false - end, 50) - return ready, explorer - end - - -- Find the tree line for (path, group); nil if absent. - local function line_for(explorer, file_path, group) - local line_count = vim.api.nvim_buf_line_count(explorer.bufnr) - for line = 1, line_count do - local node = explorer.tree:get_node(line) - if node and node.data and node.data.path == file_path and node.data.group == group then - return line - end - end - return nil - end - - it("advances to the next unstaged file after staging the reviewed file", function() - local ready, explorer = open_explorer("a.txt") - assert.is_true(ready, "explorer should open with an initial selection") - - local settled = vim.wait(3000, function() - return explorer.current_file_path == "a.txt" and explorer.current_file_group == "unstaged" - end, 50) - assert.is_true(settled, "initial selection should be a.txt/unstaged") - - -- Stage a.txt, then refresh (this is what the .git fs-watcher triggers). - repo.git("add a.txt") - refresh_module.refresh(explorer) - - -- Pre-fix: re-selection followed a.txt into the staged group - -- (current_file_path=a.txt / group=staged). Post-fix: it advances to the - -- next unstaged file, b.txt. - local advanced = vim.wait(4000, function() - return explorer.current_file_path == "b.txt" and explorer.current_file_group == "unstaged" - end, 50) - assert.is_true(advanced, - "after staging a.txt the reviewer should advance to b.txt/unstaged, got " - .. tostring(explorer.current_file_path) .. "/" .. tostring(explorer.current_file_group)) - end) - - it("advances to the next staged file after unstaging the reviewed file", function() - local ready, explorer = open_explorer("c.txt") - assert.is_true(ready, "explorer should open with an initial selection") - assert.is_true(vim.wait(3000, function() - return explorer.current_file_path == "c.txt" and explorer.current_file_group == "staged" - end, 50), "initial selection should be c.txt/staged") - - -- Unstage c.txt, then refresh (what the .git fs-watcher triggers). - repo.git("reset -- c.txt") - refresh_module.refresh(explorer) - - -- Symmetric to staging: unstaging advances to the next *staged* file - -- instead of chasing c.txt into the unstaged group. - assert.is_true(vim.wait(4000, function() - return explorer.current_file_path == "d.txt" and explorer.current_file_group == "staged" - end, 50), - "after unstaging c.txt the reviewer should advance to d.txt/staged, got " - .. tostring(explorer.current_file_path) .. "/" .. tostring(explorer.current_file_group)) - end) - - it("hiding/showing a group updates the tree synchronously and ]f skips hidden files", function() - local ready, explorer = open_explorer("a.txt") - assert.is_true(ready, "explorer should open") - assert.is_true(vim.wait(3000, function() - return explorer.current_file_path == "a.txt" and explorer.current_file_group == "unstaged" - end, 50), "initial selection should be a.txt/unstaged") - - -- Stage a.txt -> advances to b.txt/unstaged - repo.git("add a.txt") - refresh_module.refresh(explorer) - assert.is_true(vim.wait(4000, function() - return explorer.current_file_path == "b.txt" and explorer.current_file_group == "unstaged" - end, 50), "should advance to b.txt/unstaged") - - -- Hide the staged group (like `gs`). toggle_group rebuilds the tree - -- synchronously from the cached status, so staged nodes are gone at once. - explorer_actions.toggle_group(explorer, "staged") - assert.is_nil(line_for(explorer, "c.txt", "staged"), - "hiding a group must remove its files from the tree immediately") - - -- ]f can therefore never reach a hidden staged file. - for _ = 1, 4 do - explorer_actions.navigate_next(explorer) - assert.equals("unstaged", explorer.current_file_group, - "]f must not visit hidden staged files (got " .. tostring(explorer.current_file_path) - .. "/" .. tostring(explorer.current_file_group) .. ")") - end - - -- Show the staged group again: state updates synchronously the other way. - explorer_actions.toggle_group(explorer, "staged") - assert.is_not_nil(line_for(explorer, "c.txt", "staged"), - "showing a group must restore its files to the tree immediately") - end) - - it("keeps partially staged files in the unstaged group on refresh", function() - -- Put a.txt in both groups: stage its current change, then add a new - -- working-tree-only change. - repo.git("add a.txt") - repo.write_file("a.txt", { "modified a.txt", "unstaged follow-up" }) - local ready, explorer = open_explorer("a.txt") - assert.is_true(ready, "explorer should open") - assert.is_true(vim.wait(3000, function() - return explorer.current_file_path == "a.txt" and explorer.current_file_group == "unstaged" - end, 50), "initial selection should be a.txt/unstaged") - - assert.is_not_nil(line_for(explorer, "a.txt", "unstaged"), "a.txt should appear in unstaged") - assert.is_not_nil(line_for(explorer, "a.txt", "staged"), "a.txt should also appear in staged") - - refresh_module.refresh(explorer) - vim.wait(1500) - assert.equals("a.txt", explorer.current_file_path, - "a.txt should still be the current file after a partial-stage refresh") - assert.equals("unstaged", explorer.current_file_group, - "a.txt should stay in the unstaged group") - end) - - it("keeps the staged file selected when no unstaged files remain", function() - local ready, explorer = open_explorer("a.txt") - assert.is_true(ready, "explorer should open") - assert.is_true(vim.wait(3000, function() - return explorer.current_file_path == "a.txt" and explorer.current_file_group == "unstaged" - end, 50), "initial selection should be a.txt/unstaged") - - repo.git("add a.txt b.txt") - refresh_module.refresh(explorer) - - assert.is_true(vim.wait(4000, function() - return explorer.current_file_path == "a.txt" and explorer.current_file_group == "staged" - end, 50), "when review is complete, the just-staged file should remain selected") - end) -end) +-- Test explorer staging/unstaging workflow with virtual files +-- This tests buffer management during file switching in explorer mode + +local h = dofile("tests/helpers.lua") +local path = require("codediff.core.path") + +-- Ensure plugin is loaded (needed when the test framework isolates specs) +h.ensure_plugin_loaded() + +describe("Explorer Buffer Management", function() + local repo + + before_each(function() + -- Create a temp git repo using helper + repo = h.create_temp_git_repo() + + -- Create initial file and commit + repo.write_file("test.txt", { "line 1", "line 2", "line 3" }) + repo.git("add test.txt") + repo.git("commit -m initial") + end) + + after_each(function() + -- Close all extra tabs before cleanup + h.close_extra_tabs() + + -- Cleanup temp directory + if repo then + repo.cleanup() + end + end) + + it("should parse virtual file URLs correctly", function() + local virtual_file = require("codediff.core.virtual_file") + + -- Use the actual repo.dir for cross-platform compatibility + local normalized_dir = h.normalize_path(repo.dir) + + -- Test HEAD revision + local url1 = virtual_file.create_url(repo.dir, "HEAD", "file.txt") + local g1, c1, f1 = virtual_file.parse_url(url1) + assert.equals(normalized_dir, g1) + assert.equals("HEAD", c1) + assert.equals("file.txt", f1) + + -- Test :0 (staged) revision + local url2 = virtual_file.create_url(repo.dir, ":0", "file.txt") + local g2, c2, f2 = virtual_file.parse_url(url2) + assert.equals(normalized_dir, g2) + assert.equals(":0", c2) + assert.equals("file.txt", f2) + + -- Test SHA hash + local url3 = virtual_file.create_url(repo.dir, "abc123def456", "file.txt") + local g3, c3, f3 = virtual_file.parse_url(url3) + assert.equals(normalized_dir, g3) + assert.equals("abc123def456", c3) + assert.equals("file.txt", f3) + end) + + it("should load virtual file content via BufReadCmd", function() + local virtual_file = require("codediff.core.virtual_file") + + -- Listen for the loaded event + local event_fired = false + local event_buf = nil + vim.api.nvim_create_autocmd("User", { + pattern = "CodeDiffVirtualFileLoaded", + callback = function(args) + event_fired = true + event_buf = args.data and args.data.buf + end, + }) + + -- Create and edit a virtual file URL + local url = virtual_file.create_url(repo.dir, ":0", "test.txt") + vim.cmd("edit! " .. vim.fn.fnameescape(url)) + local buf = vim.api.nvim_get_current_buf() + + -- Wait for async loading to complete + local ok = vim.wait(5000, function() + return event_fired + end, 50) + + assert.is_true(ok, "Event should fire within timeout") + assert.is_true(event_fired, "CodeDiffVirtualFileLoaded should fire") + assert.equals(buf, event_buf, "Event should report correct buffer") + + -- Verify buffer content matches git content + local content = h.get_buffer_content(buf) + assert.is_not_nil(content, "Buffer should have content") + h.assert_contains(content, "line 1", "Should contain file content") + end) + + it("should refresh staged content when index changes", function() + -- This tests the full staging workflow: + -- 1. Make change A -> validate in Changes + -- 2. Stage change A -> validate in Staged Changes + -- 3. Make change B -> validate Changes has B, Staged has A + -- 4. Stage change B -> validate Staged has A+B + -- 5. Unstage file -> validate Changes has A+B + + local view = require("codediff.ui.view") + local lifecycle = require("codediff.ui.lifecycle") + + -- Step 1: Make change A + repo.write_file("test.txt", { "line 1", "line 2", "line 3", "change A" }) + + -- Create diff view for unstaged changes (index vs working) + local config_changes = { + git_root = repo.dir, + original = path.make_ref("test.txt", repo.dir), + modified = path.make_ref(repo.path("test.txt"), repo.dir), + original_revision = ":0", + modified_revision = "WORKING", + } + + local result = view.create(config_changes, "text") + assert.is_not_nil(result, "Should create diff view") + + local tabpage = vim.api.nvim_get_current_tabpage() + + -- Wait for session to be ready + local ready = h.wait_for_session_ready(tabpage) + assert.is_true(ready, "Diff session should be ready") + + -- Validate: Changes should show "change A" in modified buffer + local _, modified_buf = lifecycle.get_buffers(tabpage) + assert.is_not_nil(modified_buf, "Modified buffer should exist") + local content = h.get_buffer_content(modified_buf) + assert.is_not_nil(content, "Content should not be nil") + h.assert_contains(content, "change A", "Changes should show change A") + + -- Step 2: Stage change A + repo.git("add test.txt") + + -- Switch to staged view (HEAD vs index) + local config_staged = { + git_root = repo.dir, + original = path.make_ref("test.txt", repo.dir), + modified = path.make_ref("test.txt", repo.dir), + original_revision = "HEAD", + modified_revision = ":0", + } + + view.update(tabpage, config_staged, false) + ready = h.wait_for_session_ready(tabpage) + assert.is_true(ready, "Session should be ready after update") + + -- Validate: Staged should show "change A" + _, modified_buf = lifecycle.get_buffers(tabpage) + content = h.get_buffer_content(modified_buf) + h.assert_contains(content, "change A", "Staged should show change A after staging") + + -- Step 3: Make change B (while A is staged) + repo.write_file("test.txt", { "line 1", "line 2", "line 3", "change A", "change B" }) + + -- Switch back to Changes view (index vs working) + view.update(tabpage, config_changes, false) + ready = h.wait_for_session_ready(tabpage) + + -- Validate: Changes should show "change B" (the new unstaged change). + -- Poll the current modified buffer (view.update swaps it) until the async + -- re-render lands, so this doesn't race on slow CI runners. + h.wait_for_modified_content(tabpage, "change B", 5000) + _, modified_buf = lifecycle.get_buffers(tabpage) + content = h.get_buffer_content(modified_buf) + assert.is_not_nil(content, "Step 3 content should not be nil") + h.assert_contains(content, "change B", "Changes should show change B") + + -- Switch to Staged view - should still show only "change A" + view.update(tabpage, config_staged, false) + ready = h.wait_for_session_ready(tabpage) + assert.is_true(ready, "Session should be ready after switching to staged view") + + _, modified_buf = lifecycle.get_buffers(tabpage) + -- Wait for buffer content to actually contain expected text + local content_ready = h.wait_for_buffer_content(modified_buf, "change A", 5000) + assert.is_true(content_ready, "Staged buffer should contain 'change A'") + content = h.get_buffer_content(modified_buf) + h.assert_contains(content, "change A", "Staged should still show change A") + + -- Step 4: Stage change B + repo.git("add test.txt") + + -- Refresh staged view + view.update(tabpage, config_staged, false) + ready = h.wait_for_session_ready(tabpage) + assert.is_true(ready, "Session should be ready after step 4 update") + + -- Wait for the staged view to reflect the newly staged change B. + h.wait_for_modified_content(tabpage, "change B", 5000) + _, modified_buf = lifecycle.get_buffers(tabpage) + content = h.get_buffer_content(modified_buf) + h.assert_contains(content, "change A", "Staged should show change A after staging B") + h.assert_contains(content, "change B", "Staged should show change B after staging B") + + -- Step 5: Unstage file + repo.git("reset HEAD test.txt") + + -- Switch to Changes view - should now show both A and B + view.update(tabpage, config_changes, false) + ready = h.wait_for_session_ready(tabpage) + + -- Wait for the changes view to reflect both A and B after unstaging. + h.wait_for_modified_content(tabpage, "change B", 5000) + _, modified_buf = lifecycle.get_buffers(tabpage) + content = h.get_buffer_content(modified_buf) + h.assert_contains(content, "change A", "Changes should show change A after unstage") + h.assert_contains(content, "change B", "Changes should show change B after unstage") + end) +end) + +-- Regression tests for https://github.com/esmuellert/codediff.nvim/issues/347 +-- +-- Reviewing files one group at a time: after a full stage/unstage of the file +-- being reviewed, the explorer's post-refresh re-selection advances to the +-- next file in the SAME group — staging jumps to the next unstaged file, +-- unstaging to the next staged file — instead of chasing the toggled file into +-- another group. ]f/[f navigate only files whose group is visible. +describe("Explorer review-flow re-selection (issue #347)", function() + local repo + local lifecycle = require("codediff.ui.lifecycle") + local refresh_module = require("codediff.ui.refresh") + local explorer_actions = require("codediff.ui.explorer.actions") + + before_each(function() + require("codediff").setup({ diff = { layout = "side-by-side" } }) + lifecycle.cleanup_all() + + repo = h.create_temp_git_repo() + for _, name in ipairs({ "a.txt", "b.txt", "c.txt", "d.txt" }) do + repo.write_file(name, { "original " .. name }) + end + repo.git("add .") + repo.git("commit -m initial") + -- Modify all four files + for _, name in ipairs({ "a.txt", "b.txt", "c.txt", "d.txt" }) do + repo.write_file(name, { "modified " .. name }) + end + -- Pre-stage c and d, leaving a and b unstaged + repo.git("add c.txt d.txt") + end) + + after_each(function() + h.close_extra_tabs() + lifecycle.cleanup_all() + if repo then + repo.cleanup() + end + end) + + -- Open a fresh explorer focused on `focus_rel` and return its explorer object. + local function open_explorer(focus_rel) + vim.cmd("edit " .. repo.path(focus_rel)) + local commands = require("codediff.commands") + commands.vscode_diff({ fargs = {} }) + + local explorer + local ready = vim.wait(8000, function() + for _, tp in ipairs(vim.api.nvim_list_tabpages()) do + local sess = lifecycle.get_session(tp) + if sess and (sess.panel or {}).view and (sess.panel or {}).view.data.current_file_path ~= nil then + explorer = (sess.panel or {}).view + return true + end + end + return false + end, 50) + return ready, explorer + end + + -- Find the tree line for (path, group); nil if absent. + local function line_for(explorer, file_path, group) + local line_count = vim.api.nvim_buf_line_count(explorer.bufnr) + for line = 1, line_count do + local node = explorer.tree:get_node(line) + if node and node.data and node.data.path == file_path and node.data.group == group then + return line + end + end + return nil + end + + it("advances to the next unstaged file after staging the reviewed file", function() + local ready, explorer = open_explorer("a.txt") + assert.is_true(ready, "explorer should open with an initial selection") + + local settled = vim.wait(3000, function() + return explorer.data.current_file_path == "a.txt" and explorer.data.current_file_group == "unstaged" + end, 50) + assert.is_true(settled, "initial selection should be a.txt/unstaged") + + -- Stage a.txt, then refresh (this is what the .git fs-watcher triggers). + repo.git("add a.txt") + refresh_module.request(explorer.tabpage, { full = true }) + + -- Pre-fix: re-selection followed a.txt into the staged group + -- (current_file_path=a.txt / group=staged). Post-fix: it advances to the + -- next unstaged file, b.txt. + local advanced = vim.wait(4000, function() + return explorer.data.current_file_path == "b.txt" and explorer.data.current_file_group == "unstaged" + end, 50) + assert.is_true( + advanced, + "after staging a.txt the reviewer should advance to b.txt/unstaged, got " .. tostring(explorer.data.current_file_path) .. "/" .. tostring(explorer.data.current_file_group) + ) + end) + + it("advances to the next staged file after unstaging the reviewed file", function() + local ready, explorer = open_explorer("c.txt") + assert.is_true(ready, "explorer should open with an initial selection") + assert.is_true( + vim.wait(3000, function() + return explorer.data.current_file_path == "c.txt" and explorer.data.current_file_group == "staged" + end, 50), + "initial selection should be c.txt/staged" + ) + + -- Unstage c.txt, then refresh (what the .git fs-watcher triggers). + repo.git("reset -- c.txt") + refresh_module.request(explorer.tabpage, { full = true }) + + -- Symmetric to staging: unstaging advances to the next *staged* file + -- instead of chasing c.txt into the unstaged group. + assert.is_true( + vim.wait(4000, function() + return explorer.data.current_file_path == "d.txt" and explorer.data.current_file_group == "staged" + end, 50), + "after unstaging c.txt the reviewer should advance to d.txt/staged, got " .. tostring(explorer.data.current_file_path) .. "/" .. tostring(explorer.data.current_file_group) + ) + end) + + it("hiding/showing a group updates the tree synchronously and ]f skips hidden files", function() + local ready, explorer = open_explorer("a.txt") + assert.is_true(ready, "explorer should open") + assert.is_true( + vim.wait(3000, function() + return explorer.data.current_file_path == "a.txt" and explorer.data.current_file_group == "unstaged" + end, 50), + "initial selection should be a.txt/unstaged" + ) + + -- Stage a.txt -> advances to b.txt/unstaged + repo.git("add a.txt") + refresh_module.request(explorer.tabpage, { full = true }) + assert.is_true( + vim.wait(4000, function() + return explorer.data.current_file_path == "b.txt" and explorer.data.current_file_group == "unstaged" + end, 50), + "should advance to b.txt/unstaged" + ) + + -- Hide the staged group (like `gs`). toggle_group rebuilds the tree + -- synchronously from the cached status, so staged nodes are gone at once. + explorer_actions.toggle_group(explorer, "staged") + assert.is_nil(line_for(explorer, "c.txt", "staged"), "hiding a group must remove its files from the tree immediately") + + -- ]f can therefore never reach a hidden staged file. + for _ = 1, 4 do + explorer_actions.navigate_next(explorer) + assert.equals( + "unstaged", + explorer.data.current_file_group, + "]f must not visit hidden staged files (got " .. tostring(explorer.data.current_file_path) .. "/" .. tostring(explorer.data.current_file_group) .. ")" + ) + end + + -- Show the staged group again: state updates synchronously the other way. + explorer_actions.toggle_group(explorer, "staged") + assert.is_not_nil(line_for(explorer, "c.txt", "staged"), "showing a group must restore its files to the tree immediately") + end) + + it("keeps partially staged files in the unstaged group on refresh", function() + -- Put a.txt in both groups: stage its current change, then add a new + -- working-tree-only change. + repo.git("add a.txt") + repo.write_file("a.txt", { "modified a.txt", "unstaged follow-up" }) + local ready, explorer = open_explorer("a.txt") + assert.is_true(ready, "explorer should open") + assert.is_true( + vim.wait(3000, function() + return explorer.data.current_file_path == "a.txt" and explorer.data.current_file_group == "unstaged" + end, 50), + "initial selection should be a.txt/unstaged" + ) + + assert.is_not_nil(line_for(explorer, "a.txt", "unstaged"), "a.txt should appear in unstaged") + assert.is_not_nil(line_for(explorer, "a.txt", "staged"), "a.txt should also appear in staged") + + refresh_module.request(explorer.tabpage, { full = true }) + vim.wait(1500) + assert.equals("a.txt", explorer.data.current_file_path, "a.txt should still be the current file after a partial-stage refresh") + assert.equals("unstaged", explorer.data.current_file_group, "a.txt should stay in the unstaged group") + end) + + it("keeps the staged file selected when no unstaged files remain", function() + local ready, explorer = open_explorer("a.txt") + assert.is_true(ready, "explorer should open") + assert.is_true( + vim.wait(3000, function() + return explorer.data.current_file_path == "a.txt" and explorer.data.current_file_group == "unstaged" + end, 50), + "initial selection should be a.txt/unstaged" + ) + + repo.git("add a.txt b.txt") + refresh_module.request(explorer.tabpage, { full = true }) + + assert.is_true( + vim.wait(4000, function() + return explorer.data.current_file_path == "a.txt" and explorer.data.current_file_group == "staged" + end, 50), + "when review is complete, the just-staged file should remain selected" + ) + end) +end) diff --git a/tests/ui/explorer/explorer_tree_render_spec.lua b/tests/ui/explorer/explorer_tree_render_spec.lua index 27064279..831f5f46 100644 --- a/tests/ui/explorer/explorer_tree_render_spec.lua +++ b/tests/ui/explorer/explorer_tree_render_spec.lua @@ -55,29 +55,28 @@ describe("Explorer tree render", function() -- time it drains — an artifact of feeding a tab-scoped keymap from an -- explorer buffer that shadows navigation entries with its own maps. local navigation = require("codediff.ui.view.navigation") - local before = explorer.current_file_path + local before = explorer.data.current_file_path assert.is_not_nil(before, "explorer should have a currently-selected file after opening") -- Only one changed file? Then next_file is a no-op by design (cycle over -- a single item), and asserting a change would be wrong. Guard. - local refresh_module = require("codediff.ui.explorer.refresh") - local all_files = refresh_module.get_all_files(explorer.tree) + local all_files = require("codediff.ui.explorer.tree").get_all_files(explorer.tree) assert.is_true(#all_files >= 2, "test setup should produce >= 2 changed files, got " .. #all_files) navigation.next_file() - -- next_file updates explorer.current_file_path synchronously, but the + -- next_file updates the session selection synchronously, but the -- diff render (view.update) runs via vim.schedule + async git.get_file. -- Wait for BOTH the explorer selection AND the modified buffer name to -- catch up, so the assertions below verify the full end-to-end path. vim.wait(5000, function() - if explorer.current_file_path == before then return false end + if explorer.data.current_file_path == before then return false end local _, buf = lifecycle.get_buffers(tabpage) if not buf or not vim.api.nvim_buf_is_valid(buf) then return false end - return vim.api.nvim_buf_get_name(buf):find(explorer.current_file_path, 1, true) ~= nil + return vim.api.nvim_buf_get_name(buf):find(explorer.data.current_file_path, 1, true) ~= nil end, 25) - assert.are_not.equal(before, explorer.current_file_path, + assert.are_not.equal(before, explorer.data.current_file_path, "next_file must select a different file; still on '" .. tostring(before) .. "'") -- And the modified pane must show that new file's content, not stale @@ -86,8 +85,8 @@ describe("Explorer tree render", function() assert.is_not_nil(mod_buf) local mod_name = vim.api.nvim_buf_get_name(mod_buf) assert.is_true( - mod_name:find(explorer.current_file_path, 1, true) ~= nil, - "modified buffer name '" .. mod_name .. "' should match the newly-selected file '" .. explorer.current_file_path .. "'") + mod_name:find(explorer.data.current_file_path, 1, true) ~= nil, + "modified buffer name '" .. mod_name .. "' should match the newly-selected file '" .. explorer.data.current_file_path .. "'") end) end) diff --git a/tests/ui/explorer/file_select_branches_spec.lua b/tests/ui/explorer/file_select_branches_spec.lua index 1ae352e6..0fab78e7 100644 --- a/tests/ui/explorer/file_select_branches_spec.lua +++ b/tests/ui/explorer/file_select_branches_spec.lua @@ -59,7 +59,6 @@ describe("explorer file select: added files", function() it("shows the added file's contents, not an empty diff", function() local tabpage, explorer = open_explorer_on(repo.dir, "kept.txt") - explorer.current_file_path = "added.txt" explorer.on_file_select({ path = "added.txt", status = "A", @@ -133,7 +132,6 @@ describe("explorer file select: directory comparison", function() "directory explorer should open" ) - explorer.current_file_path = "f.txt" explorer.on_file_select({ path = "f.txt", status = "M", group = "unstaged" }, {}) assert.is_true( diff --git a/tests/ui/explorer/hunk_operations_spec.lua b/tests/ui/explorer/hunk_operations_spec.lua index e81a6f97..0ae833df 100644 --- a/tests/ui/explorer/hunk_operations_spec.lua +++ b/tests/ui/explorer/hunk_operations_spec.lua @@ -320,14 +320,14 @@ describe("Hunk operations (side-by-side)", function() local switched = vim.wait(8000, function() local s = lifecycle.get_session(tabpage) if s and s.modified_revision == ":0" then return true end - if explorer.current_file_group == "staged" then return true end + if explorer.data.current_file_group == "staged" then return true end return false end, 100) assert.is_true(switched, "After staging last hunk, should switch to staged view. " .. "modified_revision=" .. tostring(lifecycle.get_session(tabpage).modified_revision) - .. ", group=" .. tostring(explorer.current_file_group)) + .. ", group=" .. tostring(explorer.data.current_file_group)) end) -- -------------------------------------------------------------------------- @@ -458,7 +458,7 @@ describe("Hunk operations (side-by-side)", function() local _, mod_buf = lifecycle.get_buffers(tabpage) vim.api.nvim_buf_set_lines(mod_buf, 9, 10, false, { "UNSAVED line 10" }) - require("codediff.ui.auto_refresh").trigger(mod_buf) + require("codediff.ui.refresh").buffer_changed(mod_buf) assert.is_true(wait_for_hunks(tabpage, 3, 8000), "Unsaved edit should add a third hunk") assert.is_true(vim.bo[mod_buf].modified, "Buffer should contain an unsaved edit") @@ -690,14 +690,14 @@ describe("Hunk operations (inline)", function() local switched = vim.wait(8000, function() local s = lifecycle.get_session(tabpage) if s and s.modified_revision == ":0" then return true end - if explorer.current_file_group == "staged" then return true end + if explorer.data.current_file_group == "staged" then return true end return false end, 100) assert.is_true(switched, "After staging last hunk in inline mode, should switch to staged view. " .. "modified_revision=" .. tostring(lifecycle.get_session(tabpage).modified_revision) - .. ", group=" .. tostring(explorer.current_file_group)) + .. ", group=" .. tostring(explorer.data.current_file_group)) end) it("discard_hunk refreshes inline mode when autoread is disabled", function() @@ -828,7 +828,7 @@ describe("Explorer hunk/staging actions", function() local transitioned = vim.wait(8000, function() local s = lifecycle.get_session(tabpage) if s and s.modified_revision == ":0" then return true end - if explorer.current_file_group == "staged" then return true end + if explorer.data.current_file_group == "staged" then return true end return false end, 200) @@ -836,7 +836,7 @@ describe("Explorer hunk/staging actions", function() transitioned, "After stage_all, view should transition to staged automatically. " .. "modified_revision=" .. tostring(lifecycle.get_session(tabpage).modified_revision) - .. ", group=" .. tostring(explorer.current_file_group) + .. ", group=" .. tostring(explorer.data.current_file_group) ) end) @@ -969,7 +969,7 @@ describe("Sequential hunk operations", function() local s = lifecycle.get_session(tabpage) if not s then return false end if s.modified_revision == ":0" then return true end - if explorer.current_file_group == "staged" then return true end + if explorer.data.current_file_group == "staged" then return true end if s.stored_diff_result and s.stored_diff_result.changes and #s.stored_diff_result.changes == 0 then return true end return false end, 100) diff --git a/tests/ui/explorer/native_watcher_spec.lua b/tests/ui/explorer/native_watcher_spec.lua index f138c7ec..311d8abd 100644 --- a/tests/ui/explorer/native_watcher_spec.lua +++ b/tests/ui/explorer/native_watcher_spec.lua @@ -1,6 +1,6 @@ local refresh = require("codediff.ui.refresh") -local snapshot = require("codediff.ui.refresh.snapshot") -local apply = require("codediff.ui.refresh.apply") +local snapshot = require("codediff.ui.refresh.inputs") +local render = require("codediff.ui.view.render") local lifecycle = require("codediff.ui.lifecycle") local path = require("codediff.core.path") @@ -46,11 +46,11 @@ describe("session refresh scheduling", function() end end, } - old_read, old_apply = snapshot.read, apply.run + old_read, old_apply = snapshot.read, render.update snapshot.read = function(_, event, _, done) reads[#reads + 1] = { event = event, done = done } end - apply.run = function() + render.update = function() applied = applied + 1 return true end @@ -60,7 +60,7 @@ describe("session refresh scheduling", function() after_each(function() refresh.dispose(tab) - snapshot.read, apply.run = old_read, old_apply + snapshot.read, render.update = old_read, old_apply package.loaded["codediff.core.watcher"] = old_watcher uv.new_timer = old_timer require("codediff.config").options.explorer.auto_refresh = old_auto @@ -96,6 +96,8 @@ describe("session refresh scheduling", function() it("stops fallback after ready and preserves every queued event category", function() setup() + assert.is_true(controller == refresh.attach(tab)) + assert.equals(2, #timers) assert.is_true(timers[2].started) handlers.on_ready() assert.is_false(timers[2].started) @@ -110,7 +112,7 @@ describe("session refresh scheduling", function() assert.same({ worktree = true, index = true, refs = true }, reads[2].event) end) - it("completes callbacks only after applying a settled snapshot", function() + it("completes unchanged-data callbacks without notifying the diff renderer", function() setup() local completed = 0 controller:request({ index = true }, function() @@ -119,7 +121,7 @@ describe("session refresh scheduling", function() fire() assert.equals(0, completed) reads[1].done(nil, snapshot.capture(session)) - assert.equals(1, applied) + assert.equals(0, applied) assert.equals(1, completed) end) @@ -197,7 +199,9 @@ describe("session refresh scheduling", function() assert.is_false(controller.running) snapshot.read = reader fire() - reads[1].done(nil, snapshot.capture(session)) + local data = snapshot.capture(session) + data.original = { "new content" } + reads[1].done(nil, data) assert.equals(1, applied) end) @@ -216,6 +220,46 @@ describe("session refresh scheduling", function() assert.equals(1, applied) end) + it("keeps working dependencies explicit without marking working panes as revisions", function() + setup() + local comparison = require("codediff.ui.refresh.panel").comparison(session.panel, { path = "a.txt", status = "M", group = "unstaged" }) + assert.is_nil(comparison.modified_revision) + assert.equals("WORKING", comparison.source_revisions.modified) + assert.equals(":0", comparison.source_revisions.original) + end) + + it("publishes list data without invoking selection or diff rendering", function() + setup() + local observed + local view = { + on_data = function(data, changes) + observed = { data = data, changes = changes } + end, + on_file_select = function() + error("a data notification must not select a file through the view") + end, + } + lifecycle.set_panel_view(tab, view) + local next_data = vim.deepcopy(session.panel.data) + next_data.status_result.unstaged = { { path = "background.txt", status = "M" } } + controller:publish_panel(next_data) + assert.is_true(session.panel.data == observed.data) + assert.is_true(observed.changes.list) + assert.is_false(observed.changes.selection) + controller:publish(snapshot.capture(session)) + assert.equals(0, applied) + end) + + it("notifies the diff renderer only when its inputs change", function() + setup() + local data = snapshot.capture(session) + data.modified = { "new content" } + controller:publish(data) + assert.equals(1, applied) + controller:publish(vim.deepcopy(data)) + assert.equals(1, applied) + end) + it("still accepts manual requests when automatic refresh is disabled", function() require("codediff.config").options.explorer.auto_refresh = false setup() diff --git a/tests/ui/explorer/refresh_keeps_view_spec.lua b/tests/ui/explorer/refresh_keeps_view_spec.lua index 42b2a380..6c4a2554 100644 --- a/tests/ui/explorer/refresh_keeps_view_spec.lua +++ b/tests/ui/explorer/refresh_keeps_view_spec.lua @@ -89,7 +89,7 @@ describe("explorer refresh keeps the user's view", function() -- would never be rebuilt and the collapse would survive for the wrong -- reason. Make a real change first. vim.fn.writefile({ "d1 new file" }, repo.dir .. "/d.txt") - require("codediff.ui.explorer.refresh").refresh(explorer) + require("codediff.ui.refresh").request(explorer.tabpage, { full = true }) vim.wait(4000) local after @@ -106,8 +106,6 @@ describe("explorer refresh keeps the user's view", function() local explorer = open() -- Review a.txt, the first file in the unstaged group. - explorer.current_file_path = "a.txt" - explorer.current_file_group = "unstaged" explorer.on_file_select({ path = "a.txt", status = "M", group = "unstaged", git_root = repo.dir }, {}) vim.wait(2000) @@ -115,10 +113,10 @@ describe("explorer refresh keeps the user's view", function() -- staged group, the refresh keeps the reviewer where they were: on -- whatever file now occupies that slot. repo.git("add a.txt") - require("codediff.ui.explorer.refresh").refresh(explorer) + require("codediff.ui.refresh").request(explorer.tabpage, { full = true }) vim.wait(4000) - assert.equals("b.txt", explorer.current_file_path, "should advance to the file taking a.txt's slot") + assert.equals("b.txt", explorer.data.current_file_path, "should advance to the file taking a.txt's slot") local lifecycle = require("codediff.ui.lifecycle") local session = lifecycle.get_session(explorer.tabpage) diff --git a/tests/ui/explorer/reselect_spec.lua b/tests/ui/explorer/reselect_spec.lua index a87bd0f2..73337703 100644 --- a/tests/ui/explorer/reselect_spec.lua +++ b/tests/ui/explorer/reselect_spec.lua @@ -69,7 +69,6 @@ describe("explorer re-selection", function() end local function select(explorer, file) - explorer.current_file_path = file explorer.on_file_select({ path = file, status = "M", group = "unstaged", git_root = repo.dir }, {}) vim.wait(250) end @@ -109,7 +108,6 @@ describe("explorer re-selection", function() local before = updates repo.git("add a.txt") - explorer.current_file_path = "a.txt" explorer.on_file_select({ path = "a.txt", status = "M", group = "staged", git_root = repo.dir }, {}) vim.wait(1500) @@ -126,7 +124,7 @@ describe("explorer re-selection", function() vim.wait(1500) local before = updates - explorer.status_result = { + explorer.data.status_result = { staged = { { path = "a.txt" } }, unstaged = { { path = "a.txt" } }, conflicts = {}, @@ -144,7 +142,6 @@ describe("explorer re-selection", function() vim.wait(1500) local before = updates - explorer.current_file_path = "a.txt" explorer.on_file_select({ path = "a.txt", status = "M", group = "unstaged", git_root = repo.dir }, { force = true }) vim.wait(1500) diff --git a/tests/ui/explorer/stale_buffer_spec.lua b/tests/ui/explorer/stale_buffer_spec.lua index ae1e37d3..3397a591 100644 --- a/tests/ui/explorer/stale_buffer_spec.lua +++ b/tests/ui/explorer/stale_buffer_spec.lua @@ -29,8 +29,7 @@ end --- @param timeout_ms? number How long to spin (default 3000) local function refresh_and_wait(explorer, timeout_ms) timeout_ms = timeout_ms or 3000 - local refresh = require("codediff.ui.explorer.refresh") - refresh.refresh(explorer) + require("codediff.ui.refresh").request(explorer.tabpage, { full = true }) -- The refresh is async (git status → vim.schedule). We must let the -- event loop run so the callback fires and the tree / session update. vim.wait(timeout_ms, function() @@ -81,8 +80,7 @@ end --- @param explorer table --- @return number local function count_tree_files(explorer) - local refresh = require("codediff.ui.explorer.refresh") - local files = refresh.get_all_files(explorer.tree) + local files = require("codediff.ui.explorer.tree").get_all_files(explorer.tree) return #files end @@ -91,8 +89,7 @@ end --- @param path string Relative file path --- @return boolean local function file_exists_in_tree(explorer, path) - local refresh = require("codediff.ui.explorer.refresh") - local files = refresh.get_all_files(explorer.tree) + local files = require("codediff.ui.explorer.tree").get_all_files(explorer.tree) for _, f in ipairs(files) do if f.data.path == path then return true @@ -149,7 +146,7 @@ describe("Welcome Page After Git Operations", function() local welcome = require("codediff.ui.welcome") -- Precondition: file1.txt selected in unstaged - assert.equals("file1.txt", explorer.current_file_path, "Precondition: should be viewing file1.txt") + assert.equals("file1.txt", explorer.data.current_file_path, "Precondition: should be viewing file1.txt") -- Commit only file1.txt repo.git("add file1.txt") @@ -168,7 +165,7 @@ describe("Welcome Page After Git Operations", function() -- or show a different file. session = lifecycle.get_session(tabpage) local shows_welcome = welcome.is_welcome_buffer(session.modified_bufnr) - local shows_different_file = explorer.current_file_path ~= "file1.txt" + local shows_different_file = explorer.data.current_file_path ~= "file1.txt" assert.is_true(shows_welcome or shows_different_file, "After committing file1: should show welcome or a different file, not stale file1 content") end) @@ -192,8 +189,8 @@ describe("Welcome Page After Git Operations", function() -- Diff panes should show the welcome page session = lifecycle.get_session(tabpage) assert.is_true(welcome.is_welcome_buffer(session.modified_bufnr), "Welcome buffer should be shown after committing all files") - assert.is_nil(explorer.current_file_path, "Current file path should be cleared when the tree becomes empty") - assert.is_nil(explorer.current_file_group, "Current file group should be cleared when the tree becomes empty") + assert.is_nil(explorer.data.current_file_path, "Current file path should be cleared when the tree becomes empty") + assert.is_nil(explorer.data.current_file_group, "Current file group should be cleared when the tree becomes empty") end) -- -------------------------------------------------------------------------- @@ -215,7 +212,7 @@ describe("Welcome Page After Git Operations", function() -- Diff panes should show the welcome page session = lifecycle.get_session(tabpage) assert.is_true(welcome.is_welcome_buffer(session.modified_bufnr), "Welcome buffer should be shown after stashing all changes") - assert.is_nil(explorer.current_file_path, "Current file path should be cleared when the tree becomes empty") - assert.is_nil(explorer.current_file_group, "Current file group should be cleared when the tree becomes empty") + assert.is_nil(explorer.data.current_file_path, "Current file path should be cleared when the tree becomes empty") + assert.is_nil(explorer.data.current_file_group, "Current file group should be cleared when the tree becomes empty") end) end) diff --git a/tests/ui/explorer/toggle_staged_view_spec.lua b/tests/ui/explorer/toggle_staged_view_spec.lua index 7cf3ccc1..d063d163 100644 --- a/tests/ui/explorer/toggle_staged_view_spec.lua +++ b/tests/ui/explorer/toggle_staged_view_spec.lua @@ -48,7 +48,7 @@ describe("toggle_staged_view (issue #352)", function() local ready = vim.wait(8000, function() for _, tp in ipairs(vim.api.nvim_list_tabpages()) do local sess = lifecycle.get_session(tp) - if sess and (sess.panel or {}).view and (sess.panel or {}).view.current_file_path ~= nil then + if sess and (sess.panel or {}).view and (sess.panel or {}).view.data.current_file_path ~= nil then explorer = (sess.panel or {}).view return true end @@ -62,13 +62,13 @@ describe("toggle_staged_view (issue #352)", function() local ready, explorer = open_status_explorer("both.txt") assert.is_true(ready, "explorer opens with a selection") assert.is_true(vim.wait(3000, function() - return explorer.current_file_path == "both.txt" and explorer.current_file_group == "unstaged" + return explorer.data.current_file_path == "both.txt" and explorer.data.current_file_group == "unstaged" end, 50), "initial selection is both.txt/unstaged") local ok = actions.toggle_staged_view(explorer) assert.is_true(ok, "toggle succeeds when file exists in both groups") - assert.equals("both.txt", explorer.current_file_path) - assert.equals("staged", explorer.current_file_group) + assert.equals("both.txt", explorer.data.current_file_path) + assert.equals("staged", explorer.data.current_file_group) end) it("swaps back to unstaged on a second toggle", function() @@ -76,9 +76,9 @@ describe("toggle_staged_view (issue #352)", function() assert.is_true(ready) vim.wait(500) actions.toggle_staged_view(explorer) - assert.equals("staged", explorer.current_file_group) + assert.equals("staged", explorer.data.current_file_group) actions.toggle_staged_view(explorer) - assert.equals("unstaged", explorer.current_file_group) + assert.equals("unstaged", explorer.data.current_file_group) end) it("notifies and stays put when the file has no counterpart", function() @@ -91,11 +91,11 @@ describe("toggle_staged_view (issue #352)", function() path = "only_staged.txt", old_path = nil, status = "M", - git_root = explorer.git_root, + git_root = explorer.data.git_root, group = "staged", }) assert.is_true(vim.wait(2000, function() - return explorer.current_file_group == "staged" + return explorer.data.current_file_group == "staged" end, 50)) local notified @@ -107,7 +107,7 @@ describe("toggle_staged_view (issue #352)", function() vim.notify = orig assert.is_false(ok, "toggle refuses when the sibling group is empty") - assert.equals("staged", explorer.current_file_group, "selection is unchanged") + assert.equals("staged", explorer.data.current_file_group, "selection is unchanged") assert.is_not_nil(notified) h.assert_contains(notified, "No unstaged changes") end) @@ -127,7 +127,7 @@ describe("toggle_staged_view (issue #352)", function() return false end, 50)) -- Verify we're in staged-only mode. - assert.equals(":0", explorer.target_revision, "explorer is in staged-only mode") + assert.equals(":0", explorer.data.target_revision, "explorer is in staged-only mode") local notified local orig = vim.notify @@ -156,7 +156,7 @@ describe("toggle_staged_view (issue #352)", function() end return false end, 50)) - assert.is_not_nil(explorer.base_revision, "explorer is in revision mode") + assert.is_not_nil(explorer.data.base_revision, "explorer is in revision mode") local notified local orig = vim.notify diff --git a/tests/ui/history/history_commit_files_spec.lua b/tests/ui/history/history_commit_files_spec.lua index 9c1ca56f..5627fec6 100644 --- a/tests/ui/history/history_commit_files_spec.lua +++ b/tests/ui/history/history_commit_files_spec.lua @@ -1,7 +1,7 @@ -- What the history panel lists under a commit. -- --- history_file_filter_spec covers filter.apply itself; this covers whether the --- history panel calls it. Removing the filter call left the whole suite green. +-- history_file_filter_spec covers filter.apply itself; this covers whether +-- session data reaches the history view with the filter applied. local h = dofile("tests/helpers.lua") h.ensure_plugin_loaded() @@ -15,7 +15,7 @@ local function expand_newest_commit() local opened = vim.wait(15000, function() for _, tp in ipairs(vim.api.nvim_list_tabpages()) do local view = lifecycle.get_panel_view(tp) - if view and view._load_commit_files and view.tree then + if view and view.load_commit_files and view.tree then history = view return true end @@ -38,7 +38,7 @@ local function expand_newest_commit() end local done = false - history._load_commit_files(commit_node, function() + history.load_commit_files(commit_node, function() done = true end) if not vim.wait(10000, function() @@ -78,6 +78,29 @@ describe("history panel file list", function() end end) + it("rebuilds supplied commit data without fetching files from the renderer", function() + repo.write_file("kept.txt", { "content" }) + repo.git("add .") + repo.git("commit -m second") + require("codediff").setup({}) + vim.cmd("cd " .. vim.fn.fnameescape(repo.dir)) + vim.cmd("CodeDiff history") + assert.is_not_nil(expand_newest_commit()) + local session = require("codediff.ui.lifecycle").get_session(vim.api.nvim_get_current_tabpage()) + local history = session.panel.view + assert.is_true(history.data == session.panel.data) + local git = require("codediff.core.git") + local get_files = git.get_commit_files + git.get_commit_files = function() + error("history rendering must not fetch commit files") + end + local ok, err = pcall(history.on_data, session.panel.data, { list = true }) + git.get_commit_files = get_files + assert.is_true(ok, tostring(err)) + local text = table.concat(vim.api.nvim_buf_get_lines(history.bufnr, 0, -1, false), "\n") + h.assert_contains(text, "kept.txt", "expanded files should render from session data") + end) + it("hides files matching explorer.file_filter.ignore", function() vim.fn.mkdir(repo.dir .. "/dist", "p") vim.fn.writefile({ "keep me" }, repo.dir .. "/kept.txt") diff --git a/tests/ui/history/history_refresh_watcher_spec.lua b/tests/ui/history/history_refresh_watcher_spec.lua index b8c485dc..84d61094 100644 --- a/tests/ui/history/history_refresh_watcher_spec.lua +++ b/tests/ui/history/history_refresh_watcher_spec.lua @@ -37,18 +37,17 @@ describe("history refresh transport lifecycle", function() original = path.empty(), modified = path.empty(), }, { original_bufnr = a, modified_bufnr = b, original_win = win, modified_win = win, lines_diff = {} }) - local history = { git_root = repo.dir, bufnr = a, winid = win, opts = {}, commits = {}, is_hidden = false } + local history = { data = lifecycle.get_session(tab).panel.data, bufnr = a, winid = win, is_hidden = false } lifecycle.set_panel_view(tab, history) - require("codediff.ui.history.refresh").setup_auto_refresh(history, tab) - local controller = lifecycle.get_session(tab).refresh + local controller = refresh.attach(tab) assert.is_function(handlers.on_ready) handlers.on_ready() - assert.is_true(history._native_watcher_ready) + assert.is_true(controller.native) assert.is_false(controller.polling) handlers.on_error("EPERM") local timer = controller.poll assert.is_true(controller.polling) - assert.is_false(history._native_watcher_ready) + assert.is_false(controller.native) handlers.on_error("EPERM") assert.equals(timer, controller.poll) refresh.dispose(tab) diff --git a/tests/ui/refresh/policy_spec.lua b/tests/ui/refresh/policy_spec.lua index f880c268..8726d926 100644 --- a/tests/ui/refresh/policy_spec.lua +++ b/tests/ui/refresh/policy_spec.lua @@ -43,8 +43,8 @@ describe("refresh dependency policy", function() it("does not refresh fixed revision or history lists for worktree-only events", function() assert.is_false(policy.panel_needed({ name = "history" }, { worktree = true })) assert.is_true(policy.panel_needed({ name = "history" }, { refs = true })) - assert.is_false(policy.panel_needed({ name = "explorer", view = { base_revision = string.rep("a", 40), target_revision = string.rep("b", 40) } }, { worktree = true })) - assert.is_false(policy.panel_needed({ name = "explorer", view = { base_revision = "HEAD", target_revision = ":0" } }, { worktree = true })) - assert.is_true(policy.panel_needed({ name = "explorer", view = {} }, { index = true })) + assert.is_false(policy.panel_needed({ name = "explorer", data = { base_revision = string.rep("a", 40), target_revision = string.rep("b", 40) } }, { worktree = true })) + assert.is_false(policy.panel_needed({ name = "explorer", data = { base_revision = "HEAD", target_revision = ":0" } }, { worktree = true })) + assert.is_true(policy.panel_needed({ name = "explorer", data = {} }, { index = true })) end) end) diff --git a/tests/ui/refresh/refresh_e2e_spec.lua b/tests/ui/refresh/refresh_e2e_spec.lua index a4bdb03c..93c9def3 100644 --- a/tests/ui/refresh/refresh_e2e_spec.lua +++ b/tests/ui/refresh/refresh_e2e_spec.lua @@ -234,7 +234,7 @@ for _, backend in ipairs({ "native", "polling" }) do screen:await(function() return screen:exec([[ local s = refresh_session() - return s.panel and s.panel.view.commits[1].subject == 'history-B' + return s.panel and s.panel.data.commits[1].subject == 'history-B' ]]) end, "new commit did not reach history") h.preserved(screen, expected) diff --git a/tests/ui/view/cycle_hunks_across_files_spec.lua b/tests/ui/view/cycle_hunks_across_files_spec.lua index a6b370ee..fbe083c6 100644 --- a/tests/ui/view/cycle_hunks_across_files_spec.lua +++ b/tests/ui/view/cycle_hunks_across_files_spec.lua @@ -63,7 +63,7 @@ describe("cycle_hunks_across_files (#161)", function() for _, tp in ipairs(vim.api.nvim_list_tabpages()) do local s = lifecycle.get_session(tp) local e = lifecycle.get_panel_view(tp) - if has_expected_hunk_count(s, expected_hunk_count) and e and e.current_file_path == focus_file then + if has_expected_hunk_count(s, expected_hunk_count) and e and e.data.current_file_path == focus_file then return true end end @@ -85,7 +85,7 @@ describe("cycle_hunks_across_files (#161)", function() local function wait_for_file_switch(tabpage, from_file, expected_hunk_count) local switched = vim.wait(8000, function() local e = lifecycle.get_panel_view(tabpage) - return e and e.current_file_path and e.current_file_path ~= from_file + return e and e.data.current_file_path and e.data.current_file_path ~= from_file end, 20) if not switched then return false @@ -94,7 +94,7 @@ describe("cycle_hunks_across_files (#161)", function() local s = lifecycle.get_session(tabpage) local e = lifecycle.get_panel_view(tabpage) local session_path = s and s.modified.absolute ~= "" and s.modified.absolute or s and s.original.absolute - return session_path and e and e.current_file_path and session_path:find(e.current_file_path, 1, true) ~= nil and has_expected_hunk_count(s, expected_hunk_count) + return session_path and e and e.data.current_file_path and session_path:find(e.data.current_file_path, 1, true) ~= nil and has_expected_hunk_count(s, expected_hunk_count) end, 20) end @@ -110,7 +110,7 @@ describe("cycle_hunks_across_files (#161)", function() assert.is_not_nil(explorer) assert.is_false(config.options.diff.cycle_hunks_across_files, "option must be false for this test") - local starting_file = explorer.current_file_path + local starting_file = explorer.data.current_file_path local changes = session.stored_diff_result.changes assert.is_true(#changes >= 2, "test repo must produce at least 2 hunks") @@ -120,7 +120,7 @@ describe("cycle_hunks_across_files (#161)", function() nav.next_hunk() vim.wait(150) - assert.equal(starting_file, explorer.current_file_path, "with cross-file off, ]c at the last hunk must NOT change file") + assert.equal(starting_file, explorer.data.current_file_path, "with cross-file off, ]c at the last hunk must NOT change file") end) it("OFF: hunk navigation does not leave a file with no hunks", function() @@ -130,12 +130,12 @@ describe("cycle_hunks_across_files (#161)", function() assert.is_not_nil(session) assert.is_not_nil(explorer) assert.equal(0, #session.stored_diff_result.changes) - local starting_file = explorer.current_file_path + local starting_file = explorer.data.current_file_path assert.is_false(nav.next_hunk()) - assert.equal(starting_file, explorer.current_file_path) + assert.equal(starting_file, explorer.data.current_file_path) assert.is_false(nav.prev_hunk()) - assert.equal(starting_file, explorer.current_file_path) + assert.equal(starting_file, explorer.data.current_file_path) assert.is_nil(session.pending_cursor_landing) end) @@ -149,7 +149,7 @@ describe("cycle_hunks_across_files (#161)", function() assert.is_true(nav.next_hunk()) assert.is_true(wait_for_file_switch(tabpage, "c-untracked.txt")) - assert.equal("a.txt", explorer.current_file_path) + assert.equal("a.txt", explorer.data.current_file_path) assert.is_nil(lifecycle.get_session(tabpage).pending_cursor_landing) end) @@ -162,11 +162,11 @@ describe("cycle_hunks_across_files (#161)", function() assert.is_true(nav.prev_hunk()) assert.is_true(wait_for_file_switch(tabpage, "c-untracked.txt", 0)) - assert.equal("d-deleted.txt", explorer.current_file_path) + assert.equal("d-deleted.txt", explorer.data.current_file_path) assert.is_true(nav.prev_hunk()) assert.is_true(wait_for_file_switch(tabpage, "d-deleted.txt")) - assert.equal("b.txt", explorer.current_file_path) + assert.equal("b.txt", explorer.data.current_file_path) assert.is_nil(lifecycle.get_session(tabpage).pending_cursor_landing) end) @@ -176,7 +176,7 @@ describe("cycle_hunks_across_files (#161)", function() local tabpage, session, explorer = open_explorer("a.txt") assert.is_not_nil(session) assert.is_not_nil(explorer) - local first_file = explorer.current_file_path + local first_file = explorer.data.current_file_path local changes = session.stored_diff_result.changes assert.is_true(#changes >= 2) @@ -200,7 +200,7 @@ describe("cycle_hunks_across_files (#161)", function() local tabpage, session, explorer = open_explorer("b.txt") assert.is_not_nil(session) assert.is_not_nil(explorer) - local first_file = explorer.current_file_path + local first_file = explorer.data.current_file_path local changes = session.stored_diff_result.changes assert.is_true(#changes >= 2) @@ -223,7 +223,7 @@ describe("cycle_hunks_across_files (#161)", function() local tabpage, session, explorer = open_explorer("a.txt") assert.is_not_nil(session) - local first_file = explorer.current_file_path + local first_file = explorer.data.current_file_path local changes = session.stored_diff_result.changes vim.api.nvim_set_current_win(session.modified_win) @@ -246,7 +246,7 @@ describe("cycle_hunks_across_files (#161)", function() local tabpage, session, explorer = open_explorer("b.txt") assert.is_not_nil(session) - local first_file = explorer.current_file_path + local first_file = explorer.data.current_file_path local changes = session.stored_diff_result.changes assert.is_true(#changes >= 2) @@ -297,7 +297,7 @@ describe("cycle_hunks_across_files (#161)", function() local tabpage, session, explorer = open_explorer("b.txt") assert.is_not_nil(session) - local first_file = explorer.current_file_path + local first_file = explorer.data.current_file_path vim.api.nvim_set_current_win(session.modified_win) vim.api.nvim_win_set_cursor(session.modified_win, { session.stored_diff_result.changes[1].modified.start_line, 0 }) @@ -330,10 +330,10 @@ describe("cycle_hunks_across_files (#161)", function() assert.is_not_nil(explorer) assert.equal(3, vim.api.nvim_win_get_cursor(session.modified_win)[1], "EOF deletion should land on the last valid modified line") - local first_file = explorer.current_file_path + local first_file = explorer.data.current_file_path nav.next_hunk() assert.is_true(wait_for_file_switch(tabpage, first_file), "next hunk should advance past the EOF deletion") - assert.equal("b.txt", explorer.current_file_path) + assert.equal("b.txt", explorer.data.current_file_path) local next_session = lifecycle.get_session(tabpage) local first_hunk_line = next_session.stored_diff_result.changes[1].modified.start_line @@ -342,7 +342,7 @@ describe("cycle_hunks_across_files (#161)", function() nav.prev_hunk() assert.is_true(wait_for_file_switch(tabpage, "b.txt"), "previous hunk should return to the EOF deletion") local previous_session = lifecycle.get_session(tabpage) - assert.equal("a.txt", explorer.current_file_path) + assert.equal("a.txt", explorer.data.current_file_path) assert.equal(3, vim.api.nvim_win_get_cursor(previous_session.modified_win)[1], "backward landing should clamp the EOF deletion") end) end) diff --git a/tests/ui/view/inline_interaction_spec.lua b/tests/ui/view/inline_interaction_spec.lua index a58f4e16..7bf16ff7 100644 --- a/tests/ui/view/inline_interaction_spec.lua +++ b/tests/ui/view/inline_interaction_spec.lua @@ -204,8 +204,7 @@ describe("Inline diff mode interactions", function() -- Programmatic buffer changes (nvim_buf_set_lines) do not fire TextChanged, -- so trigger the auto-refresh pipeline manually. - local auto_refresh = require("codediff.ui.auto_refresh") - auto_refresh.trigger(ctx.modified_bufnr) + require("codediff.ui.refresh").buffer_changed(ctx.modified_bufnr) -- Wait for throttled refresh (THROTTLE_DELAY_MS = 200 + vim.schedule) vim.wait(500, function() diff --git a/tests/ui/view/layout_toggle_spec.lua b/tests/ui/view/layout_toggle_spec.lua index f63ea27b..bb40fd58 100644 --- a/tests/ui/view/layout_toggle_spec.lua +++ b/tests/ui/view/layout_toggle_spec.lua @@ -134,7 +134,7 @@ local function open_history_and_wait(repo, entry_file) if session and session.panel and session.panel.name == "history" and panel then tabpage = tp history = panel - return history.current_selection + return history.data.current_selection and session.original_revision and session.modified_revision and session.original_bufnr @@ -285,7 +285,7 @@ describe("Layout toggle", function() repo.git('commit -m "third"') local tabpage, session, history = open_history_and_wait(repo, "file.txt") - local selected = vim.deepcopy(history.current_selection) + local selected = vim.deepcopy(history.data.current_selection) assert.equals("side-by-side", session.layout) assert.is_not_nil(selected, "History should track the current file selection") @@ -298,9 +298,9 @@ describe("Layout toggle", function() return current_session.layout == "inline" and current_session.original_win == current_session.modified_win and current_history - and current_history.current_selection - and current_history.current_selection.commit_hash == selected.commit_hash - and current_history.current_selection.path == selected.path + and current_history.data.current_selection + and current_history.data.current_selection.commit_hash == selected.commit_hash + and current_history.data.current_selection.path == selected.path and #marks > 0 end, "History toggle should replay the selected file as a native inline render") @@ -314,9 +314,9 @@ describe("Layout toggle", function() and vim.api.nvim_win_is_valid(current_session.original_win) and vim.api.nvim_win_is_valid(current_session.modified_win) and current_history - and current_history.current_selection - and current_history.current_selection.commit_hash == selected.commit_hash - and current_history.current_selection.path == selected.path + and current_history.data.current_selection + and current_history.data.current_selection.commit_hash == selected.commit_hash + and current_history.data.current_selection.path == selected.path end, "History toggle should restore the same selected file in side-by-side mode") end) diff --git a/tests/ui/welcome_spec.lua b/tests/ui/welcome_spec.lua index a99ddd1d..484ca98e 100644 --- a/tests/ui/welcome_spec.lua +++ b/tests/ui/welcome_spec.lua @@ -264,9 +264,9 @@ describe("Welcome Page", function() vim.fn.system("git -C " .. vim.fn.shellescape(repo.dir) .. " checkout -- test.txt") -- Trigger refresh - local refresh = require("codediff.ui.explorer.refresh") + local refresh = require("codediff.ui.refresh") local explorer = (session.panel or {}).view - refresh.refresh(explorer) + refresh.request(explorer.tabpage, { full = true }) -- Wait for welcome buffer to appear local welcome = require("codediff.ui.welcome") @@ -293,12 +293,12 @@ describe("Welcome Page", function() repo.write_file("test.txt", { "line 1", "line 2 changed again" }) -- Trigger refresh again - refresh.refresh(explorer) + refresh.request(explorer.tabpage, { full = true }) -- Wait for tree to update (refresh is async) local tree_updated = vim.wait(10000, function() -- The tree should now have files - local files = refresh.get_all_files(explorer.tree) + local files = require("codediff.ui.explorer.tree").get_all_files(explorer.tree) return #files > 0 end, 100) From d05787c42092b20ae97f775575fd89870c2b104d Mon Sep 17 00:00:00 2001 From: Yanuo Ma <41042490+esmuellert@users.noreply.github.com> Date: Mon, 14 Sep 2026 14:44:23 -0400 Subject: [PATCH 6/8] test(e2e): unify Git fixtures and cover refresh workflows Use isolated temporary repositories and worktrees for Git-backed tests, with deterministic reusable UI fixtures and cleanup guarantees. Expand the refresh matrix to 132 named scenarios and 544 E2E executions across native and polling backends, layouts, and merge configurations. Fix regressions exposed by the new scenarios in history queries, root commits, renamed paths, file reloads, revision buffers, and shared-buffer lifecycle. Document the main-to-branch behavioral coverage map and fixture reproduction workflow. --- lua/codediff/commands/handlers/history.lua | 1 + lua/codediff/core/git/changes.lua | 21 +- lua/codediff/ui/lifecycle/accessors.lua | 30 +- lua/codediff/ui/lifecycle/cleanup.lua | 20 +- lua/codediff/ui/lifecycle/init.lua | 1 + lua/codediff/ui/lifecycle/state.lua | 9 + lua/codediff/ui/refresh/panel.lua | 42 +- lua/codediff/ui/view/helpers.lua | 24 +- lua/codediff/ui/view/inline_view/update.lua | 8 +- lua/codediff/ui/view/render.lua | 8 +- lua/codediff/ui/view/side_by_side/update.lua | 14 +- tests/README.md | 22 +- tests/core/git_integration_spec.lua | 4 +- tests/core/history_line_range_spec.lua | 28 +- tests/core/pull_request_spec.lua | 12 +- tests/core/rename_follow_spec.lua | 19 +- tests/core/restore_spec.lua | 53 +- tests/fixtures/README.md | 113 +++++ tests/fixtures/refresh_repo.lua | 140 ++++++ tests/framework/repository.lua | 238 +++++++++ tests/framework/repository_spec.lua | 116 +++++ tests/framework/runner.lua | 10 +- tests/full_integration_spec.lua | 19 +- tests/helpers.lua | 456 +++++++----------- tests/init.lua | 20 +- tests/ui/explorer/explorer_refresh_spec.lua | 15 +- tests/ui/explorer/explorer_spec.lua | 18 +- tests/ui/explorer/issue_498_spec.lua | 7 +- tests/ui/refresh/COVERAGE.md | 195 ++++++++ .../ui/refresh/conflict_refresh_e2e_spec.lua | 4 +- .../ui/refresh/explorer_actions_e2e_spec.lua | 289 +++++++++++ tests/ui/refresh/helpers.lua | 212 +++++++- tests/ui/refresh/history_actions_e2e_spec.lua | 196 ++++++++ tests/ui/refresh/hunk_actions_e2e_spec.lua | 210 ++++++++ tests/ui/refresh/lifecycle_e2e_spec.lua | 172 +++++++ tests/ui/refresh/merge_actions_e2e_spec.lua | 181 +++++++ tests/ui/refresh/source_refresh_e2e_spec.lua | 301 ++++++++++++ tests/ui/refresh/virtual_file_e2e_spec.lua | 95 ++++ tests/ui/view/inline_explorer_spec.lua | 16 +- 39 files changed, 2823 insertions(+), 516 deletions(-) create mode 100644 tests/fixtures/README.md create mode 100644 tests/fixtures/refresh_repo.lua create mode 100644 tests/framework/repository.lua create mode 100644 tests/framework/repository_spec.lua create mode 100644 tests/ui/refresh/COVERAGE.md create mode 100644 tests/ui/refresh/explorer_actions_e2e_spec.lua create mode 100644 tests/ui/refresh/history_actions_e2e_spec.lua create mode 100644 tests/ui/refresh/hunk_actions_e2e_spec.lua create mode 100644 tests/ui/refresh/merge_actions_e2e_spec.lua create mode 100644 tests/ui/refresh/source_refresh_e2e_spec.lua create mode 100644 tests/ui/refresh/virtual_file_e2e_spec.lua diff --git a/lua/codediff/commands/handlers/history.lua b/lua/codediff/commands/handlers/history.lua index bc9a32e6..165ca5d9 100644 --- a/lua/codediff/commands/handlers/history.lua +++ b/lua/codediff/commands/handlers/history.lua @@ -73,6 +73,7 @@ function M.run(range, file_path, flags, line_range, global_opts) file_path = history_opts.path, base_revision = flags.base, line_range = line_range, + reverse = flags.reverse, }, }, git_root = git_root, diff --git a/lua/codediff/core/git/changes.lua b/lua/codediff/core/git/changes.lua index aa0a2144..85acf6c2 100644 --- a/lua/codediff/core/git/changes.lua +++ b/lua/codediff/core/git/changes.lua @@ -61,7 +61,7 @@ function M.get_status(git_root, callback, pathspec) -- Trailing `-- ` scopes the status to a pathspec (nil/empty = all files). -- `-u` (untracked-files scan; #389) is read from explorer.untracked config. run_git_async( - vim.list_extend({ "status", "--porcelain", "-u" .. untracked_mode(), "-M", "--" }, pathspec or {}), -- -M to detect renames + vim.list_extend({ "status", "--porcelain", "-z", "-u" .. untracked_mode(), "-M", "--" }, pathspec or {}), -- -M to detect renames { cwd = git_root, no_optional_locks = true }, function(err, output) if err then @@ -75,15 +75,21 @@ function M.get_status(git_root, callback, pathspec) conflicts = {}, } - for line in output:gmatch("[^\r\n]+") do + local entries = vim.split(output, "\0", { plain = true, trimempty = true }) + local i = 1 + while i <= #entries do + local line = entries[i] if #line >= 3 then local index_status = line:sub(1, 1) local worktree_status = line:sub(2, 2) - local path_part = unquote_path(line:sub(4)) + local path, old_path = line:sub(4), nil - -- Handle renames: "old_path -> new_path" - local old_path, new_path = path_part:match("^(.+) %-> (.+)$") - local path = old_path and new_path or path_part -- Use new_path for display if rename + -- Porcelain -z provides raw paths; renamed entries put the old name + -- in the following record, without quoting or an ambiguous arrow. + if index_status == "R" or index_status == "C" or worktree_status == "R" or worktree_status == "C" then + i = i + 1 + old_path = entries[i] + end local is_rename = old_path ~= nil -- Check for merge conflicts first (takes priority) @@ -113,6 +119,7 @@ function M.get_status(git_root, callback, pathspec) end end end + i = i + 1 end callback(nil, result) @@ -300,7 +307,7 @@ end -- callback: function(err, files) where files is array of: -- { path, status, old_path } function M.get_commit_files(commit_hash, git_root, callback) - run_git_async({ "diff-tree", "--no-commit-id", "--name-status", "-r", "-M", commit_hash }, { cwd = git_root }, function(err, output) + run_git_async({ "diff-tree", "--root", "--no-commit-id", "--name-status", "-r", "-M", commit_hash }, { cwd = git_root }, function(err, output) if err then callback(err, nil) return diff --git a/lua/codediff/ui/lifecycle/accessors.lua b/lua/codediff/ui/lifecycle/accessors.lua index b0a0ea21..1e3cd2a5 100644 --- a/lua/codediff/ui/lifecycle/accessors.lua +++ b/lua/codediff/ui/lifecycle/accessors.lua @@ -115,6 +115,18 @@ function M.find_tabpage_by_buffer(bufnr) return nil end +--- Whether another live session still owns this buffer, including hidden tabs. +function M.is_buffer_shared(bufnr, except_tabpage) + for tabpage, sess in pairs(get_active_diffs()) do + if tabpage ~= except_tabpage and vim.api.nvim_tabpage_is_valid(tabpage) then + if sess.original_bufnr == bufnr or sess.modified_bufnr == bufnr or sess.result_bufnr == bufnr then + return true + end + end + end + return false +end + --- Check if original buffer is virtual function M.is_original_virtual(tabpage) local active_diffs = get_active_diffs() @@ -321,11 +333,13 @@ function M.update_buffers(tabpage, original_bufnr, modified_bufnr) local state = require("codediff.ui.lifecycle.state") local gutter_signs = require("codediff.ui.gutter_signs") - if sess.original_bufnr ~= original_bufnr and sess.original_bufnr ~= modified_bufnr then + if sess.original_bufnr ~= original_bufnr and sess.original_bufnr ~= modified_bufnr and not M.is_buffer_shared(sess.original_bufnr, tabpage) then gutter_signs.clear_buffer(sess.original_bufnr) + state.restore_buffer_state(sess.original_bufnr, sess.original_state) end - if sess.modified_bufnr ~= original_bufnr and sess.modified_bufnr ~= modified_bufnr then + if sess.modified_bufnr ~= original_bufnr and sess.modified_bufnr ~= modified_bufnr and not M.is_buffer_shared(sess.modified_bufnr, tabpage) then gutter_signs.clear_buffer(sess.modified_bufnr) + state.restore_buffer_state(sess.modified_bufnr, sess.modified_state) end -- Hand mappings back to any buffer that is leaving the session. Without this @@ -348,12 +362,18 @@ function M.update_buffers(tabpage, original_bufnr, modified_bufnr) sess.keymaps:detach_buffers_except(keep) end + local saved = { [sess.original_bufnr] = sess.original_state, [sess.modified_bufnr] = sess.modified_state } + local original_state = saved[original_bufnr] or state.save_buffer_state(original_bufnr) + local modified_state = saved[modified_bufnr] or state.save_buffer_state(modified_bufnr) sess.original_bufnr = original_bufnr sess.modified_bufnr = modified_bufnr - -- Save buffer states for new buffers (critical for suspend/resume!) - sess.original_state = state.save_buffer_state(original_bufnr) - sess.modified_state = state.save_buffer_state(modified_bufnr) + -- Keep the user's original settings when only the other pane changes. + sess.original_state, sess.modified_state = original_state, modified_state + if require("codediff.config").options.diff.disable_inlay_hints and vim.lsp.inlay_hint then + vim.lsp.inlay_hint.enable(false, { bufnr = original_bufnr }) + vim.lsp.inlay_hint.enable(false, { bufnr = modified_bufnr }) + end return true end diff --git a/lua/codediff/ui/lifecycle/cleanup.lua b/lua/codediff/ui/lifecycle/cleanup.lua index 5fe5e034..1cdb874d 100644 --- a/lua/codediff/ui/lifecycle/cleanup.lua +++ b/lua/codediff/ui/lifecycle/cleanup.lua @@ -39,26 +39,28 @@ local function cleanup_diff(tabpage) -- Restore gutter options before deleting buffers can close or reuse windows. require("codediff.ui.conflict").teardown_gutter(tabpage) - -- Clear highlights from both buffers - state.clear_buffer_highlights(diff.original_bufnr) - state.clear_buffer_highlights(diff.modified_bufnr) - - -- Restore buffer states - state.restore_buffer_state(diff.original_bufnr, diff.original_state) - state.restore_buffer_state(diff.modified_bufnr, diff.modified_state) + -- Another tab may still own the same working or revision buffer. + if not accessors.is_buffer_shared(diff.original_bufnr, tabpage) then + state.clear_buffer_highlights(diff.original_bufnr) + state.restore_buffer_state(diff.original_bufnr, diff.original_state) + end + if not accessors.is_buffer_shared(diff.modified_bufnr, tabpage) then + state.clear_buffer_highlights(diff.modified_bufnr) + state.restore_buffer_state(diff.modified_bufnr, diff.modified_state) + end -- Hand every mapped key back to whatever owned it before codediff keymaps.dispose_keymaps(tabpage) -- Delete virtual buffers if they're still valid if vim.api.nvim_buf_is_valid(diff.original_bufnr) then - if is_virtual_revision(diff.original_revision) then + if is_virtual_revision(diff.original_revision) and not accessors.is_buffer_shared(diff.original_bufnr, tabpage) then pcall(vim.api.nvim_buf_delete, diff.original_bufnr, { force = true }) end end if vim.api.nvim_buf_is_valid(diff.modified_bufnr) then - if is_virtual_revision(diff.modified_revision) then + if is_virtual_revision(diff.modified_revision) and not accessors.is_buffer_shared(diff.modified_bufnr, tabpage) then pcall(vim.api.nvim_buf_delete, diff.modified_bufnr, { force = true }) end end diff --git a/lua/codediff/ui/lifecycle/init.lua b/lua/codediff/ui/lifecycle/init.lua index d3d65b36..ee48b15e 100644 --- a/lua/codediff/ui/lifecycle/init.lua +++ b/lua/codediff/ui/lifecycle/init.lua @@ -39,6 +39,7 @@ M.get_buffers = accessors.get_buffers M.get_windows = accessors.get_windows M.get_paths = accessors.get_paths M.find_tabpage_by_buffer = accessors.find_tabpage_by_buffer +M.is_buffer_shared = accessors.is_buffer_shared M.is_original_virtual = accessors.is_original_virtual M.is_modified_virtual = accessors.is_modified_virtual M.is_suspended = accessors.is_suspended diff --git a/lua/codediff/ui/lifecycle/state.lua b/lua/codediff/ui/lifecycle/state.lua index 6dff48f2..9d460179 100644 --- a/lua/codediff/ui/lifecycle/state.lua +++ b/lua/codediff/ui/lifecycle/state.lua @@ -6,6 +6,15 @@ function M.save_buffer_state(bufnr) if not vim.api.nvim_buf_is_valid(bufnr) then return nil end + -- A second session must save the user's setting, not the first session's + -- temporary disabled value for this shared buffer. + for _, session in pairs(require("codediff.ui.lifecycle.session").get_active_diffs()) do + if session.original_bufnr == bufnr and session.original_state then + return vim.deepcopy(session.original_state) + elseif session.modified_bufnr == bufnr and session.modified_state then + return vim.deepcopy(session.modified_state) + end + end local state = {} if vim.lsp.inlay_hint then state.inlay_hints_enabled = vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }) diff --git a/lua/codediff/ui/refresh/panel.lua b/lua/codediff/ui/refresh/panel.lua index 5819a97a..5c84ddb1 100644 --- a/lua/codediff/ui/refresh/panel.lua +++ b/lua/codediff/ui/refresh/panel.lua @@ -16,8 +16,8 @@ function M.new(session_config) data.dir1, data.dir2 = session_config.original.absolute, session_config.modified.absolute end else - data.opts = { range = data.range, file_path = data.file_path, base_revision = data.base_revision, line_range = data.line_range } - data.commits, data.files = data.commits or {}, {} + data.opts = { range = data.range, file_path = data.file_path, base_revision = data.base_revision, line_range = data.line_range, reverse = data.reverse } + data.commits, data.files, data.parents = data.commits or {}, {}, {} end return data end @@ -34,7 +34,24 @@ function M.resolve(config, done) end for _, side in ipairs({ "original", "modified" }) do local revision = config[side .. "_revision"] - if revision and not policy.is_working(revision) and not revision:match("^:[0-3]:?$") then + if side == "original" and revision and config.parent_commit then + remaining = remaining + 1 + git.get_revision_parents(config.parent_commit, config.git_root, function(err, parents) + vim.schedule(function() + if not err then + if config.parent_cache then + config.parent_cache[config.parent_commit] = parents + end + config.original_revision = parents[1] + config.source_revisions.original = parents[1] + if not parents[1] then + config.original, config.single_side = path.empty(), "modified" + end + end + settled(err) + end) + end) + elseif revision and not policy.is_working(revision) and not revision:match("^:[0-3]:?$") then remaining = remaining + 1 git.resolve_revision(revision, config.git_root, function(err, hash) vim.schedule(function() @@ -57,7 +74,7 @@ function M.read(session, done) end) end if panel.name == "history" then - local opts = { no_merges = true, path = data.opts.file_path } + local opts = { no_merges = true, path = data.opts.file_path, line_range = data.opts.line_range, reverse = data.opts.reverse } local range = data.opts.range or "" if range == "" then opts.limit = 100 @@ -165,12 +182,19 @@ function M.comparison(panel, file) return end local original, modified = file.old_path or file.path, file.path - local original_revision, modified_revision, conflict, line_range + local original_revision, modified_revision, conflict, line_range, parent_commit, root_commit if panel.name == "history" then if not file.commit_hash or file.commit_hash == "" then return end - original_revision = data.opts.base_revision or (file.commit_hash .. "^") + local parents = data.parents and data.parents[file.commit_hash] + if data.opts.base_revision then + original_revision = data.opts.base_revision + elseif parents then + original_revision, root_commit = parents[1], #parents == 0 + else + original_revision, parent_commit = file.commit_hash .. "^", file.commit_hash + end modified_revision = file.commit_hash original = data.opts.base_revision and file.path or original line_range = data.opts.line_range @@ -189,7 +213,7 @@ function M.comparison(panel, file) original_revision, modified_revision = "HEAD", "WORKING" for _, staged in ipairs(data.status_result.staged or {}) do if staged.path == file.path then - original_revision = ":0" + original_revision, original = ":0", file.path break end end @@ -198,7 +222,7 @@ function M.comparison(panel, file) end end end - local single_side + local single_side = root_commit and "modified" or nil if data.git_root then if file.status == "??" or file.status == "A" then single_side, original_revision = "modified", nil @@ -216,6 +240,8 @@ function M.comparison(panel, file) conflict = conflict, single_side = single_side, line_range = line_range, + parent_commit = parent_commit, + parent_cache = data.parents, } end diff --git a/lua/codediff/ui/view/helpers.lua b/lua/codediff/ui/view/helpers.lua index 5ca22f8c..7dc79f9e 100644 --- a/lua/codediff/ui/view/helpers.lua +++ b/lua/codediff/ui/view/helpers.lua @@ -49,6 +49,12 @@ end ---@param revision string? ---@param ref Path `.relative` builds the codediff:// URL; `.absolute` identifies the real file function M.prepare_buffer(is_virtual, git_root, revision, ref) + if not is_virtual and ref.absolute == "" then + local buf = vim.api.nvim_create_buf(false, true) + vim.bo[buf].buftype = "nofile" + vim.bo[buf].bufhidden = "wipe" + return { bufnr = buf, needs_edit = false } + end if is_virtual then -- Virtual file: generate URL from the repo-relative path local virtual_url = virtual_file.create_url(git_root, revision, ref.relative) @@ -117,7 +123,17 @@ function M.show_real_file_buffer(win, bufnr) -- Only normal (file-backed) buffers are timestamp-checked by Neovim; scratch -- and codediff:// buffers are skipped, so don't bother them. if vim.api.nvim_buf_is_valid(bufnr) and vim.bo[bufnr].buftype == "" then - pcall(vim.cmd, "silent! checktime " .. bufnr) + local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) + local file = vim.api.nvim_buf_get_name(bufnr) + -- A clean BufNewFile buffer needs an explicit read when the file appears: + -- checktime asks W13 instead of reloading it, even with autoread enabled. + if not vim.bo[bufnr].modified and #lines == 1 and lines[1] == "" and vim.fn.filereadable(file) == 1 then + vim.api.nvim_buf_call(bufnr, function() + vim.cmd("silent edit!") + end) + else + pcall(vim.cmd, "silent! checktime " .. bufnr) + end end vim.api.nvim_win_set_buf(win, bufnr) end @@ -163,13 +179,13 @@ end function M.update_content(session, side, input, lines) local buf = session[side .. "_bufnr"] if not input.path or input.path.absolute == "" then - return + return buf end if not M.is_virtual_revision(input.revision) then if vim.bo[buf].buftype ~= "" then M.set_lines(buf, lines) end - return + return buf end if input.resolved ~= session[side .. "_revision"] then local name = virtual_file.create_url(session.git_root, input.resolved, input.path.relative) @@ -185,7 +201,6 @@ function M.update_content(session, side, input, lines) vim.bo[buf].bufhidden = "hide" vim.bo[buf].swapfile = false end - session[side .. "_bufnr"] = buf local win = session[side .. "_win"] local hidden = side == "original" and session.layout == "inline" and session.single_side ~= "original" if win and vim.api.nvim_win_is_valid(win) and not hidden then @@ -195,6 +210,7 @@ function M.update_content(session, side, input, lines) end virtual_file.set_content(buf, lines, input.path.relative) session[side .. "_revision"] = input.resolved + return buf end return M diff --git a/lua/codediff/ui/view/inline_view/update.lua b/lua/codediff/ui/view/inline_view/update.lua index 38b7c2b2..f0576ec0 100644 --- a/lua/codediff/ui/view/inline_view/update.lua +++ b/lua/codediff/ui/view/inline_view/update.lua @@ -30,7 +30,7 @@ local setup_keymaps = inline_keymaps.setup local function fetch_into_scratch(revision, git_root, relative, bufnr, done) require("codediff.core.git").get_file_content(revision, git_root, relative, function(err, lines) vim.schedule(function() - if set_scratch_lines(bufnr, err and {} or lines) then + if require("codediff.core.virtual_file").set_content(bufnr, err and {} or lines, relative) then done() end end) @@ -49,10 +49,6 @@ local function open_modified_for_update(win, session_config, is_virtual) local mod_buf = new_scratch() vim.bo[mod_buf].modifiable = true vim.api.nvim_win_set_buf(win, mod_buf) - local ft = vim.filetype.match({ filename = session_config.modified.absolute }) - if ft then - vim.bo[mod_buf].filetype = ft - end return mod_buf end @@ -79,7 +75,7 @@ local function fill_original_for_update(orig_buf, session_config, is_virtual, do return end - local orig_path = (session_config.original.absolute ~= "" and session_config.original.absolute) or session_config.modified.absolute + local orig_path = session_config.original.absolute if orig_path and orig_path ~= "" then local real_bufnr = vim.fn.bufadd(orig_path) vim.fn.bufload(real_bufnr) diff --git a/lua/codediff/ui/view/render.lua b/lua/codediff/ui/view/render.lua index fdb2de76..187fc351 100644 --- a/lua/codediff/ui/view/render.lua +++ b/lua/codediff/ui/view/render.lua @@ -205,8 +205,11 @@ function M.update(session, data, changes) local old_original, old_modified = session.original_bufnr, session.modified_bufnr local ok, err = xpcall(function() if changes.inputs then - helpers.update_content(session, "original", data.sources.original, data.original) - helpers.update_content(session, "modified", data.sources.modified, data.modified) + local original = helpers.update_content(session, "original", data.sources.original, data.original) + local modified = helpers.update_content(session, "modified", data.sources.modified, data.modified) + if original ~= old_original or modified ~= old_modified then + require("codediff.ui.lifecycle").update_buffers(session.tabpage, original, modified) + end end if session.result_bufnr then local diffs = @@ -226,7 +229,6 @@ function M.update(session, data, changes) session.changedtick.original = api.nvim_buf_get_changedtick(session.original_bufnr) session.changedtick.modified = api.nvim_buf_get_changedtick(session.modified_bufnr) if old_original ~= session.original_bufnr or old_modified ~= session.modified_bufnr then - require("codediff.ui.lifecycle").update_buffers(session.tabpage, session.original_bufnr, session.modified_bufnr) if session.reapply_keymaps then session.reapply_keymaps() end diff --git a/lua/codediff/ui/view/side_by_side/update.lua b/lua/codediff/ui/view/side_by_side/update.lua index 73f667ae..eaaad89d 100644 --- a/lua/codediff/ui/view/side_by_side/update.lua +++ b/lua/codediff/ui/view/side_by_side/update.lua @@ -296,11 +296,21 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) lifecycle.update_paths(tabpage, session_config.original, session_config.modified) -- Delete old virtual buffers if they were virtual AND are not reused - if lifecycle.is_original_virtual(tabpage) and old_original_buf ~= original_info.bufnr and old_original_buf ~= modified_info.bufnr then + if + lifecycle.is_original_virtual(tabpage) + and old_original_buf ~= original_info.bufnr + and old_original_buf ~= modified_info.bufnr + and not lifecycle.is_buffer_shared(old_original_buf, tabpage) + then pcall(vim.api.nvim_buf_delete, old_original_buf, { force = true }) end - if lifecycle.is_modified_virtual(tabpage) and old_modified_buf ~= modified_info.bufnr and old_modified_buf ~= original_info.bufnr then + if + lifecycle.is_modified_virtual(tabpage) + and old_modified_buf ~= modified_info.bufnr + and old_modified_buf ~= original_info.bufnr + and not lifecycle.is_buffer_shared(old_modified_buf, tabpage) + then pcall(vim.api.nvim_buf_delete, old_modified_buf, { force = true }) end diff --git a/tests/README.md b/tests/README.md index 06ef379d..44ed901a 100644 --- a/tests/README.md +++ b/tests/README.md @@ -64,8 +64,8 @@ nvim --headless --noplugin -u tests/init.lua \ Each spec file gets its own child `nvim --headless` process, so specs stay isolated from one another. `tests/framework/supervisor.lua` runs those children -concurrently from a single parent Neovim, which cuts the suite from ~150s to -~35s on a 4-core machine. +concurrently from a single parent Neovim. Runtime depends on the selected +scenario matrix and available workers; use `CODEDIFF_TEST_JOBS` to control it. Children never share the parent's stdout: their output is buffered in full and printed as one contiguous block when they exit. Letting concurrent processes @@ -96,6 +96,20 @@ they opened files from, and a watcher left pointing at a deleted path prints | `CODEDIFF_TEST_TIMEOUT` | `300000` | Per-spec timeout in ms; guards against a hung spec stalling CI. | | `NO_COLOR` / `CODEDIFF_TEST_NO_COLOR` | unset | Disable ANSI colors. | +## Repository fixtures + +Git-backed tests share [`framework/repository.lua`](framework/repository.lua). +Each case gets an isolated repository and linked worktree in TMP, cloned from an +immutable seed without hardlinks. Refs, index files and object databases are not +shared between cases. Cleanup removes the worktree and its Git metadata. + +[`fixtures/refresh_repo.lua`](fixtures/refresh_repo.lua) supplies the named UI +profiles: basic, hunks, workspace, history and merge. Empty/unborn repositories, +regular `.git` directories, bare local remotes and SHA-256 use the same factory. +The test bootstrap isolates Git configuration and inherited repository overrides. +See [`fixtures/README.md`](fixtures/README.md) for the graph, API and interactive +reproduction commands. + ## Screen-grid regressions `tests/framework/screen.lua` starts a separate `nvim --embed` and attaches an @@ -131,6 +145,10 @@ text and actual text. These are cell-level checks, not font or pixel snapshots. ## Refresh regressions +The [main-to-branch coverage map](ui/refresh/COVERAGE.md) lists each changed +production responsibility, its scenario IDs, and matrix parameters. It separates +named scenarios from expanded executions and from unit/component tests. + `ui/refresh/*_e2e_spec.lua` exercises the session refresh controller through real file writes, Git index/ref changes and rendered screen cells. It covers both layouts, Explorer and bare comparisons, history, single-file previews, diff --git a/tests/core/git_integration_spec.lua b/tests/core/git_integration_spec.lua index cb4b1ed5..02c6b804 100644 --- a/tests/core/git_integration_spec.lua +++ b/tests/core/git_integration_spec.lua @@ -434,7 +434,7 @@ describe("Git read-only queries do not write the index (#494)", function() end local function index_bytes(repo) - return table.concat(vim.fn.readfile(repo.dir .. "/.git/index", "b"), "\n") + return table.concat(vim.fn.readfile(repo.git_path("index"), "b"), "\n") end it("get_status leaves .git/index untouched", function() @@ -463,7 +463,7 @@ describe("Git read-only queries do not write the index (#494)", function() -- error to the user. it("read-only queries still succeed while another git process holds index.lock", function() local repo = make_repo_with_stale_index() - local lock = repo.dir .. "/.git/index.lock" + local lock = repo.git_path("index.lock") vim.fn.writefile({ "" }, lock) local done, err = false, nil diff --git a/tests/core/history_line_range_spec.lua b/tests/core/history_line_range_spec.lua index 6dc382c8..917741e6 100644 --- a/tests/core/history_line_range_spec.lua +++ b/tests/core/history_line_range_spec.lua @@ -5,26 +5,11 @@ local git = require('codediff.core.git') -- Helper: create a temp git repo with multiple commits affecting different line ranges local function create_test_repo() - local temp_dir = vim.fn.tempname() - vim.fn.mkdir(temp_dir, "p") - + local repo = require("tests.framework.repository").new({ unborn = true }) local function run_git(args) - local cmd = string.format('git -C "%s" %s', temp_dir, args) - local output = vim.fn.system(cmd) - return output, vim.v.shell_error - end - - run_git("init") - run_git("config user.email 'test@test.com'") - run_git("config user.name 'Test'") - run_git("branch -m main") - - local function write_file(name, lines) - local path = temp_dir .. "/" .. name - local f = io.open(path, "w") - f:write(table.concat(lines, "\n") .. "\n") - f:close() + return repo.git(args, 0) end + local write_file = repo.write_file -- Commit 1: initial file with header + two functions write_file("test.lua", { @@ -86,12 +71,7 @@ local function create_test_repo() run_git("add .") run_git('commit -m "update header"') - return { - dir = temp_dir, - cleanup = function() - vim.fn.delete(temp_dir, "rf") - end, - } + return repo end describe("Line-range History - get_commit_list with line_range", function() diff --git a/tests/core/pull_request_spec.lua b/tests/core/pull_request_spec.lua index e8bf58b2..fe95b50e 100644 --- a/tests/core/pull_request_spec.lua +++ b/tests/core/pull_request_spec.lua @@ -52,7 +52,7 @@ end describe("pull request fetching", function() local repo - local remote + local remote, remote_fixture local base_revision local head_revision local merge_revision @@ -60,9 +60,8 @@ describe("pull request fetching", function() before_each(function() repo = h.create_temp_git_repo() - remote = h.create_temp_dir() - run(remote, { "init", "--bare" }) - run(remote, { "symbolic-ref", "HEAD", "refs/heads/main" }) + remote_fixture = require("tests.framework.repository").new({ bare = true, unborn = true }) + remote = remote_fixture.dir repo.write_file("review.txt", { "base" }) repo.git("add review.txt") @@ -101,8 +100,9 @@ describe("pull request fetching", function() if repo then repo.cleanup() end - if remote then - vim.fn.delete(remote, "rf") + if remote_fixture then + remote_fixture.cleanup() + remote_fixture = nil end end) diff --git a/tests/core/rename_follow_spec.lua b/tests/core/rename_follow_spec.lua index 07e5a3e7..ec9f57c5 100644 --- a/tests/core/rename_follow_spec.lua +++ b/tests/core/rename_follow_spec.lua @@ -3,22 +3,17 @@ local git = require("codediff.core.git") --- Helper: create a temp git repo (uses table-form vim.fn.system for Windows compat) local function create_rename_repo() - local dir = vim.fn.tempname() - vim.fn.mkdir(dir, "p") + local repo = require("tests.framework.repository").new({ unborn = true }) local function run(...) - return vim.fn.system(vim.list_extend({ "git", "-C", dir }, { ... })) + return repo.command({ ... }) end - run("init") - run("config", "user.email", "test@test.com") - run("config", "user.name", "test") - return dir, run + return repo.dir, run, repo.cleanup end describe("resolve_path_at_revision", function() it("Returns old path for a renamed file", function() - local dir, run = create_rename_repo() + local dir, run, cleanup = create_rename_repo() vim.fn.writefile({ "content" }, dir .. "/old.lua") run("add", ".") @@ -41,11 +36,11 @@ describe("resolve_path_at_revision", function() assert.is_true(done, "Callback should complete") assert.equal("old.lua", resolved, "Should resolve to old path before rename") - vim.fn.delete(dir, "rf") + cleanup() end) it("Returns same path for a file without renames", function() - local dir, run = create_rename_repo() + local dir, run, cleanup = create_rename_repo() vim.fn.writefile({ "content" }, dir .. "/stable.lua") run("add", ".") @@ -69,7 +64,7 @@ describe("resolve_path_at_revision", function() assert.is_true(done, "Callback should complete") assert.equal("stable.lua", resolved, "Should return same path when no rename") - vim.fn.delete(dir, "rf") + cleanup() end) end) diff --git a/tests/core/restore_spec.lua b/tests/core/restore_spec.lua index c855594a..0edc78a9 100644 --- a/tests/core/restore_spec.lua +++ b/tests/core/restore_spec.lua @@ -4,53 +4,14 @@ local git = require("codediff.core.git") --- Helper to run sync git commands in a directory -local function git_sync(args, cwd) - local cmd = vim.list_extend({ "git" }, args) - local result = vim.fn.system(cmd, nil) - if vim.v.shell_error ~= 0 then - error("git command failed: " .. table.concat(cmd, " ") .. "\n" .. result) - end - return vim.trim(result) -end - --- Helper to create a temp git repo with history local function create_test_repo() - local temp_dir = vim.fn.tempname() - vim.fn.mkdir(temp_dir, "p") - - local old_dir = vim.fn.getcwd() - vim.fn.chdir(temp_dir) - - git_sync({ "init" }, temp_dir) - git_sync({ "config", "user.email", "test@test.com" }, temp_dir) - git_sync({ "config", "user.name", "Test" }, temp_dir) - - -- Commit 1: initial content - vim.fn.writefile({ "version 1" }, temp_dir .. "/file.txt") - git_sync({ "add", "file.txt" }, temp_dir) - git_sync({ "commit", "-m", "commit 1" }, temp_dir) - local commit1 = git_sync({ "rev-parse", "HEAD" }, temp_dir) - - -- Commit 2: updated content - vim.fn.writefile({ "version 2" }, temp_dir .. "/file.txt") - git_sync({ "add", "file.txt" }, temp_dir) - git_sync({ "commit", "-m", "commit 2" }, temp_dir) - local commit2 = git_sync({ "rev-parse", "HEAD" }, temp_dir) - - -- Working tree change (unstaged) - vim.fn.writefile({ "version 3 working" }, temp_dir .. "/file.txt") - - vim.fn.chdir(old_dir) - - return { - dir = temp_dir, - commit1 = commit1, - commit2 = commit2, - cleanup = function() - vim.fn.delete(temp_dir, "rf") - end, - } + local repo = require("tests.framework.repository").new({ unborn = true }) + repo.write_file("file.txt", { "version 1" }) + repo.commit1 = repo.commit("commit 1") + repo.write_file("file.txt", { "version 2" }) + repo.commit2 = repo.commit("commit 2") + repo.write_file("file.txt", { "version 3 working" }) + return repo end describe("restore_file", function() diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md new file mode 100644 index 00000000..3e678ea6 --- /dev/null +++ b/tests/fixtures/README.md @@ -0,0 +1,113 @@ +# Repository fixtures + +Git-backed tests share `tests/framework/repository.lua`. The UI E2Es use the +small deterministic graph in `refresh_repo.lua`; older tests obtain an empty +worktree through `tests/helpers.lua:create_temp_git_repo()`. + +## Isolation and lifecycle + +The factory builds each seed once per spec process, entirely in Neovim's TMP +area. Each test receives: + +```text +TMP/case/ +├── repository.git/ independent bare clone of the seed +└── worktree/ git worktree add ... main + └── .git Git's link to this case's metadata +``` + +The clone uses `--no-hardlinks`. Refs, indexes, Git config and loose objects are +not shared between cases. Tests can commit, reset, merge, stage, move refs and +temporarily remove an object without affecting another test or the plugin's +repository. `repo.git_path("index")` locates metadata correctly for both linked +worktrees and ordinary repositories; tests must not assume `.git` is a directory. + +`repo.cleanup()` removes the whole case, including its Git metadata, and restores +a valid current directory when necessary. Call it after closing the embedded UI. +A `VimLeavePre` fallback also removes seeds and abandoned cases. No fixture lives +in the checked-out source tree. If an unavailable backend skips a case during +setup, its cleanup hooks still run; cleanup failures are reported rather than +hidden by the skip. + +`tests/init.lua` removes inherited repository/index environment overrides and +isolates global/system Git configuration. The factory also rejects inherited +repository overrides, disables hooks and signing, sets a local test identity, +and defaults to SHA-1. Explicit SHA-256 cases use the same factory. + +## Refresh graph + +The seed contains 13 small text files: ordinary files, two distant hunks, a moved +block, nested paths, spaces/Unicode, an empty file, a Lua file and a merge file. +Its five commits have fixed authors and dates: + +```text +fixture/base +├── history one ── history two +├── incoming changes +└── current changes +``` + +Tags `fixture/one`, `fixture/two`, `fixture/incoming` and `fixture/current` retain +the corresponding commits. The seed's `main` stays at `fixture/base`. + +| Profile | Initial state of the test worktree | +| --- | --- | +| `basic` / omitted | Clean base commit and named fixture tags | +| `hunks` | Two separated working-tree changes in `hunks.txt` | +| `workspace` | Mixed staged/unstaged content, nested changes, rename, deletion, untracked file | +| `history` | Two subsequent commits, added/deleted/renamed files, two review branches | +| `merge` | Real in-progress merge with two separated conflicts and automatic one-sided edits | + +Golden contents are declared in `refresh_repo.files`; assertions do not ask the +production diff/merge calculator to construct their expectations. + +## API + +```lua +local fixture = require("tests.fixtures.refresh_repo") +local repo = fixture.new("workspace") + +repo.command({ "add", "a.txt" }) -- assert exit code 0 +repo.command({ "diff", "--quiet" }, 1) -- explicit expected nonzero status +repo.write_file("a.txt", { "one", "two" }) +repo.write_bytes("a.txt", "one\r\ntwo") +repo.replace("a.txt", 2, "changed") +local index = repo.blob_lines(":0", "a.txt") +local index_path = repo.git_path("index") +repo.cleanup() +``` + +Prefer argv-form `command` for new cases. `git` also accepts existing string-form +commands; the refresh fixture checks their exit status, including merge failures +that must explicitly expect code 1. + +The lower-level factory supports special states through the same lifecycle: + +```lua +local repositories = require("tests.framework.repository") +local unborn = repositories.new({ unborn = true }) +local ordinary = repositories.new({ worktree = false, unborn = true }) +local remote = repositories.new({ bare = true, unborn = true }) +local sha256 = fixture.new("history", { object_format = "sha256" }) +``` + +An unborn worktree really has no `HEAD` commit. Its first commit is parentless; +it is not a test repo with a hidden extra initial commit. Bare fixtures serve as +local remotes. Ordinary `.git`-directory cases ensure the tests do not cover only +linked worktrees. + +## Interactive reproduction + +From the plugin checkout, start Neovim with `nvim --noplugin -u tests/init.lua`, +then run: + +```vim +:lua fixture_repo = require('tests.fixtures.refresh_repo').new('workspace') +:lua vim.cmd('cd ' .. vim.fn.fnameescape(fixture_repo.dir)) +:CodeDiff +``` + +Use the same profile to reproduce a failing operation. Print `fixture_repo.dir` +to inspect it from another shell while Neovim is running. The worktree is removed +when this Neovim exits. The full scenario map is in +[`ui/refresh/COVERAGE.md`](../ui/refresh/COVERAGE.md). diff --git a/tests/fixtures/refresh_repo.lua b/tests/fixtures/refresh_repo.lua new file mode 100644 index 00000000..25ad5fbc --- /dev/null +++ b/tests/fixtures/refresh_repo.lua @@ -0,0 +1,140 @@ +-- A deterministic Git graph shared by refresh and UI-operation E2Es. +-- Every invocation returns a separate TMP repository and linked worktree. +local M = {} +local repositories = require("tests.framework.repository") + +M.files = { + ["a.txt"] = { "start", "base-A", "context", "end", "tail" }, + ["b.txt"] = { "start", "base-B", "end" }, + ["background.txt"] = { "unchanged" }, + ["hunks.txt"] = { + "base-one", + "context-02", + "context-03", + "context-04", + "context-05", + "context-06", + "context-07", + "context-08", + "context-09", + "context-10", + "context-11", + "base-two", + "tail", + }, + ["moves.txt"] = { "alpha_1", "alpha_2", "alpha_3", "alpha_4", "alpha_5", "unchanged_1", "unchanged_2", "unchanged_3", "beta_1", "beta_2", "beta_3", "beta_4", "beta_5" }, + ["nested/alpha.txt"] = { "alpha", "base-alpha", "end" }, + ["nested/deep/beta.txt"] = { "beta", "base-beta", "end" }, + ["rename/source file.txt"] = { "rename header", "rename body 1", "rename body 2", "rename body 3", "rename tail" }, + ["gone.txt"] = { "delete header", "delete body", "delete tail" }, + ["empty.txt"] = {}, + ["utf8/文件 name.txt"] = { "开始", "原始内容", "结束" }, + ["sample.lua"] = { "local value = 'base'", "return value" }, + ["merge.txt"] = { + "merge start", + "context-02", + "context-03", + "base-one", + "context-05", + "context-06", + "context-07", + "base-incoming-only", + "context-09", + "context-10", + "context-11", + "base-current-only", + "context-13", + "context-14", + "context-15", + "base-two", + "context-17", + "context-18", + "merge end", + }, +} + +local function build(repo) + for filename, content in pairs(M.files) do + repo.write_file(filename, vim.deepcopy(content)) + end + local refs = { base = repo.commit("fixture base") } + repo.command({ "tag", "fixture/base", refs.base }) + + repo.replace("a.txt", 2, "history-one") + repo.write_file("history/added.txt", { "added in history" }) + refs.first = repo.commit("history one") + repo.replace("a.txt", 2, "history-two") + repo.replace("b.txt", 2, "history-two-B") + repo.command({ "mv", "rename/source file.txt", "rename/renamed file.txt" }) + repo.command({ "rm", "gone.txt" }) + refs.second = repo.commit("history two") + repo.command({ "tag", "fixture/one", refs.first }) + repo.command({ "tag", "fixture/two", refs.second }) + + repo.command({ "reset", "--hard", refs.base }) + repo.command({ "checkout", "-b", "seed-incoming" }) + repo.replace("a.txt", 2, "incoming-A") + repo.replace("b.txt", 2, "incoming-B") + repo.replace("merge.txt", 4, "incoming-one") + repo.replace("merge.txt", 8, "incoming-only") + repo.replace("merge.txt", 16, "incoming-two") + refs.incoming = repo.commit("incoming changes") + repo.command({ "tag", "fixture/incoming", refs.incoming }) + repo.command({ "checkout", "main" }) + repo.replace("a.txt", 2, "current-A") + repo.replace("b.txt", 2, "current-B") + repo.replace("merge.txt", 4, "current-one") + repo.replace("merge.txt", 12, "current-only") + repo.replace("merge.txt", 16, "current-two") + refs.current = repo.commit("current changes") + repo.command({ "tag", "fixture/current", refs.current }) + repo.command({ "reset", "--hard", refs.base }) + repo.command({ "branch", "-D", "seed-incoming" }) + return refs +end + +function M.new(profile, options) + local repo = repositories.new(vim.tbl_extend("force", { key = "refresh", build = build }, options or {})) + for name, revision in pairs(repo.seed) do + repo[name] = revision + end + local git = repo.git + repo.git = function(args, expected) + return git(args, expected or 0) + end + local ok, err = pcall(function() + if profile == "hunks" then + repo.replace("hunks.txt", 1, "working-one") + repo.replace("hunks.txt", 12, "working-two") + elseif profile == "workspace" then + repo.replace("a.txt", 2, "index-A") + repo.command({ "add", "a.txt" }) + repo.replace("a.txt", 2, "working-A") + repo.replace("b.txt", 2, "working-B") + repo.replace("nested/alpha.txt", 2, "working-alpha") + repo.replace("nested/deep/beta.txt", 2, "working-beta") + repo.write_file("fresh.txt", { "new header", "new body", "new tail" }) + assert.equals(0, vim.fn.delete(repo.path("gone.txt"))) + repo.command({ "mv", "rename/source file.txt", "rename/renamed file.txt" }) + elseif profile == "history" then + repo.command({ "reset", "--hard", repo.second }) + repo.command({ "branch", "review/left", repo.first }) + repo.command({ "branch", "review/right", repo.second }) + elseif profile == "merge" then + repo.command({ "reset", "--hard", repo.current }) + repo.command({ "branch", "incoming", repo.incoming }) + repo.command({ "merge", "incoming", "--no-edit" }, 1) + assert.is_true(repo.command({ "ls-files", "--unmerged" }) ~= "", "merge fixture must contain real index conflicts") + else + assert(profile == nil or profile == "basic", "unknown fixture profile: " .. tostring(profile)) + assert.equals("", repo.command({ "status", "--porcelain" }), "base fixture must be clean") + end + end) + if not ok then + repo.cleanup() + error(err) + end + return repo +end + +return M diff --git a/tests/framework/repository.lua b/tests/framework/repository.lua new file mode 100644 index 00000000..def1ae84 --- /dev/null +++ b/tests/framework/repository.lua @@ -0,0 +1,238 @@ +-- Isolated Git worktree fixtures. Seeds are immutable; each case owns its refs, +-- object database, index and worktree beneath one disposable TMP directory. +local M = {} +local uv = vim.uv or vim.loop +local seeds, owned = {}, {} +local project_root = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h:h:h") + +local function run(argv, opts) + return vim.system(argv, vim.tbl_extend("force", { text = true }, opts or {})):wait() +end + +local function checked(argv, expected, opts) + local result = run(argv, opts) + assert.equals(expected or 0, result.code, table.concat(argv, " ") .. "\n" .. (result.stderr or "")) + return result.stdout or "", result.code +end + +function M.git(dir, args) + if type(args) == "table" then + local argv = { "git", "-C", dir } + vim.list_extend(argv, args) + local result = run(argv) + return (result.stdout or "") .. (result.stderr or ""), result.code + end + local root = vim.fn.has("win32") == 1 and ('"' .. dir .. '"') or vim.fn.shellescape(dir) + local output = vim.fn.system("git -C " .. root .. " " .. args) + return output, vim.v.shell_error +end + +local function remove(root) + if not owned[root] then + return + end + local cwd = vim.fn.getcwd():gsub("\\", "/") + if cwd == root or cwd:sub(1, #root + 1) == root .. "/" then + vim.fn.chdir(project_root) + end + if vim.fn.delete(root, "rf") ~= 0 then + assert( + vim.wait(2000, function() + return vim.fn.delete(root, "rf") == 0 or vim.fn.isdirectory(root) == 0 + end, 25), + "Cannot remove fixture directory: " .. root + ) + end + owned[root] = nil +end + +local function directory() + local root = vim.fn.tempname():gsub("\\", "/") + vim.fn.mkdir(root, "p") + root = assert(uv.fs_realpath(root)):gsub("\\", "/") + owned[root] = true + return root +end + +local function repository(dir) + local repo = { dir = dir } + local commit_number = 0 + + function repo.path(filename) + return repo.dir .. "/" .. filename + end + + function repo.git(args, expected) + local output, code = M.git(repo.dir, args) + if expected ~= nil then + assert.equals(expected, code, "git " .. vim.inspect(args) .. "\n" .. output) + end + return output, code + end + + function repo.command(args, expected, opts) + local argv = { "git", "-C", repo.dir } + vim.list_extend(argv, args) + return checked(argv, expected, opts) + end + + function repo.git_path(name) + local value = vim.trim(repo.command({ "rev-parse", "--path-format=absolute", "--git-path", name })) + return value:gsub("\\", "/") + end + + function repo.write_file(filename, lines) + local target = repo.path(filename) + vim.fn.mkdir(vim.fn.fnamemodify(target, ":h"), "p") + assert.equals(0, vim.fn.writefile(lines, target), "Cannot write fixture file: " .. target) + return target + end + + function repo.read_file(filename) + return vim.fn.readfile(repo.path(filename)) + end + + function repo.write_bytes(filename, value) + vim.fn.mkdir(vim.fn.fnamemodify(repo.path(filename), ":h"), "p") + local file = assert(uv.fs_open(repo.path(filename), "w", 420)) + assert(uv.fs_write(file, value, 0)) + assert(uv.fs_close(file)) + end + + function repo.replace(filename, row, value) + local content = repo.read_file(filename) + content[row] = value + repo.write_file(filename, content) + return content + end + + function repo.blob(revision, filename) + return repo.command({ "show", revision .. ":" .. filename }, 0, { text = false }) + end + + function repo.blob_lines(revision, filename) + local value = repo.blob(revision, filename) + return value == "" and {} or vim.split(value:gsub("\n$", ""), "\n", { plain = true }) + end + + function repo.commit(message) + commit_number = commit_number + 1 + local date = string.format("2001-01-%02dT12:00:00+00:00", commit_number) + repo.command({ "add", "-A" }) + repo.command({ "commit", "--allow-empty", "-m", message }, 0, { env = { GIT_AUTHOR_DATE = date, GIT_COMMITTER_DATE = date } }) + return vim.trim(repo.command({ "rev-parse", "HEAD" })) + end + + return repo +end + +local function configure(repo) + for key, value in pairs({ + ["user.name"] = "Test", + ["user.email"] = "test@test.com", + ["commit.gpgsign"] = "false", + ["tag.gpgsign"] = "false", + ["core.autocrlf"] = "false", + ["core.quotePath"] = "false", + ["core.hooksPath"] = repo.git_path("hooks"), + }) do + repo.command({ "config", key, value }) + end +end + +local function seed_for(key, build, object_format) + if seeds[key] then + return seeds[key] + end + local root = directory() + local ok, value = pcall(function() + local argv = { "git", "init", "-q" } + if object_format then + argv[#argv + 1] = "--object-format=" .. object_format + end + argv[#argv + 1] = root + checked(argv) + local repo = repository(root) + repo.command({ "symbolic-ref", "HEAD", "refs/heads/main" }) + configure(repo) + local metadata = build and build(repo) or { base = repo.commit("fixture bootstrap") } + assert.equals("", repo.command({ "status", "--porcelain" }), "fixture seed must be clean") + return { root = root, metadata = metadata } + end) + if not ok then + remove(root) + error(value) + end + seeds[key] = value + return value +end + +-- build runs once per spec process. A bare clone per case prevents shared refs +-- and object-file mutations from coupling otherwise independent worktrees. +function M.new(opts) + opts = opts or {} + for _, name in ipairs({ "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES" }) do + assert(not vim.env[name] or vim.env[name] == "", "Refusing fixture creation with inherited " .. name) + end + local format = opts.object_format or "sha1" + local key = (opts.key or "empty") .. ":" .. format + local seed = seed_for(key, opts.build, format) + local root = directory() + local ok, value = pcall(function() + local common, worktree = root .. "/repository.git", root .. "/worktree" + if opts.bare then + checked({ "git", "clone", "--bare", "--no-hardlinks", "--quiet", seed.root, common }) + elseif opts.worktree == false then + checked({ "git", "clone", "--no-hardlinks", "--quiet", seed.root, worktree }) + common = worktree .. "/.git" + else + checked({ "git", "clone", "--bare", "--no-hardlinks", "--quiet", seed.root, common }) + checked({ "git", "--git-dir", common, "worktree", "add", "--quiet", worktree, "main" }) + end + local repo = repository(opts.bare and common or worktree) + if not opts.bare then + repo.dir = vim.trim(repo.command({ "rev-parse", "--show-toplevel" })):gsub("\\", "/") + end + repo.root, repo.common_dir = root, common + repo.seed = vim.deepcopy(seed.metadata) + repo.command({ "remote", "remove", "origin" }) + configure(repo) + if opts.unborn then + if opts.bare then + repo.command({ "update-ref", "-d", "refs/heads/main" }) + else + repo.command({ "checkout", "--orphan", "fixture-unborn" }) + repo.command({ "rm", "-rf", "--ignore-unmatch", "." }) + repo.command({ "branch", "-D", "main" }) + end + repo.command({ "symbolic-ref", "HEAD", "refs/heads/main" }) + end + repo.cleanup = function() + remove(root) + end + if opts.bare then + assert.equals("true", vim.trim(repo.command({ "rev-parse", "--is-bare-repository" }))) + else + local valid = opts.worktree == false and vim.fn.isdirectory(repo.path(".git")) or vim.fn.filereadable(repo.path(".git")) + assert.equals(1, valid, "fixture Git layout was not created") + end + return repo + end) + if not ok then + remove(root) + error(value) + end + return value +end + +-- Also collect seeds and fixtures whose setup failed before after_each ran. +vim.api.nvim_create_autocmd("VimLeavePre", { + group = vim.api.nvim_create_augroup("CodeDiffTestRepositories", { clear = true }), + callback = function() + for root in pairs(owned) do + remove(root) + end + end, +}) + +return M diff --git a/tests/framework/repository_spec.lua b/tests/framework/repository_spec.lua new file mode 100644 index 00000000..7bc9ea5e --- /dev/null +++ b/tests/framework/repository_spec.lua @@ -0,0 +1,116 @@ +local repositories = require("tests.framework.repository") + +describe("isolated fixture worktrees", function() + local repos + before_each(function() + repos = {} + end) + after_each(function() + for _, repo in ipairs(repos) do + repo.cleanup() + end + end) + local function new(opts) + local repo = repositories.new(opts) + repos[#repos + 1] = repo + return repo + end + + it("refuses repository overrides that could redirect commands outside the fixture", function() + local saved = vim.env.GIT_DIR + vim.env.GIT_DIR = "/not-a-fixture" + local ok, err = pcall(repositories.new) + vim.env.GIT_DIR = saved + assert.is_false(ok) + assert.is_not_nil(tostring(err):find("inherited GIT_DIR", 1, true)) + end) + + it("preserves an unborn main branch and creates a parentless first commit", function() + local repo = new({ unborn = true }) + assert.equals(1, vim.fn.filereadable(repo.path(".git"))) + assert.equals("true", vim.trim(repo.command({ "rev-parse", "--is-inside-work-tree" }))) + assert.equals("main", vim.trim(repo.command({ "symbolic-ref", "--short", "HEAD" }))) + assert.equals("", repo.command({ "remote" }), "fixtures must not retain a remote pointing at their seed") + local _, code = repo.git({ "rev-parse", "--verify", "HEAD" }) + assert.not_equal(0, code) + repo.write_file("first.txt", { "first" }) + repo.commit("first") + assert.equals("", vim.trim(repo.command({ "log", "-1", "--format=%P" }))) + end) + + it("isolates refs, indexes and objects between worktrees from the same seed", function() + local first, second = new(), new() + local before = vim.trim(second.command({ "rev-parse", "HEAD" })) + assert.equals(before, vim.trim(first.command({ "rev-parse", "HEAD" }))) + assert.not_equal(first.common_dir, second.common_dir) + assert.not_equal(first.git_path("index"), second.git_path("index")) + first.write_file("one.txt", { "changed" }) + first.commit("first only") + first.command({ "branch", "shared-name" }) + second.command({ "branch", "shared-name" }) + assert.equals(before, vim.trim(second.command({ "rev-parse", "shared-name" }))) + assert.not_equal(before, vim.trim(first.command({ "rev-parse", "shared-name" }))) + first.write_file("staged.txt", { "only first" }) + first.command({ "add", "staged.txt" }) + assert.equals("", second.command({ "status", "--porcelain" })) + assert.equals("", second.command({ "ls-files", "staged.txt" })) + end) + + it("also supplies regular Git-directory fixtures through the same factory", function() + local repo = new({ worktree = false, unborn = true }) + assert.equals(1, vim.fn.isdirectory(repo.path(".git"))) + assert.equals("", repo.command({ "remote" })) + repo.write_file("first.txt", { "first" }) + repo.commit("first") + assert.equals("", vim.trim(repo.command({ "log", "-1", "--format=%P" }))) + end) + + it("supplies empty bare repositories for local remote fixtures", function() + local repo = new({ bare = true, unborn = true }) + assert.equals("true", vim.trim(repo.command({ "rev-parse", "--is-bare-repository" }))) + local _, code = repo.git({ "rev-parse", "--verify", "HEAD" }) + assert.not_equal(0, code) + assert.equals("", repo.command({ "remote" })) + end) + + for _, cleanup_error in ipairs({ false, true }) do + it(cleanup_error and "reports cleanup failures even when fixture setup skips a case" or "skips unavailable fixture backends and still runs cleanup", function() + local repo = new() + local script = repo.write_file("pending_fixture.lua", { + "local repo", + "describe('unavailable backend', function()", + " before_each(function()", + " repo = require('tests.framework.repository').new({ unborn = true })", + " pending('backend unavailable')", + " end)", + " after_each(function()", + " repo.cleanup()", + cleanup_error and " error('expected cleanup failure')" or " assert(vim.fn.isdirectory(repo.root) == 0)", + " end)", + " it('does not run the body', function() error('body must not run') end)", + "end)", + }) + local result = vim + .system({ + vim.v.progpath, + "--headless", + "--noplugin", + "-u", + "tests/init.lua", + "-c", + "lua require('tests.framework').run_and_exit(" .. string.format("%q", script) .. ")", + }, { text = true }) + :wait() + assert.equals(cleanup_error and 1 or 0, result.code, (result.stdout or "") .. (result.stderr or "")) + end) + end + + it("removes the worktree and its Git metadata and leaves a valid current directory", function() + local repo = new() + vim.fn.chdir(repo.dir) + repo.cleanup() + assert.equals(0, vim.fn.isdirectory(repo.root)) + assert.equals(1, vim.fn.isdirectory(vim.fn.getcwd())) + repo.cleanup() + end) +end) diff --git a/tests/framework/runner.lua b/tests/framework/runner.lua index 0753f0f7..3c6339da 100644 --- a/tests/framework/runner.lua +++ b/tests/framework/runner.lua @@ -52,14 +52,16 @@ local function run_test(test) for _, hook in ipairs(busted.hooks_for(test, "before_each")) do local ok, err = guarded(hook) if not ok then - before_err = err + if err ~= busted.PENDING_SENTINEL then + before_err = err + end break end end -- Run the test body local test_err - if not before_err then + if not before_err and not test.pending then local ok, err = guarded(test.fn) if not ok and err ~= busted.PENDING_SENTINEL then test_err = err @@ -88,8 +90,8 @@ local function run_test(test) return "fail" end - if test.pending then - -- pending() was called inside the running body + if test.pending and #after_errs == 0 then + -- pending() was called during setup or inside the running body reporter.print_test(desc, test.name, "pending", test.pending_msg) return "pending" end diff --git a/tests/full_integration_spec.lua b/tests/full_integration_spec.lua index 7feee6b5..2745aa62 100644 --- a/tests/full_integration_spec.lua +++ b/tests/full_integration_spec.lua @@ -17,7 +17,7 @@ local function setup_command() end describe("Full Integration Suite", function() - local temp_dir + local temp_dir, repo local commit_hash_1 local commit_hash_2 @@ -31,16 +31,8 @@ describe("Full Integration Suite", function() -- Setup command setup_command() - -- Create temporary git repository for testing - temp_dir = vim.fn.tempname() - vim.fn.mkdir(temp_dir, "p") - - -- Initialize git repo - git("init") - -- Rename branch to main to be sure - git("branch -m main") - git('config user.email "test@example.com"') - git('config user.name "Test User"') + repo = require("tests.framework.repository").new({ unborn = true }) + temp_dir = repo.dir -- Commit 1 vim.fn.writefile({ "line 1", "line 2" }, temp_dir .. "/file.txt") @@ -74,8 +66,9 @@ describe("Full Integration Suite", function() vim.wait(200) -- Clean up - if temp_dir and vim.fn.isdirectory(temp_dir) == 1 then - vim.fn.delete(temp_dir, "rf") + if repo then + repo.cleanup() + repo = nil end end) diff --git a/tests/helpers.lua b/tests/helpers.lua index e1126467..86b75dda 100644 --- a/tests/helpers.lua +++ b/tests/helpers.lua @@ -1,292 +1,164 @@ --- Test helpers for vscode-diff tests --- Provides cross-platform utilities and common test patterns - -local M = {} - --- Ensure the plugin is loaded --- This is needed because the test runner may not have auto-loaded plugin/codediff.lua -function M.ensure_plugin_loaded() - if not vim.g.loaded_codediff then - local plugin_file = vim.fn.getcwd() .. '/plugin/codediff.lua' - if vim.fn.filereadable(plugin_file) == 1 then - dofile(plugin_file) - end - end - -- Also ensure virtual_file autocmds are set up (the test runner may clear them between tests) - local virtual_file = require('codediff.core.virtual_file') - virtual_file.setup() -end - --- Detect if running on Windows -M.is_windows = vim.fn.has("win32") == 1 or vim.fn.has("win64") == 1 - --- Get path separator for current OS -M.path_sep = M.is_windows and "\\" or "/" - --- Get temp directory path -function M.get_temp_dir() - if M.is_windows then - return vim.fn.getenv("TEMP") or "C:\\Windows\\Temp" - else - return "/tmp" - end -end - --- Get a temp file path with given filename -function M.get_temp_path(filename) - return M.get_temp_dir() .. M.path_sep .. filename -end - --- Create a unique temp directory and return its path -function M.create_temp_dir() - local temp_dir = vim.fn.tempname() - vim.fn.mkdir(temp_dir, "p") - -- On Windows, normalize to forward slashes for consistency - if M.is_windows then - temp_dir = temp_dir:gsub("\\", "/") - end - return temp_dir -end - --- Run git command in a specific directory (cross-platform) --- Uses git -C which works on both Windows and Unix -function M.git_cmd(dir, args) - local safe_dir - if M.is_windows then - -- On Windows, use double quotes for paths with spaces - safe_dir = '"' .. dir .. '"' - else - safe_dir = vim.fn.shellescape(dir) - end - local cmd = string.format('git -C %s %s', safe_dir, args) - local output = vim.fn.system(cmd) - local exit_code = vim.v.shell_error - return output, exit_code -end - --- Initialize a temp git repository with basic config --- Returns: { dir = path, cleanup = function } -function M.create_temp_git_repo() - local temp_dir = M.create_temp_dir() - - M.git_cmd(temp_dir, "init") - M.git_cmd(temp_dir, "config user.email 'test@test.com'") - M.git_cmd(temp_dir, "config user.name 'Test'") - -- Set default branch name to avoid warnings - M.git_cmd(temp_dir, "branch -m main") - - -- Get the canonical path from git to match what get_git_root() returns - -- On Windows: avoids 8.3 short name vs long name mismatches - -- On macOS: avoids /var vs /private/var symlink issues - local output = M.git_cmd(temp_dir, "rev-parse --show-toplevel") - if output then - local canonical = vim.trim(output) - if canonical and canonical ~= '' then - temp_dir = canonical - end - end - - return { - dir = temp_dir, - -- Helper to run git in this repo - git = function(args) - return M.git_cmd(temp_dir, args) - end, - -- Helper to create a file in this repo - write_file = function(rel_path, lines) - local full_path = temp_dir .. "/" .. rel_path - -- Ensure parent directory exists - local parent = vim.fn.fnamemodify(full_path, ":h") - vim.fn.mkdir(parent, "p") - vim.fn.writefile(lines, full_path) - return full_path - end, - -- Helper to get full path - path = function(rel_path) - return temp_dir .. "/" .. rel_path - end, - -- Cleanup function - cleanup = function() - vim.fn.delete(temp_dir, "rf") - end - } -end - --- Wait for an async operation to complete --- This processes the event loop properly for vim.system callbacks --- @param timeout_ms: Maximum time to wait --- @param condition_fn: Function that returns true when done (optional) --- @param interval_ms: Check interval (default 50ms) --- @return boolean: true if condition was met, false if timed out -function M.wait_async(timeout_ms, condition_fn, interval_ms) - timeout_ms = timeout_ms or 5000 - interval_ms = interval_ms or 50 - - if condition_fn then - return vim.wait(timeout_ms, condition_fn, interval_ms) - else - -- Fixed wait - just process events for the duration - vim.wait(timeout_ms) - return true - end -end - --- Wait for a lifecycle session to be fully ready --- This handles the async virtual file loading --- @param tabpage: The tabpage number --- @param timeout_ms: Maximum time to wait (default 10000ms for CI) --- @return boolean: true if session is ready -function M.wait_for_session_ready(tabpage, timeout_ms) - timeout_ms = timeout_ms or 10000 - local lifecycle = require('codediff.ui.lifecycle') - - return vim.wait(timeout_ms, function() - local session = lifecycle.get_session(tabpage) - if not session then return false end - if not session.stored_diff_result then return false end - - local orig_buf, mod_buf = lifecycle.get_buffers(tabpage) - if not orig_buf or not mod_buf then return false end - - return vim.api.nvim_buf_is_valid(orig_buf) and vim.api.nvim_buf_is_valid(mod_buf) - end, 100) -end - --- Wait for a virtual file load event to fire for the specified buffer --- This is useful when calling view.update with mutable revisions like :0 --- @param bufnr: The buffer number to wait for --- @param timeout_ms: Maximum time to wait (default 5000ms) --- @return boolean: true if event fired -function M.wait_for_virtual_file_load(bufnr, timeout_ms) - timeout_ms = timeout_ms or 5000 - local loaded = false - - local group = vim.api.nvim_create_augroup('TestWaitVirtualFile', { clear = true }) - vim.api.nvim_create_autocmd('User', { - group = group, - pattern = 'CodeDiffVirtualFileLoaded', - callback = function(event) - if event.data and event.data.buf == bufnr then - loaded = true - end - end, - }) - - local ok = vim.wait(timeout_ms, function() return loaded end, 50) - pcall(vim.api.nvim_del_augroup_by_id, group) - return ok -end - --- Wait for buffer content to contain expected text --- @param bufnr: The buffer number --- @param expected: Text that should be in the buffer --- @param timeout_ms: Maximum time to wait (default 5000ms) --- @return boolean: true if content found -function M.wait_for_buffer_content(bufnr, expected, timeout_ms) - timeout_ms = timeout_ms or 5000 - return vim.wait(timeout_ms, function() - if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then - return false - end - local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) - local content = table.concat(lines, '\n') - return content:find(expected, 1, true) ~= nil - end, 50) -end - ---- Wait until the tabpage's *current* modified diff buffer contains `expected`. ---- Unlike wait_for_buffer_content (fixed bufnr), this re-fetches the modified ---- buffer on every poll, so it tolerates the buffer swap that view.update does ---- when a diff switches between working-tree and staged (:0) revisions. -function M.wait_for_modified_content(tabpage, expected, timeout_ms) - timeout_ms = timeout_ms or 5000 - local lifecycle = require('codediff.ui.lifecycle') - return vim.wait(timeout_ms, function() - local _, mod_buf = lifecycle.get_buffers(tabpage) - if not mod_buf or not vim.api.nvim_buf_is_valid(mod_buf) then - return false - end - local lines = vim.api.nvim_buf_get_lines(mod_buf, 0, -1, false) - return table.concat(lines, '\n'):find(expected, 1, true) ~= nil - end, 50) -end - --- Get buffer content as a single string -function M.get_buffer_content(bufnr) - if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then - return nil - end - local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) - return table.concat(lines, "\n") -end - --- Get buffer content as lines table -function M.get_buffer_lines(bufnr) - if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then - return nil - end - return vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) -end - --- Normalize a path for comparison (forward slashes, no trailing slash) -function M.normalize_path(path) - if not path then return nil end - -- Convert to absolute - path = vim.fn.fnamemodify(path, ':p') - -- Remove trailing slashes - path = path:gsub('[/\\]$', '') - -- Normalize to forward slashes - path = path:gsub('\\', '/') - return path -end - --- Close all tabs except the first one (cleanup helper) -function M.close_extra_tabs() - while vim.fn.tabpagenr('$') > 1 do - vim.cmd('tabclose') - end -end - --- Find the first window in the current tab whose buffer has the given --- filetype. Returns (winid, bufnr) or (nil, nil). -function M.find_window_by_filetype(filetype) - for _, winid in ipairs(vim.api.nvim_tabpage_list_wins(0)) do - local bufnr = vim.api.nvim_win_get_buf(winid) - if vim.bo[bufnr].filetype == filetype then - return winid, bufnr - end - end - return nil, nil -end - --- Wait for a codediff explorer window to appear in the current tab. --- Returns true if it appeared before the timeout. -function M.wait_for_explorer(timeout_ms) - return vim.wait(timeout_ms or 5000, function() - return M.find_window_by_filetype("codediff-explorer") ~= nil - end, 50) -end - --- Wait until the current tab has a codediff session with valid buffers. --- Distinct from wait_for_session_ready (which polls stored_diff_result); this --- is the minimal readiness check the pre-conversion E2E scenarios used. -function M.wait_for_diff_ready(timeout_ms) - local lifecycle = require("codediff.ui.lifecycle") - local tabpage = vim.api.nvim_get_current_tabpage() - return vim.wait(timeout_ms or 10000, function() - local session = lifecycle.get_session(tabpage) - if not session or not session.stored_diff_result then - return false - end - local orig, mod = lifecycle.get_buffers(tabpage) - return orig and mod and vim.api.nvim_buf_is_valid(orig) and vim.api.nvim_buf_is_valid(mod) - end, 100) -end - --- Assert that a string contains a substring -function M.assert_contains(str, substr, msg) - local found = str and str:find(substr, 1, true) ~= nil - assert(found, msg or string.format("Expected '%s' to contain '%s'", str or "nil", substr)) -end - -return M +-- Cross-platform helpers shared by unit, integration and embedded UI tests. +local M = {} + +function M.ensure_plugin_loaded() + if not vim.g.loaded_codediff then + local plugin_file = vim.fn.getcwd() .. "/plugin/codediff.lua" + if vim.fn.filereadable(plugin_file) == 1 then + dofile(plugin_file) + end + end + -- Specs may clear autocmds between tests. + require("codediff.core.virtual_file").setup() +end + +M.is_windows = vim.fn.has("win32") == 1 or vim.fn.has("win64") == 1 +M.path_sep = M.is_windows and "\\" or "/" + +function M.get_temp_dir() + return M.is_windows and (vim.fn.getenv("TEMP") or "C:\\Windows\\Temp") or "/tmp" +end + +function M.get_temp_path(filename) + return M.get_temp_dir() .. M.path_sep .. filename +end + +function M.create_temp_dir() + local dir = vim.fn.tempname() + vim.fn.mkdir(dir, "p") + return M.is_windows and dir:gsub("\\", "/") or dir +end + +function M.git_cmd(dir, args) + return require("tests.framework.repository").git(dir, args) +end + +-- A fresh unborn main branch in an isolated TMP repository and worktree. +function M.create_temp_git_repo() + return require("tests.framework.repository").new({ unborn = true }) +end + +function M.wait_async(timeout_ms, condition_fn, interval_ms) + timeout_ms = timeout_ms or 5000 + interval_ms = interval_ms or 50 + if condition_fn then + return vim.wait(timeout_ms, condition_fn, interval_ms) + end + vim.wait(timeout_ms) + return true +end + +function M.wait_for_session_ready(tabpage, timeout_ms) + local lifecycle = require("codediff.ui.lifecycle") + return vim.wait(timeout_ms or 10000, function() + local session = lifecycle.get_session(tabpage) + if not session or not session.stored_diff_result then + return false + end + local original, modified = lifecycle.get_buffers(tabpage) + return original and modified and vim.api.nvim_buf_is_valid(original) and vim.api.nvim_buf_is_valid(modified) + end, 100) +end + +function M.wait_for_virtual_file_load(bufnr, timeout_ms) + local loaded = false + local group = vim.api.nvim_create_augroup("TestWaitVirtualFile", { clear = true }) + vim.api.nvim_create_autocmd("User", { + group = group, + pattern = "CodeDiffVirtualFileLoaded", + callback = function(event) + if event.data and event.data.buf == bufnr then + loaded = true + end + end, + }) + local ok = vim.wait(timeout_ms or 5000, function() + return loaded + end, 50) + pcall(vim.api.nvim_del_augroup_by_id, group) + return ok +end + +function M.wait_for_buffer_content(bufnr, expected, timeout_ms) + return vim.wait(timeout_ms or 5000, function() + if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then + return false + end + return table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, false), "\n"):find(expected, 1, true) ~= nil + end, 50) +end + +-- Re-fetch the pane's buffer each time: updates can replace revision buffers. +function M.wait_for_modified_content(tabpage, expected, timeout_ms) + local lifecycle = require("codediff.ui.lifecycle") + return vim.wait(timeout_ms or 5000, function() + local _, buf = lifecycle.get_buffers(tabpage) + if not buf or not vim.api.nvim_buf_is_valid(buf) then + return false + end + return table.concat(vim.api.nvim_buf_get_lines(buf, 0, -1, false), "\n"):find(expected, 1, true) ~= nil + end, 50) +end + +function M.get_buffer_content(bufnr) + if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then + return nil + end + return table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, false), "\n") +end + +function M.get_buffer_lines(bufnr) + if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then + return nil + end + return vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) +end + +function M.normalize_path(path) + if not path then + return nil + end + local normalized = vim.fn.fnamemodify(path, ":p"):gsub("[/\\]$", ""):gsub("\\", "/") + return normalized +end + +function M.close_extra_tabs() + while vim.fn.tabpagenr("$") > 1 do + vim.cmd("tabclose") + end +end + +function M.find_window_by_filetype(filetype) + for _, win in ipairs(vim.api.nvim_tabpage_list_wins(0)) do + local buf = vim.api.nvim_win_get_buf(win) + if vim.bo[buf].filetype == filetype then + return win, buf + end + end + return nil, nil +end + +function M.wait_for_explorer(timeout_ms) + return vim.wait(timeout_ms or 5000, function() + return M.find_window_by_filetype("codediff-explorer") ~= nil + end, 50) +end + +function M.wait_for_diff_ready(timeout_ms) + local lifecycle = require("codediff.ui.lifecycle") + local tabpage = vim.api.nvim_get_current_tabpage() + return vim.wait(timeout_ms or 10000, function() + local session = lifecycle.get_session(tabpage) + if not session or not session.stored_diff_result then + return false + end + local original, modified = lifecycle.get_buffers(tabpage) + return original and modified and vim.api.nvim_buf_is_valid(original) and vim.api.nvim_buf_is_valid(modified) + end, 100) +end + +function M.assert_contains(value, text, message) + assert(value and value:find(text, 1, true), message or string.format("Expected '%s' to contain '%s'", value or "nil", text)) +end + +return M diff --git a/tests/init.lua b/tests/init.lua index cbaa3c6c..f509f39c 100644 --- a/tests/init.lua +++ b/tests/init.lua @@ -11,6 +11,14 @@ vim.env.CODEDIFF_WATCHER_NO_AUTO_INSTALL = "1" -- Disable ShaDa (fixes Windows permission issues in CI) vim.opt.shadafile = "NONE" +-- Never inherit a hook's repository/index overrides or user Git filters into +-- fixture operations. Every test process and embedded UI gets the same sandbox. +for _, name in ipairs({ "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES" }) do + vim.env[name] = nil +end +vim.env.GIT_CONFIG_NOSYSTEM = "1" +vim.env.GIT_CONFIG_GLOBAL = vim.fn.tempname() .. "_gitconfig" + -- Keep git line-ending-neutral for every throwaway repository the specs create. -- -- GitHub's Windows runners ship `core.autocrlf=true` in the global git config, so @@ -22,8 +30,8 @@ vim.opt.shadafile = "NONE" -- real output and turns green assertions red on Windows only. -- -- `GIT_CONFIG_COUNT` (git 2.31+) injects the override into every git process this --- Neovim spawns, which covers the plugin's own calls as well as the several --- helpers that run `git init` themselves. Environment config outranks the system, +-- Neovim spawns, covering both the plugin's calls and the shared repository +-- fixture factory. Environment config outranks the system, -- global and repository config files. vim.env.GIT_CONFIG_COUNT = "1" vim.env.GIT_CONFIG_KEY_0 = "core.autocrlf" @@ -35,11 +43,7 @@ vim.opt.rtp:prepend(cwd) -- Ensure lua/ directory is in package.path for direct requires. Also add the -- repository root so `require("tests.framework")` resolves to tests/framework/init.lua. -package.path = package.path - .. ";" .. cwd .. "/lua/?.lua" - .. ";" .. cwd .. "/lua/?/init.lua" - .. ";" .. cwd .. "/?.lua" - .. ";" .. cwd .. "/?/init.lua" +package.path = package.path .. ";" .. cwd .. "/lua/?.lua" .. ";" .. cwd .. "/lua/?/init.lua" .. ";" .. cwd .. "/?.lua" .. ";" .. cwd .. "/?/init.lua" vim.opt.swapfile = false @@ -61,7 +65,7 @@ vim.opt.swapfile = false vim.g.loaded_autoread = 1 -- Load plugin files (for integration tests that need commands) -vim.cmd('runtime! plugin/*.lua plugin/*.vim') +vim.cmd("runtime! plugin/*.lua plugin/*.vim") -- Setup plugin require("codediff").setup() diff --git a/tests/ui/explorer/explorer_refresh_spec.lua b/tests/ui/explorer/explorer_refresh_spec.lua index 54366a97..53394b69 100644 --- a/tests/ui/explorer/explorer_refresh_spec.lua +++ b/tests/ui/explorer/explorer_refresh_spec.lua @@ -32,7 +32,7 @@ local function setup_command() end describe("Explorer refresh and single-file stability", function() - local temp_dir + local temp_dir, repo local original_cwd local original_get_panel_view local original_get_status_with_line_stats @@ -80,13 +80,9 @@ describe("Explorer refresh and single-file stability", function() require("codediff").setup({ diff = { layout = "side-by-side" } }) setup_command() original_cwd = vim.fn.getcwd() - temp_dir = vim.fn.tempname() - vim.fn.mkdir(temp_dir, "p") + repo = h.create_temp_git_repo() + temp_dir = repo.dir vim.fn.chdir(temp_dir) - h.git_cmd(temp_dir, "init") - h.git_cmd(temp_dir, "branch -m main") - h.git_cmd(temp_dir, 'config user.email "test@example.com"') - h.git_cmd(temp_dir, 'config user.name "Test User"') vim.fn.writefile({ "line 1", "line 2" }, temp_dir .. "/file1.txt") h.git_cmd(temp_dir, "add file1.txt") h.git_cmd(temp_dir, 'commit -m "initial"') @@ -109,8 +105,9 @@ describe("Explorer refresh and single-file stability", function() vim.cmd("tabonly") vim.fn.chdir(original_cwd) vim.wait(200) - if temp_dir and vim.fn.isdirectory(temp_dir) == 1 then - vim.fn.delete(temp_dir, "rf") + if repo then + repo.cleanup() + repo = nil end end) diff --git a/tests/ui/explorer/explorer_spec.lua b/tests/ui/explorer/explorer_spec.lua index e984443c..7559f932 100644 --- a/tests/ui/explorer/explorer_spec.lua +++ b/tests/ui/explorer/explorer_spec.lua @@ -118,7 +118,7 @@ local function find_file_node(explorer, predicate) end describe("Explorer Mode", function() - local temp_dir + local temp_dir, repo local original_cwd before_each(function() @@ -133,17 +133,10 @@ describe("Explorer Mode", function() -- Save original working directory original_cwd = vim.fn.getcwd() - -- Create temporary git repository for testing - temp_dir = vim.fn.tempname() - vim.fn.mkdir(temp_dir, "p") + repo = h.create_temp_git_repo() + temp_dir = repo.dir vim.fn.chdir(temp_dir) - -- Initialize git repo - h.git_cmd(temp_dir, "init") - h.git_cmd(temp_dir, "branch -m main") - h.git_cmd(temp_dir, 'config user.email "test@example.com"') - h.git_cmd(temp_dir, 'config user.name "Test User"') - -- Create and commit initial file vim.fn.writefile({"line 1", "line 2"}, temp_dir .. "/file1.txt") vim.fn.mkdir(temp_dir .. "/nested", "p") @@ -176,8 +169,9 @@ describe("Explorer Mode", function() -- Wait for async operations to complete before deleting temp directory vim.wait(200) - if temp_dir and vim.fn.isdirectory(temp_dir) == 1 then - vim.fn.delete(temp_dir, "rf") + if repo then + repo.cleanup() + repo = nil end end) diff --git a/tests/ui/explorer/issue_498_spec.lua b/tests/ui/explorer/issue_498_spec.lua index 333adb47..75e5915a 100644 --- a/tests/ui/explorer/issue_498_spec.lua +++ b/tests/ui/explorer/issue_498_spec.lua @@ -22,11 +22,8 @@ describe("Issue #498 regression — unborn HEAD is treated as the empty tree", f local GIT_EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" local function make_unborn_repo() - -- `h.create_temp_git_repo()` already runs `git init` + `git config` + `git - -- branch -m main` but never commits, so the returned repo is in the - -- unborn-branch state we need. We rely on this rather than wiping and - -- reinitializing manually so the setup stays cross-platform (the previous - -- attempt used `rm -rf` and `cd &&` chains that don't work on Windows). + -- The shared fixture provides an unborn main branch in a TMP worktree; + -- it has no HEAD commit despite being cloned from an internal seed. repo = h.create_temp_git_repo() end diff --git a/tests/ui/refresh/COVERAGE.md b/tests/ui/refresh/COVERAGE.md new file mode 100644 index 00000000..28eda4d8 --- /dev/null +++ b/tests/ui/refresh/COVERAGE.md @@ -0,0 +1,195 @@ +# Refresh E2E coverage against main + +Baseline: `main` / `origin/main` at +`4b3ad7eb99dd0f02e64bbaf562ca1e87e8c07cc9`. + +This audit covers the refresh implementation, its session-data refactor, and +regressions found while expanding the tests. Paths below are relative to +`lua/codediff/`. Deleted modules are mapped to their replacement behavior rather +than tested through compatibility adapters. + +## Fixture and observation contract + +All Git-backed tests use `tests/framework/repository.lua`, including callers of +`tests/helpers.lua:create_temp_git_repo`. The richer UI scenarios share +`tests/fixtures/refresh_repo.lua`. Each case owns a temporary repository and +worktree; cases never share mutable refs, indexes or object files. See +[the fixture documentation](../../fixtures/README.md). + +The tests start an actual `nvim --embed`, issue commands or keyboard/mouse input, +and observe rendered screen cells. Git operations affect a real repository. +Native cases require the real watcher to become ready. Polling cases explicitly +disable the native transport and exercise the 500 ms fallback. No test replaces +notifications with a call to an internal refresh method. + +Race cases delay delivery of **real Git results**, without replacing their +contents. The read-error case temporarily removes a real loose Git object. +Dialog cases answer Neovim's actual confirmation prompt. Expected file contents, +Git blobs, paths, colors and navigation destinations come from the fixture or +Git, not production diff/gutter calculators. + +The existing hand-authored gutter shape tests remain component-level screen +checks. They deliberately use synthetic buffers to test visual projections that +are difficult to express through a Git merge. They are not counted below. + +## Scenario matrix + +A named scenario is distinct from its parameterized executions. The matrix has +132 named scenarios and 544 E2E executions on a platform with a native watcher. +Fixture tests and unit tests are not included in these counts. + +| Spec in this directory | Scenarios | Executions | Parameters | +| --- | ---: | ---: | --- | +| `refresh_e2e_spec.lua` | 16 | 64 | native/polling × side-by-side/inline | +| `conflict_refresh_e2e_spec.lua` | 10 | 20 | native/polling; three missing-stage shapes | +| `file_refresh_e2e_spec.lua` | 3 | 6 | side-by-side/inline; plain-file polling | +| `lifecycle_e2e_spec.lua` | 17 | 66 | both transports/layouts; process exit is native-only | +| `hunk_actions_e2e_spec.lua` | 14 | 54 | both transports/layouts; manual-only mode runs per layout | +| `explorer_actions_e2e_spec.lua` | 20 | 80 | both transports/layouts | +| `history_actions_e2e_spec.lua` | 14 | 56 | both transports/layouts | +| `merge_actions_e2e_spec.lua` | 15 | 120 | both transports × ours left/right × Result bottom/center | +| `source_refresh_e2e_spec.lua` | 19 | 74 | both transports/layouts; plain-file case runs per layout | +| `virtual_file_e2e_spec.lua` | 4 | 4 | direct public `codediff://` buffer commands | + +## Production change map + +### Commands and source identity + +- `commands/handlers/explorer.lua`: existing symbolic-ref and two-revision E2Es; + S06–S08, S12–S14, S19. +- `commands/handlers/explorer_staged.lua`: H02–H03, E03–E04, S04, S08, S14. +- `commands/handlers/git_diff.lua`: existing bare HEAD/ref and layout-toggle + E2Es; S01, S03, S05, S07, S09–S10, T13, T15. +- `commands/handlers/history.lua`: Y07–Y08, Y13–Y14. +- `core/git/revision.lua`: existing fixed SHA / movable ref E2Es; S07–S10, + S14, Y07–Y08. +- `core/git/content.lua`: existing index and missing-stage E2Es; S02, S04, + S06–S10, V02–V04, T12. +- `core/git/changes.lua`: E01–E16, Y01–Y14, S06, S12–S14. Quoted rename paths, + literal arrows, and root-commit file discovery have dedicated cases. +- `core/virtual_file.lua`: S02, S04, V01–V04, existing delayed-read/file-switch + E2Es, and T16. + +### Refresh ownership and lifecycle + +- `ui/refresh/init.lua`: all transport E2Es; H13, E04, Y06, T09–T16 and the + existing real watcher-exit case. +- `ui/refresh/inputs.lua`: existing unchanged-status, unsaved-edit, fixed-ref, + staged-only, missing-stage and pending-read E2Es; S01–S19, T12–T13. +- `ui/refresh/panel.lua`: E01–E20, Y01–Y14, S06–S08, S12–S14, S19. +- `ui/refresh/policy.lua`: actual worktree/index/HEAD/refs changes throughout + the transport matrix; unit coverage additionally checks all 16 watcher masks. +- `ui/auto_refresh.lua` (removed): H01–H14, C01–C15, T09–T16. +- `ui/explorer/refresh/init.lua` (removed): existing same-status refresh E2Es; + E01–E20, S04–S06, S08, S12–S14, S19. +- `ui/explorer/refresh/scheduler.lua` (removed): existing native-ready, polling, + burst and process-exit E2Es; H13 and T09–T12. +- `ui/history/refresh.lua` (removed): Y01–Y14 and the existing history-head refresh. +- `ui/follow_working_file.lua`: existing HEAD-follow and cross-repository E2Es; + T13 covers leaving Git and returning to a different repository. +- `ui/lifecycle/accessors.lua`: T10–T16, E15, Y12, C14–C15, H11. +- `ui/lifecycle/cleanup.lua`: T10–T11, T14–T16, C14–C15 and existing pending-close + and buffer-wipe E2Es. +- `ui/lifecycle/init.lua`: the shared-buffer ownership contract in T16. +- `ui/lifecycle/session.lua`: T09–T16, H11, C14–C15 and multi-tab E2Es. +- `ui/lifecycle/state.lua`: T09–T10, T15–T16, H12, S16, and existing conflict + suspension/Result preservation E2Es. + +### Explorer and History presentation + +- `ui/explorer/actions.lua`: E01–E20. +- `ui/explorer/init.lua`: E01–E20 and command-driven construction. +- `ui/explorer/keymaps.lua`: E01–E20, H13; these send actual keys/mouse events. +- `ui/explorer/render.lua`: E01–E20, S04, S06, S12–S14, S19. +- `ui/explorer/tree.lua`: E05–E06, E09–E11, E13, E18. +- `ui/history/init.lua`: Y01–Y14. +- `ui/history/keymaps.lua`: Y02–Y14. +- `ui/history/render.lua`: Y01–Y14, including lazy expansion, filtering, ordering, + added/deleted/renamed files and layout transitions. + +### Comparison and merge rendering + +- `ui/view/init.lua`: H11, E15, E19, Y02–Y04, Y07, Y11–Y12, S04–S05, S17, T13, + C14–C15 and existing layout-toggle E2Es. +- `ui/view/helpers.lua`: E15, S01–S19, T13, T15–T16, V01–V04. +- `ui/view/render.lua`: H01–H14, S15–S18, T09, T15–T16, C01–C15. +- `ui/view/panel.lua`: E01–E20, Y01–Y14, S19. +- `ui/view/toggle.lua`: H11, Y12, existing ref-follow-after-toggle and layout + snapshot regressions. +- `ui/view/actions/diffget.lua`: H08–H09, H11, S17. +- `ui/view/actions/hunk.lua`: H01–H14, E16. +- `ui/view/actions/stage.lua`: E01–E05, C15. +- `ui/view/inline_view/buffers.lua`: inline H/E/Y/S/T cases and E15. +- `ui/view/inline_view/create.lua`: inline command-driven E2Es, S01–S19. +- `ui/view/inline_view/render.lua`: inline H01–H14, S15–S18, T09. +- `ui/view/inline_view/single_file.lua`: inline E15, Y02–Y03, Y07, Y11, S04, + S14, S16, C15. +- `ui/view/inline_view/update.lua`: inline E/Y/T transitions, S02, S06, T13. +- `ui/view/side_by_side/create.lua`: side-by-side command-driven E2Es. +- `ui/view/side_by_side/single_file.lua`: E15, Y02–Y03, Y07, Y11, S04, S14, + S16, C15. +- `ui/view/side_by_side/update.lua`: H11, E15, Y02–Y04, Y07, Y11–Y12, T13, + T15–T16, C15 and existing delayed-selection E2Es. +- `ui/conflict/resolution/block.lua`: C02–C05. +- `ui/conflict/resolution/diffget.lua`: C10–C11. +- `ui/conflict/resolution/file.lua`: C06–C09, C15. +- `ui/conflict/view/inputs.lua`: C01–C15 and existing actual-stage-change E2Es. +- `ui/conflict/view/result.lua`: C01–C15, existing edited/untouched/empty Result + and missing-stage E2Es. + +## New scenario index + +Each ID is part of the test name, making failures and source searches traceable. + +| IDs | Contract | +| --- | --- | +| H01–H03 | Stage one/all hunks, unstage one, preserve unaffected index/working text | +| H04–H07 | Real discard/cancel dialogs, deleted lines, BOF insertions | +| H08–H10 | Diffget, undo/redo/save, layout-specific diffput, staging unsaved text | +| H11–H14 | Layout toggle, compact folds, manual-only refresh, hunk text object | +| E01–E04 | Panel/pane staging, same-group advancement, gS, stage/unstage all | +| E05–E08 | Directory staging/restoration, cancel, untracked deletion | +| E09–E13 | Group visibility, folds, list/tree, auto-open, hidden panels, filters/pathspec | +| E14–E16 | Staged rename, deleted-file return, customized mappings after buffer replacement | +| E17–E20 | Rendered hover path, tree navigation, gf/tab return, real double-click | +| Y01–Y05 | Latest/older commits, lazy files, added/deleted previews, list/tree preservation | +| Y06–Y10 | HEAD refresh, root commit, movable base tag, collapse preservation, filtering | +| Y11–Y14 | Rename paths, layout changes, line-range filtering, reverse ordering | +| C01–C05 | Independent fixture seed, marker cells/colors, per-block resolution, undo/redo/discard | +| C06–C11 | Whole-file resolution/reset and numbered diffget | +| C12–C15 | Conflict navigation, save, unrelated staging, quit dialogs, finish-and-stage workflow | +| S01–S05 | Unicode/BOM/CRLF, virtual syntax/readonly, no final newline, empty files | +| S06–S10 | Renames, fixed ancestry, movable tags, regular Git directories, SHA-256 | +| S11–S14 | Plain paths with spaces/Unicode, literal arrows, renamed arrows, unborn branches | +| S15–S19 | Whitespace policy, whole-file highlights, original-right layout, moves, --repo | +| T09–T12 | Hidden updates, hidden wipe, pane close, actual missing-object read/retry | +| T13–T16 | Leaving/returning to Git, user keymaps, inlay hints, shared buffers across tabs | +| V01–V04 | Public revision URI, write protection, reversed load completions, wipe, missing file | + +The existing 38 scenarios cover unchanged-status worktree changes, unsaved +buffers, mutable index/refs/HEAD, fixed revisions, added/deleted previews, +unchanged grids, directory scans, editable Result protection, missing merge +stages, late Git callbacks, tab/buffer retirement, cross-repository following, +hidden panels, shared subscriptions and native-process failover. + +## Regressions found by the expanded scenarios + +| Cases | Correction | +| --- | --- | +| E15 | Read a clean, previously missing file when it reappears instead of blocking on W13 | +| S02 | Populate inline revision buffers without firing FileType/LSP attachment | +| S06, S12–S13 | Parse raw NUL-delimited status paths; use the renamed index path for unstaged content | +| Y07, Y14 | Handle parentless history commits and list their files | +| Y13–Y14 | Preserve line-range and reverse query options during history refresh | +| T13 | Materialize a genuinely empty comparison side when following a file outside Git | +| T15–T16 | Retain original buffer settings and respect buffers still owned by another session | + +## Scope of the assurance + +This is a behavioral change map, not a claim of 100% line/branch coverage or an +exhaustive Cartesian product of every option. Tests validate Neovim's rendered +cells, not fonts or pixels. FileType/readonly/diagnostic/inlay contracts are +covered; every external LSP server, distribution, filesystem failure, and +third-party UI plugin is not installed or simulated. OS/version results must be +reported separately. A passing matrix is evidence for these contracts, not an +absolute guarantee that no other bug exists. diff --git a/tests/ui/refresh/conflict_refresh_e2e_spec.lua b/tests/ui/refresh/conflict_refresh_e2e_spec.lua index 7cf8811a..d79ca468 100644 --- a/tests/ui/refresh/conflict_refresh_e2e_spec.lua +++ b/tests/ui/refresh/conflict_refresh_e2e_spec.lua @@ -8,7 +8,7 @@ local function merge_repo() repo.git("checkout main") repo.write_file("a.txt", { "start", "current-A", "context", "end", "tail" }) repo.git("commit -am current") - local _, code = repo.git("merge incoming --no-edit") + local _, code = repo.git("merge incoming --no-edit", 1) assert.equals(1, code, "fixture must conflict") return repo end @@ -166,7 +166,7 @@ for _, backend in ipairs({ "native", "polling" }) do end repo.git("add -A") repo.git("commit -m current") - local _, code = repo.git("merge incoming --no-edit") + local _, code = repo.git("merge incoming --no-edit", 1) assert.equals(1, code) screen = h.screen(backend, "side-by-side") h.open(screen, repo) diff --git a/tests/ui/refresh/explorer_actions_e2e_spec.lua b/tests/ui/refresh/explorer_actions_e2e_spec.lua new file mode 100644 index 00000000..36b8257d --- /dev/null +++ b/tests/ui/refresh/explorer_actions_e2e_spec.lua @@ -0,0 +1,289 @@ +local h = require("tests.ui.refresh.helpers") +local fixture = require("tests.fixtures.refresh_repo") + +for _, backend in ipairs({ "native", "polling" }) do + for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("Explorer actions E2E / " .. backend .. " / " .. layout, function() + local repo, screen + before_each(function() + repo = h.repo("workspace") + screen = h.screen(backend, layout, { explorer = { width = 38, flatten_dirs = false } }) + end) + after_each(function() + h.close(screen, repo) + screen, repo = nil, nil + end) + local function open(command, filename) + h.open(screen, repo, command or "CodeDiff", filename or "a.txt", filename or "a.txt") + end + + it("[E01] staging a panel entry advances within its original group", function() + open("CodeDiff -- b.txt nested/alpha.txt", "b.txt") + h.panel_cursor(screen, "b.txt", "unstaged") + h.action(screen, "view", "toggle_stage") + h.expect_text(screen, "modified", "working-alpha") + assert.equals("working-B", repo.blob_lines(":0", "b.txt")[2]) + assert.equals("base-alpha", repo.blob_lines(":0", "nested/alpha.txt")[2]) + end) + + it("[E02] staging from a diff pane uses its selected file rather than the panel cursor", function() + open() + h.panel_cursor(screen, "b.txt", "unstaged") + h.action(screen, "view", "toggle_stage", "modified", 2) + h.expect_text(screen, "modified", "working-B") + assert.equals("working-A", repo.blob_lines(":0", "a.txt")[2]) + assert.equals("base-B", repo.blob_lines(":0", "b.txt")[2]) + end) + + it("[E03] swaps staged and unstaged comparisons using gS without changing Git", function() + open() + h.expect_text(screen, "original", "index-A") + h.action(screen, "view", "toggle_staged_view", "modified", 2) + h.expect_text(screen, "original", "base-A") + h.expect_lines(screen, "modified", { "start", "index-A", "context", "end", "tail" }) + h.action(screen, "view", "toggle_staged_view", "modified", 2) + h.expect_lines(screen, "modified", { "start", "working-A", "context", "end", "tail" }) + h.expect_text(screen, "original", "index-A") + assert.equals("index-A", repo.blob_lines(":0", "a.txt")[2]) + assert.equals("working-A", repo.read_file("a.txt")[2]) + end) + + it("[E04] stage-all and unstage-all update both Git and the displayed comparison", function() + open() + h.action(screen, "explorer", "stage_all", "panel") + screen:await(function() + return screen:exec("return refresh_session().modified_revision == ':0'") + end) + h.expect_text(screen, "modified", "working-A") + assert.equals("", repo.command({ "diff", "--name-only" })) + h.action(screen, "explorer", "unstage_all", "panel") + screen:await(function() + return screen:exec("return refresh_session().modified_revision == nil and not refresh_session().refresh.loading") + end) + h.expect_lines(screen, "original", fixture.files["a.txt"]) + h.expect_text(screen, "modified", "working-A") + assert.equals("", repo.command({ "diff", "--cached", "--name-only" })) + end) + + it("[E05] stages every file under a tree directory without touching other changes", function() + screen:exec("require('codediff').setup({ explorer = { view_mode = 'tree' } })") + open() + h.panel_cursor(screen, "nested", "unstaged") + h.action(screen, "view", "toggle_stage") + screen:await(function() + return repo.blob_lines(":0", "nested/alpha.txt")[2] == "working-alpha" and repo.blob_lines(":0", "nested/deep/beta.txt")[2] == "working-beta" + end) + h.idle(screen) + h.expect_text(screen, "modified", "working-A") + assert.equals("index-A", repo.blob_lines(":0", "a.txt")[2]) + assert.equals("base-B", repo.blob_lines(":0", "b.txt")[2]) + end) + + it("[E06] restoring a directory uses the confirmation dialog and preserves other files", function() + screen:exec("require('codediff').setup({ explorer = { view_mode = 'tree' } })") + open() + h.panel_cursor(screen, "nested", "unstaged") + h.confirm(screen, h.key(screen, "explorer", "restore"), "Discard all changes in", "d") + h.expect_panel(screen, "nested", false) + assert.same(fixture.files["nested/alpha.txt"], repo.read_file("nested/alpha.txt")) + assert.same(fixture.files["nested/deep/beta.txt"], repo.read_file("nested/deep/beta.txt")) + assert.equals("working-A", repo.read_file("a.txt")[2]) + h.expect_text(screen, "modified", "working-A") + end) + + it("[E07] cancelling file restore leaves the selected comparison and working file intact", function() + open() + h.panel_cursor(screen, "b.txt", "unstaged") + local before = h.panes(screen) + h.confirm(screen, h.key(screen, "explorer", "restore"), "Discard changes to", "c") + h.preserved(screen, before, 100) + h.expect_panel(screen, "b.txt") + assert.equals("working-B", repo.read_file("b.txt")[2]) + end) + + it("[E08] deletes an untracked entry through the actual restore confirmation", function() + open() + h.panel_cursor(screen, "fresh.txt", "unstaged") + h.confirm(screen, h.key(screen, "explorer", "restore"), "Delete fresh.txt", "d") + h.expect_panel(screen, "fresh.txt", false) + assert.equals(0, vim.fn.filereadable(repo.path("fresh.txt"))) + h.expect_text(screen, "modified", "working-A") + end) + + it("[E09] group visibility keys affect navigation without changing repository data", function() + open("CodeDiff -- a.txt b.txt") + local status = repo.command({ "status", "--porcelain" }) + h.action(screen, "explorer", "toggle_staged", "panel") + h.expect_panel(screen, "Staged Changes", false) + h.action(screen, "view", "next_file", "modified") + h.expect_text(screen, "modified", "working-B") + h.idle(screen) + h.action(screen, "view", "prev_file", "modified") + h.expect_text(screen, "original", "index-A") + h.action(screen, "explorer", "toggle_staged", "panel") + h.expect_panel(screen, "Staged Changes") + assert.equals(status, repo.command({ "status", "--porcelain" })) + end) + + it("[E10] list/tree toggles and fold keys preserve the diff through a repository update", function() + open() + h.action(screen, "explorer", "toggle_view_mode", "panel") + h.expect_panel(screen, "nested") + h.panel_cursor(screen, "Changes") + h.action(screen, "explorer", "fold_close") + h.expect_panel(screen, "b.txt", false) + local before, unchanged = h.panes(screen), h.watch_grid(screen) + local event = h.checkpoint(screen) + repo.write_file("background.txt", { "changed while folded" }) + h.wait_event(screen, event) + h.preserved(screen, before, 100) + unchanged() + h.expect_panel(screen, "b.txt", false) + h.panel_cursor(screen, "Changes") + h.action(screen, "explorer", "fold_open") + h.expect_panel(screen, "b.txt") + h.action(screen, "explorer", "toggle_view_mode") + h.expect_text(screen, "modified", "working-A") + end) + + it("[E11] auto-open-on-cursor drives file selection through real movement keys", function() + screen:exec("require('codediff').setup({ explorer = { auto_open_on_cursor = true } })") + open("CodeDiff -- a.txt b.txt") + h.panel_cursor(screen, "a.txt", "unstaged") + h.feed(screen, "j") + h.expect_text(screen, "modified", "working-B") + h.idle(screen) + h.feed(screen, "k") + h.expect_text(screen, "original", "index-A") + end) + + it("[E12] a hidden panel shows accumulated list changes when reopened", function() + open() + h.action(screen, "view", "toggle_explorer", "modified") + repo.write_file("visible-later.txt", { "new entry" }) + h.action(screen, "view", "toggle_explorer", "modified") + h.expect_panel(screen, "visible-later.txt") + h.expect_text(screen, "modified", "working-A") + end) + + it("[E13] pathspecs and ignore filters continue to apply after external changes", function() + screen:exec("require('codediff').setup({ explorer = { file_filter = { ignore = { 'nested/**' } } } })") + open("CodeDiff -- a.txt nested/alpha.txt") + h.expect_panel(screen, "alpha.txt", false) + local event = h.checkpoint(screen) + repo.replace("nested/alpha.txt", 2, "next-alpha") + repo.replace("b.txt", 2, "outside-pathspec") + h.wait_event(screen, event) + h.expect_panel(screen, "alpha.txt", false) + h.expect_panel(screen, "b.txt", false) + h.expect_text(screen, "modified", "working-A") + end) + + it("[E14] a staged rename retains both paths and ignores unstaged changes", function() + open("CodeDiff --staged") + h.select(screen, "renamed file.txt", "staged") + h.expect_lines(screen, "original", fixture.files["rename/source file.txt"]) + h.expect_lines(screen, "modified", fixture.files["rename/source file.txt"]) + h.expect_text(screen, "modified", "rename body 2") + h.idle(screen) + local before, event = h.panes(screen), h.checkpoint(screen) + repo.replace("rename/renamed file.txt", 3, "unstaged-rename") + h.wait_event(screen, event) + h.preserved(screen, before, 100) + assert.equals("rename body 2", repo.blob_lines(":0", "rename/renamed file.txt")[3]) + end) + + it("[E15] a deleted preview regains its comparison panes when the file returns", function() + open("CodeDiff -- gone.txt", "gone.txt") + h.expect_text(screen, "original", "delete body") + repo.write_file("gone.txt", { "delete header", "restored body", "delete tail" }) + h.expect_text(screen, "modified", "restored body") + h.expect_lines(screen, "original", fixture.files["gone.txt"]) + assert.is_nil(screen:exec("return refresh_session().single_side")) + end) + + it("[E17] hover displays the selected entry's full path without changing the comparison", function() + open() + h.panel_cursor(screen, "a.txt", "unstaged") + local before = h.panes(screen) + h.action(screen, "explorer", "hover") + local hover = screen:exec([[ + for _, win in ipairs(vim.api.nvim_list_wins()) do + if vim.api.nvim_win_get_config(win).relative ~= '' then return win end + end + ]]) + assert.is_not_nil(hover) + screen:await(function() + return h.window_text(screen, hover) == repo.path("a.txt") + end, "hover path was not rendered") + h.action(screen, "explorer", "hover") + assert.is_false(screen:exec("return vim.api.nvim_win_is_valid(...)", { hover })) + h.preserved(screen, before, 100) + end) + + it("[E18] tree navigation skips files inside a collapsed directory", function() + screen:exec("require('codediff').setup({ explorer = { view_mode = 'tree' } })") + open("CodeDiff -- nested/alpha.txt nested/deep/beta.txt", "nested/alpha.txt") + h.action(screen, "view", "next_file", "modified") + h.expect_text(screen, "modified", "working-beta") + h.idle(screen) + h.panel_cursor(screen, "deep", "unstaged") + h.action(screen, "explorer", "fold_close") + h.expect_panel(screen, "beta.txt", false) + h.action(screen, "view", "prev_file", "modified") + h.expect_text(screen, "modified", "working-alpha") + end) + + it("[E19] gf opens the working file in the previous tab and the comparison resumes", function() + open() + local diff_tab = h.panes(screen).tab + h.action(screen, "view", "open_in_prev_tab", "original", 2) + screen:await(function() + return screen:exec("return vim.api.nvim_get_current_tabpage() ~= (...) and vim.api.nvim_buf_get_name(0) == select(2, ...)", { diff_tab, repo.path("a.txt") }) + end) + screen:await(function() + return h.grid_contains(screen, "working-A") + end) + screen:command("tabnext") + h.expect_text(screen, "original", "index-A") + h.expect_text(screen, "modified", "working-A") + end) + + it("[E20] double-clicking a panel file selects it through the real mouse mapping", function() + open() + h.panel_cursor(screen, "b.txt", "unstaged") + local p = screen:exec([[ + local win = refresh_session().panel.view.winid + local pos = vim.api.nvim_win_get_position(win) + local view = vim.api.nvim_win_call(win, vim.fn.winsaveview) + return { pos[1] + vim.api.nvim_win_get_cursor(win)[1] - view.topline, pos[2] + 4 } + ]]) + for _ = 1, 2 do + screen:request("nvim_input_mouse", { "left", "press", "", 0, p[1], p[2] }) + screen:request("nvim_input_mouse", { "left", "release", "", 0, p[1], p[2] }) + end + h.expect_text(screen, "modified", "working-B") + end) + + it("[E16] customized hunk mappings survive replacement of revision buffers", function() + screen:exec("require('codediff').setup({ keymaps = { view = { next_hunk = '', stage_hunk = '' } } })") + repo.replace("hunks.txt", 1, "working-one") + repo.replace("hunks.txt", 12, "working-two") + open("CodeDiff -- hunks.txt", "hunks.txt") + h.action(screen, "view", "stage_hunk", "modified", 1) + local original = vim.deepcopy(fixture.files["hunks.txt"]) + original[1] = "working-one" + h.expect_lines(screen, "original", original) + h.action(screen, "view", "next_hunk", "original", 1) + assert.equals(12, screen:exec("return vim.api.nvim_win_get_cursor(0)[1]")) + h.action(screen, "view", "stage_hunk", "modified", 12) + screen:await(function() + return screen:exec("return refresh_session().modified_revision == ':0'") + end) + h.action(screen, "view", "next_hunk", "modified", 1) + h.expect_text(screen, "modified", "working-two") + assert.equals(12, screen:exec("return vim.api.nvim_win_get_cursor(0)[1]")) + end) + end) + end +end diff --git a/tests/ui/refresh/helpers.lua b/tests/ui/refresh/helpers.lua index becc4424..c7aab0d3 100644 --- a/tests/ui/refresh/helpers.lua +++ b/tests/ui/refresh/helpers.lua @@ -1,6 +1,6 @@ local M = {} local Screen = require("tests.framework.screen") -local helpers = require("tests.helpers") +local fixture = require("tests.fixtures.refresh_repo") local watcher_path function M.native_watcher() @@ -20,28 +20,22 @@ function M.native_watcher() return watcher_path end -function M.repo() - local repo = helpers.create_temp_git_repo() - repo.write_file("a.txt", { "start", "base-A", "context", "end", "tail" }) - repo.write_file("b.txt", { "start", "base-B", "end" }) - repo.write_file("background.txt", { "unchanged" }) - repo.git("add -A") - repo.git("commit -m base") - repo.base = vim.trim(repo.git("rev-parse HEAD")) - return repo +function M.repo(profile, options) + return fixture.new(profile, options) end -function M.screen(backend, layout) +function M.screen(backend, layout, options) local binary = backend == "native" and M.native_watcher() or "" local screen = Screen.new(120, 40) screen.backend = backend screen:exec( [[ - local backend, layout, binary = ... - require('codediff').setup({ + local backend, layout, binary, options = ... + vim.g.mapleader = ' ' + require('codediff').setup(vim.tbl_deep_extend('force', { diff = { layout = layout, jump_to_first_change = false, compute_moves = false }, explorer = { width = 28 }, - }) + }, options)) vim.o.hidden = true vim.o.autoread = true vim.o.number = false @@ -132,21 +126,21 @@ function M.screen(backend, layout) return require('codediff.ui.lifecycle').get_session(refresh_test.tab or vim.api.nvim_get_current_tabpage()) end ]], - { backend, layout or "side-by-side", binary } + { backend, layout or "side-by-side", binary, options or {} } ) return screen end -function M.open(screen, repo, command, expected) +function M.open(screen, repo, command, expected, source_file) screen:exec( [[ - local root, command = ... + local root, command, source_file = ... refresh_test.tab = nil vim.cmd('cd ' .. vim.fn.fnameescape(root)) - vim.cmd('edit ' .. vim.fn.fnameescape(root .. '/a.txt')) + vim.cmd('edit ' .. vim.fn.fnameescape(root .. '/' .. source_file)) vim.cmd(command) ]], - { repo.dir, command or "CodeDiff" } + { repo.dir, command or "CodeDiff", source_file or "a.txt" } ) screen:await(function() M.assert_no_errors(screen) @@ -307,21 +301,27 @@ function M.watch_grid(screen) end end -function M.select(screen, filename) +function M.panel_cursor(screen, text, group) screen:exec( [[ + local text, group = ... local panel = refresh_session().panel.view vim.api.nvim_set_current_win(panel.winid) - for row, text in ipairs(vim.api.nvim_buf_get_lines(panel.bufnr, 0, -1, false)) do - if text:find((...), 1, true) then + for row, line in ipairs(vim.api.nvim_buf_get_lines(panel.bufnr, 0, -1, false)) do + local node = panel.tree:get_node(row) + if line:find(text, 1, true) and (not group or node and node.data and node.data.group == group) then vim.api.nvim_win_set_cursor(panel.winid, { row, 0 }) return end end - error('file is absent from the rendered panel') + error('entry is absent from the rendered panel: ' .. text) ]], - { filename } + { text, group } ) +end + +function M.select(screen, filename, group) + M.panel_cursor(screen, filename, group) M.feed(screen, "") end @@ -364,4 +364,168 @@ function M.feed(screen, keys) end, "keys did not finish") end +function M.focus(screen, side, line) + screen:exec( + [[ + local side, line = ... + local s = refresh_session() + local win = side == 'panel' and s.panel.view.winid or s[side .. '_win'] + assert(win and vim.api.nvim_win_is_valid(win), 'pane is not visible: ' .. side) + vim.api.nvim_set_current_win(win) + if line then vim.api.nvim_win_set_cursor(win, { line, 0 }) end + ]], + { side, line } + ) +end + +function M.key(screen, group, action) + return screen:exec( + [[ + local group, action = ... + local key = require('codediff.config').options.keymaps[group][action] + assert(type(key) == 'string', 'missing key binding: ' .. group .. '.' .. action) + return key:gsub('<[Ll]eader>', vim.g.mapleader or '\\'):gsub('<[Ll]ocal[Ll]eader>', vim.g.maplocalleader or '\\') + ]], + { group, action } + ) +end + +function M.action(screen, group, action, side, line) + if side then + M.focus(screen, side, line) + end + M.feed(screen, M.key(screen, group, action)) +end + +function M.grid_contains(screen, text) + for row = 1, screen.height do + if screen:text(row, 1, screen.width):find(text, 1, true) then + return true + end + end + return false +end + +function M.panel_contains(screen, text) + local rect = screen:exec([[ + local panel = refresh_session().panel.view + if panel.is_hidden or not panel.winid or not vim.api.nvim_win_is_valid(panel.winid) then return nil end + local p = vim.api.nvim_win_get_position(panel.winid) + return { p[1] + 1, p[2] + 1, vim.api.nvim_win_get_height(panel.winid), vim.api.nvim_win_get_width(panel.winid) } + ]]) + if not rect then + return false + end + for row = rect[1], rect[1] + rect[3] - 1 do + if screen:text(row, rect[2], rect[4]):find(text, 1, true) then + return true + end + end + return false +end + +function M.expect_panel(screen, text, present) + screen:await(function() + M.assert_no_errors(screen) + return M.panel_contains(screen, text) == (present ~= false) + end, "panel grid did not " .. (present == false and "remove " or "show ") .. text) +end + +function M.reveal(screen, side, text) + M.focus(screen, side) + screen:exec( + [[ + local text = ... + for line, value in ipairs(vim.api.nvim_buf_get_lines(0, 0, -1, false)) do + if value:find(text, 1, true) then + vim.api.nvim_win_set_cursor(0, { line, 0 }) + return + end + end + error('buffer does not contain ' .. text) + ]], + { text } + ) + M.feed(screen, "zz") + M.expect_text(screen, side, text) +end + +-- Confirm through Neovim's actual dialog, without replacing vim.fn.confirm. +function M.confirm(screen, keys, prompt, answer) + screen:input(keys) + screen:await(function() + return M.grid_contains(screen, prompt) + end, "confirmation prompt was not rendered") + screen:input(answer) + M.feed(screen, "") +end + +function M.expect_lines(screen, side, expected) + screen:await(function() + M.assert_no_errors(screen) + local panes = M.panes(screen) + return panes[side] and vim.deep_equal(expected, panes[side].lines) + end, side .. " contents did not match the fixture expectation") +end + +function M.cell_for(screen, side, text) + local rect = screen:exec( + [[ + local s = refresh_session() + local win = s[(...) .. '_win'] + if not win or not vim.api.nvim_win_is_valid(win) then return nil end + local p = vim.api.nvim_win_get_position(win) + return { p[1] + 1, p[2] + 1, vim.api.nvim_win_get_height(win), vim.api.nvim_win_get_width(win) } + ]], + { side } + ) + if not rect then + return + end + for row = rect[1], rect[1] + rect[3] - 1 do + local value = screen:text(row, rect[2], rect[4]) + local first = value:find(text, 1, true) + if first then + return row, rect[2] + vim.fn.strdisplaywidth(value:sub(1, first - 1)) + end + end +end + +function M.window_text(screen, win) + local rect = screen:exec( + [[ + local win = ... + if not vim.api.nvim_win_is_valid(win) then return nil end + local p = vim.api.nvim_win_get_position(win) + local border = vim.api.nvim_win_get_config(win).border + local top = border and border[2] and border[2] ~= '' and 1 or 0 + local left = border and border[8] and border[8] ~= '' and 1 or 0 + return { p[1] + 1 + top, p[2] + 1 + left, vim.api.nvim_win_get_height(win), vim.api.nvim_win_get_width(win) } + ]], + { win } + ) + if not rect then + return "" + end + local rows = {} + for row = rect[1], rect[1] + rect[3] - 1 do + rows[#rows + 1] = screen:text(row, rect[2], rect[4]) + end + return table.concat(rows):gsub("%s+$", "") +end + +function M.close(screen, repo) + local ok, err = true, nil + if screen then + if screen.exit_code == nil then + ok, err = pcall(M.assert_no_errors, screen) + end + screen:close() + end + if repo then + repo.cleanup() + end + assert(ok, err) +end + return M diff --git a/tests/ui/refresh/history_actions_e2e_spec.lua b/tests/ui/refresh/history_actions_e2e_spec.lua new file mode 100644 index 00000000..70635af9 --- /dev/null +++ b/tests/ui/refresh/history_actions_e2e_spec.lua @@ -0,0 +1,196 @@ +local h = require("tests.ui.refresh.helpers") +local fixture = require("tests.fixtures.refresh_repo") + +for _, backend in ipairs({ "native", "polling" }) do + for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("History actions E2E / " .. backend .. " / " .. layout, function() + local repo, screen + before_each(function() + repo = h.repo("history") + screen = h.screen(backend, layout) + end) + after_each(function() + h.close(screen, repo) + screen, repo = nil, nil + end) + local function open(command) + h.open(screen, repo, command or "CodeDiff history") + h.expect_text(screen, "modified", "history-two") + h.idle(screen) + end + + it("[Y01] opens and expands the latest commit with its real file changes", function() + open() + h.expect_panel(screen, "history two") + h.expect_panel(screen, "history one") + h.expect_panel(screen, "b.txt") + h.expect_panel(screen, "gone.txt") + h.expect_panel(screen, "renamed file.txt") + h.expect_text(screen, "original", "history-one") + assert.equals("history-two", repo.blob_lines(repo.second, "a.txt")[2]) + end) + + it("[Y02] navigates files through deleted previews and back to two-sided comparisons", function() + open() + h.select(screen, "b.txt") + h.expect_text(screen, "modified", "history-two-B") + h.idle(screen) + h.action(screen, "view", "next_file", "modified") + h.expect_text(screen, "original", "delete body") + h.idle(screen) + h.action(screen, "view", "prev_file", "original") + h.expect_text(screen, "modified", "history-two-B") + h.expect_text(screen, "original", "base-B") + end) + + it("[Y03] lazily expands an older commit and renders an added-file preview", function() + open() + h.panel_cursor(screen, "history one") + h.feed(screen, "") + h.expect_panel(screen, "added.txt") + h.select(screen, "added.txt") + h.expect_text(screen, "modified", "added in history") + assert.equals("modified", screen:exec("return refresh_session().single_side")) + assert.same({ "added in history" }, repo.blob_lines(repo.first, "history/added.txt")) + end) + + it("[Y04] selecting an older file uses that commit's parent and not current HEAD", function() + open() + h.panel_cursor(screen, "history one") + h.feed(screen, "") + h.expect_panel(screen, "added.txt") + h.panel_cursor(screen, "history one") + h.feed(screen, "j") + h.expect_text(screen, "original", "base-A") + h.expect_text(screen, "modified", "history-one") + assert.equals(repo.second, vim.trim(repo.command({ "rev-parse", "HEAD" }))) + end) + + it("[Y05] list/tree toggles retain expanded files and the selected comparison", function() + open() + h.focus(screen, "panel") + local before, unchanged = h.panes(screen), h.watch_grid(screen) + h.action(screen, "history", "toggle_view_mode") + h.expect_panel(screen, "rename") + h.expect_panel(screen, "renamed file.txt") + h.action(screen, "history", "toggle_view_mode") + h.expect_panel(screen, "b.txt") + h.preserved(screen, before, 150) + unchanged() + end) + + it("[Y06] a new commit and manual R update the list without reopening history", function() + open() + h.focus(screen, "panel") + local before = h.panes(screen) + repo.replace("a.txt", 2, "history-three") + repo.git("commit -am history-three") + h.action(screen, "history", "refresh") + h.expect_panel(screen, "history-three") + h.preserved(screen, before, 150) + h.expect_text(screen, "modified", "history-two") + end) + + it("[Y07] single-file history navigates commits and reaches the parentless root", function() + open("CodeDiff history %") + h.action(screen, "view", "next_file", "modified") + h.expect_text(screen, "modified", "history-one") + h.idle(screen) + h.action(screen, "view", "next_file", "modified") + h.expect_lines(screen, "original", { "" }) + h.expect_text(screen, "modified", "base-A") + h.idle(screen) + h.action(screen, "view", "prev_file", "modified") + h.expect_text(screen, "modified", "history-one") + end) + + it("[Y08] follows a symbolic history base when its tag moves", function() + open("CodeDiff history --base fixture/base") + h.expect_text(screen, "original", "base-A") + repo.command({ "tag", "-f", "fixture/base", repo.first }) + h.expect_text(screen, "original", "history-one") + h.expect_text(screen, "modified", "history-two") + end) + + it("[Y09] a collapsed commit remains collapsed after a refs refresh", function() + open() + h.panel_cursor(screen, "history two") + h.feed(screen, "") + h.expect_panel(screen, "b.txt", false) + local before = h.panes(screen) + local event = h.checkpoint(screen) + repo.command({ "tag", "new-tag", repo.first }) + h.wait_event(screen, event) + h.expect_panel(screen, "b.txt", false) + h.preserved(screen, before, 100) + end) + + it("[Y10] ignored files stay absent through tree mode and manual refresh", function() + screen:exec("require('codediff').setup({ explorer = { file_filter = { ignore = { 'rename/**' } } } })") + open() + h.expect_panel(screen, "renamed file.txt", false) + h.action(screen, "history", "toggle_view_mode", "panel") + h.expect_panel(screen, "renamed file.txt", false) + h.action(screen, "history", "refresh") + h.idle(screen) + h.expect_panel(screen, "renamed file.txt", false) + h.expect_text(screen, "modified", "history-two") + end) + + it("[Y11] renamed history files resolve both their old and new paths", function() + open() + h.select(screen, "gone.txt") + h.expect_text(screen, "original", "delete body") + h.idle(screen) + h.select(screen, "renamed file.txt") + h.expect_lines(screen, "original", fixture.files["rename/source file.txt"]) + h.expect_lines(screen, "modified", fixture.files["rename/source file.txt"]) + h.expect_text(screen, "modified", "rename body 2") + assert.equals(0, vim.fn.filereadable(repo.path("rename/source file.txt"))) + end) + + it("[Y13] line-range history remains filtered after HEAD changes", function() + h.open(screen, repo, "2,2CodeDiff history") + h.expect_text(screen, "modified", "history-two") + h.idle(screen) + local event = h.checkpoint(screen) + repo.replace("a.txt", 5, "unrelated tail edit") + repo.git("commit -am history-unrelated") + h.wait_event(screen, event) + h.expect_panel(screen, "history-unrelated", false) + h.expect_text(screen, "modified", "history-two") + end) + + it("[Y14] reverse history opens the root commit and preserves ordering on refresh", function() + h.open(screen, repo, "CodeDiff history --reverse") + h.expect_text(screen, "modified", "base-A") + h.idle(screen) + h.panel_cursor(screen, "fixture base") + h.feed(screen, "") + local function ordered() + local win = screen:exec("return refresh_session().panel.view.winid") + local text = h.window_text(screen, win) + local root, first, second = text:find("fixture base", 1, true), text:find("history one", 1, true), text:find("history two", 1, true) + return root and first and second and root < first and first < second + end + screen:await(ordered, "reverse commit order was not rendered") + repo.replace("a.txt", 2, "history-three") + repo.git("commit -am history-three") + h.expect_panel(screen, "history-three") + screen:await(ordered, "refresh lost reverse commit ordering") + h.expect_text(screen, "modified", "base-A") + end) + + it("[Y12] layout changes retain a selected historical comparison", function() + open() + h.action(screen, "view", "toggle_layout", "modified") + screen:await(function() + return screen:exec("return refresh_session().layout ~= (...) and not refresh_session().refresh.loading", { layout }) + end) + h.expect_text(screen, "modified", "history-two") + h.expect_text(screen, "original", "history-one") + assert.same({ "start", "history-two", "context", "end", "tail" }, h.panes(screen).modified.lines) + end) + end) + end +end diff --git a/tests/ui/refresh/hunk_actions_e2e_spec.lua b/tests/ui/refresh/hunk_actions_e2e_spec.lua new file mode 100644 index 00000000..93f0ae05 --- /dev/null +++ b/tests/ui/refresh/hunk_actions_e2e_spec.lua @@ -0,0 +1,210 @@ +local h = require("tests.ui.refresh.helpers") +local fixture = require("tests.fixtures.refresh_repo") + +local function expected(first, second) + local value = vim.deepcopy(fixture.files["hunks.txt"]) + value[1], value[12] = first or "base-one", second or "base-two" + return value +end + +for _, backend in ipairs({ "native", "polling" }) do + for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("hunk actions E2E / " .. backend .. " / " .. layout, function() + local repo, screen + before_each(function() + repo = h.repo("hunks") + screen = h.screen(backend, layout, { + diff = { compact_context_lines = 1 }, + highlights = { line_insert = "#102030", char_insert = "#117733", line_delete = "#301020", char_delete = "#aa2233" }, + }) + end) + after_each(function() + h.close(screen, repo) + screen, repo = nil, nil + end) + local function open(staged) + h.open(screen, repo, staged and "CodeDiff --staged -- hunks.txt" or "CodeDiff -- hunks.txt", "hunks.txt", "hunks.txt") + end + + it("[H01] stages one hunk and removes only its rendered highlight", function() + open() + h.expect_text(screen, "modified", "working-one") + local row, col = h.cell_for(screen, "modified", "working-one") + assert.equals(0x117733, screen:highlight(row, col).background) + h.action(screen, "view", "stage_hunk", "modified", 1) + h.expect_lines(screen, "original", expected("working-one")) + h.expect_text(screen, "modified", "working-two") + screen:await(function() + local r, c = h.cell_for(screen, "modified", "working-one") + return r and screen:highlight(r, c).background ~= 0x117733 + end, "staged hunk still has an insertion highlight") + assert.same(expected("working-one"), repo.blob_lines(":0", "hunks.txt")) + assert.same(expected("working-one", "working-two"), repo.read_file("hunks.txt")) + end) + + it("[H02] stages both hunks sequentially and enters the staged comparison", function() + open() + h.action(screen, "view", "stage_hunk", "modified", 1) + h.expect_lines(screen, "original", expected("working-one")) + h.action(screen, "view", "stage_hunk", "modified", 12) + screen:await(function() + return screen:exec("return refresh_session().modified_revision == ':0'") + end, "last staged hunk did not switch comparisons") + h.expect_text(screen, "modified", "working-two") + assert.same(expected("working-one", "working-two"), repo.blob_lines(":0", "hunks.txt")) + assert.equals("", repo.command({ "diff", "--name-only" })) + end) + + it("[H03] unstages one hunk while preserving the other index change", function() + repo.command({ "add", "hunks.txt" }) + open(true) + h.action(screen, "view", "unstage_hunk", "modified", 1) + h.expect_lines(screen, "modified", expected(nil, "working-two")) + h.expect_text(screen, "modified", "working-two") + assert.same(expected(nil, "working-two"), repo.blob_lines(":0", "hunks.txt")) + assert.same(expected("working-one", "working-two"), repo.read_file("hunks.txt")) + end) + + it("[H04] confirms discard through the real dialog and preserves the other hunk", function() + open() + h.focus(screen, "modified", 1) + h.confirm(screen, h.key(screen, "view", "discard_hunk"), "Discard hunk", "d") + h.expect_lines(screen, "modified", expected(nil, "working-two")) + h.expect_text(screen, "modified", "base-one") + assert.same(expected(nil, "working-two"), repo.read_file("hunks.txt")) + assert.same(expected(), repo.blob_lines(":0", "hunks.txt")) + end) + + it("[H05] cancelling discard leaves buffers, index and working file intact", function() + open() + h.focus(screen, "modified", 1) + local before = h.panes(screen) + h.confirm(screen, h.key(screen, "view", "discard_hunk"), "Discard hunk", "c") + h.preserved(screen, before, 100) + h.expect_text(screen, "modified", "working-one") + assert.same(expected("working-one", "working-two"), repo.read_file("hunks.txt")) + assert.same(expected(), repo.blob_lines(":0", "hunks.txt")) + end) + + it("[H06] discarding a deletion restores the missing lines exactly once", function() + local value = expected(nil, "working-two") + table.remove(value, 2) + table.remove(value, 2) + repo.write_file("hunks.txt", value) + open() + h.focus(screen, "modified", 2) + h.confirm(screen, h.key(screen, "view", "discard_hunk"), "Discard hunk", "d") + h.expect_lines(screen, "modified", expected(nil, "working-two")) + h.expect_text(screen, "modified", "context-02") + assert.same(expected(nil, "working-two"), repo.read_file("hunks.txt")) + end) + + it("[H07] discarding a BOF insertion removes only the inserted text", function() + local value = expected(nil, "working-two") + table.insert(value, 1, "inserted-at-BOF") + repo.write_file("hunks.txt", value) + open() + h.focus(screen, "modified", 1) + h.confirm(screen, h.key(screen, "view", "discard_hunk"), "Discard hunk", "d") + h.expect_lines(screen, "modified", expected(nil, "working-two")) + h.expect_text(screen, "modified", "base-one") + assert.same(expected(nil, "working-two"), repo.read_file("hunks.txt")) + end) + + it("[H08] diffget, undo and redo refresh the view without implicitly saving", function() + open() + h.action(screen, "view", "diff_get", "modified", 1) + h.expect_lines(screen, "modified", expected(nil, "working-two")) + h.expect_text(screen, "modified", "base-one") + assert.same(expected("working-one", "working-two"), repo.read_file("hunks.txt")) + h.feed(screen, "u") + h.expect_lines(screen, "modified", expected("working-one", "working-two")) + h.expect_text(screen, "modified", "working-one") + h.feed(screen, "") + h.expect_lines(screen, "modified", expected(nil, "working-two")) + h.feed(screen, ":write") + assert.same(expected(nil, "working-two"), repo.read_file("hunks.txt")) + end) + + it("[H09] diffput follows the active layout's editing semantics", function() + open() + if layout == "side-by-side" then + h.action(screen, "view", "diff_put", "original", 1) + h.expect_lines(screen, "modified", expected(nil, "working-two")) + h.expect_text(screen, "modified", "base-one") + else + h.action(screen, "view", "diff_put", "modified", 1) + h.expect_lines(screen, "modified", expected("working-one", "working-two")) + h.expect_text(screen, "modified", "working-one") + end + assert.same(expected("working-one", "working-two"), repo.read_file("hunks.txt")) + end) + + it("[H10] stages unsaved buffer content without replacing it with disk contents", function() + open() + h.focus(screen, "modified", 1) + h.feed(screen, "ccUNSAVED-ONE") + h.expect_text(screen, "modified", "UNSAVED-ONE") + h.action(screen, "view", "stage_hunk") + h.expect_lines(screen, "original", expected("UNSAVED-ONE")) + h.expect_lines(screen, "modified", expected("UNSAVED-ONE", "working-two")) + assert.same(expected("UNSAVED-ONE"), repo.blob_lines(":0", "hunks.txt")) + assert.same(expected("working-one", "working-two"), repo.read_file("hunks.txt")) + end) + + it("[H11] hunk editing still works after changing layout through its keymap", function() + open() + h.action(screen, "view", "toggle_layout", "modified", 1) + screen:await(function() + return screen:exec("return refresh_session().layout ~= (...) and not refresh_session().refresh.loading", { layout }) + end) + h.action(screen, "view", "diff_get", "modified", 1) + h.expect_lines(screen, "modified", expected(nil, "working-two")) + h.expect_text(screen, "modified", "base-one") + end) + + it("[H14] the hunk text object selects only the current rendered hunk", function() + open() + h.focus(screen, "modified", 1) + h.feed(screen, "vihy") + assert.equals("working-one\n", screen:exec([[return vim.fn.getreg('"')]])) + h.expect_lines(screen, "modified", expected("working-one", "working-two")) + h.expect_text(screen, "modified", "working-two") + end) + + it("[H12] compact folds and diff cells survive an unrelated repository update", function() + open() + h.action(screen, "view", "toggle_compact", "modified", 1) + assert.is_true(screen:exec("return vim.api.nvim_win_call(refresh_session().modified_win, function() return vim.fn.foldclosed(5) > 0 end)")) + h.idle(screen) + local before, unchanged = h.panes(screen), h.watch_grid(screen) + local event = h.checkpoint(screen) + repo.write_file("background.txt", { "background-only" }) + h.wait_event(screen, event) + h.preserved(screen, before, 150) + unchanged() + end) + end) + end +end + +for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("manual refresh E2E / " .. layout, function() + local repo, screen + after_each(function() + h.close(screen, repo) + screen, repo = nil, nil + end) + it("[H13] disabled automatic refresh still permits a manual R refresh", function() + repo = h.repo("hunks") + screen = h.screen("manual", layout, { explorer = { auto_refresh = false } }) + h.open(screen, repo, "CodeDiff -- hunks.txt", "hunks.txt", "hunks.txt") + local before = h.panes(screen) + repo.replace("hunks.txt", 1, "external-one") + h.preserved(screen, before, 650) + h.action(screen, "explorer", "refresh", "panel") + h.expect_lines(screen, "modified", expected("external-one", "working-two")) + h.expect_text(screen, "modified", "external-one") + end) + end) +end diff --git a/tests/ui/refresh/lifecycle_e2e_spec.lua b/tests/ui/refresh/lifecycle_e2e_spec.lua index 1151cee0..cb6a1b48 100644 --- a/tests/ui/refresh/lifecycle_e2e_spec.lua +++ b/tests/ui/refresh/lifecycle_e2e_spec.lua @@ -194,6 +194,178 @@ for _, backend in ipairs({ "native", "polling" }) do h.expect_text(screen, "modified", "next-B") end) + it("[T09] defers ordinary-file updates while hidden and restores them without moving focus", function() + write_a("working-A") + h.open(screen, repo) + h.focus(screen, "modified", 4) + local view = h.panes(screen).modified.view + screen:command("tabnew") + local away = screen:exec("return vim.api.nvim_get_current_tabpage()") + write_a("changed-while-away") + vim.wait(650) + assert.equals(away, screen:exec("return vim.api.nvim_get_current_tabpage()")) + screen:command("tabprevious") + h.expect_text(screen, "modified", "changed-while-away") + h.idle(screen) + assert.same(view, h.panes(screen).modified.view) + end) + + it("[T10] a hidden input wipe retires its controller before the tab is resumed", function() + write_a("working-A") + h.open(screen, repo) + local buf = h.panes(screen).original.buf + screen:exec("refresh_test.retired = refresh_session().refresh") + screen:command("tabnew") + screen:command("bwipeout! " .. buf) + screen:command("tabprevious") + screen:await(function() + return screen:exec("return refresh_test.retired.closed and refresh_session() == nil") + end) + write_a("after-wipe") + vim.wait(100) + h.assert_no_errors(screen) + end) + + it("[T11] closing a diff pane releases the session and its pending work", function() + write_a("working-A") + h.open(screen, repo) + h.focus(screen, "modified") + screen:command("close!") + screen:await(function() + return screen:exec("return refresh_session() == nil") + end) + write_a("after-close") + vim.wait(100) + h.assert_no_errors(screen) + end) + + it("[T12] retries a real Git read failure without publishing partial inputs", function() + open_staged() + local expected = h.panes(screen).modified.lines + screen:command("tabnew") + write_a("recovered-index") + repo.command({ "add", "a.txt" }) + local oid = vim.trim(repo.command({ "rev-parse", ":0:a.txt" })) + local object = repo.git_path("objects") .. "/" .. oid:sub(1, 2) .. "/" .. oid:sub(3) + assert((vim.uv or vim.loop).fs_rename(object, object .. ".held")) + screen:command("tabprevious") + screen:await(function() + return screen:exec([[ + for _, message in ipairs(refresh_test.notifications) do + if message.message:find('CodeDiff refresh:', 1, true) then return true end + end + return false + ]]) + end, "failed Git read was not reported") + assert.same(expected, h.panes(screen).modified.lines) + assert((vim.uv or vim.loop).fs_rename(object .. ".held", object)) + h.expect_text(screen, "modified", "recovered-index") + h.idle(screen) + end) + + it("[T13] follows a file outside Git and can return to another repository", function() + write_a("working-A") + repo.write_file("../outside.txt", { "outside-repository" }) + other_repo = h.repo() + other_repo.replace("b.txt", 2, "other-working") + h.open(screen, repo, "CodeDiff file HEAD") + h.focus(screen, "modified") + h.feed(screen, ":edit " .. vim.fn.fnameescape(repo.root .. "/outside.txt") .. "") + h.expect_text(screen, "modified", "outside-repository") + h.expect_lines(screen, "original", { "" }) + h.idle(screen) + assert.is_nil(screen:exec("return refresh_session().git_root")) + h.feed(screen, ":edit " .. vim.fn.fnameescape(other_repo.path("b.txt")) .. "") + h.expect_text(screen, "original", "base-B") + h.expect_text(screen, "modified", "other-working") + end) + + it("[T14] restores user buffer mappings after a refreshed session closes", function() + write_a("working-A") + screen:exec( + [[ + local filename = ... + require('codediff').setup({ keymaps = { view = { stage_hunk = '' } } }) + vim.cmd('edit ' .. vim.fn.fnameescape(filename)) + vim.keymap.set('n', '', function() + vim.api.nvim_buf_set_lines(0, 0, 1, false, { 'USER-MAPPING' }) + end, { buffer = true }) + ]], + { repo.path("a.txt") } + ) + h.open(screen, repo) + h.action(screen, "view", "stage_hunk", "modified", 2) + screen:await(function() + return screen:exec("return refresh_session().modified_revision == ':0'") + end) + h.idle(screen) + h.action(screen, "view", "quit", "modified") + screen:await(function() + return screen:exec("return refresh_session() == nil") + end) + h.feed(screen, "") + screen:await(function() + return h.grid_contains(screen, "USER-MAPPING") + end) + assert.equals("working-A", repo.blob_lines(":0", "a.txt")[2]) + end) + + it("[T15] restores the working buffer's original inlay-hint setting after refresh", function() + write_a("working-A") + local buf = screen:exec( + [[ + vim.cmd('edit ' .. vim.fn.fnameescape((...))) + local buf = vim.api.nvim_get_current_buf() + vim.lsp.inlay_hint.enable(true, { bufnr = buf }) + return buf + ]], + { repo.path("a.txt") } + ) + h.open(screen, repo, "CodeDiff file HEAD") + assert.is_false(screen:exec("return vim.lsp.inlay_hint.is_enabled({ bufnr = ... })", { buf })) + repo.git("commit -am moved-head") + h.expect_text(screen, "original", "working-A") + h.idle(screen) + h.action(screen, "view", "quit", "modified") + screen:await(function() + return screen:exec("return refresh_session() == nil") + end) + assert.is_true(screen:exec("return vim.lsp.inlay_hint.is_enabled({ bufnr = ... })", { buf })) + end) + + it("[T16] shares a working buffer across tabs without losing edits when one closes", function() + write_a("working-A") + local buf = screen:exec( + [[ + vim.cmd('edit ' .. vim.fn.fnameescape((...))) + local buf = vim.api.nvim_get_current_buf() + vim.lsp.inlay_hint.enable(true, { bufnr = buf }) + return buf + ]], + { repo.path("a.txt") } + ) + h.open(screen, repo) + local first = h.panes(screen).tab + screen:command("tabnew") + h.open(screen, repo) + write_a("next-A") + h.expect_text(screen, "modified", "next-A") + h.focus(screen, "modified", 2) + h.feed(screen, "ccSHARED-EDIT") + h.expect_text(screen, "modified", "SHARED-EDIT") + h.action(screen, "view", "quit", "modified") + screen:exec("refresh_test.tab = ...; vim.api.nvim_set_current_tabpage(refresh_test.tab)", { first }) + h.expect_text(screen, "modified", "SHARED-EDIT") + h.idle(screen) + assert.equals("next-A", repo.read_file("a.txt")[2]) + assert.is_false(screen:exec("return vim.lsp.inlay_hint.is_enabled({ bufnr = ... })", { buf })) + h.action(screen, "view", "quit", "modified") + screen:await(function() + return screen:exec("return refresh_session() == nil") + end) + assert.is_true(screen:exec("return vim.lsp.inlay_hint.is_enabled({ bufnr = ... })", { buf })) + end) + if backend == "native" then it("continues from the real watcher into polling after the process exits", function() write_a("working-A") diff --git a/tests/ui/refresh/merge_actions_e2e_spec.lua b/tests/ui/refresh/merge_actions_e2e_spec.lua new file mode 100644 index 00000000..7f1898ce --- /dev/null +++ b/tests/ui/refresh/merge_actions_e2e_spec.lua @@ -0,0 +1,181 @@ +local h = require("tests.ui.refresh.helpers") +local fixture = require("tests.fixtures.refresh_repo") + +local function compose(choice, all, first) + local seed = vim.deepcopy(fixture.files["merge.txt"]) + seed[8], seed[12] = "incoming-only", "current-only" + if not choice then + return seed + end + local result = {} + for line, text in ipairs(seed) do + if line == 4 or all and line == 16 then + local suffix = line == 4 and "one" or "two" + if choice == "both" then + result[#result + 1] = first .. "-" .. suffix + result[#result + 1] = (first == "current" and "incoming" or "current") .. "-" .. suffix + else + result[#result + 1] = choice .. "-" .. suffix + end + else + result[#result + 1] = text + end + end + return result +end + +for _, backend in ipairs({ "native", "polling" }) do + for _, ours in ipairs({ "left", "right" }) do + for _, position in ipairs({ "bottom", "center" }) do + describe("merge actions E2E / " .. backend .. " / ours " .. ours .. " / " .. position, function() + local repo, screen + local current_side = ours == "left" and "original" or "modified" + -- The existing bindings address input 1 / input 2. Accept-both starts + -- with the focused input; accept-all-both defaults to input 1. + local function role(choice) + if ours == "left" then + if choice == "incoming" then + return "current" + end + if choice == "current" then + return "incoming" + end + end + return choice + end + local function expected(choice, all) + local first = all and (ours == "left" and "current" or "incoming") or "current" + return compose(role(choice), all, first) + end + local function visible(choice, suffix) + return (choice == "both" and "current" or role(choice)) .. "-" .. (suffix or "one") + end + before_each(function() + repo = h.repo("merge") + screen = h.screen(backend, "side-by-side", { diff = { conflict_ours_position = ours, conflict_result_position = position } }) + screen:exec([[ + for name, color in pairs({ CodeDiffConflictSign = '#eeee00', CodeDiffConflictSignResolved = '#777777', + CodeDiffConflictSignAccepted = '#00ff00', CodeDiffConflictSignRejected = '#ff0000' }) do + vim.api.nvim_set_hl(0, name, { fg = color }) + end + ]]) + h.open(screen, repo, "CodeDiff -- merge.txt", "merge.txt", "merge.txt") + h.expect_lines(screen, "result", expected()) + end) + after_each(function() + h.close(screen, repo) + screen, repo = nil, nil + end) + local function expect_result(lines, text) + h.expect_lines(screen, "result", lines) + h.reveal(screen, "result", text) + end + local function act(name) + h.action(screen, "conflict", name, current_side, 4) + end + + it("[C01] seeds one-sided changes and renders unresolved conflict markers", function() + h.reveal(screen, "result", "base-one") + local row, col = h.cell_for(screen, "result", "base-one") + assert.equals("[", screen:text(row, col - 2, 1)) + assert.equals(0xeeee00, screen:highlight(row, col - 2).foreground) + assert.equals("base-one", repo.blob_lines(":1", "merge.txt")[4]) + assert.equals("current-one", repo.blob_lines(":2", "merge.txt")[4]) + assert.equals("incoming-one", repo.blob_lines(":3", "merge.txt")[4]) + end) + + for i, choice in ipairs({ "incoming", "current", "both" }) do + it(string.format("[C%02d] runs accept_%s for only the current conflict", i + 1, choice), function() + act("accept_" .. choice) + expect_result(expected(choice), visible(choice)) + assert.is_true(repo.command({ "ls-files", "--unmerged", "merge.txt" }) ~= "", "resolution must not implicitly stage the file") + end) + end + + it("[C05] undo, redo and discard restore the Result and marker state", function() + act("accept_both") + expect_result(expected("both"), "current-one") + h.feed(screen, "u") + expect_result(expected(), "base-one") + h.feed(screen, "") + expect_result(expected("both"), "current-one") + act("discard") + expect_result(expected(), "base-one") + local row, col = h.cell_for(screen, "result", "base-one") + assert.equals(0xeeee00, screen:highlight(row, col - 2).foreground) + end) + + for i, choice in ipairs({ "incoming", "current", "both" }) do + it(string.format("[C%02d] runs accept_all_%s including the later conflict", i + 5, choice), function() + act("accept_all_" .. choice) + expect_result(expected(choice, true), visible(choice, "two")) + end) + end + + it("[C09] discard-all resets resolutions but retains automatic one-sided edits", function() + act("accept_all_both") + expect_result(expected("both", true), "current-two") + act("discard_all") + expect_result(expected(), "base-two") + end) + + for i, choice in ipairs({ "incoming", "current" }) do + it(string.format("[C%02d] numbered diffget obtains input %d from the Result pane", i + 9, i), function() + h.action(screen, "conflict", "diffget_" .. choice, "result", 4) + expect_result(expected(choice), visible(choice)) + end) + end + + it("[C12] next and previous conflict keys use the displayed pane's coordinates", function() + h.action(screen, "conflict", "next_conflict", current_side, 1) + assert.equals(4, screen:exec("return vim.api.nvim_win_get_cursor(0)[1]")) + h.action(screen, "conflict", "next_conflict") + assert.equals(16, screen:exec("return vim.api.nvim_win_get_cursor(0)[1]")) + h.action(screen, "conflict", "prev_conflict") + assert.equals(4, screen:exec("return vim.api.nvim_win_get_cursor(0)[1]")) + h.expect_text(screen, current_side, "current-one") + end) + + it("[C13] saves a resolution and preserves it through unrelated index changes", function() + act("accept_current") + expect_result(expected("current"), visible("current")) + h.feed(screen, ":write") + assert.same(expected("current"), repo.read_file("merge.txt")) + h.idle(screen) + local before, event = h.panes(screen), h.checkpoint(screen) + repo.write_file("background.txt", { "unrelated staged edit" }) + repo.command({ "add", "background.txt" }) + h.wait_event(screen, event) + h.preserved(screen, before, 100) + end) + + it("[C14] cancel and discard on quit respect the real unsaved-results dialog", function() + act("accept_current") + expect_result(expected("current"), visible("current")) + h.confirm(screen, h.key(screen, "view", "quit"), "Discard changes and close", "c") + h.expect_lines(screen, "result", expected("current")) + h.confirm(screen, h.key(screen, "view", "quit"), "Discard changes and close", "d") + screen:await(function() + return screen:exec("return refresh_session() == nil") + end) + assert.is_true(table.concat(repo.read_file("merge.txt"), "\n"):find("<<<<<<<", 1, true) ~= nil) + assert.is_true(repo.command({ "ls-files", "--unmerged", "merge.txt" }) ~= "") + end) + + it("[C15] saving and staging a resolved file leaves merge mode cleanly", function() + act("accept_all_current") + expect_result(expected("current", true), visible("current", "two")) + h.feed(screen, ":write") + h.action(screen, "view", "toggle_stage", current_side, 4) + screen:await(function() + return screen:exec("return refresh_session().result_bufnr == nil and refresh_session().modified_revision == ':0'") + end) + h.expect_lines(screen, "modified", expected("current", true)) + h.reveal(screen, "modified", visible("current", "two")) + assert.equals("", repo.command({ "ls-files", "--unmerged", "merge.txt" })) + assert.same(expected("current", true), repo.blob_lines(":0", "merge.txt")) + end) + end) + end + end +end diff --git a/tests/ui/refresh/source_refresh_e2e_spec.lua b/tests/ui/refresh/source_refresh_e2e_spec.lua new file mode 100644 index 00000000..815121a1 --- /dev/null +++ b/tests/ui/refresh/source_refresh_e2e_spec.lua @@ -0,0 +1,301 @@ +local h = require("tests.ui.refresh.helpers") +local fixture = require("tests.fixtures.refresh_repo") + +for _, backend in ipairs({ "native", "polling" }) do + for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("source refresh E2E / " .. backend .. " / " .. layout, function() + local repo, other_repo, screen + before_each(function() + screen = h.screen(backend, layout) + end) + after_each(function() + h.close(screen, repo) + if other_repo then + other_repo.cleanup() + end + screen, repo, other_repo = nil, nil, nil + end) + + it("[S01] reloads BOM/CRLF content at a Unicode path without introducing phantom lines", function() + repo = h.repo() + local file = "utf8/文件 name.txt" + repo.write_bytes(file, "\239\187\191开始\r\n已修改\r\n结束\r\n") + h.open(screen, repo, "CodeDiff file HEAD", file, file) + h.expect_lines(screen, "original", fixture.files[file]) + h.expect_lines(screen, "modified", { "开始", "已修改", "结束" }) + h.expect_text(screen, "modified", "已修改") + repo.write_bytes(file, "\239\187\191开始\r\n再次修改\r\n结束\r\n") + h.expect_lines(screen, "modified", { "开始", "再次修改", "结束" }) + h.expect_text(screen, "modified", "再次修改") + end) + + it("[S02] keeps refreshed Lua revisions read-only without triggering FileType attachment", function() + repo = h.repo() + repo.write_bytes("sample.lua", "local value = 'index-one'\r\nreturn value\r\n") + repo.command({ "add", "sample.lua" }) + screen:exec([[ + refresh_test.lua_filetypes = {} + vim.api.nvim_create_autocmd('FileType', { pattern = 'lua', callback = function(ev) + refresh_test.lua_filetypes[#refresh_test.lua_filetypes + 1] = vim.api.nvim_buf_get_name(ev.buf) + end }) + ]]) + h.open(screen, repo, "CodeDiff --staged -- sample.lua", "sample.lua") + h.expect_text(screen, "modified", "index-one") + repo.write_bytes("sample.lua", "local value = 'index-two'\r\nreturn value\r\n") + repo.command({ "add", "sample.lua" }) + h.expect_text(screen, "modified", "index-two") + h.expect_lines(screen, "modified", { "local value = 'index-two'", "return value" }) + local state = screen:exec([[ + local buf = refresh_session().modified_bufnr + return { readonly = vim.bo[buf].readonly, modifiable = vim.bo[buf].modifiable, + filetype = vim.bo[buf].filetype, events = refresh_test.lua_filetypes, + diagnostics = vim.diagnostic.is_enabled({ bufnr = buf }) } + ]]) + assert.is_true(state.readonly) + assert.is_false(state.modifiable) + assert.equals("", state.filetype) + assert.same({}, state.events) + assert.is_false(state.diagnostics) + end) + + it("[S03] preserves a missing final newline across external updates", function() + repo = h.repo() + repo.write_bytes("a.txt", "start\none\nend") + repo.git("commit -am no-final-newline") + repo.write_bytes("a.txt", "start\ntwo\nend") + h.open(screen, repo, "CodeDiff file HEAD") + h.expect_lines(screen, "original", { "start", "one", "end" }) + h.expect_text(screen, "modified", "two") + repo.write_bytes("a.txt", "start\nthree\nend") + h.expect_lines(screen, "modified", { "start", "three", "end" }) + h.expect_text(screen, "modified", "three") + assert.is_false(screen:exec("return vim.bo[refresh_session().modified_bufnr].endofline")) + end) + + it("[S04] turns an empty staged addition into a populated preview in place", function() + repo = h.repo() + repo.write_file("empty-added.txt", {}) + repo.command({ "add", "empty-added.txt" }) + h.open(screen, repo, "CodeDiff --staged -- empty-added.txt", "empty-added.txt") + h.expect_lines(screen, "modified", { "" }) + local before = h.panes(screen) + repo.write_file("empty-added.txt", { "now populated" }) + repo.command({ "add", "empty-added.txt" }) + h.expect_text(screen, "modified", "now populated") + assert.equals(before.modified.win, h.panes(screen).modified.win) + assert.equals(before.modified.buf, h.panes(screen).modified.buf) + end) + + it("[S05] a bare comparison follows an empty working file in both directions", function() + repo = h.repo() + h.open(screen, repo, "CodeDiff file HEAD", "empty.txt", "empty.txt") + h.expect_lines(screen, "modified", { "" }) + repo.write_file("empty.txt", { "created content" }) + h.expect_text(screen, "modified", "created content") + repo.write_file("empty.txt", {}) + h.expect_lines(screen, "modified", { "" }) + h.idle(screen) + assert.is_false(h.contains(screen, "modified", "created content")) + end) + + it("[S06] an unstaged renamed file compares against the renamed index path", function() + repo = h.repo() + repo.command({ "mv", "rename/source file.txt", "rename/renamed file.txt" }) + repo.replace("rename/renamed file.txt", 3, "working rename") + h.open(screen, repo, "CodeDiff", "rename/renamed file.txt", "rename/renamed file.txt") + h.expect_lines(screen, "original", fixture.files["rename/source file.txt"]) + h.expect_text(screen, "modified", "working rename") + h.action(screen, "view", "toggle_staged_view", "modified") + h.expect_lines(screen, "modified", fixture.files["rename/source file.txt"]) + h.expect_text(screen, "original", "rename body 2") + end) + + it("[S07] full-SHA ancestry remains fixed while HEAD and working contents move", function() + repo = h.repo("history") + h.open(screen, repo, "CodeDiff file " .. repo.second .. "^") + h.expect_text(screen, "original", "history-one") + repo.command({ "reset", "--hard", repo.base }) + h.expect_text(screen, "modified", "base-A") + h.expect_text(screen, "original", "history-one") + end) + + it("[S08] a staged symbolic base follows a moved tag without losing index content", function() + repo = h.repo("history") + repo.replace("a.txt", 2, "index-three") + repo.command({ "add", "a.txt" }) + h.open(screen, repo, "CodeDiff --staged fixture/one -- a.txt") + h.expect_text(screen, "original", "history-one") + h.expect_text(screen, "modified", "index-three") + repo.command({ "tag", "-f", "fixture/one", repo.second }) + h.expect_text(screen, "original", "history-two") + h.expect_text(screen, "modified", "index-three") + end) + + it("[S09] regular .git-directory repositories use the same refresh behavior", function() + repo = h.repo(nil, { worktree = false }) + assert.equals(1, vim.fn.isdirectory(repo.path(".git"))) + repo.replace("a.txt", 2, "regular-working") + h.open(screen, repo, "CodeDiff file HEAD") + h.expect_text(screen, "modified", "regular-working") + repo.git("commit -am regular-next") + h.expect_text(screen, "original", "regular-working") + end) + + it("[S12] a literal arrow in a filename is not parsed as a rename", function() + repo = h.repo() + local file = "literal -> name.txt" + repo.write_file(file, { "header", "old value", "tail" }) + repo.commit("literal arrow path") + repo.replace(file, 2, "new value") + h.open(screen, repo, "CodeDiff", file, file) + h.expect_lines(screen, "original", { "header", "old value", "tail" }) + h.expect_text(screen, "modified", "new value") + end) + + it("[S13] a renamed destination containing an arrow retains its complete path", function() + repo = h.repo() + local file = "rename/target -> final.txt" + repo.command({ "mv", "rename/source file.txt", file }) + repo.replace(file, 3, "working arrow rename") + h.open(screen, repo, "CodeDiff", file, file) + h.expect_lines(screen, "original", fixture.files["rename/source file.txt"]) + h.expect_text(screen, "modified", "working arrow rename") + end) + + it("[S14] an unborn branch opens staged content against an empty base", function() + repo = require("tests.framework.repository").new({ unborn = true }) + repo.write_file("a.txt", { "unborn-index" }) + repo.command({ "add", "a.txt" }) + h.open(screen, repo, "CodeDiff --staged") + h.expect_lines(screen, "original", { "" }) + h.expect_text(screen, "modified", "unborn-index") + repo.write_file("a.txt", { "next-index" }) + repo.command({ "add", "a.txt" }) + h.expect_text(screen, "modified", "next-index") + end) + + it("[S15] whitespace-ignore policy applies to initial and refreshed comparisons", function() + repo = h.repo() + screen:exec("require('codediff').setup({ diff = { ignore_trim_whitespace = true } })") + repo.replace("a.txt", 2, " base-A ") + h.open(screen, repo, "CodeDiff file HEAD") + h.expect_text(screen, "modified", "base-A") + h.action(screen, "view", "next_hunk", "modified", 1) + assert.equals(1, screen:exec("return vim.api.nvim_win_get_cursor(0)[1]")) + repo.replace("a.txt", 2, " changed-A ") + h.expect_text(screen, "modified", "changed-A") + h.idle(screen) + h.action(screen, "view", "next_hunk", "modified", 1) + assert.equals(2, screen:exec("return vim.api.nvim_win_get_cursor(0)[1]")) + end) + + it("[S16] whole-file preview highlighting survives tab suspension and refresh", function() + repo = h.repo() + screen:exec("require('codediff').setup({ diff = { highlight_added_deleted_files = true }, highlights = { line_insert = '#123456' } })") + repo.write_file("preview.txt", { "whole-file-preview", "tail" }) + h.open(screen, repo, "CodeDiff -- preview.txt", "preview.txt") + h.expect_text(screen, "modified", "whole-file-preview") + local row, col = h.cell_for(screen, "modified", "whole-file-preview") + assert.equals(0x123456, screen:highlight(row, col).background) + screen:command("tabnew") + screen:command("tabprevious") + h.idle(screen) + h.expect_text(screen, "modified", "whole-file-preview") + row, col = h.cell_for(screen, "modified", "whole-file-preview") + assert.equals(0x123456, screen:highlight(row, col).background) + end) + + it("[S17] right-positioned originals retain logical diffget behavior", function() + repo = h.repo("hunks") + screen:exec("require('codediff').setup({ diff = { original_position = 'right' } })") + h.open(screen, repo, "CodeDiff -- hunks.txt", "hunks.txt", "hunks.txt") + if layout == "side-by-side" then + assert.is_true(screen:exec([[ + local s = refresh_session() + return vim.api.nvim_win_get_position(s.original_win)[2] > vim.api.nvim_win_get_position(s.modified_win)[2] + ]])) + end + h.action(screen, "view", "diff_get", "modified", 1) + h.expect_text(screen, "modified", "base-one") + assert.equals("working-two", h.panes(screen).modified.lines[12]) + end) + + it("[S18] move detection reaches the renderer and side-by-side alignment key", function() + repo = h.repo() + screen:exec("require('codediff').setup({ diff = { compute_moves = true } })") + repo.write_file( + "moves.txt", + { "unchanged_1", "unchanged_2", "unchanged_3", "beta_1", "beta_2", "beta_3", "beta_4", "beta_5", "alpha_1", "alpha_2", "alpha_3", "alpha_4", "alpha_5" } + ) + h.open(screen, repo, "CodeDiff file HEAD", "moves.txt", "moves.txt") + assert.is_true(screen:exec("return #refresh_session().stored_diff_result.moves > 0")) + if layout == "side-by-side" then + h.reveal(screen, "original", "alpha_1") + h.action(screen, "view", "align_move") + screen:await(function() + local original = h.cell_for(screen, "original", "alpha_1") + local modified = h.cell_for(screen, "modified", "alpha_1") + return original ~= nil and original == modified + end, "paired moved lines did not align on the screen") + h.feed(screen, "G") + screen:await(function() + return screen:exec("local s = refresh_session(); return vim.wo[s.original_win].scrollbind and vim.wo[s.modified_win].scrollbind") + end) + else + h.expect_text(screen, "modified", "alpha_1") + end + end) + + it("[S19] --repo resolves and refreshes symbolic refs in the requested repository", function() + repo = h.repo() + other_repo = h.repo() + other_repo.replace("b.txt", 2, "other-base") + other_repo.commit("other base") + other_repo.command({ "branch", "review/other" }) + other_repo.replace("b.txt", 2, "other-next") + local next_revision = other_repo.commit("other next") + other_repo.command({ "reset", "--hard", "HEAD^" }) + other_repo.replace("b.txt", 2, "other-working") + local command = "CodeDiff --repo " .. vim.fn.fnameescape(other_repo.dir) .. " review/other -- b.txt" + h.open(screen, repo, command, "b.txt") + h.expect_text(screen, "original", "other-base") + other_repo.command({ "update-ref", "refs/heads/review/other", next_revision }) + h.expect_text(screen, "original", "other-next") + h.expect_text(screen, "modified", "other-working") + end) + + it("[S10] SHA-256 repositories resolve and refresh their complete object IDs", function() + repo = h.repo("history", { object_format = "sha256" }) + assert.equals(64, #repo.base) + repo.replace("a.txt", 2, "sha256-working") + h.open(screen, repo, "CodeDiff file HEAD") + h.expect_text(screen, "modified", "sha256-working") + repo.git("commit -am sha256-next") + h.expect_text(screen, "original", "sha256-working") + end) + end) + end +end + +for _, layout in ipairs({ "side-by-side", "inline" }) do + describe("plain source E2E / " .. layout, function() + local repo, screen + after_each(function() + h.close(screen, repo) + screen, repo = nil, nil + end) + it("[S11] compares and refreshes real files with spaces and Unicode names", function() + repo = h.repo() + local left, right = "left/文件 name.txt", "right/文件 name.txt" + repo.write_file(left, { "标题", "LEFT-UTF", "尾部" }) + repo.write_file(right, { "标题", "RIGHT-UTF", "尾部" }) + screen = h.screen("files", layout) + local command = "CodeDiff file " .. vim.fn.fnameescape(repo.path(left)) .. " " .. vim.fn.fnameescape(repo.path(right)) + h.open(screen, repo, command, right) + h.expect_text(screen, "modified", "RIGHT-UTF") + repo.replace(right, 2, "UPDATED-UTF") + h.expect_text(screen, "modified", "UPDATED-UTF") + h.expect_lines(screen, "original", { "标题", "LEFT-UTF", "尾部" }) + end) + end) +end diff --git a/tests/ui/refresh/virtual_file_e2e_spec.lua b/tests/ui/refresh/virtual_file_e2e_spec.lua new file mode 100644 index 00000000..dd291c7e --- /dev/null +++ b/tests/ui/refresh/virtual_file_e2e_spec.lua @@ -0,0 +1,95 @@ +local h = require("tests.ui.refresh.helpers") + +-- These exercise the public codediff:// BufReadCmd path without a diff session. +-- Callback timing is controlled, but every response comes from a real Git read. +describe("virtual revision buffer E2E", function() + local repo, screen + before_each(function() + repo = h.repo() + repo.write_file("sample.lua", { "local value = 'index-one'", "return value" }) + repo.command({ "add", "sample.lua" }) + screen = h.screen("virtual") + end) + after_each(function() + h.close(screen, repo) + screen, repo = nil, nil + end) + local function open(file) + local url = "codediff:///" .. repo.dir .. "///:0/" .. (file or "sample.lua") + screen:command("edit " .. vim.fn.fnameescape(url)) + end + local function text(value) + screen:await(function() + h.assert_no_errors(screen) + return h.grid_contains(screen, value) + end, "revision buffer grid never showed " .. value) + end + + it("[V01] loads a revision as a highlighted, read-only buffer", function() + open() + text("index-one") + local opts = screen:exec([[ + return { vim.bo.buftype, vim.bo.modifiable, vim.bo.readonly, vim.bo.filetype, + vim.diagnostic.is_enabled({ bufnr = vim.api.nvim_get_current_buf() }) } + ]]) + assert.same({ "nowrite", false, true, "", false }, opts) + -- Even an explicitly unlocked virtual buffer must not write to Git or disk. + screen:command("setlocal modifiable noreadonly") + h.feed(screen, "ggccLOCAL-ONLY") + h.feed(screen, ":write!") + text("LOCAL-ONLY") + assert.equals("local value = 'index-one'", repo.read_file("sample.lua")[1]) + assert.equals("local value = 'index-one'", repo.blob_lines(":0", "sample.lua")[1]) + end) + + it("[V02] an older BufReadCmd completion cannot replace a newer load", function() + h.hold_content(screen, "sample.lua") + open() + screen:await(function() + return screen:exec("return #refresh_test.held == 1") + end) + repo.write_file("sample.lua", { "local value = 'index-two'", "return value" }) + repo.command({ "add", "sample.lua" }) + screen:command("edit!") + screen:await(function() + return screen:exec("return #refresh_test.held == 2") + end) + screen:exec("table.remove(refresh_test.held)()") + text("index-two") + local stale = false + screen.on_flush = function() + stale = stale or h.grid_contains(screen, "index-one") + end + h.release_content(screen) + vim.wait(200) + screen.on_flush = nil + assert.is_false(stale, "a stale Git read appeared on the screen") + text("index-two") + assert.same({ "local value = 'index-two'", "return value" }, screen:exec("return vim.api.nvim_buf_get_lines(0, 0, -1, false)")) + end) + + it("[V03] wiping a revision while its read is pending leaves the replacement buffer intact", function() + h.hold_content(screen, "sample.lua") + open() + screen:await(function() + return screen:exec("return #refresh_test.held == 1") + end) + local old = screen:exec("return vim.api.nvim_get_current_buf()") + screen:command("enew!") + h.feed(screen, "iREPLACEMENT") + h.release_content(screen) + text("REPLACEMENT") + vim.wait(150) + assert.is_false(screen:exec("return vim.api.nvim_buf_is_valid(...)", { old })) + assert.same({ "REPLACEMENT" }, screen:exec("return vim.api.nvim_buf_get_lines(0, 0, -1, false)")) + end) + + it("[V04] a file missing from the requested revision loads an empty read-only buffer", function() + open("absent.lua") + h.idle(screen) + assert.same({ "" }, screen:exec("return vim.api.nvim_buf_get_lines(0, 0, -1, false)")) + assert.is_false(screen:exec("return vim.bo.modifiable")) + assert.is_true(screen:exec("return vim.bo.readonly")) + assert.is_false(h.grid_contains(screen, "index-one")) + end) +end) diff --git a/tests/ui/view/inline_explorer_spec.lua b/tests/ui/view/inline_explorer_spec.lua index 17777ea6..1261ed51 100644 --- a/tests/ui/view/inline_explorer_spec.lua +++ b/tests/ui/view/inline_explorer_spec.lua @@ -395,16 +395,9 @@ describe("Inline diff with explorer", function() return end - -- Create a real git repo with a staged newly-added file - local repo = vim.fn.tempname() - vim.fn.mkdir(repo, "p") - local function git(args) - local out = vim.fn.system({ "git", "-C", repo, unpack(args) }) - assert(vim.v.shell_error == 0, "git " .. table.concat(args, " ") .. " failed: " .. out) - end - git({ "init", "-q" }) - git({ "config", "user.email", "t@t" }) - git({ "config", "user.name", "t" }) + local fixture = require("tests.framework.repository").new({ unborn = true }) + local repo = fixture.dir + local git = fixture.command local rel = "newfile.txt" vim.fn.writefile({ "alpha", "beta", "gamma", "delta" }, repo .. "/" .. rel) @@ -452,7 +445,8 @@ describe("Inline diff with explorer", function() .. ")" ) - vim.fn.delete(repo, "rf") + lifecycle.cleanup(tabpage) + fixture.cleanup() end) it("Deleted files use a whole-file delete highlight across suspend and resume", function() From 2dc5a5a2915b620588dd669f3da7ea560ac19473 Mon Sep 17 00:00:00 2001 From: Yanuo Ma <41042490+esmuellert@users.noreply.github.com> Date: Mon, 14 Sep 2026 17:01:10 -0400 Subject: [PATCH 7/8] test: organize suite by test level and feature Separate unit, integration and E2E specs from shared support, fixtures and the test framework. Preserve all 1590 existing case registrations and add five discovery and directory-boundary checks. Add layer, directory and single-spec selection to both test entry points. Remove old helper paths and checkout-history dependencies, use registered command and keymap entry points in E2Es, and update CI, documentation and testing guidance. Validated all 123 specs on Neovim 0.13-dev, all 587 E2E executions on 0.12.3, targeted 0.12.3 integration and unit suites, C tests, formatting, CLI selection and reference audits. Production Lua and the keymap golden are unchanged. --- .agents/skills/nvim-headless/SKILL.md | 24 +- .github/instructions/tests.instructions.md | 7 +- .github/workflows/standalone-build-test.yml | 8 +- README.md | 10 +- .../virtual-file-implementation.md | 2 +- .../05-architecture/timeout-mechanism.md | 210 +++---- lua/codediff/core/argparse/README.md | 2 +- tests/README.md | 306 +++++----- tests/completion_spec.lua | 129 ----- tests/core/git_integration_spec.lua | 522 ------------------ tests/{ui/refresh => e2e}/COVERAGE.md | 32 +- .../commands/dispatch_spec.lua} | 57 +- .../commands/merge_spec.lua} | 13 +- .../commands/smoke_spec.lua} | 26 +- .../conflict/actions_spec.lua} | 2 +- .../conflict/refresh_spec.lua} | 2 +- .../explorer/actions_spec.lua} | 2 +- .../explorer/untracked_tab_spec.lua} | 30 +- .../history/actions_spec.lua} | 2 +- .../refresh/files_spec.lua} | 2 +- .../refresh/lifecycle_spec.lua} | 2 +- .../refresh/repository_spec.lua} | 2 +- .../refresh/sources_spec.lua} | 4 +- .../view/follow_working_file_spec.lua | 2 +- .../view/hunk_actions_spec.lua} | 2 +- .../virtual_file/buffers_spec.lua} | 2 +- tests/e2e/virtual_file/diagnostics_spec.lua | 34 ++ tests/fixtures/README.md | 14 +- tests/fixtures/conflict_gutter.lua | 39 +- tests/fixtures/refresh_repo.lua | 2 +- tests/framework/init.lua | 17 +- tests/framework/supervisor.lua | 54 +- .../integration/commands/completion_spec.lua | 87 +++ .../core/diff/ffi_spec.lua} | 0 .../core/diff/moves_spec.lua} | 0 .../core/diff}/timeout_spec.lua | 0 .../core/diff/whitespace_spec.lua} | 0 .../core/directory_spec.lua} | 2 +- .../core/git/history_lines_spec.lua} | 2 +- .../core/git/line_stats_spec.lua} | 2 +- .../core/git}/pull_request_spec.lua | 4 +- tests/integration/core/git/queries_spec.lua | 282 ++++++++++ .../core/git/renames_spec.lua} | 2 +- .../core/git}/restore_spec.lua | 2 +- .../core/installer/library_spec.lua} | 15 +- .../core/installer/watcher_spec.lua} | 0 .../core/virtual_file_spec.lua} | 2 +- tests/integration/framework/runner_spec.lua | 46 ++ .../integration/framework/supervisor_spec.lua | 48 ++ .../keymap/actions_spec.lua} | 2 +- .../keymap/golden_matrix_spec.lua | 9 +- .../keymap/help_spec.lua} | 2 +- .../keymap/lifecycle_spec.lua} | 4 +- .../keymap/ownership_regressions_spec.lua} | 2 +- .../keymap/registry_spec.lua | 2 +- tests/{ => integration/plugin}/api_spec.lua | 0 .../plugin/modules_spec.lua} | 0 .../plugin/setup_spec.lua} | 0 .../support}/repository_spec.lua | 35 +- .../ui/conflict/accept_all_spec.lua} | 0 .../ui/conflict/auto_merge_spec.lua} | 2 +- .../ui/conflict/file_switch_spec.lua} | 2 +- .../ui/conflict/gutter_grid_spec.lua | 2 +- .../ui/conflict/gutter_lifecycle_spec.lua | 21 +- .../ui/conflict/gutter_options_spec.lua | 0 .../ui/conflict/inline_tab_conflict_spec.lua | 2 +- .../ui/conflict/input_highlights_spec.lua} | 2 +- .../ui/conflict/keymap_ownership_spec.lua} | 2 +- .../ui/conflict/layout_spec.lua} | 2 +- .../ui/conflict/navigation_spec.lua} | 0 .../ui/conflict/resolution_spec.lua} | 0 .../ui/conflict/selection_dedup_spec.lua} | 0 .../ui/conflict/signs_spec.lua} | 0 .../ui/conflict/tracking_spec.lua} | 0 .../ui/explorer/creation_spec.lua} | 18 +- .../ui/explorer/deleted_revision_spec.lua} | 2 +- .../ui/explorer/file_select_branches_spec.lua | 2 +- .../ui/explorer/hunk_operations_spec.lua | 16 +- .../ui/explorer/line_formatters_spec.lua | 0 .../ui/explorer/line_stats_spec.lua | 0 .../ui/explorer/refresh_keeps_view_spec.lua | 2 +- .../ui/explorer/refresh_spec.lua} | 4 +- .../ui/explorer/reselect_spec.lua | 2 +- .../ui/explorer/revision_explorer_spec.lua | 2 +- .../ui/explorer/scroll_independence_spec.lua} | 2 +- .../ui/explorer/staging_spec.lua} | 2 +- .../ui/explorer/stale_buffer_spec.lua | 4 +- .../ui/explorer/toggle_staged_view_spec.lua | 2 +- .../ui/explorer/tree_render_spec.lua} | 2 +- .../ui/explorer/unborn_spec.lua} | 2 +- .../ui/explorer/visibility_spec.lua} | 2 +- .../ui/explorer/window_layout_spec.lua} | 2 +- tests/{ => integration}/ui/filler_spec.lua | 0 .../ui/gutter_signs_spec.lua | 0 .../{ => integration}/ui/highlights_spec.lua | 0 .../ui/history/commit_files_spec.lua} | 2 +- .../ui/history/initial_file_spec.lua} | 2 +- .../ui/history/layout_spec.lua} | 2 +- .../ui/history/refresh_spec.lua} | 2 +- tests/{ => integration}/ui/inline_spec.lua | 0 .../ui/inline_syntax_spec.lua | 0 tests/{ => integration}/ui/layout_spec.lua | 0 .../ui/lifecycle/close_spec.lua | 0 .../ui/lifecycle/placeholder_paths_spec.lua | 2 +- .../ui/lifecycle/session_spec.lua} | 0 .../ui/move_virtlines_spec.lua | 0 .../ui/refresh/controller_spec.lua} | 0 .../ui/refresh/inputs_spec.lua} | 0 .../ui/render_spec.lua} | 0 .../{ => integration/ui}/scrollbind_spec.lua | 0 .../ui/view/autoscroll_spec.lua | 0 .../ui/view/compact_spec.lua | 0 .../ui/view/creation_spec.lua} | 0 .../ui/view/cycle_hunks_across_files_spec.lua | 2 +- .../ui/view/diffget_diffput_spec.lua | 0 .../ui/view/hunk_textobject_spec.lua | 0 .../ui/view/inline_explorer_spec.lua | 2 +- .../ui/view/inline_history_spec.lua | 2 +- .../ui/view/inline_interaction_spec.lua | 0 .../ui/view/inline_standalone_spec.lua | 0 .../ui/view/layout_toggle_spec.lua | 2 +- .../ui/view/move_keymap_spec.lua | 0 .../ui/view/move_rendering_spec.lua | 0 .../ui/view/pane_setup_spec.lua | 2 +- tests/{ => integration}/ui/welcome_spec.lua | 2 +- .../ui/widgets_spec.lua} | 0 tests/integration_diagnostics_spec.lua | 103 ---- tests/run_tests.cmd | 31 +- tests/run_tests.sh | 29 +- .../refresh/helpers.lua => support/e2e.lua} | 0 .../gutter_helpers.lua => support/gutter.lua} | 37 -- tests/{helpers.lua => support/init.lua} | 7 +- .../keymaps.lua} | 0 tests/{framework => support}/repository.lua | 4 +- tests/{ => unit}/core/argparse_spec.lua | 0 .../core/installer_spec.lua} | 0 tests/{ => unit}/core/path_spec.lua | 2 +- .../core/watcher/manager_spec.lua} | 0 .../core/watcher/protocol_spec.lua} | 0 .../ui/conflict}/merge_alignment_spec.lua | 0 .../ui/explorer/filter_spec.lua} | 0 .../ui/explorer/flatten_dirs_spec.lua | 0 .../ui/explorer/git_filter_spec.lua | 0 .../ui/history/date_format_spec.lua} | 0 .../ui/history/file_filter_spec.lua} | 0 tests/{ => unit}/ui/refresh/policy_spec.lua | 0 tests/{ => unit}/ui/view/readiness_spec.lua | 0 147 files changed, 1043 insertions(+), 1405 deletions(-) delete mode 100644 tests/completion_spec.lua delete mode 100644 tests/core/git_integration_spec.lua rename tests/{ui/refresh => e2e}/COVERAGE.md (85%) rename tests/{command_e2e_spec.lua => e2e/commands/dispatch_spec.lua} (88%) rename tests/{commands_uncovered_spec.lua => e2e/commands/merge_spec.lua} (91%) rename tests/{full_integration_spec.lua => e2e/commands/smoke_spec.lua} (91%) rename tests/{ui/refresh/merge_actions_e2e_spec.lua => e2e/conflict/actions_spec.lua} (99%) rename tests/{ui/refresh/conflict_refresh_e2e_spec.lua => e2e/conflict/refresh_spec.lua} (99%) rename tests/{ui/refresh/explorer_actions_e2e_spec.lua => e2e/explorer/actions_spec.lua} (99%) rename tests/{ui/explorer/issue_309_spec.lua => e2e/explorer/untracked_tab_spec.lua} (82%) rename tests/{ui/refresh/history_actions_e2e_spec.lua => e2e/history/actions_spec.lua} (99%) rename tests/{ui/refresh/file_refresh_e2e_spec.lua => e2e/refresh/files_spec.lua} (97%) rename tests/{ui/refresh/lifecycle_e2e_spec.lua => e2e/refresh/lifecycle_spec.lua} (99%) rename tests/{ui/refresh/refresh_e2e_spec.lua => e2e/refresh/repository_spec.lua} (99%) rename tests/{ui/refresh/source_refresh_e2e_spec.lua => e2e/refresh/sources_spec.lua} (99%) rename tests/{ui => e2e}/view/follow_working_file_spec.lua (99%) rename tests/{ui/refresh/hunk_actions_e2e_spec.lua => e2e/view/hunk_actions_spec.lua} (99%) rename tests/{ui/refresh/virtual_file_e2e_spec.lua => e2e/virtual_file/buffers_spec.lua} (98%) create mode 100644 tests/e2e/virtual_file/diagnostics_spec.lua create mode 100644 tests/integration/commands/completion_spec.lua rename tests/{core/ffi_integration_spec.lua => integration/core/diff/ffi_spec.lua} (100%) rename tests/{core/move_detection_spec.lua => integration/core/diff/moves_spec.lua} (100%) rename tests/{core => integration/core/diff}/timeout_spec.lua (100%) rename tests/{core/ignore_whitespace_spec.lua => integration/core/diff/whitespace_spec.lua} (100%) rename tests/{core/dir_spec.lua => integration/core/directory_spec.lua} (99%) rename tests/{core/history_line_range_spec.lua => integration/core/git/history_lines_spec.lua} (99%) rename tests/{core/git_line_stats_spec.lua => integration/core/git/line_stats_spec.lua} (99%) rename tests/{core => integration/core/git}/pull_request_spec.lua (98%) create mode 100644 tests/integration/core/git/queries_spec.lua rename tests/{core/rename_follow_spec.lua => integration/core/git/renames_spec.lua} (96%) rename tests/{core => integration/core/git}/restore_spec.lua (98%) rename tests/{core/installer_spec.lua => integration/core/installer/library_spec.lua} (95%) rename tests/{core/watcher_install_spec.lua => integration/core/installer/watcher_spec.lua} (100%) rename tests/{core/virtual_file_lsp_spec.lua => integration/core/virtual_file_spec.lua} (99%) create mode 100644 tests/integration/framework/runner_spec.lua create mode 100644 tests/integration/framework/supervisor_spec.lua rename tests/{keymap/keymap_coverage_spec.lua => integration/keymap/actions_spec.lua} (99%) rename tests/{ => integration}/keymap/golden_matrix_spec.lua (95%) rename tests/{keymap/keymap_help_spec.lua => integration/keymap/help_spec.lua} (99%) rename tests/{keymap/keymap_lifecycle_spec.lua => integration/keymap/lifecycle_spec.lua} (99%) rename tests/{keymap/issue_regressions_spec.lua => integration/keymap/ownership_regressions_spec.lua} (99%) rename tests/{ => integration}/keymap/registry_spec.lua (99%) rename tests/{ => integration/plugin}/api_spec.lua (100%) rename tests/{module_loading_spec.lua => integration/plugin/modules_spec.lua} (100%) rename tests/{lazy_spec.lua => integration/plugin/setup_spec.lua} (100%) rename tests/{framework => integration/support}/repository_spec.lua (71%) rename tests/{ui/conflict/conflict_accept_all_spec.lua => integration/ui/conflict/accept_all_spec.lua} (100%) rename tests/{ui/conflict/issue_353_spec.lua => integration/ui/conflict/auto_merge_spec.lua} (99%) rename tests/{ui/conflict/conflict_file_switch_spec.lua => integration/ui/conflict/file_switch_spec.lua} (99%) rename tests/{ => integration}/ui/conflict/gutter_grid_spec.lua (99%) rename tests/{ => integration}/ui/conflict/gutter_lifecycle_spec.lua (94%) rename tests/{ => integration}/ui/conflict/gutter_options_spec.lua (100%) rename tests/{ => integration}/ui/conflict/inline_tab_conflict_spec.lua (99%) rename tests/{ui/conflict/issue_387_spec.lua => integration/ui/conflict/input_highlights_spec.lua} (99%) rename tests/{ui/conflict/merge_keymap_ownership_spec.lua => integration/ui/conflict/keymap_ownership_spec.lua} (99%) rename tests/{ui/conflict/conflict_layout_spec.lua => integration/ui/conflict/layout_spec.lua} (98%) rename tests/{ui/conflict/conflict_navigation_spec.lua => integration/ui/conflict/navigation_spec.lua} (100%) rename tests/{ui/conflict/conflict_resolution_spec.lua => integration/ui/conflict/resolution_spec.lua} (100%) rename tests/{ui/conflict/conflict_dedup_spec.lua => integration/ui/conflict/selection_dedup_spec.lua} (100%) rename tests/{ui/conflict/conflict_signs_spec.lua => integration/ui/conflict/signs_spec.lua} (100%) rename tests/{ui/conflict/conflict_spec.lua => integration/ui/conflict/tracking_spec.lua} (100%) rename tests/{ui/explorer/explorer_spec.lua => integration/ui/explorer/creation_spec.lua} (97%) rename tests/{ui/explorer/issue_390_spec.lua => integration/ui/explorer/deleted_revision_spec.lua} (99%) rename tests/{ => integration}/ui/explorer/file_select_branches_spec.lua (99%) rename tests/{ => integration}/ui/explorer/hunk_operations_spec.lua (98%) rename tests/{ => integration}/ui/explorer/line_formatters_spec.lua (100%) rename tests/{ => integration}/ui/explorer/line_stats_spec.lua (100%) rename tests/{ => integration}/ui/explorer/refresh_keeps_view_spec.lua (99%) rename tests/{ui/explorer/explorer_refresh_spec.lua => integration/ui/explorer/refresh_spec.lua} (98%) rename tests/{ => integration}/ui/explorer/reselect_spec.lua (99%) rename tests/{ => integration}/ui/explorer/revision_explorer_spec.lua (98%) rename tests/{ui/explorer/explorer_scroll_independence_spec.lua => integration/ui/explorer/scroll_independence_spec.lua} (99%) rename tests/{ui/explorer/explorer_staging_spec.lua => integration/ui/explorer/staging_spec.lua} (99%) rename tests/{ => integration}/ui/explorer/stale_buffer_spec.lua (98%) rename tests/{ => integration}/ui/explorer/toggle_staged_view_spec.lua (99%) rename tests/{ui/explorer/explorer_tree_render_spec.lua => integration/ui/explorer/tree_render_spec.lua} (99%) rename tests/{ui/explorer/issue_498_spec.lua => integration/ui/explorer/unborn_spec.lua} (99%) rename tests/{ui/explorer/explorer_visibility_spec.lua => integration/ui/explorer/visibility_spec.lua} (98%) rename tests/{ui/explorer/explorer_window_layout_spec.lua => integration/ui/explorer/window_layout_spec.lua} (98%) rename tests/{ => integration}/ui/filler_spec.lua (100%) rename tests/{ => integration}/ui/gutter_signs_spec.lua (100%) rename tests/{ => integration}/ui/highlights_spec.lua (100%) rename tests/{ui/history/history_commit_files_spec.lua => integration/ui/history/commit_files_spec.lua} (99%) rename tests/{ui/history/history_initial_file_spec.lua => integration/ui/history/initial_file_spec.lua} (98%) rename tests/{ui/history/history_layout_spec.lua => integration/ui/history/layout_spec.lua} (98%) rename tests/{ui/history/history_refresh_watcher_spec.lua => integration/ui/history/refresh_spec.lua} (98%) rename tests/{ => integration}/ui/inline_spec.lua (100%) rename tests/{ => integration}/ui/inline_syntax_spec.lua (100%) rename tests/{ => integration}/ui/layout_spec.lua (100%) rename tests/{ => integration}/ui/lifecycle/close_spec.lua (100%) rename tests/{ => integration}/ui/lifecycle/placeholder_paths_spec.lua (98%) rename tests/{ui/lifecycle/lifecycle_spec.lua => integration/ui/lifecycle/session_spec.lua} (100%) rename tests/{ => integration}/ui/move_virtlines_spec.lua (100%) rename tests/{ui/explorer/native_watcher_spec.lua => integration/ui/refresh/controller_spec.lua} (100%) rename tests/{ui/auto_refresh_spec.lua => integration/ui/refresh/inputs_spec.lua} (100%) rename tests/{ui/render_core_spec.lua => integration/ui/render_spec.lua} (100%) rename tests/{ => integration/ui}/scrollbind_spec.lua (100%) rename tests/{ => integration}/ui/view/autoscroll_spec.lua (100%) rename tests/{ => integration}/ui/view/compact_spec.lua (100%) rename tests/{ui/view/view_spec.lua => integration/ui/view/creation_spec.lua} (100%) rename tests/{ => integration}/ui/view/cycle_hunks_across_files_spec.lua (99%) rename tests/{ => integration}/ui/view/diffget_diffput_spec.lua (100%) rename tests/{ => integration}/ui/view/hunk_textobject_spec.lua (100%) rename tests/{ => integration}/ui/view/inline_explorer_spec.lua (99%) rename tests/{ => integration}/ui/view/inline_history_spec.lua (99%) rename tests/{ => integration}/ui/view/inline_interaction_spec.lua (100%) rename tests/{ => integration}/ui/view/inline_standalone_spec.lua (100%) rename tests/{ => integration}/ui/view/layout_toggle_spec.lua (99%) rename tests/{ => integration}/ui/view/move_keymap_spec.lua (100%) rename tests/{ => integration}/ui/view/move_rendering_spec.lua (100%) rename tests/{ => integration}/ui/view/pane_setup_spec.lua (98%) rename tests/{ => integration}/ui/welcome_spec.lua (99%) rename tests/{ui/lib/lib_spec.lua => integration/ui/widgets_spec.lua} (100%) delete mode 100644 tests/integration_diagnostics_spec.lua rename tests/{ui/refresh/helpers.lua => support/e2e.lua} (100%) rename tests/{ui/conflict/gutter_helpers.lua => support/gutter.lua} (80%) rename tests/{helpers.lua => support/init.lua} (94%) rename tests/{keymap_matrix.lua => support/keymaps.lua} (100%) rename tests/{framework => support}/repository.lua (98%) rename tests/{ => unit}/core/argparse_spec.lua (100%) rename tests/{core/install_spec.lua => unit/core/installer_spec.lua} (100%) rename tests/{ => unit}/core/path_spec.lua (99%) rename tests/{core/watcher_manager_spec.lua => unit/core/watcher/manager_spec.lua} (100%) rename tests/{core/watcher_protocol_spec.lua => unit/core/watcher/protocol_spec.lua} (100%) rename tests/{ui => unit/ui/conflict}/merge_alignment_spec.lua (100%) rename tests/{ui/explorer/explorer_file_filter_spec.lua => unit/ui/explorer/filter_spec.lua} (100%) rename tests/{ => unit}/ui/explorer/flatten_dirs_spec.lua (100%) rename tests/{ => unit}/ui/explorer/git_filter_spec.lua (100%) rename tests/{ui/history/history_date_format_spec.lua => unit/ui/history/date_format_spec.lua} (100%) rename tests/{ui/history/history_file_filter_spec.lua => unit/ui/history/file_filter_spec.lua} (100%) rename tests/{ => unit}/ui/refresh/policy_spec.lua (100%) rename tests/{ => unit}/ui/view/readiness_spec.lua (100%) diff --git a/.agents/skills/nvim-headless/SKILL.md b/.agents/skills/nvim-headless/SKILL.md index 05194028..f2609c6e 100644 --- a/.agents/skills/nvim-headless/SKILL.md +++ b/.agents/skills/nvim-headless/SKILL.md @@ -29,7 +29,7 @@ Everything data-level: - `vim.uv` timers under `vim.wait` - keymaps via `feedkeys` with `"x"` (execute immediately) flag - treesitter parsers and queries -- git operations via `tests/helpers` (`create_temp_git_repo`, `git_cmd`) +- git operations via `require("tests.support")` (`create_temp_git_repo`, `git_cmd`) ## What needs a workaround @@ -42,13 +42,18 @@ vim.api.nvim_exec_autocmds("WinScrolled", {}) This is what existing specs already do. -## What is not possible +## What requires a separate UI -- **Rendered screen content** (which character is at row/col, its color). - Neovim's own test suite solves this by spawning a child `nvim --embed` and - attaching a fake UI over RPC — a different architecture from ours. -- **`UIEnter`** never fires. Plugins that lazy-load on `UIEnter` (e.g. - `snacks.nvim`) must be initialized manually with `.enable()` or equivalent. +- **Rendered screen content** (which character is at row/col, its color) is not + observable in the synchronous headless test process. Use + `tests/framework/screen.lua`, which starts `nvim --embed` and attaches an RPC + UI. Close it in `after_each`, even on assertion failure. +- **`UIEnter`** does not fire without an attached UI. Plugins that lazy-load on + it (e.g. `snacks.nvim`) need explicit initialization in a plain headless spec. + +The observation tool does not define the test level. Screen checks that call +renderers directly are integration tests; public commands or actual key input +through the complete application belong in `tests/e2e/`. ## Driving styles @@ -94,8 +99,9 @@ vim.defer_fn(resume, 100) | What | Where | |---|---| | Test bootstrap | `tests/init.lua` | -| Helpers (git repos, waiters) | `tests/helpers.lua` | +| Helpers (git repos, waiters) | `tests/support/init.lua` (`require("tests.support")`) | | Framework (describe/it/assert) | `tests/framework/init.lua` | | Run all specs | `./tests/run_tests.sh` or `make test-lua` | -| Run one spec | `nvim --headless --noplugin -u tests/init.lua -c "lua require('tests.framework').run_and_exit('tests/path/to_spec.lua')"` | +| Run one layer | `./tests/run_tests.sh unit` / `integration` / `e2e` | +| Run one spec | `./tests/run_tests.sh tests/unit/core/path_spec.lua` | | Throwaway repro | Save to `/tmp/repro.lua`, run with `nvim --headless -u tests/init.lua -c "luafile /tmp/repro.lua" -c "qa!"` | diff --git a/.github/instructions/tests.instructions.md b/.github/instructions/tests.instructions.md index 4e43273b..0b140379 100644 --- a/.github/instructions/tests.instructions.md +++ b/.github/instructions/tests.instructions.md @@ -7,6 +7,9 @@ applyTo: "tests/**" When working with tests in this directory: - **Headless boundaries**: Read `.agents/skills/nvim-headless/SKILL.md` before writing specs that involve scroll events, timers, or window geometry -- **Extend existing tests**: Add new test cases to existing test files whenever possible; only create new test files when covering genuinely distinct functionality -- **Test runner**: Spec files are auto-discovered by `tests/framework/supervisor.lua`; a new `*_spec.lua` under `tests/` runs in CI with no runner changes +- **Test levels**: Put runnable specs under `tests/unit/`, `tests/integration/`, or `tests/e2e/`, then group by feature. Isolated logic belongs in unit; direct component calls and Neovim/Git/FFI boundaries belong in integration; public commands or real user input through the whole application belong in E2E. Using Git or an embedded screen alone does not make a component test E2E. +- **Names and shared code**: Use behavior-based `*_spec.lua` names, without redundant `_e2e`/`_integration` suffixes. Keep issue references inside cases. Shared drivers and the Git factory belong in `tests/support/`, data in `tests/fixtures/`, and the runner/RPC transport in `tests/framework/`. Infrastructure self-tests also belong in a test layer. +- **Extend existing tests**: Add new test cases to existing test files whenever possible; only create new test files when covering genuinely distinct functionality. +- **Fixtures and imports**: Use the shared repository factory rather than the source checkout's Git history. Import helpers through `require("tests.support")` and its submodules, not cwd-relative `dofile` or old-path adapters. Use `support.project_root` rather than counting a spec's parent directories. +- **Test runner**: Specs are auto-discovered by `tests/framework/supervisor.lua` with no CI enumeration changes. `tests/run_tests.sh` and `.cmd` accept `all`, `unit`, `integration`, `e2e`, a directory, or a single spec. Discovery self-tests enforce the directory boundary. - **No legacy API in tests**: When fixing tests, always update them to use the latest API; never add backward compatibility or reintroduce removed APIs for test compatibility—tests must use current production APIs diff --git a/.github/workflows/standalone-build-test.yml b/.github/workflows/standalone-build-test.yml index 7b31ab14..86234158 100644 --- a/.github/workflows/standalone-build-test.yml +++ b/.github/workflows/standalone-build-test.yml @@ -79,14 +79,14 @@ jobs: - name: Setup Neovim uses: ./.github/actions/setup-neovim - - name: Run integration test (Ubuntu/macOS) + - name: Run command smoke E2E (Ubuntu/macOS) if: matrix.os != 'windows-latest' run: | nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('tests.framework').run_and_exit('tests/full_integration_spec.lua')" + -c "lua require('tests.framework').run_and_exit('tests/e2e/commands/smoke_spec.lua')" - - name: Run integration test (Windows) + - name: Run command smoke E2E (Windows) if: matrix.os == 'windows-latest' shell: pwsh run: | - nvim --headless --noplugin -u tests/init.lua -c "lua require('tests.framework').run_and_exit('tests/full_integration_spec.lua')" + nvim --headless --noplugin -u tests/init.lua -c "lua require('tests.framework').run_and_exit('tests/e2e/commands/smoke_spec.lua')" diff --git a/README.md b/README.md index ce120a78..6d78cb72 100644 --- a/README.md +++ b/README.md @@ -683,13 +683,14 @@ cmake --build build --config Release ctest --test-dir build --output-on-failure -C Release ``` -Run the Lua integration suite: +Run the Lua test suite or select a test layer: ```bash -./tests/run_tests.sh +./tests/run_tests.sh # all tests +./tests/run_tests.sh e2e # or: unit, integration ``` -On Windows, use `tests\run_tests.cmd`. +On Windows, use `tests\run_tests.cmd` with the same arguments. See [tests/README.md](tests/README.md) for test organization and fixtures. Check Lua formatting: @@ -700,8 +701,7 @@ stylua --check lua Run one Lua spec: ```bash -nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('tests.framework').run_and_exit('tests/path/to/spec.lua')" +./tests/run_tests.sh tests/unit/core/path_spec.lua ``` ## Contributing diff --git a/docs/development/04-lua-features/virtual-file-implementation.md b/docs/development/04-lua-features/virtual-file-implementation.md index 8debdd6c..71e1dd58 100644 --- a/docs/development/04-lua-features/virtual-file-implementation.md +++ b/docs/development/04-lua-features/virtual-file-implementation.md @@ -62,5 +62,5 @@ not be passed to tools or language servers that only accept `file://` URIs. - `lua/codediff/core/virtual_file.lua` — URI parsing, loading, and Tree-sitter setup - `lua/codediff/ui/view/render.lua` — side-by-side rendering after load - `lua/codediff/ui/inline_view/render.lua` — inline rendering after load -- `tests/core/virtual_file_lsp_spec.lua` — regression coverage ensuring virtual +- `tests/integration/core/virtual_file_spec.lua` — regression coverage ensuring virtual buffers do not trigger LSP attachment diff --git a/docs/development/05-architecture/timeout-mechanism.md b/docs/development/05-architecture/timeout-mechanism.md index 3ee9d2eb..ed809147 100644 --- a/docs/development/05-architecture/timeout-mechanism.md +++ b/docs/development/05-architecture/timeout-mechanism.md @@ -1,105 +1,105 @@ -# Timeout Mechanism - Fixed & Tested - -## The Bug -Character-level Myers was hardcoded to timeout=0 (infinite) instead of using the configured timeout. - -```c -// BEFORE (Bug): -myers_nd_diff_algorithm(seq1_iface, seq2_iface, 0, &hit_timeout); // ✗ Hardcoded! - -// AFTER (Fixed): -myers_nd_diff_algorithm(seq1_iface, seq2_iface, options->timeout_ms, &hit_timeout); // ✓ -``` - -## The Fix -The timeout infrastructure **already existed** in Myers from day one. We just completed the wiring: - -1. Added `timeout_ms` to `CharLevelOptions` struct -2. Passed timeout through `refine_diff()` → `char_opts.timeout_ms = timeout->timeout_ms` -3. Used it in char_level.c instead of hardcoded 0 -4. Removed misleading comment: `// timeout handled inside refine_diff_char_level` - -**This was incomplete plumbing, not a missing feature.** - -## Timeout Flow (End-to-End) - -``` -Lua Config (5000ms) - ↓ -lua/vscode-diff/config.lua: config.options.diff.max_computation_time_ms - ↓ -lua/vscode-diff/commands.lua: diff.compute_diff(..., { max_computation_time_ms = 5000 }) - ↓ -lua/vscode-diff/diff.lua: c_options.max_computation_time_ms = 5000 - ↓ -libvscode-diff/api.c: compute_diff(options->max_computation_time_ms) - ↓ -default_lines_diff_computer.c: timeout.timeout_ms = options->max_computation_time_ms - ↓ -Line-level Myers: myers_nd_diff_algorithm(..., timeout_ms, ...) ✓ - ↓ -Char-level Myers: myers_nd_diff_algorithm(..., options->timeout_ms, ...) ✓ FIXED! -``` - -## VSCode Parity: 100% ✓ - -| Aspect | VSCode | Before Fix | After Fix | -|--------|--------|------------|-----------| -| Timeout in Myers signature | ✓ | ✓ | ✓ | -| Line-level uses timeout | ✓ | ✓ | ✓ | -| Char-level uses timeout | ✓ | ✗ (0) | ✓ | -| Default: 5000ms | ✓ | ✓ | ✓ | -| Early exit on timeout | ✓ | Line only | Both ✓ | -| Trivial diff fallback | ✓ | Line only | Both ✓ | - -## Performance Impact - -Test file (1150 → 2352 lines): - -| Timeout | Time | Hit? | Detail | -|---------|------|------|--------| -| 5000ms | 1221ms | No | Full (1188 inner changes) | -| 50ms | 139ms | Yes | Partial (61 regions, 1 inner each) | -| 10ms | 26ms | Yes | Trivial (1 region, 1 inner) | - -## User Configuration - -```lua -require("vscode-diff").setup({ - diff = { - max_computation_time_ms = 5000, -- Default (VSCode parity) - -- Lower = faster but less detail on large files - -- Higher = more accurate but slower on complex diffs - } -}) -``` - -## Tests: 13/13 Passing ✓ - -**Location**: `tests/timeout_spec.lua` - -Coverage: -- Basic functionality (3): parameter acceptance, completion, defaults -- Large files (3): normal/short/very-short timeouts -- Config integration (2): respects config, VSCode default -- VSCode parity (2): line+char Myers, structure consistency -- Edge cases (3): zero/negative timeout, empty files - -Run: `nvim --headless -u tests/init.lua -c "lua require('tests.framework').run_and_exit('tests/timeout_spec.lua')"` - -## Files Modified - -1. `libvscode-diff/include/char_level.h` - Added timeout_ms field -2. `libvscode-diff/src/char_level.c` - Use timeout instead of 0 -3. `libvscode-diff/default_lines_diff_computer.c` - Thread timeout through -4. `libvscode-diff/diff_tool.c` - Test env var support -5. `lua/vscode-diff/config.lua` - Added config option -6. `lua/vscode-diff/auto_refresh.lua` - Pass timeout from config -7. `lua/vscode-diff/commands.lua` - Pass timeout from config (2 places) -8. `tests/timeout_spec.lua` - Comprehensive test suite -9. `tests/run_tests.sh` - Added to test runner - ---- - -**Date**: 2025-01-07 -**Status**: ✅ Complete - Bug fixed, tests passing, VSCode parity achieved +# Timeout Mechanism - Fixed & Tested + +## The Bug +Character-level Myers was hardcoded to timeout=0 (infinite) instead of using the configured timeout. + +```c +// BEFORE (Bug): +myers_nd_diff_algorithm(seq1_iface, seq2_iface, 0, &hit_timeout); // ✗ Hardcoded! + +// AFTER (Fixed): +myers_nd_diff_algorithm(seq1_iface, seq2_iface, options->timeout_ms, &hit_timeout); // ✓ +``` + +## The Fix +The timeout infrastructure **already existed** in Myers from day one. We just completed the wiring: + +1. Added `timeout_ms` to `CharLevelOptions` struct +2. Passed timeout through `refine_diff()` → `char_opts.timeout_ms = timeout->timeout_ms` +3. Used it in char_level.c instead of hardcoded 0 +4. Removed misleading comment: `// timeout handled inside refine_diff_char_level` + +**This was incomplete plumbing, not a missing feature.** + +## Timeout Flow (End-to-End) + +``` +Lua Config (5000ms) + ↓ +lua/vscode-diff/config.lua: config.options.diff.max_computation_time_ms + ↓ +lua/vscode-diff/commands.lua: diff.compute_diff(..., { max_computation_time_ms = 5000 }) + ↓ +lua/vscode-diff/diff.lua: c_options.max_computation_time_ms = 5000 + ↓ +libvscode-diff/api.c: compute_diff(options->max_computation_time_ms) + ↓ +default_lines_diff_computer.c: timeout.timeout_ms = options->max_computation_time_ms + ↓ +Line-level Myers: myers_nd_diff_algorithm(..., timeout_ms, ...) ✓ + ↓ +Char-level Myers: myers_nd_diff_algorithm(..., options->timeout_ms, ...) ✓ FIXED! +``` + +## VSCode Parity: 100% ✓ + +| Aspect | VSCode | Before Fix | After Fix | +|--------|--------|------------|-----------| +| Timeout in Myers signature | ✓ | ✓ | ✓ | +| Line-level uses timeout | ✓ | ✓ | ✓ | +| Char-level uses timeout | ✓ | ✗ (0) | ✓ | +| Default: 5000ms | ✓ | ✓ | ✓ | +| Early exit on timeout | ✓ | Line only | Both ✓ | +| Trivial diff fallback | ✓ | Line only | Both ✓ | + +## Performance Impact + +Test file (1150 → 2352 lines): + +| Timeout | Time | Hit? | Detail | +|---------|------|------|--------| +| 5000ms | 1221ms | No | Full (1188 inner changes) | +| 50ms | 139ms | Yes | Partial (61 regions, 1 inner each) | +| 10ms | 26ms | Yes | Trivial (1 region, 1 inner) | + +## User Configuration + +```lua +require("vscode-diff").setup({ + diff = { + max_computation_time_ms = 5000, -- Default (VSCode parity) + -- Lower = faster but less detail on large files + -- Higher = more accurate but slower on complex diffs + } +}) +``` + +## Tests: 13/13 Passing ✓ + +**Current location**: `tests/integration/core/diff/timeout_spec.lua` + +Coverage: +- Basic functionality (3): parameter acceptance, completion, defaults +- Large files (3): normal/short/very-short timeouts +- Config integration (2): respects config, VSCode default +- VSCode parity (2): line+char Myers, structure consistency +- Edge cases (3): zero/negative timeout, empty files + +Run: `./tests/run_tests.sh tests/integration/core/diff/timeout_spec.lua` + +## Files Modified + +1. `libvscode-diff/include/char_level.h` - Added timeout_ms field +2. `libvscode-diff/src/char_level.c` - Use timeout instead of 0 +3. `libvscode-diff/default_lines_diff_computer.c` - Thread timeout through +4. `libvscode-diff/diff_tool.c` - Test env var support +5. `lua/vscode-diff/config.lua` - Added config option +6. `lua/vscode-diff/auto_refresh.lua` - Pass timeout from config +7. `lua/vscode-diff/commands.lua` - Pass timeout from config (2 places) +8. `tests/integration/core/diff/timeout_spec.lua` - Comprehensive test suite (current path) +9. `tests/run_tests.sh` - Added to test runner + +--- + +**Date**: 2025-01-07 +**Status**: ✅ Complete - Bug fixed, tests passing, VSCode parity achieved diff --git a/lua/codediff/core/argparse/README.md b/lua/codediff/core/argparse/README.md index 6b6a9358..1e19f982 100644 --- a/lua/codediff/core/argparse/README.md +++ b/lua/codediff/core/argparse/README.md @@ -167,5 +167,5 @@ Each is a small, additive extension if a future need arises. ```sh nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('tests.framework').run_and_exit('tests/core/argparse_spec.lua')" + -c "lua require('tests.framework').run_and_exit('tests/unit/core/argparse_spec.lua')" ``` diff --git a/tests/README.md b/tests/README.md index 44ed901a..aa12224a 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,187 +1,151 @@ -# Test Suite - -Integration tests for codediff.nvim using an in-tree, self-contained test framework -(`tests/framework/`) that implements the familiar `describe/it/before_each/after_each/assert.*` -API in pure Lua + Neovim built-ins. No external test dependencies are required. - -## Test Coverage - -### ✅ FFI Integration (ffi_integration_spec.lua) -C ↔ Lua boundary validation: -- Data structure conversion -- Memory management (no leaks) -- Native and Lua version agreement -- Edge cases (empty diffs, large files) - -**10 tests** - -### ✅ Git Integration (git_integration_spec.lua) -Git operations and async handling: -- Repository detection -- Async callbacks -- Error handling for invalid revisions -- Path calculation -- LRU cache validation - -**9 tests** - -### ✅ Installer (installer_spec.lua) -Automatic binary installation and version management: -- Module API validation -- VERSION loading from version.lua -- Library path construction -- Version detection from filenames -- Update necessity logic -- Platform-specific extension handling - -**10 tests** - -### ✅ Auto-scroll (autoscroll_spec.lua) -Diff view scrolling behavior: -- Scroll to first change -- Window centering -- Scroll sync activation - -**5 tests** +# Test suite + +The Lua suite runs in Neovim with the in-tree framework; no Plenary/Busted +installation is needed. Build the native library first (`make build`). Native +algorithm tests remain in `c-diff-core/tests/` and run with `make test-c`. + +## Directory contract + +```text +tests/ +├── unit/ isolated logic and controlled collaborators +│ ├── core/ argparse, paths, installer policy, watcher protocol/manager +│ └── ui/ filters, tree data, merge alignment, refresh policy, readiness +├── integration/ component boundaries with Neovim, Git or the native library +│ ├── commands/ completion queries +│ ├── core/ Git, filesystem, FFI, installer and virtual-buffer integration +│ ├── framework/ runner and discovery self-tests +│ ├── keymap/ real buffer mappings, ownership and golden captures +│ ├── plugin/ public exports, module loading and setup compatibility +│ ├── support/ fixture-factory isolation and cleanup tests +│ └── ui/ rendering, windows, sessions and panel/controller integration +├── e2e/ public commands/keys through the complete application +│ ├── commands/ dispatch, completion, merge commands, standalone-build smoke +│ ├── conflict/ resolution actions and refresh protection +│ ├── explorer/ file actions and navigation +│ ├── history/ commit/file operations +│ ├── refresh/ repository/file inputs, transport and session lifetime +│ ├── view/ hunk operations and working-file following +│ └── virtual_file/ public revision URI and diagnostic isolation +├── fixtures/ deterministic repository profiles and hand-authored golden data +├── support/ shared Git factory, plugin helpers and UI drivers +├── framework/ collector, assertions, reporter, runner and RPC screen transport +├── init.lua shared Neovim/Git sandbox bootstrap +└── run_tests.{sh,cmd} equivalent POSIX/Windows entry points +``` -## Running Tests +**The first directory defines the test level; the next directories define the +feature.** All runnable `*_spec.lua` files live in `unit/`, `integration/` or +`e2e/`, including tests of the test infrastructure itself. Discovery self-tests +enforce this boundary and verify that the layers form a complete, disjoint suite. + +- **Unit:** isolated logic such as parsing, policy or data transformations. + Neovim supplies LuaJIT and `vim` utilities; this does not make a test E2E. +- **Integration:** exercises component APIs and their real boundaries. Creating a + view directly, invoking a registered callback, supplying synthetic conflict + ranges or manually emitting an autocmd belongs here. The gutter screen tests + are integration tests even though they attach a real RPC UI. +- **E2E:** starts at a public command or user input, runs the real Git/file/view + pipeline, and checks observable outcomes. Older command scenarios inspect + buffers and window state; the interaction/refresh matrix also asserts actual + screen cells. Git-backed cases use disposable fixtures, not checkout history. + +Name files for their behavior, not an issue number or test level. For example, +`e2e/explorer/untracked_tab_spec.lua` retains its issue reference inside the test. +Do not add redundant `_e2e`/`_integration` suffixes or helper compatibility shims. +Extend an existing spec when it covers the same responsibility. + +## Running tests -### All tests: ```bash -./tests/run_tests.sh # or: make test-lua +./tests/run_tests.sh # all layers; same as make test-lua +./tests/run_tests.sh unit +./tests/run_tests.sh integration +./tests/run_tests.sh e2e +./tests/run_tests.sh tests/e2e/conflict # one feature +./tests/run_tests.sh tests/unit/core/path_spec.lua # one file +./tests/run_tests.sh --help ``` -Spec files are auto-discovered under `tests/`, so a new `*_spec.lua` is picked -up with no runner changes. +Use `tests\run_tests.cmd` with the same arguments on Windows. Targets may be +layer names, directories or individual specs. Paths are resolved from the +checkout root, regardless of the shell's starting directory. Missing targets +and selections containing no specs fail rather than reporting a green empty run. + +For direct Neovim use: -### Individual spec: ```bash nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('tests.framework').run_and_exit('tests/core/ffi_integration_spec.lua')" + -c "lua require('tests.framework').run_all_and_exit({ dir = 'e2e' })" ``` -### How the suite runs - -Each spec file gets its own child `nvim --headless` process, so specs stay -isolated from one another. `tests/framework/supervisor.lua` runs those children -concurrently from a single parent Neovim. Runtime depends on the selected -scenario matrix and available workers; use `CODEDIFF_TEST_JOBS` to control it. - -Children never share the parent's stdout: their output is buffered in full and -printed as one contiguous block when they exit. Letting concurrent processes -write to the same stream interleaves their output, both block-wise (stdout is -fully buffered when it isn't a tty) and line-wise (Neovim writes some messages -without a trailing newline). - -Concurrency needs `vim.system()` (Neovim 0.10+). On older versions the suite -automatically falls back to running the same children one at a time, producing -the same output, just slower. +Each spec gets its own child Neovim process. The supervisor discovers files +recursively, runs a bounded worker pool and prints each child's output as one +block. New specs need no manifest or CI enumeration changes. -### Test environment - -`tests/init.lua` is the bootstrap every child loads. Besides putting the plugin -on the runtimepath it disables a few pieces of Neovim that fight with throwaway -temp repositories: ShaDa, swap files, and the filewatcher backing for -`'autoread'` (via `g:loaded_autoread`, which must stay set before the -`runtime! plugin/*.lua` line that sources Neovim's own runtime plugins). +| Environment variable | Default | Purpose | +| --- | --- | --- | +| `CODEDIFF_TEST_TARGET` | `all` | Same selector as the positional argument; an explicit argument wins | +| `CODEDIFF_TEST_JOBS` | 2× CPUs, capped at 16 | Concurrent spec workers; `1` runs sequentially | +| `CODEDIFF_TEST_TIMEOUT` | `300000` | Per-spec timeout in milliseconds | +| `NO_COLOR` / `CODEDIFF_TEST_NO_COLOR` | unset | Disable ANSI output | +| `CODEDIFF_WATCHER_PATH` | installer default | Existing native watcher executable for offline E2Es | -The `'autoread'` option itself stays on, so `:checktime` still reloads buffers -silently. Only the per-buffer `uv_fs_event` goes away — specs delete the repos -they opened files from, and a watcher left pointing at a deleted path prints -`E211` on Linux and raises `EPERM` in an unbreakable loop on Windows. +## Fixtures and shared support -| Env var | Default | Purpose | -| --- | --- | --- | -| `CODEDIFF_TEST_JOBS` | 2x CPUs, capped at 16 | Concurrent spec workers. `1` forces sequential. | -| `CODEDIFF_TEST_TIMEOUT` | `300000` | Per-spec timeout in ms; guards against a hung spec stalling CI. | -| `NO_COLOR` / `CODEDIFF_TEST_NO_COLOR` | unset | Disable ANSI colors. | - -## Repository fixtures - -Git-backed tests share [`framework/repository.lua`](framework/repository.lua). -Each case gets an isolated repository and linked worktree in TMP, cloned from an -immutable seed without hardlinks. Refs, index files and object databases are not -shared between cases. Cleanup removes the worktree and its Git metadata. - -[`fixtures/refresh_repo.lua`](fixtures/refresh_repo.lua) supplies the named UI -profiles: basic, hunks, workspace, history and merge. Empty/unborn repositories, -regular `.git` directories, bare local remotes and SHA-256 use the same factory. -The test bootstrap isolates Git configuration and inherited repository overrides. -See [`fixtures/README.md`](fixtures/README.md) for the graph, API and interactive -reproduction commands. - -## Screen-grid regressions - -`tests/framework/screen.lua` starts a separate `nvim --embed` and attaches an -RPC UI. Assertions read actual `grid_line` cells and highlight colors, not -extmark metadata or screen functions in the headless test process. It uses -Neovim's bundled MessagePack and libuv, with no external dependencies. - -The conflict gutter has three automatically discovered specs: - -- `ui/conflict/gutter_grid_spec.lua`: hand-authored block shapes from - `fixtures/conflict_gutter.lua`, including empty/filler-only blocks, BOF/EOF, - partial scrolling, unrelated blank rows, multiple blocks and Result - projections. Checks both glyph cells and colors in all three panes under - each focus state. Fixtures go through the production conflict renderer; - expected rows do not call or duplicate the gutter calculator. -- `ui/conflict/gutter_options_spec.lua`: compares ordinary columns against - Neovim's native rendering, including relative/hybrid numbers, folds, wrapped - rows and other signs; checks custom-option ownership and restoration. -- `ui/conflict/gutter_lifecycle_spec.lua`: real Git merges, file/window/tab - transitions, resizing, accept/undo/redo/discard, manual Result edits and - teardown of stale callbacks and invalid sessions. - -Run these like any other spec, for example: +Import helpers as modules, not cwd-relative `dofile` calls: -```bash -nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('tests.framework').run_and_exit('tests/ui/conflict/gutter_grid_spec.lua')" +```lua +local h = require("tests.support") +local ui = require("tests.support.e2e") +local repositories = require("tests.support.repository") +local fixture = require("tests.fixtures.refresh_repo") ``` -Always close the embedded UI in `after_each`, including when an assertion -fails. A grid failure reports the pane/focus context, display row, expected -text and actual text. These are cell-level checks, not font or pixel snapshots. - -## Refresh regressions - -The [main-to-branch coverage map](ui/refresh/COVERAGE.md) lists each changed -production responsibility, its scenario IDs, and matrix parameters. It separates -named scenarios from expanded executions and from unit/component tests. - -`ui/refresh/*_e2e_spec.lua` exercises the session refresh controller through real -file writes, Git index/ref changes and rendered screen cells. It covers both -layouts, Explorer and bare comparisons, history, single-file previews, -directory comparisons, and editable merge Results. Lifecycle cases hold actual -Git responses to test file switches, buffer deletion, tab closure and edits -made while reads are pending. Unrelated changes must preserve pane identities, -cursors, viewports, folds and every observed diff-grid frame. - -Git cases run twice: once with the native watcher, and once with its 500 ms -polling fallback. Native tests require the real `codediff-watcher` binary and -assert that it became ready; silently falling back is not a native-test pass. -The normal installer supplies the binary, or set `CODEDIFF_WATCHER_PATH` to an -existing executable for offline runs. Android has no native release and skips -only the native cases. A process-exit case verifies actual watcher-to-polling -failover. Plain file/directory comparisons use polling without Git metadata. - -`ui/refresh/policy_spec.lua`, `ui/auto_refresh_spec.lua` and -`ui/explorer/native_watcher_spec.lua` cover dependency selection, settled input -snapshots, event coalescing, retries and stale callback rejection independently -of the screen tests. Controller tests also check that unchanged inputs do not -notify the diff renderer and list-only updates do not invoke file selection. -Explorer and History specs verify that their `on_data` handlers render supplied -session data without fetching Git data from the view. - -## Test Philosophy - -Focus on **integration points** that C tests cannot validate: -- FFI boundary integrity -- Lua async operations -- System integration (git) -- UI behavior (scrolling, rendering) - -## What's NOT Covered - -❌ **Diff algorithm** - Validated by C tests in `c-diff-core/tests/` (3,490 lines) -❌ **Other visual features and third-party UI integrations** - Manual testing unless covered by a dedicated grid spec +- `support/repository.lua` owns the isolated TMP repository/worktree factory. + Cases never share mutable refs, indexes or object files. +- `fixtures/refresh_repo.lua` supplies the basic, hunks, workspace, history and + merge profiles; `fixtures/conflict_gutter.lua` supplies independent visual + expectations and the focused gutter merge fixture. +- `support/init.lua` exposes plugin waiters and `project_root`. Tests must not + infer the checkout root by counting their own parent directories. +- `support/e2e.lua` drives embedded UI workflows. `support/gutter.lua` drives + focused renderer checks. `support/keymaps.lua` captures mapping matrices. +- `framework/screen.lua` owns generic RPC transport and screen-grid observation, + not feature fixtures or business assertions. + +Close embedded UIs before cleaning up their repositories, including on failed +assertions. Skipping during setup still runs cleanup; cleanup failures must not +be hidden by a skip. See [fixtures/README.md](fixtures/README.md) for the graph, +factory options, cleanup guarantees and interactive reproduction commands. + +## Environment and observable behavior + +`init.lua` disables auto-installation, ShaDa and swap files, isolates Git config, +and removes inherited repository/index overrides. It pins `core.autocrlf=false` +for all Git children, including on Windows. Neovim's per-buffer autoread watcher +is disabled to avoid watching deleted fixture paths, while `autoread` itself +remains available to `:checktime`. + +Synchronous headless specs can inspect buffers, extmarks, windows and options. +They cannot observe rendered cells or naturally dispatched `WinScrolled` / +`WinResized` merely by calling `vim.wait`. Use `framework/screen.lua` and a +separate `nvim --embed` for those observations. Always close the screen in +`after_each`. + +Native refresh E2Es require a real watcher and verify that it became ready; +silent fallback is not a native-test pass. Polling cases disable native startup +and exercise the 500 ms fallback. Android skips native cases only. Race tests +may delay delivery of real Git results, but do not fabricate their contents. + +## Behavioral coverage + +[e2e/COVERAGE.md](e2e/COVERAGE.md) maps the refresh changes against `main` to +scenario IDs and parameterized executions. Its 132 named scenarios / 544 +executions are a specific cross-feature matrix, **not the total E2E suite** and +not a count of unit or integration tests. Additional command and working-file +E2Es live alongside it. The runner reports the selected suite's actual counts. + +These tests provide evidence for documented behaviors, not an absolute safety +guarantee, pixel/font snapshots, or coverage of every external LSP, UI plugin, +filesystem and operating-system combination. diff --git a/tests/completion_spec.lua b/tests/completion_spec.lua deleted file mode 100644 index bc5ee397..00000000 --- a/tests/completion_spec.lua +++ /dev/null @@ -1,129 +0,0 @@ --- Test: Command completion --- Validates :CodeDiff command completion with dynamic git refs - -local git = require("codediff.core.git") -local commands = require("codediff.commands") - -describe("Command Completion", function() - describe("git.get_git_root_sync", function() - it("Returns git root for valid directory", function() - local cwd = vim.fn.getcwd() - local root = git.get_git_root_sync(cwd) - - -- We're running in the codediff.nvim repo - if root then - assert.equal("string", type(root)) - assert.equal(1, vim.fn.isdirectory(root)) - end - end) - - it("Returns nil for non-git directory", function() - local root = git.get_git_root_sync("/tmp") - -- /tmp might or might not be in a git repo depending on system - assert.is_true(root == nil or type(root) == "string") - end) - - it("Handles file path input", function() - local test_file = vim.fn.getcwd() .. "/README.md" - local root = git.get_git_root_sync(test_file) - - if root then - assert.equal("string", type(root)) - end - end) - end) - - describe("git.get_rev_candidates", function() - it("Returns empty table for nil git_root", function() - local candidates = git.get_rev_candidates(nil) - assert.equal("table", type(candidates)) - assert.equal(0, #candidates) - end) - - it("Returns HEAD refs for valid git repo", function() - local cwd = vim.fn.getcwd() - local git_root = git.get_git_root_sync(cwd) - - if git_root then - local candidates = git.get_rev_candidates(git_root) - assert.equal("table", type(candidates)) - assert.is_true(#candidates > 0, "Should return some candidates") - - -- Should include HEAD refs - assert.is_true(vim.tbl_contains(candidates, "HEAD"), "Should include HEAD") - assert.is_true(vim.tbl_contains(candidates, "HEAD~1"), "Should include HEAD~1") - end - end) - - it("Returns branches for valid git repo", function() - local cwd = vim.fn.getcwd() - local git_root = git.get_git_root_sync(cwd) - - if git_root then - local candidates = git.get_rev_candidates(git_root) - - -- In CI, shallow clones may not have full branch info - -- Just verify we got some candidates (HEAD refs at minimum) - assert.is_true(#candidates >= 4, "Should have at least HEAD refs") - end - end) - - it("Returns tags for valid git repo", function() - local cwd = vim.fn.getcwd() - local git_root = git.get_git_root_sync(cwd) - - if git_root then - local candidates = git.get_rev_candidates(git_root) - - -- In CI, shallow clones may not have tags - -- Just verify candidates is a valid table - assert.equal("table", type(candidates)) - end - end) - - it("Returns remotes for valid git repo", function() - local cwd = vim.fn.getcwd() - local git_root = git.get_git_root_sync(cwd) - - if git_root then - local candidates = git.get_rev_candidates(git_root) - - -- In CI, shallow clones may not have remote refs - -- Just verify candidates is a valid table - assert.equal("table", type(candidates)) - end - end) - end) - - describe("commands.SUBCOMMANDS", function() - it("Exports SUBCOMMANDS list", function() - assert.equal("table", type(commands.SUBCOMMANDS)) - assert.is_true(#commands.SUBCOMMANDS > 0, "Should have subcommands") - end) - - it("Contains expected subcommands", function() - assert.is_true(vim.tbl_contains(commands.SUBCOMMANDS, "file"), "Should include 'file'") - assert.is_true(vim.tbl_contains(commands.SUBCOMMANDS, "pr"), "Should include 'pr'") - assert.is_true(vim.tbl_contains(commands.SUBCOMMANDS, "install"), "Should include 'install'") - end) - end) - - describe("Completion caching", function() - it("Returns consistent results on repeated calls", function() - local cwd = vim.fn.getcwd() - local git_root = git.get_git_root_sync(cwd) - - if git_root then - local candidates1 = git.get_rev_candidates(git_root) - local candidates2 = git.get_rev_candidates(git_root) - - assert.equal(#candidates1, #candidates2, "Should return same number of candidates") - - -- Verify content matches - for i, c in ipairs(candidates1) do - assert.equal(c, candidates2[i], "Candidates should match at index " .. i) - end - end - end) - end) -end) diff --git a/tests/core/git_integration_spec.lua b/tests/core/git_integration_spec.lua deleted file mode 100644 index 02c6b804..00000000 --- a/tests/core/git_integration_spec.lua +++ /dev/null @@ -1,522 +0,0 @@ --- Test: Git Integration --- Validates git operations, error handling, and async callbacks - -local git = require('codediff.core.git') -local h = dofile('tests/helpers.lua') -local config = require('codediff.config') - -describe("Git Integration", function() - -- Test 1: Detect non-git directory (async) - it("Detects non-git directory", function() - local callback_called = false - local is_git = nil - - git.get_git_root("/tmp", function(err, root) - callback_called = true - is_git = (err == nil and root ~= nil) - end) - - vim.wait(2000, function() return callback_called end) - assert.is_true(callback_called, "Callback should be invoked") - assert.equal("boolean", type(is_git), "Should determine if in git repo") - end) - - -- Test 2: Get git root for valid repo (async) - it("Gets git root for current repo", function() - local current_file = vim.fn.expand("%:p") - if current_file == "" then - current_file = vim.fn.getcwd() .. "/README.md" - end - - local callback_called = false - local root = nil - - git.get_git_root(current_file, function(err, git_root) - callback_called = true - if not err then - root = git_root - end - end) - - vim.wait(2000, function() return callback_called end) - assert.is_true(callback_called, "Callback should be invoked") - - if root then - assert.equal("string", type(root), "Git root should be a string") - assert.equal(1, vim.fn.isdirectory(root), "Git root should be a directory") - end - end) - - -- Test 3: Error callback for invalid revision - it("Error callback for invalid revision", function() - local current_file = debug.getinfo(1).source:sub(2) - local callback_called = false - local got_error = false - - -- First get git root - git.get_git_root(current_file, function(err_root, git_root) - if not err_root and git_root then - local rel_path = git.get_relative_path(current_file, git_root) - - git.get_file_content("invalid-revision-12345", git_root, rel_path, function(err, data) - callback_called = true - if err then - got_error = true - end - end) - else - callback_called = true - got_error = true - end - end) - - vim.wait(2000, function() return callback_called end) - assert.is_true(callback_called, "Callback should be invoked") - end) - - -- Test 4: Async callback with actual git repo (if available) - it("Can retrieve file from HEAD (if in git repo)", function() - local test_passed = false - local current_file = debug.getinfo(1).source:sub(2) - - git.get_git_root(current_file, function(err_root, git_root) - if not err_root and git_root then - local rel_path = git.get_relative_path(current_file, git_root) - - -- First resolve HEAD to commit hash - git.resolve_revision("HEAD", git_root, function(err_resolve, commit_hash) - if not err_resolve and commit_hash then - git.get_file_content(commit_hash, git_root, rel_path, function(err, lines) - if not err and lines then - assert.equal("table", type(lines), "Should return table of lines") - assert.is_true(#lines > 0, "Should have content") - test_passed = true - elseif err then - test_passed = true - end - end) - else - test_passed = true - end - end) - else - test_passed = true - end - end) - - vim.wait(3000, function() return test_passed end) - assert.is_true(test_passed, "Test should complete") - end) - - -- Test 5: Relative path calculation - it("Calculates relative path correctly", function() - -- Use Windows-style paths on Windows, Unix on Unix - local sep = package.config:sub(1,1) - local git_root, file_path, expected - - if sep == "\\" then - -- Windows - git_root = "C:\\Users\\test\\project" - file_path = "C:\\Users\\test\\project\\src\\file.lua" - expected = "src/file.lua" - else - -- Unix - git_root = "/home/user/project" - file_path = "/home/user/project/src/file.lua" - expected = "src/file.lua" - end - - local rel_path = git.get_relative_path(file_path, git_root) - assert.equal("string", type(rel_path), "Should return string") - assert.equal(expected, rel_path, "Should strip git root: got " .. rel_path) - end) - - -- Test 6: Error message quality for missing file in revision - it("Provides good error for missing file in revision", function() - local current_file = debug.getinfo(1).source:sub(2) - local test_passed = false - - git.get_git_root(current_file, function(err_root, git_root) - if not err_root and git_root then - git.resolve_revision("HEAD", git_root, function(err_resolve, commit_hash) - if not err_resolve and commit_hash then - local fake_path = "nonexistent_file_12345.txt" - - git.get_file_content(commit_hash, git_root, fake_path, function(err, data) - if err then - assert.equal("string", type(err), "Error should be a string") - assert.is_true(#err > 0, "Error message should not be empty") - end - test_passed = true - end) - else - test_passed = true - end - end) - else - test_passed = true - end - end) - - vim.wait(3000, function() return test_passed end) - assert.is_true(test_passed, "Test should complete") - end) - - -- Test 7: Handles special characters in filenames - it("Handles filenames with spaces", function() - -- Use Windows-style paths on Windows, Unix on Unix - local sep = package.config:sub(1,1) - local git_root, file_path, expected - - if sep == "\\" then - -- Windows - git_root = "C:\\Users\\test\\project" - file_path = "C:\\Users\\test\\project\\src\\my file.lua" - expected = "src/my file.lua" - else - -- Unix - git_root = "/home/user/project" - file_path = "/home/user/project/src/my file.lua" - expected = "src/my file.lua" - end - - local rel_path = git.get_relative_path(file_path, git_root) - assert.equal(expected, rel_path, "Should handle spaces: got " .. rel_path) - end) - - -- Test 8: Multiple async calls don't interfere - it("Multiple async calls work independently", function() - local current_file = debug.getinfo(1).source:sub(2) - local call1_done = false - local call2_done = false - - git.get_git_root(current_file, function(err_root, git_root) - if not err_root and git_root then - local rel_path = git.get_relative_path(current_file, git_root) - - git.get_file_content("invalid1", git_root, rel_path, function() - call1_done = true - end) - - git.get_file_content("invalid2", git_root, rel_path, function() - call2_done = true - end) - else - call1_done = true - call2_done = true - end - end) - - vim.wait(3000, function() return call1_done and call2_done end) - - assert.is_true(call1_done, "First call should complete") - assert.is_true(call2_done, "Second call should complete") - end) - - -- Test 9: LRU Cache functionality - it("LRU cache returns same content", function() - local current_file = debug.getinfo(1).source:sub(2) - local test_passed = false - local first_result = nil - local second_result = nil - - git.get_git_root(current_file, function(err_root, git_root) - if not err_root and git_root then - git.resolve_revision("HEAD", git_root, function(err_resolve, commit_hash) - if not err_resolve and commit_hash then - local rel_path = git.get_relative_path(current_file, git_root) - - -- First call (cache miss) - git.get_file_content(commit_hash, git_root, rel_path, function(err1, lines1) - first_result = lines1 - - -- Second call (cache hit) - git.get_file_content(commit_hash, git_root, rel_path, function(err2, lines2) - second_result = lines2 - - if first_result and second_result then - assert.equal(#first_result, #second_result, "Cached content should match") - -- Verify they are separate copies (not same reference) - assert.are_not.equal(first_result, second_result, "Should return copies, not same reference") - test_passed = true - else - test_passed = true - end - end) - end) - else - test_passed = true - end - end) - else - test_passed = true - end - end) - - vim.wait(3000, function() return test_passed end) - assert.is_true(test_passed, "Test should complete") - end) - - -- Test 10: get_merge_base returns valid commit hash - it("get_merge_base returns merge-base commit", function() - local current_file = debug.getinfo(1).source:sub(2) - local test_passed = false - - git.get_git_root(current_file, function(err_root, git_root) - if not err_root and git_root then - -- Use HEAD and HEAD~1 which are guaranteed to exist and have a merge-base - git.get_merge_base("HEAD~1", "HEAD", git_root, function(err, merge_base_hash) - if not err and merge_base_hash then - -- Merge-base of HEAD~1 and HEAD should be HEAD~1 - assert.equal("string", type(merge_base_hash), "Should return commit hash") - assert.is_true(#merge_base_hash >= 7, "Hash should be at least 7 chars") - assert.is_true(merge_base_hash:match("^[a-f0-9]+$") ~= nil, "Should be hex hash") - test_passed = true - elseif err then - -- If merge-base fails (e.g., not enough commits), that's acceptable - test_passed = true - end - end) - else - test_passed = true - end - end) - - vim.wait(3000, function() return test_passed end) - assert.is_true(test_passed, "Test should complete") - end) - - -- Test 11: get_merge_base with invalid revision - it("get_merge_base handles invalid revision", function() - local current_file = debug.getinfo(1).source:sub(2) - local test_passed = false - - git.get_git_root(current_file, function(err_root, git_root) - if not err_root and git_root then - git.get_merge_base("nonexistent-branch-12345", "HEAD", git_root, function(err, merge_base_hash) - assert.is_not_nil(err, "Should return error for invalid branch") - assert.is_nil(merge_base_hash, "Should not return hash on error") - test_passed = true - end) - else - test_passed = true - end - end) - - vim.wait(3000, function() return test_passed end) - assert.is_true(test_passed, "Test should complete") - end) -end) - --- Untracked-files policy (#389): config.options.explorer.untracked controls the --- -u scan, applied centrally in run_git_async for both `git status` --- (get_status) and the untracked `ls-files` scan (get_diff_revision). -describe("Git untracked policy (#389)", function() - local prev - before_each(function() - prev = config.options.explorer.untracked - end) - after_each(function() - config.options.explorer.untracked = prev - end) - - -- Repo with a tracked change + a top-level untracked file + a nested untracked dir. - local function make_repo() - local repo = h.create_temp_git_repo() - repo.write_file("tracked.txt", { "base" }) - repo.git("add tracked.txt") - repo.git("commit -m initial") - repo.write_file("tracked.txt", { "changed" }) - repo.write_file("newfile.txt", { "u" }) - repo.write_file("untracked_dir/nested.txt", { "n" }) - return repo - end - - -- path -> status map from the unstaged group of an async git call. - local function unstaged_set(fn) - local done, res = false, nil - fn(function(_, r) - res = r - done = true - end) - vim.wait(3000, function() return done end) - assert.is_not_nil(res, "callback should fire") - local set = {} - for _, f in ipairs(res.unstaged or {}) do - set[f.path] = f.status - end - return set - end - - local function status_set(repo, mode) - config.options.explorer.untracked = mode - return unstaged_set(function(cb) git.get_status(repo.dir, cb) end) - end - - local function diffrev_set(repo, mode) - config.options.explorer.untracked = mode - return unstaged_set(function(cb) git.get_diff_revision("HEAD", repo.dir, cb) end) - end - - it("all lists every untracked file individually (get_status)", function() - local repo = make_repo() - local s = status_set(repo, "all") - assert.is_not_nil(s["newfile.txt"], "top-level untracked shown") - assert.is_not_nil(s["untracked_dir/nested.txt"], "nested untracked file shown") - repo.cleanup() - end) - - it("normal collapses untracked directories (get_status)", function() - local repo = make_repo() - local s = status_set(repo, "normal") - assert.is_not_nil(s["newfile.txt"], "top-level untracked still shown") - assert.is_nil(s["untracked_dir/nested.txt"], "nested file not listed individually") - assert.is_not_nil(s["untracked_dir/"], "directory collapsed to one entry") - repo.cleanup() - end) - - it("no skips untracked files entirely — the hang fix (get_status)", function() - local repo = make_repo() - local s = status_set(repo, "no") - assert.is_nil(s["newfile.txt"], "untracked hidden") - assert.is_nil(s["untracked_dir/nested.txt"], "untracked hidden") - assert.is_not_nil(s["tracked.txt"], "tracked change still present") - repo.cleanup() - end) - - it("no skips the ls-files untracked scan (get_diff_revision)", function() - local repo = make_repo() - local s = diffrev_set(repo, "no") - assert.is_nil(s["newfile.txt"], "untracked skipped in revision mode too") - assert.is_not_nil(s["tracked.txt"], "tracked change still present") - repo.cleanup() - end) - - it("normal collapses untracked directories (get_diff_revision)", function() - local repo = make_repo() - local s = diffrev_set(repo, "normal") - assert.is_not_nil(s["untracked_dir/"], "directory collapsed via --directory") - assert.is_nil(s["untracked_dir/nested.txt"], "nested file not listed individually") - repo.cleanup() - end) - - it("defaults to all when the config value is invalid", function() - local repo = make_repo() - local s = status_set(repo, "bogus") - assert.is_not_nil(s["untracked_dir/nested.txt"], "invalid mode falls back to all") - repo.cleanup() - end) -end) - --- The explorer polls `git status` every 500ms. A plain `git status` refreshes --- the index stat cache and writes it back, which takes `.git/index.lock`; a --- poll landing while the user stages/discards a hunk makes the *staging* --- command fail with "Unable to create '.../.git/index.lock': File exists". --- The read-only queries therefore pass `--no-optional-locks`, which skips --- exactly that write. -describe("Git read-only queries do not write the index (#494)", function() - local uv = vim.uv or vim.loop - - --- Repo whose index stat cache is stale: `tracked.txt` still has its - --- committed content, but its mtime was moved 60s into the past. git sees the - --- stat mismatch, re-reads the file, finds it clean, and — unless told not to - --- — rewrites the index to refresh the cache. The timestamp is strictly older - --- than the index, so this does not depend on filesystem mtime granularity. - local function make_repo_with_stale_index() - local repo = h.create_temp_git_repo() - repo.write_file("tracked.txt", { "base" }) - repo.git("add tracked.txt") - repo.git("commit -m initial") - - local past = os.time() - 60 - assert.is_not_nil(uv.fs_utime(repo.dir .. "/tracked.txt", past, past), "should be able to backdate the tracked file") - return repo - end - - local function index_bytes(repo) - return table.concat(vim.fn.readfile(repo.git_path("index"), "b"), "\n") - end - - it("get_status leaves .git/index untouched", function() - local repo = make_repo_with_stale_index() - local before = index_bytes(repo) - - local done, err = false, nil - git.get_status(repo.dir, function(e) - err = e - done = true - end) - vim.wait(5000, function() - return done - end) - - assert.is_true(done, "callback should fire") - assert.is_nil(err, "git status should succeed") - assert.equals(before, index_bytes(repo), "git status must not rewrite the index, or it would contend for index.lock") - repo.cleanup() - end) - - -- `git diff` refreshes the index unconditionally — it does not honor - -- `--no-optional-locks` the way `status` does — so it can still hold - -- index.lock briefly. What must hold is that neither query ever *fails* - -- because another git process owns the lock, so a poll can never surface an - -- error to the user. - it("read-only queries still succeed while another git process holds index.lock", function() - local repo = make_repo_with_stale_index() - local lock = repo.git_path("index.lock") - vim.fn.writefile({ "" }, lock) - - local done, err = false, nil - git.get_diff_revision("HEAD", repo.dir, function(e) - err = e - done = true - end) - vim.wait(5000, function() - return done - end) - - vim.fn.delete(lock) - assert.is_true(done, "callback should fire") - assert.is_nil(err, "a held index.lock must not fail a read-only query") - repo.cleanup() - end) -end) - - - - --- GitHub's Windows runners set `core.autocrlf=true` globally. git then warns --- "LF will be replaced by CRLF the next time Git touches it" on stderr for every --- LF file the specs write, and `vim.fn.system()` folds stderr into its return --- value ('shellredir' is `>%s 2>&1`) — so the warning ends up inside strings the --- specs compare against git output. tests/init.lua pins `core.autocrlf=false` --- through GIT_CONFIG_COUNT for every git process instead. -describe("Git output is free of line-ending warnings (#494)", function() - --- Repo configured exactly like a Windows CI runner: autocrlf on, LF content. - local function make_autocrlf_repo() - local repo = h.create_temp_git_repo() - repo.git("config core.autocrlf true") - repo.write_file("file1.txt", { "alpha", "beta", "gamma" }) - repo.git("add file1.txt") - repo.git("commit -m initial") - repo.write_file("file1.txt", { "alpha", "BETA", "gamma" }) - return repo - end - - it("git_cmd output carries no CRLF conversion warning", function() - local repo = make_autocrlf_repo() - - local output = repo.git("diff --name-only") - - assert.is_nil(output:match("LF will be replaced by CRLF"), "line-ending warning must not pollute git output: " .. output) - assert.equals("file1.txt", vim.trim(output), "git diff --name-only should report exactly the modified file") - repo.cleanup() - end) - - it("core.autocrlf is pinned off for every git process", function() - local repo = make_autocrlf_repo() - - assert.equals("false", vim.trim(repo.git("config --get core.autocrlf")), "environment config must outrank the repository config") - repo.cleanup() - end) -end) diff --git a/tests/ui/refresh/COVERAGE.md b/tests/e2e/COVERAGE.md similarity index 85% rename from tests/ui/refresh/COVERAGE.md rename to tests/e2e/COVERAGE.md index 28eda4d8..220cac91 100644 --- a/tests/ui/refresh/COVERAGE.md +++ b/tests/e2e/COVERAGE.md @@ -10,11 +10,11 @@ than tested through compatibility adapters. ## Fixture and observation contract -All Git-backed tests use `tests/framework/repository.lua`, including callers of -`tests/helpers.lua:create_temp_git_repo`. The richer UI scenarios share +All Git-backed tests use `tests/support/repository.lua`, including callers of +`require("tests.support").create_temp_git_repo`. The richer UI scenarios share `tests/fixtures/refresh_repo.lua`. Each case owns a temporary repository and worktree; cases never share mutable refs, indexes or object files. See -[the fixture documentation](../../fixtures/README.md). +[the fixture documentation](../fixtures/README.md). The tests start an actual `nvim --embed`, issue commands or keyboard/mouse input, and observe rendered screen cells. Git operations affect a real repository. @@ -36,20 +36,22 @@ are difficult to express through a Git merge. They are not counted below. A named scenario is distinct from its parameterized executions. The matrix has 132 named scenarios and 544 E2E executions on a platform with a native watcher. -Fixture tests and unit tests are not included in these counts. +This is the refresh change-audit matrix, not the entire E2E suite. Other command, +working-file and diagnostic E2Es are additional coverage. Fixture self-tests, +unit tests and component integrations are not included in these counts. -| Spec in this directory | Scenarios | Executions | Parameters | +| Spec relative to `tests/e2e/` | Scenarios | Executions | Parameters | | --- | ---: | ---: | --- | -| `refresh_e2e_spec.lua` | 16 | 64 | native/polling × side-by-side/inline | -| `conflict_refresh_e2e_spec.lua` | 10 | 20 | native/polling; three missing-stage shapes | -| `file_refresh_e2e_spec.lua` | 3 | 6 | side-by-side/inline; plain-file polling | -| `lifecycle_e2e_spec.lua` | 17 | 66 | both transports/layouts; process exit is native-only | -| `hunk_actions_e2e_spec.lua` | 14 | 54 | both transports/layouts; manual-only mode runs per layout | -| `explorer_actions_e2e_spec.lua` | 20 | 80 | both transports/layouts | -| `history_actions_e2e_spec.lua` | 14 | 56 | both transports/layouts | -| `merge_actions_e2e_spec.lua` | 15 | 120 | both transports × ours left/right × Result bottom/center | -| `source_refresh_e2e_spec.lua` | 19 | 74 | both transports/layouts; plain-file case runs per layout | -| `virtual_file_e2e_spec.lua` | 4 | 4 | direct public `codediff://` buffer commands | +| [refresh/repository_spec.lua](refresh/repository_spec.lua) | 16 | 64 | native/polling × side-by-side/inline | +| [conflict/refresh_spec.lua](conflict/refresh_spec.lua) | 10 | 20 | native/polling; three missing-stage shapes | +| [refresh/files_spec.lua](refresh/files_spec.lua) | 3 | 6 | side-by-side/inline; plain-file polling | +| [refresh/lifecycle_spec.lua](refresh/lifecycle_spec.lua) | 17 | 66 | both transports/layouts; process exit is native-only | +| [view/hunk_actions_spec.lua](view/hunk_actions_spec.lua) | 14 | 54 | both transports/layouts; manual-only mode runs per layout | +| [explorer/actions_spec.lua](explorer/actions_spec.lua) | 20 | 80 | both transports/layouts | +| [history/actions_spec.lua](history/actions_spec.lua) | 14 | 56 | both transports/layouts | +| [conflict/actions_spec.lua](conflict/actions_spec.lua) | 15 | 120 | both transports × ours left/right × Result bottom/center | +| [refresh/sources_spec.lua](refresh/sources_spec.lua) | 19 | 74 | both transports/layouts; plain-file case runs per layout | +| [virtual_file/buffers_spec.lua](virtual_file/buffers_spec.lua) | 4 | 4 | direct public `codediff://` buffer commands | ## Production change map diff --git a/tests/command_e2e_spec.lua b/tests/e2e/commands/dispatch_spec.lua similarity index 88% rename from tests/command_e2e_spec.lua rename to tests/e2e/commands/dispatch_spec.lua index db041bf0..28ca9505 100644 --- a/tests/command_e2e_spec.lua +++ b/tests/e2e/commands/dispatch_spec.lua @@ -1,32 +1,14 @@ --- End-to-end coverage of the :CodeDiff command grammars. Each case triggers the --- real command in a real temp git repo and asserts the actual rendered result --- (diff buffer contents, explorer file list, history commits, layout) — not just --- that dispatch routed correctly. --- --- Scope note: the headless test runner cannot drive the async codediff:// virtual-file --- load (git-show for a revision) — a diff whose original is a git *revision* --- opens a tab but never finishes registering its session under the test runner --- (it works fine interactively; see scripts/nvim-e2e.lua). So the git-revision --- single-file diffs (`file HEAD`, `file `) and 3-way `merge` are not --- asserted here; their dispatch is covered by tests/core/argparse_spec.lua and --- the command-parity differential. The single-file diff *render* and the layout --- flags are still covered below using two real files (no virtual buffer). - -local h = dofile("tests/helpers.lua") +-- State-observed E2Es through the registered :CodeDiff command and completion. +-- These assert real buffers, panel lists and layouts. Embedded-UI specs cover +-- screen cells and naturally deferred display events separately. +local h = require("tests.support") local lifecycle = require("codediff.ui.lifecycle") -local commands = require("codediff.commands") describe("Command E2E (real dispatch + render)", function() local repo local hash1, hash2 local original_cwd = vim.fn.getcwd() -- restored in after_each so temp-repo cleanup can't strand cwd (E739) - local function setup_command() - vim.api.nvim_create_user_command("CodeDiff", function(opts) - commands.vscode_diff(opts) - end, { nargs = "*", bang = true, range = true }) - end - local function find_explorer_buf() for _, tp in ipairs(vim.api.nvim_list_tabpages()) do for _, win in ipairs(vim.api.nvim_tabpage_list_wins(tp)) do @@ -108,7 +90,7 @@ describe("Command E2E (real dispatch + render)", function() end before_each(function() - setup_command() + h.ensure_plugin_loaded() repo = h.create_temp_git_repo() repo.write_file("file.txt", { "line 1", "line 2", "line 3" }) repo.git("add file.txt") @@ -433,13 +415,13 @@ describe("Command E2E (real dispatch + render)", function() h.assert_contains(text, "n.txt", "initial open shows files under modules/net") assert.is_nil(text:find("s.txt", 1, true), "initial open hides files outside the pathspec") - -- Add a fresh out-of-scope change AND an in-scope one, then force a refresh - -- through the real code path. Waiting on the in-scope marker guarantees the - -- async refresh actually completed before we assert on scope. + -- The real refresh key must retain scope. Wait for the new in-scope entry + -- before checking that the out-of-scope additions stayed hidden. repo.write_file("modules/store/s2.txt", { "s2" }) repo.write_file("modules/net/n2.txt", { "n2" }) local explorer = lifecycle.get_panel_view(find_explorer_tab()) - require("codediff.ui.refresh").request(explorer.tabpage, { full = true }) + vim.api.nvim_set_current_win(explorer.winid) + vim.api.nvim_feedkeys("R", "mx", false) local refreshed = vim.wait(10000, function() local buf = find_explorer_buf() @@ -456,24 +438,27 @@ describe("Command E2E (real dispatch + render)", function() it("completion offers subcommands and git refs", function() vim.cmd("lcd " .. repo.dir) - local cands = commands.complete("", "CodeDiff ") + local function complete(line) + return vim.fn.getcompletion(line, "cmdline") + end + local cands = complete("CodeDiff ") for _, name in ipairs({ "file", "dir", "history", "pr", "merge", "install" }) do assert.is_true(vim.tbl_contains(cands, name), "offers subcommand " .. name) end assert.is_true(vim.tbl_contains(cands, "HEAD"), "offers HEAD ref") - assert.is_true(vim.tbl_contains(commands.complete("--r", "CodeDiff --r"), "--repo"), "offers --repo flag") - assert.is_true(vim.tbl_contains(commands.complete("", "CodeDiff pr "), "clean"), "offers PR cleanup") - assert.is_true(vim.tbl_contains(commands.complete("--r", "CodeDiff pr 12 --r"), "--remote"), "offers PR remote flag") - assert.is_true(vim.tbl_contains(commands.complete("--b", "CodeDiff pr 12 --b"), "--base"), "offers PR base flag") - assert.is_true(vim.tbl_contains(commands.complete("--a", "CodeDiff pr clean --a"), "--all"), "offers cleanup all flag") - assert.is_false(vim.tbl_contains(commands.complete("-a", "CodeDiff pr clean -a"), "-a"), "does not offer a short cleanup alias") - assert.is_false(vim.tbl_contains(commands.complete("", "CodeDiff pr 12 -- "), "HEAD"), "PR path scope excludes revisions") + assert.is_true(vim.tbl_contains(complete("CodeDiff --r"), "--repo"), "offers --repo flag") + assert.is_true(vim.tbl_contains(complete("CodeDiff pr "), "clean"), "offers PR cleanup") + assert.is_true(vim.tbl_contains(complete("CodeDiff pr 12 --r"), "--remote"), "offers PR remote flag") + assert.is_true(vim.tbl_contains(complete("CodeDiff pr 12 --b"), "--base"), "offers PR base flag") + assert.is_true(vim.tbl_contains(complete("CodeDiff pr clean --a"), "--all"), "offers cleanup all flag") + assert.is_false(vim.tbl_contains(complete("CodeDiff pr clean -a"), "-a"), "does not offer a short cleanup alias") + assert.is_false(vim.tbl_contains(complete("CodeDiff pr 12 -- "), "HEAD"), "PR path scope excludes revisions") end) it("completion after -- offers file paths, not subcommands or refs (#74)", function() vim.cmd("lcd " .. repo.dir) repo.write_file("modules/net/n.txt", { "n" }) - local cands = commands.complete("modules/", "CodeDiff -- modules/") + local cands = vim.fn.getcompletion("CodeDiff -- modules/", "cmdline") assert.is_true(table.concat(cands, "\n"):find("modules/net", 1, true) ~= nil, "offers a path under modules/") assert.is_false(vim.tbl_contains(cands, "file"), "does not offer subcommands after --") assert.is_false(vim.tbl_contains(cands, "HEAD"), "does not offer git refs after --") diff --git a/tests/commands_uncovered_spec.lua b/tests/e2e/commands/merge_spec.lua similarity index 91% rename from tests/commands_uncovered_spec.lua rename to tests/e2e/commands/merge_spec.lua index 2fc7664f..66e9904d 100644 --- a/tests/commands_uncovered_spec.lua +++ b/tests/e2e/commands/merge_spec.lua @@ -1,11 +1,5 @@ --- Two command paths had no coverage: stubbing either left every spec green. --- --- :CodeDiff file A...B diff against the merge base of A and B --- :CodeDiff merge open the three-way merge view for a conflicted file --- --- Both are about to move into their own modules. - -local h = dofile("tests/helpers.lua") +-- Public merge-base and three-way merge commands against real Git fixtures. +local h = require("tests.support") h.ensure_plugin_loaded() describe("CodeDiff file A...B", function() @@ -132,8 +126,7 @@ describe("CodeDiff merge", function() local ours = table.concat(vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(session.original_win), 0, -1, false), "\n") local theirs = table.concat(vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(session.modified_win), 0, -1, false), "\n") assert.is_true( - (ours:find("MAIN1", 1, true) ~= nil and theirs:find("FEATURE1", 1, true) ~= nil) - or (ours:find("FEATURE1", 1, true) ~= nil and theirs:find("MAIN1", 1, true) ~= nil), + (ours:find("MAIN1", 1, true) ~= nil and theirs:find("FEATURE1", 1, true) ~= nil) or (ours:find("FEATURE1", 1, true) ~= nil and theirs:find("MAIN1", 1, true) ~= nil), "the two panes should hold the two sides of the conflict" ) end) diff --git a/tests/full_integration_spec.lua b/tests/e2e/commands/smoke_spec.lua similarity index 91% rename from tests/full_integration_spec.lua rename to tests/e2e/commands/smoke_spec.lua index 2745aa62..4223de63 100644 --- a/tests/full_integration_spec.lua +++ b/tests/e2e/commands/smoke_spec.lua @@ -1,20 +1,5 @@ --- Test: Full Integration --- Validates all supported commands documented in README.md - -local commands = require("codediff.commands") - --- Setup CodeDiff command for tests -local function setup_command() - vim.api.nvim_create_user_command("CodeDiff", function(opts) - commands.vscode_diff(opts) - end, { - nargs = "*", - bang = true, - complete = function() - return { "file", "install" } - end, - }) -end +-- Lightweight command smoke E2Es, also run against standalone native builds. +local h = require("tests.support") describe("Full Integration Suite", function() local temp_dir, repo @@ -23,15 +8,12 @@ describe("Full Integration Suite", function() -- Helper to run git in temp_dir (cross-platform) local function git(args) - local h = dofile("tests/helpers.lua") return h.git_cmd(temp_dir, args) end before_each(function() - -- Setup command - setup_command() - - repo = require("tests.framework.repository").new({ unborn = true }) + h.ensure_plugin_loaded() + repo = h.create_temp_git_repo() temp_dir = repo.dir -- Commit 1 diff --git a/tests/ui/refresh/merge_actions_e2e_spec.lua b/tests/e2e/conflict/actions_spec.lua similarity index 99% rename from tests/ui/refresh/merge_actions_e2e_spec.lua rename to tests/e2e/conflict/actions_spec.lua index 7f1898ce..11404ce1 100644 --- a/tests/ui/refresh/merge_actions_e2e_spec.lua +++ b/tests/e2e/conflict/actions_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") local fixture = require("tests.fixtures.refresh_repo") local function compose(choice, all, first) diff --git a/tests/ui/refresh/conflict_refresh_e2e_spec.lua b/tests/e2e/conflict/refresh_spec.lua similarity index 99% rename from tests/ui/refresh/conflict_refresh_e2e_spec.lua rename to tests/e2e/conflict/refresh_spec.lua index d79ca468..027b93bf 100644 --- a/tests/ui/refresh/conflict_refresh_e2e_spec.lua +++ b/tests/e2e/conflict/refresh_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") local function merge_repo() local repo = h.repo() diff --git a/tests/ui/refresh/explorer_actions_e2e_spec.lua b/tests/e2e/explorer/actions_spec.lua similarity index 99% rename from tests/ui/refresh/explorer_actions_e2e_spec.lua rename to tests/e2e/explorer/actions_spec.lua index 36b8257d..e04744e2 100644 --- a/tests/ui/refresh/explorer_actions_e2e_spec.lua +++ b/tests/e2e/explorer/actions_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") local fixture = require("tests.fixtures.refresh_repo") for _, backend in ipairs({ "native", "polling" }) do diff --git a/tests/ui/explorer/issue_309_spec.lua b/tests/e2e/explorer/untracked_tab_spec.lua similarity index 82% rename from tests/ui/explorer/issue_309_spec.lua rename to tests/e2e/explorer/untracked_tab_spec.lua index f309bf6d..fc976a8e 100644 --- a/tests/ui/explorer/issue_309_spec.lua +++ b/tests/e2e/explorer/untracked_tab_spec.lua @@ -10,7 +10,7 @@ -- must be a table right after selecting the untracked file), then exercises -- the full suspend → resume path via a tabnew + tabnext to catch a re-break. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() describe("PR #309 regression — tab cycle with an untracked file", function() @@ -55,8 +55,7 @@ describe("PR #309 regression — tab cycle with an untracked file", function() for i, l in ipairs(lines) do if l:find("ntracked") then vim.api.nvim_win_set_cursor(0, { i, 0 }) - vim.api.nvim_feedkeys( - vim.api.nvim_replace_termcodes("", true, false, true), "nx", false) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("", true, false, true), "mx", false) vim.wait(500) break end @@ -75,14 +74,11 @@ describe("PR #309 regression — tab cycle with an untracked file", function() vim.api.nvim_set_current_win(explorer_win) local target_line = find_untracked_line(explorer_buf) - assert.is_not_nil(target_line, - "untracked.txt should be findable in the explorer tree; buffer:\n" - .. h.get_buffer_content(explorer_buf)) + assert.is_not_nil(target_line, "untracked.txt should be findable in the explorer tree; buffer:\n" .. h.get_buffer_content(explorer_buf)) -- Select it → triggers show_untracked_file → single-pane view. vim.api.nvim_win_set_cursor(explorer_win, { target_line, 0 }) - vim.api.nvim_feedkeys( - vim.api.nvim_replace_termcodes("", true, false, true), "nx", false) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("", true, false, true), "mx", false) vim.wait(1000) -- Core invariant: stored_diff_result must have .changes and .moves as @@ -91,14 +87,9 @@ describe("PR #309 regression — tab cycle with an untracked file", function() local tabpage = vim.api.nvim_get_current_tabpage() local session = lifecycle.get_session(tabpage) assert.is_not_nil(session, "session should exist after selecting a file") - assert.is_not_nil(session.stored_diff_result, - "stored_diff_result should be set after show_untracked_file") - assert.equal("table", type(session.stored_diff_result.changes), - "stored_diff_result.changes must be a table (was: " - .. type(session.stored_diff_result.changes) .. ")") - assert.equal("table", type(session.stored_diff_result.moves), - "stored_diff_result.moves must be a table (was: " - .. type(session.stored_diff_result.moves) .. ")") + assert.is_not_nil(session.stored_diff_result, "stored_diff_result should be set after show_untracked_file") + assert.equal("table", type(session.stored_diff_result.changes), "stored_diff_result.changes must be a table (was: " .. type(session.stored_diff_result.changes) .. ")") + assert.equal("table", type(session.stored_diff_result.moves), "stored_diff_result.moves must be a table (was: " .. type(session.stored_diff_result.moves) .. ")") end) it("tabnew then tabnext to a codediff tab with an untracked file selected does not crash", function() @@ -113,8 +104,7 @@ describe("PR #309 regression — tab cycle with an untracked file", function() assert.is_not_nil(target_line) vim.api.nvim_win_set_cursor(explorer_win, { target_line, 0 }) - vim.api.nvim_feedkeys( - vim.api.nvim_replace_termcodes("", true, false, true), "nx", false) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("", true, false, true), "mx", false) vim.wait(1000) -- Now trigger the suspend → resume cycle: open a fresh tab, then jump @@ -139,8 +129,6 @@ describe("PR #309 regression — tab cycle with an untracked file", function() local after = lifecycle.get_session(codediff_tabpage) assert.is_not_nil(after, "session should survive the tab cycle") assert.is_false(after.suspended, "session should be resumed after tab cycle") - assert.is_true( - after.modified_win and vim.api.nvim_win_is_valid(after.modified_win), - "modified window should be valid after tab cycle") + assert.is_true(after.modified_win and vim.api.nvim_win_is_valid(after.modified_win), "modified window should be valid after tab cycle") end) end) diff --git a/tests/ui/refresh/history_actions_e2e_spec.lua b/tests/e2e/history/actions_spec.lua similarity index 99% rename from tests/ui/refresh/history_actions_e2e_spec.lua rename to tests/e2e/history/actions_spec.lua index 70635af9..f2c1a17a 100644 --- a/tests/ui/refresh/history_actions_e2e_spec.lua +++ b/tests/e2e/history/actions_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") local fixture = require("tests.fixtures.refresh_repo") for _, backend in ipairs({ "native", "polling" }) do diff --git a/tests/ui/refresh/file_refresh_e2e_spec.lua b/tests/e2e/refresh/files_spec.lua similarity index 97% rename from tests/ui/refresh/file_refresh_e2e_spec.lua rename to tests/e2e/refresh/files_spec.lua index 190d5085..b488ec0c 100644 --- a/tests/ui/refresh/file_refresh_e2e_spec.lua +++ b/tests/e2e/refresh/files_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") for _, layout in ipairs({ "side-by-side", "inline" }) do describe("file-source refresh E2E / " .. layout, function() diff --git a/tests/ui/refresh/lifecycle_e2e_spec.lua b/tests/e2e/refresh/lifecycle_spec.lua similarity index 99% rename from tests/ui/refresh/lifecycle_e2e_spec.lua rename to tests/e2e/refresh/lifecycle_spec.lua index cb6a1b48..74c6d266 100644 --- a/tests/ui/refresh/lifecycle_e2e_spec.lua +++ b/tests/e2e/refresh/lifecycle_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") for _, backend in ipairs({ "native", "polling" }) do for _, layout in ipairs({ "side-by-side", "inline" }) do diff --git a/tests/ui/refresh/refresh_e2e_spec.lua b/tests/e2e/refresh/repository_spec.lua similarity index 99% rename from tests/ui/refresh/refresh_e2e_spec.lua rename to tests/e2e/refresh/repository_spec.lua index 93c9def3..98b879af 100644 --- a/tests/ui/refresh/refresh_e2e_spec.lua +++ b/tests/e2e/refresh/repository_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") for _, backend in ipairs({ "native", "polling" }) do for _, layout in ipairs({ "side-by-side", "inline" }) do diff --git a/tests/ui/refresh/source_refresh_e2e_spec.lua b/tests/e2e/refresh/sources_spec.lua similarity index 99% rename from tests/ui/refresh/source_refresh_e2e_spec.lua rename to tests/e2e/refresh/sources_spec.lua index 815121a1..5ad19690 100644 --- a/tests/ui/refresh/source_refresh_e2e_spec.lua +++ b/tests/e2e/refresh/sources_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") local fixture = require("tests.fixtures.refresh_repo") for _, backend in ipairs({ "native", "polling" }) do @@ -163,7 +163,7 @@ for _, backend in ipairs({ "native", "polling" }) do end) it("[S14] an unborn branch opens staged content against an empty base", function() - repo = require("tests.framework.repository").new({ unborn = true }) + repo = require("tests.support.repository").new({ unborn = true }) repo.write_file("a.txt", { "unborn-index" }) repo.command({ "add", "a.txt" }) h.open(screen, repo, "CodeDiff --staged") diff --git a/tests/ui/view/follow_working_file_spec.lua b/tests/e2e/view/follow_working_file_spec.lua similarity index 99% rename from tests/ui/view/follow_working_file_spec.lua rename to tests/e2e/view/follow_working_file_spec.lua index f75fbdf9..6b45c33f 100644 --- a/tests/ui/view/follow_working_file_spec.lua +++ b/tests/e2e/view/follow_working_file_spec.lua @@ -9,7 +9,7 @@ -- defeated the listener's change guard, with nothing to catch it — so these -- pin down the behaviour rather than the implementation. -local helpers = require("tests.helpers") +local helpers = require("tests.support") describe("following the working file", function() local repo diff --git a/tests/ui/refresh/hunk_actions_e2e_spec.lua b/tests/e2e/view/hunk_actions_spec.lua similarity index 99% rename from tests/ui/refresh/hunk_actions_e2e_spec.lua rename to tests/e2e/view/hunk_actions_spec.lua index 93f0ae05..04a875dc 100644 --- a/tests/ui/refresh/hunk_actions_e2e_spec.lua +++ b/tests/e2e/view/hunk_actions_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") local fixture = require("tests.fixtures.refresh_repo") local function expected(first, second) diff --git a/tests/ui/refresh/virtual_file_e2e_spec.lua b/tests/e2e/virtual_file/buffers_spec.lua similarity index 98% rename from tests/ui/refresh/virtual_file_e2e_spec.lua rename to tests/e2e/virtual_file/buffers_spec.lua index dd291c7e..d295525f 100644 --- a/tests/ui/refresh/virtual_file_e2e_spec.lua +++ b/tests/e2e/virtual_file/buffers_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.ui.refresh.helpers") +local h = require("tests.support.e2e") -- These exercise the public codediff:// BufReadCmd path without a diff session. -- Callback timing is controlled, but every response comes from a real Git read. diff --git a/tests/e2e/virtual_file/diagnostics_spec.lua b/tests/e2e/virtual_file/diagnostics_spec.lua new file mode 100644 index 00000000..85f93d91 --- /dev/null +++ b/tests/e2e/virtual_file/diagnostics_spec.lua @@ -0,0 +1,34 @@ +-- Public command coverage of diagnostic isolation, independent of source history. +local h = require("tests.support.e2e") + +describe("Virtual buffer diagnostics integration", function() + local repo, screen + + before_each(function() + repo = h.repo() + repo.write_file("sample.lua", { "local value = 'working'", "return value" }) + screen = h.screen("polling", "side-by-side") + end) + + after_each(function() + h.close(screen, repo) + screen, repo = nil, nil + end) + + it("Disables diagnostics on virtual buffers in real CodeDiff usage", function() + h.open(screen, repo, "CodeDiff file HEAD", "sample.lua", "sample.lua") + h.expect_text(screen, "original", "local value = 'base'") + h.expect_text(screen, "modified", "local value = 'working'") + local state = screen:exec([[ + local session = refresh_session() + return { + virtual = vim.api.nvim_buf_get_name(session.original_bufnr):match('^codediff://') ~= nil, + original = vim.diagnostic.is_enabled({ bufnr = session.original_bufnr }), + modified = vim.diagnostic.is_enabled({ bufnr = session.modified_bufnr }), + } + ]]) + assert.is_true(state.virtual, "original pane must be a real revision buffer") + assert.is_false(state.original, "revision buffers must suppress diagnostics") + assert.is_true(state.modified, "the working buffer must retain diagnostics") + end) +end) diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 3e678ea6..ab6d01dd 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -1,8 +1,8 @@ # Repository fixtures -Git-backed tests share `tests/framework/repository.lua`. The UI E2Es use the -small deterministic graph in `refresh_repo.lua`; older tests obtain an empty -worktree through `tests/helpers.lua:create_temp_git_repo()`. +Git-backed tests share `tests/support/repository.lua`. The UI E2Es use the +small deterministic graph in `refresh_repo.lua`; empty fixtures are available +through `require("tests.support").create_temp_git_repo()`. ## Isolation and lifecycle @@ -61,6 +61,10 @@ the corresponding commits. The seed's `main` stays at `fixture/base`. Golden contents are declared in `refresh_repo.files`; assertions do not ask the production diff/merge calculator to construct their expectations. +`conflict_gutter.lua` keeps the focused gutter expectations and a `new_repo()` +builder on the same factory. `keymap_matrix.txt` is the hand-reviewed mapping +golden; its capture driver belongs to `support/keymaps.lua`, not to fixture data. + ## API ```lua @@ -84,7 +88,7 @@ that must explicitly expect code 1. The lower-level factory supports special states through the same lifecycle: ```lua -local repositories = require("tests.framework.repository") +local repositories = require("tests.support.repository") local unborn = repositories.new({ unborn = true }) local ordinary = repositories.new({ worktree = false, unborn = true }) local remote = repositories.new({ bare = true, unborn = true }) @@ -110,4 +114,4 @@ then run: Use the same profile to reproduce a failing operation. Print `fixture_repo.dir` to inspect it from another shell while Neovim is running. The worktree is removed when this Neovim exits. The full scenario map is in -[`ui/refresh/COVERAGE.md`](../ui/refresh/COVERAGE.md). +[`e2e/COVERAGE.md`](../e2e/COVERAGE.md). diff --git a/tests/fixtures/conflict_gutter.lua b/tests/fixtures/conflict_gutter.lua index 3dcfc771..bec1a4ba 100644 --- a/tests/fixtures/conflict_gutter.lua +++ b/tests/fixtures/conflict_gutter.lua @@ -1,6 +1,6 @@ -- Hand-authored screen rows for a six-line buffer: one, two, three, four, five, six. -- These are visual expectations, not output from the gutter calculator. -return { +local M = { { name = "single real position", range = { start_line = 2, end_line = 3 }, @@ -116,3 +116,40 @@ return { rows = { " one", " ╱╱╱╱", " two", "╭─three", "╰─four", " five", " ╱╱╱╱", " six" }, }, } + +-- A real merge with an interior filler in incoming, plus a second file whose +-- filler is on the opposite side. Both use independently authored expectations. +function M.new_repo() + local repo = require("tests.support.repository").new({ unborn = true }) + repo.write_file("conf.txt", { "before", "base1", "base2", "base3", "after", "tail" }) + repo.write_file("other.txt", { "beforeB", "baseB", "afterB" }) + repo.write_file("deleted.txt", { "deleted one", "deleted two" }) + repo.commit("base") + repo.command({ "checkout", "-b", "incoming" }) + repo.write_file("conf.txt", { "before", "base1", "THEIRS2", "THEIRS3", "after", "tail" }) + repo.write_file("other.txt", { "beforeB", "THEIRS_B", "extraB", "afterB" }) + repo.commit("incoming") + repo.command({ "checkout", "main" }) + repo.write_file("conf.txt", { "before", "OURS1", "inserted", "OURS2", "base3", "after", "tail" }) + repo.write_file("other.txt", { "beforeB", "OURS_B", "afterB" }) + repo.commit("current") + repo.command({ "merge", "incoming", "--no-edit" }, 1) + repo.write_file("fresh.txt", { "fresh one", "fresh two" }) + repo.write_file("plain-left.txt", { "before", "same", "keep", "after" }) + repo.write_file("plain-right.txt", { "before", "same", "keep", "inserted", "after" }) + return repo +end + +M.merge_rows = { + original = { " before", "╭─base1", "│ THEIRS2", "│ ╱╱╱╱", "╰─THEIRS3", " after", " tail" }, + modified = { " before", "╭─OURS1", "│ inserted", "│ OURS2", "╰─base3", " after", " tail" }, + result = { " before", "╭─base1", "│ base2", "╰─base3", " after", " tail" }, +} + +M.other_merge_rows = { + original = { " beforeB", "╭─THEIRS_B", "╰─extraB", " afterB" }, + modified = { " beforeB", "╭─╱╱╱╱", "╰─OURS_B", " afterB" }, + result = { " beforeB", "[ baseB", " afterB" }, +} + +return M diff --git a/tests/fixtures/refresh_repo.lua b/tests/fixtures/refresh_repo.lua index 25ad5fbc..d9ddd1dd 100644 --- a/tests/fixtures/refresh_repo.lua +++ b/tests/fixtures/refresh_repo.lua @@ -1,7 +1,7 @@ -- A deterministic Git graph shared by refresh and UI-operation E2Es. -- Every invocation returns a separate TMP repository and linked worktree. local M = {} -local repositories = require("tests.framework.repository") +local repositories = require("tests.support.repository") M.files = { ["a.txt"] = { "start", "base-A", "context", "end", "tail" }, diff --git a/tests/framework/init.lua b/tests/framework/init.lua index 6c628939..b67d407c 100644 --- a/tests/framework/init.lua +++ b/tests/framework/init.lua @@ -5,12 +5,9 @@ -- busted-style DSL (`describe`, `it`, `before_each`, `after_each`, `pending`), -- and exposing `run_file(spec)` / `run_and_exit(spec)` for the shell scripts. -- --- Rationale: mirrors the "own the small dep" pattern already established by --- `lua/codediff/ui/lib/` (which replaced `nui.nvim` with a ~300 LOC in-tree --- copy of just the pieces this plugin actually uses). Replacing plenary.nvim --- required ~500 LOC of pure Lua + Neovim built-ins — no `git clone` on CI, no --- external network dependency, and the identical `describe/it/assert.*` API --- means zero changes to any of the 66 existing `*_spec.lua` files. +-- The framework has no external test dependency. Runnable specs, including its +-- own self-tests, live in unit/, integration/ and e2e/ rather than beside the +-- runner implementation. Shared feature drivers live separately in support/. local M = {} @@ -19,7 +16,9 @@ local installed = false --- Install framework globals and start collecting tests. -- Idempotent — calling it more than once is a no-op. function M.setup() - if installed then return end + if installed then + return + end installed = true -- Assertion library replaces `_G.assert`. It is a callable table so the @@ -31,7 +30,9 @@ function M.setup() -- Some legacy spec files explicitly do `local assert = require("luassert")`. -- Route those requires to our in-tree assert module so those specs work -- unchanged. - package.preload["luassert"] = function() return a end + package.preload["luassert"] = function() + return a + end -- describe/it/before_each/after_each/pending globals require("tests.framework.busted").install() diff --git a/tests/framework/supervisor.lua b/tests/framework/supervisor.lua index 6a98ee5e..8076851b 100644 --- a/tests/framework/supervisor.lua +++ b/tests/framework/supervisor.lua @@ -39,9 +39,13 @@ local DEFAULT_TIMEOUT_MS = 300000 local function env_number(name) local raw = vim.env[name] - if not raw or raw == "" then return nil end + if not raw or raw == "" then + return nil + end local n = tonumber(raw) - if not n or n < 1 then return nil end + if not n or n < 1 then + return nil + end return math.floor(n) end @@ -54,7 +58,9 @@ local function default_jobs() local ok, cpus = pcall(function() return uv.available_parallelism() end) - if not ok or type(cpus) ~= "number" or cpus < 1 then cpus = 2 end + if not ok or type(cpus) ~= "number" or cpus < 1 then + cpus = 2 + end return math.max(2, math.min(cpus * 2, 16)) end @@ -62,25 +68,25 @@ end -- Discovery -- --------------------------------------------------------------------------- ---- Find every `*_spec.lua` under `dir`, as sorted repo-relative paths. --- --- Replaces the shell-side `find`/`for /r` discovery. Paths are normalized to --- forward slashes so the ordering, the log, and the `%q`-quoted argument --- handed to the child are identical on every platform (a Windows path pasted --- raw into a Lua string would also mangle `\U`, `\t`, ... escapes). --- --- `globpath()` rather than `vim.fs.find()`: it exists on every Neovim version, --- so discovery never becomes the reason an older Neovim can't run the suite. --- `nosuf = true` keeps a stray 'wildignore' from silently hiding spec files. -function M.discover(dir) - dir = dir or "tests" +--- Discover a test layer, directory or single spec as sorted repo-relative paths. +-- `nosuf = true` prevents 'wildignore' from silently hiding coverage. +function M.discover(target) + local layers = { all = "tests", unit = "tests/unit", integration = "tests/integration", e2e = "tests/e2e" } + if not target or target == "" then + target = "all" + end + local dir = (layers[target] or target):gsub("\\", "/") local root = vim.fn.getcwd():gsub("\\", "/") - - local matches = vim.fn.globpath(dir, "**/*_spec.lua", true, true) + local matches + if vim.fn.filereadable(dir) == 1 then + matches = dir:match("_spec%.lua$") and { dir } or {} + else + matches = vim.fn.globpath(dir, "**/*_spec.lua", true, true) + end local specs = {} for _, path in ipairs(matches) do - local norm = path:gsub("\\", "/") + local norm = vim.fn.fnamemodify(path, ":p"):gsub("\\", "/") -- Make absolute paths relative to the repo root so the log is readable and -- the child's loader resolves them from cwd. if norm:sub(1, #root + 1) == root .. "/" then @@ -129,7 +135,9 @@ local function run_parallel(specs, opts) local next_index, emitted = 1, 0 local function spawn_next() - if next_index > #specs then return end + if next_index > #specs then + return + end local spec = specs[next_index] next_index = next_index + 1 @@ -184,10 +192,10 @@ end -- --------------------------------------------------------------------------- --- Run every discovered spec file. Returns (ok, results). --- @param opts table|nil { dir, jobs, timeout } +-- @param opts table|nil { dir = layer|directory|spec, jobs, timeout } function M.run(opts) opts = opts or {} - local specs = M.discover(opts.dir) + local specs = M.discover(opts.dir or vim.env.CODEDIFF_TEST_TARGET) local timeout = opts.timeout or env_number("CODEDIFF_TEST_TIMEOUT") or DEFAULT_TIMEOUT_MS local jobs = opts.jobs or env_number("CODEDIFF_TEST_JOBS") or default_jobs() @@ -233,7 +241,9 @@ function M.run(opts) reporter.print_suite_summary(results, total_ms) for _, r in ipairs(results) do - if not r.ok then return false, results end + if not r.ok then + return false, results + end end return true, results end diff --git a/tests/integration/commands/completion_spec.lua b/tests/integration/commands/completion_spec.lua new file mode 100644 index 00000000..0e374df5 --- /dev/null +++ b/tests/integration/commands/completion_spec.lua @@ -0,0 +1,87 @@ +-- Completion queries use a deterministic fixture, not the checkout's refs. +local git = require("codediff.core.git") +local commands = require("codediff.commands") +local fixture = require("tests.fixtures.refresh_repo") +local h = require("tests.support") + +describe("Command Completion", function() + local repo, non_repo + + before_each(function() + repo = fixture.new("history") + repo.command({ "update-ref", "refs/remotes/origin/main", repo.second }) + non_repo = h.create_temp_dir() + end) + + after_each(function() + if repo then + repo.cleanup() + end + if non_repo then + vim.fn.delete(non_repo, "rf") + end + end) + + describe("git.get_git_root_sync", function() + it("Returns git root for valid directory", function() + assert.equals(repo.dir, git.get_git_root_sync(repo.dir)) + end) + + it("Returns nil for non-git directory", function() + assert.is_nil(git.get_git_root_sync(non_repo)) + end) + + it("Handles file path input", function() + assert.equals(repo.dir, git.get_git_root_sync(repo.path("a.txt"))) + end) + end) + + describe("git.get_rev_candidates", function() + it("Returns empty table for nil git_root", function() + assert.same({}, git.get_rev_candidates(nil)) + end) + + it("Returns HEAD refs for valid git repo", function() + local candidates = git.get_rev_candidates(repo.dir) + assert.is_true(vim.tbl_contains(candidates, "HEAD")) + assert.is_true(vim.tbl_contains(candidates, "HEAD~1")) + end) + + it("Returns branches for valid git repo", function() + local candidates = git.get_rev_candidates(repo.dir) + for _, branch in ipairs({ "main", "review/left", "review/right" }) do + assert.is_true(vim.tbl_contains(candidates, branch), "missing fixture branch " .. branch) + end + end) + + it("Returns tags for valid git repo", function() + local candidates = git.get_rev_candidates(repo.dir) + for _, tag in ipairs({ "fixture/base", "fixture/one", "fixture/two" }) do + assert.is_true(vim.tbl_contains(candidates, tag), "missing fixture tag " .. tag) + end + end) + + it("Returns remotes for valid git repo", function() + assert.is_true(vim.tbl_contains(git.get_rev_candidates(repo.dir), "origin/main")) + end) + end) + + describe("commands.SUBCOMMANDS", function() + it("Exports SUBCOMMANDS list", function() + assert.is_table(commands.SUBCOMMANDS) + assert.is_true(#commands.SUBCOMMANDS > 0) + end) + + it("Contains expected subcommands", function() + for _, name in ipairs({ "file", "pr", "install" }) do + assert.is_true(vim.tbl_contains(commands.SUBCOMMANDS, name), "missing subcommand " .. name) + end + end) + end) + + describe("Completion caching", function() + it("Returns consistent results on repeated calls", function() + assert.same(git.get_rev_candidates(repo.dir), git.get_rev_candidates(repo.dir)) + end) + end) +end) diff --git a/tests/core/ffi_integration_spec.lua b/tests/integration/core/diff/ffi_spec.lua similarity index 100% rename from tests/core/ffi_integration_spec.lua rename to tests/integration/core/diff/ffi_spec.lua diff --git a/tests/core/move_detection_spec.lua b/tests/integration/core/diff/moves_spec.lua similarity index 100% rename from tests/core/move_detection_spec.lua rename to tests/integration/core/diff/moves_spec.lua diff --git a/tests/core/timeout_spec.lua b/tests/integration/core/diff/timeout_spec.lua similarity index 100% rename from tests/core/timeout_spec.lua rename to tests/integration/core/diff/timeout_spec.lua diff --git a/tests/core/ignore_whitespace_spec.lua b/tests/integration/core/diff/whitespace_spec.lua similarity index 100% rename from tests/core/ignore_whitespace_spec.lua rename to tests/integration/core/diff/whitespace_spec.lua diff --git a/tests/core/dir_spec.lua b/tests/integration/core/directory_spec.lua similarity index 99% rename from tests/core/dir_spec.lua rename to tests/integration/core/directory_spec.lua index 36de525c..dabc4b9b 100644 --- a/tests/core/dir_spec.lua +++ b/tests/integration/core/directory_spec.lua @@ -1,5 +1,5 @@ -- Tests for directory comparison (dir.lua) -local helpers = require('tests.helpers') +local helpers = require('tests.support') describe('dir module', function() local dir_mod diff --git a/tests/core/history_line_range_spec.lua b/tests/integration/core/git/history_lines_spec.lua similarity index 99% rename from tests/core/history_line_range_spec.lua rename to tests/integration/core/git/history_lines_spec.lua index 917741e6..213cdf18 100644 --- a/tests/core/history_line_range_spec.lua +++ b/tests/integration/core/git/history_lines_spec.lua @@ -5,7 +5,7 @@ local git = require('codediff.core.git') -- Helper: create a temp git repo with multiple commits affecting different line ranges local function create_test_repo() - local repo = require("tests.framework.repository").new({ unborn = true }) + local repo = require("tests.support.repository").new({ unborn = true }) local function run_git(args) return repo.git(args, 0) end diff --git a/tests/core/git_line_stats_spec.lua b/tests/integration/core/git/line_stats_spec.lua similarity index 99% rename from tests/core/git_line_stats_spec.lua rename to tests/integration/core/git/line_stats_spec.lua index 7df7e9ba..d324ea0f 100644 --- a/tests/core/git_line_stats_spec.lua +++ b/tests/integration/core/git/line_stats_spec.lua @@ -1,6 +1,6 @@ local config = require("codediff.config") local git = require("codediff.core.git") -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local get_file = function(files, path) for _, file in ipairs(files or {}) do diff --git a/tests/core/pull_request_spec.lua b/tests/integration/core/git/pull_request_spec.lua similarity index 98% rename from tests/core/pull_request_spec.lua rename to tests/integration/core/git/pull_request_spec.lua index fe95b50e..308e50bf 100644 --- a/tests/core/pull_request_spec.lua +++ b/tests/integration/core/git/pull_request_spec.lua @@ -1,5 +1,5 @@ local pull_request = require("codediff.core.pull_request") -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local function run(cwd, args) local command = { "git", "-C", cwd } @@ -60,7 +60,7 @@ describe("pull request fetching", function() before_each(function() repo = h.create_temp_git_repo() - remote_fixture = require("tests.framework.repository").new({ bare = true, unborn = true }) + remote_fixture = require("tests.support.repository").new({ bare = true, unborn = true }) remote = remote_fixture.dir repo.write_file("review.txt", { "base" }) diff --git a/tests/integration/core/git/queries_spec.lua b/tests/integration/core/git/queries_spec.lua new file mode 100644 index 00000000..0b097a16 --- /dev/null +++ b/tests/integration/core/git/queries_spec.lua @@ -0,0 +1,282 @@ +-- Git queries run against isolated fixtures, never the source checkout's HEAD. +local git = require("codediff.core.git") +local h = require("tests.support") +local fixture = require("tests.fixtures.refresh_repo") +local config = require("codediff.config") + +local function await(start) + local result + start(function(...) + result = { n = select("#", ...), ... } + end) + assert.is_true( + vim.wait(5000, function() + return result ~= nil + end, 20), + "Git callback did not complete" + ) + return unpack(result, 1, result.n) +end + +describe("Git Integration", function() + local repo, non_repo + + before_each(function() + repo = fixture.new("history") + non_repo = h.create_temp_dir() + end) + + after_each(function() + if repo then + repo.cleanup() + end + if non_repo then + vim.fn.delete(non_repo, "rf") + end + end) + + it("Detects non-git directory", function() + local err, root = await(function(done) + git.get_git_root(non_repo, done) + end) + assert.is_not_nil(err) + assert.is_nil(root) + end) + + it("Gets git root for current repo", function() + local err, root = await(function(done) + git.get_git_root(repo.path("a.txt"), done) + end) + assert.is_nil(err) + assert.equals(repo.dir, root) + end) + + it("Error callback for invalid revision", function() + local err, lines = await(function(done) + git.get_file_content("invalid-revision-12345", repo.dir, "a.txt", done) + end) + assert.is_string(err) + assert.is_nil(lines) + end) + + it("Can retrieve file from HEAD (if in git repo)", function() + local err, revision = await(function(done) + git.resolve_revision("HEAD", repo.dir, done) + end) + assert.is_nil(err) + assert.equals(repo.second, revision) + local read_error, lines = await(function(done) + git.get_file_content(revision, repo.dir, "a.txt", done) + end) + assert.is_nil(read_error) + assert.same(repo.blob_lines("HEAD", "a.txt"), lines) + end) + + it("Calculates relative path correctly", function() + assert.equals("nested/deep/beta.txt", git.get_relative_path(repo.path("nested/deep/beta.txt"), repo.dir)) + end) + + it("Provides good error for missing file in revision", function() + local err, lines = await(function(done) + git.get_file_content(repo.second, repo.dir, "nonexistent_file_12345.txt", done) + end) + assert.is_string(err) + assert.is_not_nil(err:find("nonexistent_file_12345.txt", 1, true)) + assert.is_nil(lines) + end) + + it("Handles filenames with spaces", function() + assert.equals("rename/renamed file.txt", git.get_relative_path(repo.path("rename/renamed file.txt"), repo.dir)) + end) + + it("Multiple async calls work independently", function() + local results = {} + for i, revision in ipairs({ repo.first, repo.second }) do + git.get_file_content(revision, repo.dir, "a.txt", function(err, lines) + results[i] = { err = err, lines = lines } + end) + end + assert.is_true(vim.wait(5000, function() + return results[1] ~= nil and results[2] ~= nil + end, 20)) + assert.is_nil(results[1].err) + assert.is_nil(results[2].err) + assert.same(repo.blob_lines(repo.first, "a.txt"), results[1].lines) + assert.same(repo.blob_lines(repo.second, "a.txt"), results[2].lines) + end) + + it("LRU cache returns same content", function() + local function read(done) + git.get_file_content(repo.second, repo.dir, "a.txt", done) + end + local first_error, first = await(read) + local second_error, second = await(read) + assert.is_nil(first_error) + assert.is_nil(second_error) + assert.same(repo.blob_lines(repo.second, "a.txt"), first) + assert.same(first, second) + assert.are_not.equal(first, second, "cached reads must return independent arrays") + end) + + it("get_merge_base returns merge-base commit", function() + local err, revision = await(function(done) + git.get_merge_base("HEAD~1", "HEAD", repo.dir, done) + end) + assert.is_nil(err) + assert.equals(repo.first, revision) + end) + + it("get_merge_base handles invalid revision", function() + local err, revision = await(function(done) + git.get_merge_base("nonexistent-branch-12345", "HEAD", repo.dir, done) + end) + assert.is_not_nil(err) + assert.is_nil(revision) + end) +end) + +-- The untracked policy applies to both status and revision-comparison queries. +describe("Git untracked policy (#389)", function() + local repo, previous + + before_each(function() + previous = config.options.explorer.untracked + repo = h.create_temp_git_repo() + repo.write_file("tracked.txt", { "base" }) + repo.commit("initial") + repo.write_file("tracked.txt", { "changed" }) + repo.write_file("newfile.txt", { "u" }) + repo.write_file("untracked_dir/nested.txt", { "n" }) + end) + + after_each(function() + config.options.explorer.untracked = previous + if repo then + repo.cleanup() + end + end) + + local function unstaged_set(mode, revision) + config.options.explorer.untracked = mode + local err, status = await(function(done) + if revision then + git.get_diff_revision("HEAD", repo.dir, done) + else + git.get_status(repo.dir, done) + end + end) + assert.is_nil(err) + local paths = {} + for _, file in ipairs(status.unstaged) do + paths[file.path] = file.status + end + return paths + end + + it("all lists every untracked file individually (get_status)", function() + local paths = unstaged_set("all") + assert.is_not_nil(paths["newfile.txt"]) + assert.is_not_nil(paths["untracked_dir/nested.txt"]) + end) + + it("normal collapses untracked directories (get_status)", function() + local paths = unstaged_set("normal") + assert.is_not_nil(paths["newfile.txt"]) + assert.is_nil(paths["untracked_dir/nested.txt"]) + assert.is_not_nil(paths["untracked_dir/"]) + end) + + it("no skips untracked files entirely — the hang fix (get_status)", function() + local paths = unstaged_set("no") + assert.is_nil(paths["newfile.txt"]) + assert.is_nil(paths["untracked_dir/nested.txt"]) + assert.is_not_nil(paths["tracked.txt"]) + end) + + it("no skips the ls-files untracked scan (get_diff_revision)", function() + local paths = unstaged_set("no", true) + assert.is_nil(paths["newfile.txt"]) + assert.is_not_nil(paths["tracked.txt"]) + end) + + it("normal collapses untracked directories (get_diff_revision)", function() + local paths = unstaged_set("normal", true) + assert.is_not_nil(paths["untracked_dir/"]) + assert.is_nil(paths["untracked_dir/nested.txt"]) + end) + + it("defaults to all when the config value is invalid", function() + local paths = unstaged_set("bogus") + assert.is_not_nil(paths["untracked_dir/nested.txt"]) + end) +end) + +-- A read-only poll must not contend with staging for index.lock. +describe("Git read-only queries do not write the index (#494)", function() + local repo + + before_each(function() + repo = h.create_temp_git_repo() + repo.write_file("tracked.txt", { "base" }) + repo.commit("initial") + -- Older than the index even on filesystems with coarse mtime resolution. + local past = os.time() - 60 + assert((vim.uv or vim.loop).fs_utime(repo.path("tracked.txt"), past, past)) + end) + + after_each(function() + if repo then + repo.cleanup() + end + end) + + local function index_bytes() + return table.concat(vim.fn.readfile(repo.git_path("index"), "b"), "\n") + end + + it("get_status leaves .git/index untouched", function() + local before = index_bytes() + local err = await(function(done) + git.get_status(repo.dir, done) + end) + assert.is_nil(err) + assert.equals(before, index_bytes(), "read-only status must not rewrite the index") + end) + + it("read-only queries still succeed while another git process holds index.lock", function() + vim.fn.writefile({ "" }, repo.git_path("index.lock")) + local err = await(function(done) + git.get_diff_revision("HEAD", repo.dir, done) + end) + assert.is_nil(err, "a held index.lock must not fail a read-only query") + end) +end) + +-- Bootstrap configuration outranks Windows runners' autocrlf setting. +describe("Git output is free of line-ending warnings (#494)", function() + local repo + + before_each(function() + repo = h.create_temp_git_repo() + repo.command({ "config", "core.autocrlf", "true" }) + repo.write_file("file1.txt", { "alpha", "beta", "gamma" }) + repo.commit("initial") + repo.write_file("file1.txt", { "alpha", "BETA", "gamma" }) + end) + + after_each(function() + if repo then + repo.cleanup() + end + end) + + it("git_cmd output carries no CRLF conversion warning", function() + local output = repo.git("diff --name-only") + assert.is_nil(output:match("LF will be replaced by CRLF"), "line-ending warning must not pollute Git output") + assert.equals("file1.txt", vim.trim(output)) + end) + + it("core.autocrlf is pinned off for every git process", function() + assert.equals("false", vim.trim(repo.command({ "config", "--get", "core.autocrlf" }))) + end) +end) diff --git a/tests/core/rename_follow_spec.lua b/tests/integration/core/git/renames_spec.lua similarity index 96% rename from tests/core/rename_follow_spec.lua rename to tests/integration/core/git/renames_spec.lua index ec9f57c5..798e21f3 100644 --- a/tests/core/rename_follow_spec.lua +++ b/tests/integration/core/git/renames_spec.lua @@ -4,7 +4,7 @@ local git = require("codediff.core.git") local function create_rename_repo() - local repo = require("tests.framework.repository").new({ unborn = true }) + local repo = require("tests.support.repository").new({ unborn = true }) local function run(...) return repo.command({ ... }) end diff --git a/tests/core/restore_spec.lua b/tests/integration/core/git/restore_spec.lua similarity index 98% rename from tests/core/restore_spec.lua rename to tests/integration/core/git/restore_spec.lua index 0edc78a9..3bdd33a7 100644 --- a/tests/core/restore_spec.lua +++ b/tests/integration/core/git/restore_spec.lua @@ -5,7 +5,7 @@ local git = require("codediff.core.git") local function create_test_repo() - local repo = require("tests.framework.repository").new({ unborn = true }) + local repo = require("tests.support.repository").new({ unborn = true }) repo.write_file("file.txt", { "version 1" }) repo.commit1 = repo.commit("commit 1") repo.write_file("file.txt", { "version 2" }) diff --git a/tests/core/installer_spec.lua b/tests/integration/core/installer/library_spec.lua similarity index 95% rename from tests/core/installer_spec.lua rename to tests/integration/core/installer/library_spec.lua index db8a9cf8..fc442261 100644 --- a/tests/core/installer_spec.lua +++ b/tests/integration/core/installer/library_spec.lua @@ -3,6 +3,7 @@ local installer = require('codediff.core.installer.libvscode_diff') local version = require("codediff.version") +local test_root = require("tests.support").project_root describe("Installer Module", function() -- Test 1: Module loads correctly @@ -129,7 +130,7 @@ describe("Installer Module", function() -- (assumes manual build is always up to date), so only assert mismatch -- when no unversioned library is present if installed_version and installed_version ~= current_version then - local plugin_root = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":h:h:h") + local plugin_root = test_root local has_unversioned = vim.fn.filereadable(plugin_root .. "/libvscode_diff." .. (jit.os == "Windows" and "dll" or jit.os == "OSX" and "dylib" or "so")) == 1 if not has_unversioned then assert.is_true(installer.needs_update(), @@ -156,17 +157,7 @@ describe("Installer Module", function() -- Test 11: Priority of unversioned library (manual build) it("Prioritizes unversioned library over versioned one", function() local lib_path_initial = installer.get_lib_path() - if not lib_path_initial then - -- If nothing installed, we can't easily determine plugin root without internal access - -- But usually tests run with something installed. - -- Let's try to get plugin root from debug info like the module does - local source = debug.getinfo(1).source:sub(2) - local plugin_root = vim.fn.fnamemodify(source, ":h:h:h") - - -- Continue with test... - end - - local plugin_root = lib_path_initial and lib_path_initial:match("(.*/)") or vim.fn.fnamemodify(debug.getinfo(1).source:sub(2), ":h:h:h") .. "/" + local plugin_root = lib_path_initial and lib_path_initial:match("(.*/)") or test_root .. "/" local ext = require("ffi").os == "Windows" and "dll" or (require("ffi").os == "OSX" and "dylib" or "so") local unversioned_name = "libvscode_diff." .. ext local unversioned_path = plugin_root .. unversioned_name diff --git a/tests/core/watcher_install_spec.lua b/tests/integration/core/installer/watcher_spec.lua similarity index 100% rename from tests/core/watcher_install_spec.lua rename to tests/integration/core/installer/watcher_spec.lua diff --git a/tests/core/virtual_file_lsp_spec.lua b/tests/integration/core/virtual_file_spec.lua similarity index 99% rename from tests/core/virtual_file_lsp_spec.lua rename to tests/integration/core/virtual_file_spec.lua index e0845840..d3aa6509 100644 --- a/tests/core/virtual_file_lsp_spec.lua +++ b/tests/integration/core/virtual_file_spec.lua @@ -8,7 +8,7 @@ -- and PASS when TreeSitter is started directly without setting filetype. local virtual_file = require("codediff.core.virtual_file") -local h = dofile('tests/helpers.lua') +local h = require('tests.support') describe("Virtual buffer LSP prevention", function() it("prevents LSP attachment while keeping TreeSitter active", function() diff --git a/tests/integration/framework/runner_spec.lua b/tests/integration/framework/runner_spec.lua new file mode 100644 index 00000000..d5aa2c6f --- /dev/null +++ b/tests/integration/framework/runner_spec.lua @@ -0,0 +1,46 @@ +local repositories = require("tests.support.repository") + +describe("runner fixture cleanup", function() + local repo + + before_each(function() + repo = repositories.new() + end) + + after_each(function() + if repo then + repo.cleanup() + end + end) + + for _, cleanup_error in ipairs({ false, true }) do + it(cleanup_error and "reports cleanup failures even when fixture setup skips a case" or "skips unavailable fixture backends and still runs cleanup", function() + local script = repo.write_file("pending_fixture.lua", { + "local repo", + "describe('unavailable backend', function()", + " before_each(function()", + " repo = require('tests.support.repository').new({ unborn = true })", + " pending('backend unavailable')", + " end)", + " after_each(function()", + " repo.cleanup()", + cleanup_error and " error('expected cleanup failure')" or " assert(vim.fn.isdirectory(repo.root) == 0)", + " end)", + " it('does not run the body', function() error('body must not run') end)", + "end)", + }) + local result = vim + .system({ + vim.v.progpath, + "--headless", + "--noplugin", + "-u", + "tests/init.lua", + "-c", + "lua require('tests.framework').run_and_exit(" .. string.format("%q", script) .. ")", + }, { text = true, timeout = 30000 }) + :wait() + assert.equals(cleanup_error and 1 or 0, result.code, (result.stdout or "") .. (result.stderr or "")) + end) + end +end) diff --git a/tests/integration/framework/supervisor_spec.lua b/tests/integration/framework/supervisor_spec.lua new file mode 100644 index 00000000..8f1ace7d --- /dev/null +++ b/tests/integration/framework/supervisor_spec.lua @@ -0,0 +1,48 @@ +local supervisor = require("tests.framework.supervisor") +local h = require("tests.support") + +describe("test discovery and directory boundaries", function() + it("partitions every spec into exactly one test layer", function() + local all, combined, seen = supervisor.discover("all"), {}, {} + for _, layer in ipairs({ "unit", "integration", "e2e" }) do + local specs = supervisor.discover(layer) + assert.is_true(#specs > 0, "empty test layer: " .. layer) + assert.same(specs, supervisor.discover("tests/" .. layer)) + for _, spec in ipairs(specs) do + assert.is_nil(seen[spec], "spec discovered more than once: " .. spec) + seen[spec] = true + combined[#combined + 1] = spec + assert.is_nil(spec:match("_e2e_spec%.lua$"), "encode the test layer in its directory, not its filename") + end + end + table.sort(combined) + assert.same(all, combined, "a spec is outside unit/, integration/ or e2e/") + assert.same(all, supervisor.discover()) + end) + + it("keeps runnable specs out of test infrastructure and fixtures", function() + for _, dir in ipairs({ "framework", "support", "fixtures" }) do + assert.same({}, supervisor.discover("tests/" .. dir), "misplaced spec in " .. dir) + end + end) + + it("selects a feature directory without including adjacent features", function() + assert.same({ + "tests/unit/core/watcher/manager_spec.lua", + "tests/unit/core/watcher/protocol_spec.lua", + }, supervisor.discover("tests/unit/core/watcher")) + end) + + it("normalizes relative, absolute and Windows-style single-spec paths", function() + local spec = "tests/unit/core/path_spec.lua" + for _, target in ipairs({ spec, "./" .. spec, h.project_root .. "/" .. spec, (spec:gsub("/", "\\")) }) do + assert.same({ spec }, supervisor.discover(target)) + end + end) + + it("does not turn a missing target or support file into a successful selection", function() + assert.same({}, supervisor.discover("tests/not-a-test-layer")) + assert.same({}, supervisor.discover("tests/unit/missing_spec.lua")) + assert.same({}, supervisor.discover("tests/support/init.lua")) + end) +end) diff --git a/tests/keymap/keymap_coverage_spec.lua b/tests/integration/keymap/actions_spec.lua similarity index 99% rename from tests/keymap/keymap_coverage_spec.lua rename to tests/integration/keymap/actions_spec.lua index a04ccf26..3071c7c0 100644 --- a/tests/keymap/keymap_coverage_spec.lua +++ b/tests/integration/keymap/actions_spec.lua @@ -5,7 +5,7 @@ -- mapping can be listed yet unreachable if its lhs was encoded twice, which is -- exactly the regression that broke <2-LeftMouse>, and . -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local path = require("codediff.core.path") h.ensure_plugin_loaded() diff --git a/tests/keymap/golden_matrix_spec.lua b/tests/integration/keymap/golden_matrix_spec.lua similarity index 95% rename from tests/keymap/golden_matrix_spec.lua rename to tests/integration/keymap/golden_matrix_spec.lua index b703aa5f..2111147d 100644 --- a/tests/keymap/golden_matrix_spec.lua +++ b/tests/integration/keymap/golden_matrix_spec.lua @@ -6,11 +6,10 @@ -- identical fixture; an intended change produces a small, reviewable diff. -- -- Regenerate after an intentional change: --- CODEDIFF_WRITE_KEYMAP_GOLDEN=1 nvim --headless --noplugin -u tests/init.lua \ --- -c "lua require('plenary.test_harness').test_file('tests/ui/keymap/golden_matrix_spec.lua', { minimal_init = 'tests/init.lua' })" +-- CODEDIFF_WRITE_KEYMAP_GOLDEN=1 ./tests/run_tests.sh tests/integration/keymap/golden_matrix_spec.lua -local h = dofile("tests/helpers.lua") -local matrix = dofile("tests/keymap_matrix.lua") +local h = require("tests.support") +local matrix = require("tests.support.keymaps") local path = require("codediff.core.path") h.ensure_plugin_loaded() @@ -22,7 +21,7 @@ local view = require("codediff.ui.view") local lifecycle = require("codediff.ui.lifecycle") local compact = require("codediff.ui.view.compact") -local FIXTURE = "tests/fixtures/keymap_matrix.txt" +local FIXTURE = h.project_root .. "/tests/fixtures/keymap_matrix.txt" local WRITE_MODE = vim.env.CODEDIFF_WRITE_KEYMAP_GOLDEN == "1" -- Mappings capture at creation time, so the fixture would otherwise diff --git a/tests/keymap/keymap_help_spec.lua b/tests/integration/keymap/help_spec.lua similarity index 99% rename from tests/keymap/keymap_help_spec.lua rename to tests/integration/keymap/help_spec.lua index 25140162..dccb4359 100644 --- a/tests/keymap/keymap_help_spec.lua +++ b/tests/integration/keymap/help_spec.lua @@ -4,7 +4,7 @@ -- mappings actually installed (see #343). These tests pin the contract in both -- directions: everything shown is really bound, and nothing bound is missing. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local path = require("codediff.core.path") h.ensure_plugin_loaded() diff --git a/tests/keymap/keymap_lifecycle_spec.lua b/tests/integration/keymap/lifecycle_spec.lua similarity index 99% rename from tests/keymap/keymap_lifecycle_spec.lua rename to tests/integration/keymap/lifecycle_spec.lua index 1c5e9555..c9692686 100644 --- a/tests/keymap/keymap_lifecycle_spec.lua +++ b/tests/integration/keymap/lifecycle_spec.lua @@ -10,8 +10,8 @@ -- These fail against the pre-refactor implementation; that is -- the point — they are the executable specification. -local h = dofile("tests/helpers.lua") -local matrix = dofile("tests/keymap_matrix.lua") +local h = require("tests.support") +local matrix = require("tests.support.keymaps") local path = require("codediff.core.path") h.ensure_plugin_loaded() diff --git a/tests/keymap/issue_regressions_spec.lua b/tests/integration/keymap/ownership_regressions_spec.lua similarity index 99% rename from tests/keymap/issue_regressions_spec.lua rename to tests/integration/keymap/ownership_regressions_spec.lua index b0747a1b..b8825f68 100644 --- a/tests/keymap/issue_regressions_spec.lua +++ b/tests/integration/keymap/ownership_regressions_spec.lua @@ -9,7 +9,7 @@ -- -- The remaining checks are guard rails for issues fixed earlier, so this -- refactor cannot silently reopen them. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() local path = require("codediff.core.path") diff --git a/tests/keymap/registry_spec.lua b/tests/integration/keymap/registry_spec.lua similarity index 99% rename from tests/keymap/registry_spec.lua rename to tests/integration/keymap/registry_spec.lua index 16fa010a..a18f46a1 100644 --- a/tests/keymap/registry_spec.lua +++ b/tests/integration/keymap/registry_spec.lua @@ -1,4 +1,4 @@ --- Unit tests for the keymap slot arbiter and per-session registry. +-- Integration tests for the keymap registry and Neovim's real buffer mappings. -- These exercise the machinery directly on scratch buffers, independent of any -- diff session, so ownership logic can be reviewed in isolation. diff --git a/tests/api_spec.lua b/tests/integration/plugin/api_spec.lua similarity index 100% rename from tests/api_spec.lua rename to tests/integration/plugin/api_spec.lua diff --git a/tests/module_loading_spec.lua b/tests/integration/plugin/modules_spec.lua similarity index 100% rename from tests/module_loading_spec.lua rename to tests/integration/plugin/modules_spec.lua diff --git a/tests/lazy_spec.lua b/tests/integration/plugin/setup_spec.lua similarity index 100% rename from tests/lazy_spec.lua rename to tests/integration/plugin/setup_spec.lua diff --git a/tests/framework/repository_spec.lua b/tests/integration/support/repository_spec.lua similarity index 71% rename from tests/framework/repository_spec.lua rename to tests/integration/support/repository_spec.lua index 7bc9ea5e..f4c88940 100644 --- a/tests/framework/repository_spec.lua +++ b/tests/integration/support/repository_spec.lua @@ -1,4 +1,4 @@ -local repositories = require("tests.framework.repository") +local repositories = require("tests.support.repository") describe("isolated fixture worktrees", function() local repos @@ -28,6 +28,7 @@ describe("isolated fixture worktrees", function() it("preserves an unborn main branch and creates a parentless first commit", function() local repo = new({ unborn = true }) assert.equals(1, vim.fn.filereadable(repo.path(".git"))) + assert.equals(1, select("#", repo.git_path("index")), "git_path returns only a path, not gsub's replacement count") assert.equals("true", vim.trim(repo.command({ "rev-parse", "--is-inside-work-tree" }))) assert.equals("main", vim.trim(repo.command({ "symbolic-ref", "--short", "HEAD" }))) assert.equals("", repo.command({ "remote" }), "fixtures must not retain a remote pointing at their seed") @@ -73,38 +74,6 @@ describe("isolated fixture worktrees", function() assert.equals("", repo.command({ "remote" })) end) - for _, cleanup_error in ipairs({ false, true }) do - it(cleanup_error and "reports cleanup failures even when fixture setup skips a case" or "skips unavailable fixture backends and still runs cleanup", function() - local repo = new() - local script = repo.write_file("pending_fixture.lua", { - "local repo", - "describe('unavailable backend', function()", - " before_each(function()", - " repo = require('tests.framework.repository').new({ unborn = true })", - " pending('backend unavailable')", - " end)", - " after_each(function()", - " repo.cleanup()", - cleanup_error and " error('expected cleanup failure')" or " assert(vim.fn.isdirectory(repo.root) == 0)", - " end)", - " it('does not run the body', function() error('body must not run') end)", - "end)", - }) - local result = vim - .system({ - vim.v.progpath, - "--headless", - "--noplugin", - "-u", - "tests/init.lua", - "-c", - "lua require('tests.framework').run_and_exit(" .. string.format("%q", script) .. ")", - }, { text = true }) - :wait() - assert.equals(cleanup_error and 1 or 0, result.code, (result.stdout or "") .. (result.stderr or "")) - end) - end - it("removes the worktree and its Git metadata and leaves a valid current directory", function() local repo = new() vim.fn.chdir(repo.dir) diff --git a/tests/ui/conflict/conflict_accept_all_spec.lua b/tests/integration/ui/conflict/accept_all_spec.lua similarity index 100% rename from tests/ui/conflict/conflict_accept_all_spec.lua rename to tests/integration/ui/conflict/accept_all_spec.lua diff --git a/tests/ui/conflict/issue_353_spec.lua b/tests/integration/ui/conflict/auto_merge_spec.lua similarity index 99% rename from tests/ui/conflict/issue_353_spec.lua rename to tests/integration/ui/conflict/auto_merge_spec.lua index 5b350b0c..03c33bff 100644 --- a/tests/ui/conflict/issue_353_spec.lua +++ b/tests/integration/ui/conflict/auto_merge_spec.lua @@ -9,7 +9,7 @@ -- auto-merged content (BASE + every non-conflicting change from both sides) -- and only true two-sided conflicts are left as BASE for the user to resolve. -local h = require('tests.helpers') +local h = require('tests.support') local diff_module = require('codediff.core.diff') local merge_alignment = require('codediff.ui.conflict.merge') diff --git a/tests/ui/conflict/conflict_file_switch_spec.lua b/tests/integration/ui/conflict/file_switch_spec.lua similarity index 99% rename from tests/ui/conflict/conflict_file_switch_spec.lua rename to tests/integration/ui/conflict/file_switch_spec.lua index 496a3a00..146916cf 100644 --- a/tests/ui/conflict/conflict_file_switch_spec.lua +++ b/tests/integration/ui/conflict/file_switch_spec.lua @@ -8,7 +8,7 @@ -- holds unsaved merge edits -- so `:edit` failed with E37 "No write since last -- change" and the result pane never came back. -local h = require("tests.helpers") +local h = require("tests.support") local path = require("codediff.core.path") describe("conflict mode single-file switching", function() diff --git a/tests/ui/conflict/gutter_grid_spec.lua b/tests/integration/ui/conflict/gutter_grid_spec.lua similarity index 99% rename from tests/ui/conflict/gutter_grid_spec.lua rename to tests/integration/ui/conflict/gutter_grid_spec.lua index bb493f82..16e9fa33 100644 --- a/tests/ui/conflict/gutter_grid_spec.lua +++ b/tests/integration/ui/conflict/gutter_grid_spec.lua @@ -1,5 +1,5 @@ local Screen = require("tests.framework.screen") -local gutter = require("tests.ui.conflict.gutter_helpers") +local gutter = require("tests.support.gutter") local cases = require("tests.fixtures.conflict_gutter") describe("conflict block gutter on the screen grid", function() diff --git a/tests/ui/conflict/gutter_lifecycle_spec.lua b/tests/integration/ui/conflict/gutter_lifecycle_spec.lua similarity index 94% rename from tests/ui/conflict/gutter_lifecycle_spec.lua rename to tests/integration/ui/conflict/gutter_lifecycle_spec.lua index 4603dbc3..e68883fd 100644 --- a/tests/ui/conflict/gutter_lifecycle_spec.lua +++ b/tests/integration/ui/conflict/gutter_lifecycle_spec.lua @@ -1,11 +1,12 @@ local Screen = require("tests.framework.screen") -local gutter = require("tests.ui.conflict.gutter_helpers") +local gutter = require("tests.support.gutter") +local fixture = require("tests.fixtures.conflict_gutter") describe("conflict gutter lifecycle on the screen grid", function() local screen, repo, panes before_each(function() - repo = gutter.create_repo() + repo = fixture.new_repo() screen = Screen.new(120, 40) panes = gutter.open_merge(screen, repo) end) @@ -22,7 +23,7 @@ describe("conflict gutter lifecycle on the screen grid", function() end) local function expect_merge(rows, colors) - rows = rows or gutter.merge_rows + rows = rows or fixture.merge_rows for _, focus in ipairs({ "original", "modified", "result" }) do screen:exec("vim.api.nvim_set_current_win(...)", { panes[focus] }) screen:flush() @@ -91,7 +92,7 @@ describe("conflict gutter lifecycle on the screen grid", function() it("rebinds a recreated current pane after a deleted file", function() panes = gutter.return_to_merge(screen, "other.txt") - expect_merge(gutter.other_merge_rows) + expect_merge(fixture.other_merge_rows) screen:exec( [[ local root = ... @@ -100,12 +101,12 @@ describe("conflict gutter lifecycle on the screen grid", function() { repo.dir } ) panes = gutter.return_to_merge(screen, "other.txt") - expect_merge(gutter.other_merge_rows) + expect_merge(fixture.other_merge_rows) end) it("replaces marker maps when switching between two conflict files", function() panes = gutter.return_to_merge(screen, "other.txt") - expect_merge(gutter.other_merge_rows) + expect_merge(fixture.other_merge_rows) panes = gutter.return_to_merge(screen) expect_merge() end) @@ -132,7 +133,7 @@ describe("conflict gutter lifecycle on the screen grid", function() vim.api.nvim_win_set_cursor(s.modified_win, { 2, 0 }) assert(require('codediff.ui.conflict').accept_current(gutter_test_tab)) ]]) - local resolved = vim.deepcopy(gutter.merge_rows) + local resolved = vim.deepcopy(fixture.merge_rows) resolved.result = { " before", "╭─OURS1", "│ inserted", "│ OURS2", "╰─base3", " after", " tail" } expect_merge(resolved, colors("Rejected", "Accepted", "Resolved")) @@ -171,7 +172,7 @@ describe("conflict gutter lifecycle on the screen grid", function() screen:wait_for(function() return screen:exec("return not require('codediff.ui.lifecycle').get_session(gutter_test_tab).suspended") end) - local rows = vim.deepcopy(gutter.merge_rows) + local rows = vim.deepcopy(fixture.merge_rows) rows.result = { " before", "╭─OURS1", "│ inserted", "│ OURS2", "╰─base3", " after", " tail" } expect_merge(rows, colors("Rejected", "Accepted", "Resolved")) end) @@ -182,7 +183,7 @@ describe("conflict gutter lifecycle on the screen grid", function() screen:wait_for(function() return screen:exec("return vim.api.nvim_buf_line_count(...) == 3", { panes.result_buf }) end) - local rows = vim.deepcopy(gutter.merge_rows) + local rows = vim.deepcopy(fixture.merge_rows) rows.result = { "before", "after", "tail" } expect_merge(rows, colors("Resolved", "Resolved", "Resolved")) end) @@ -193,7 +194,7 @@ describe("conflict gutter lifecycle on the screen grid", function() screen:wait_for(function() return screen:exec("return vim.api.nvim_buf_get_lines(..., 1, 2, false)[1] == 'MANUAL'", { panes.result_buf }) end) - local rows = vim.deepcopy(gutter.merge_rows) + local rows = vim.deepcopy(fixture.merge_rows) rows.result[2] = "╭─MANUAL" expect_merge(rows, colors("Resolved", "Resolved", "Resolved")) end) diff --git a/tests/ui/conflict/gutter_options_spec.lua b/tests/integration/ui/conflict/gutter_options_spec.lua similarity index 100% rename from tests/ui/conflict/gutter_options_spec.lua rename to tests/integration/ui/conflict/gutter_options_spec.lua diff --git a/tests/ui/conflict/inline_tab_conflict_spec.lua b/tests/integration/ui/conflict/inline_tab_conflict_spec.lua similarity index 99% rename from tests/ui/conflict/inline_tab_conflict_spec.lua rename to tests/integration/ui/conflict/inline_tab_conflict_spec.lua index a1eb57a3..590740a4 100644 --- a/tests/ui/conflict/inline_tab_conflict_spec.lua +++ b/tests/integration/ui/conflict/inline_tab_conflict_spec.lua @@ -3,7 +3,7 @@ -- then wrote both into that window, THEIRS overwriting OURS, and never opened -- the result pane. :CodeDiff was fine; it goes through create. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") describe("conflicted file in an inline tab", function() local repo, saved_layout diff --git a/tests/ui/conflict/issue_387_spec.lua b/tests/integration/ui/conflict/input_highlights_spec.lua similarity index 99% rename from tests/ui/conflict/issue_387_spec.lua rename to tests/integration/ui/conflict/input_highlights_spec.lua index d75cfcf9..d6f7cc98 100644 --- a/tests/ui/conflict/issue_387_spec.lua +++ b/tests/integration/ui/conflict/input_highlights_spec.lua @@ -5,7 +5,7 @@ -- TextChanged-like event without being overwritten by the normal diff -- renderer's red/green scheme. -local h = require('tests.helpers') +local h = require('tests.support') local path = require("codediff.core.path") describe('Issue #387 regression — conflict-mode input panes stay green on TextChanged', function() diff --git a/tests/ui/conflict/merge_keymap_ownership_spec.lua b/tests/integration/ui/conflict/keymap_ownership_spec.lua similarity index 99% rename from tests/ui/conflict/merge_keymap_ownership_spec.lua rename to tests/integration/ui/conflict/keymap_ownership_spec.lua index 9b61a343..45437029 100644 --- a/tests/ui/conflict/merge_keymap_ownership_spec.lua +++ b/tests/integration/ui/conflict/keymap_ownership_spec.lua @@ -9,7 +9,7 @@ -- from a distance: setup_all_keymaps decides via `is_conflict`, and any change -- to how a session reports "I am a merge view" lands here first. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local path = require("codediff.core.path") --- What `key` actually resolves to in `bufnr`, and whether it is buffer-local. diff --git a/tests/ui/conflict/conflict_layout_spec.lua b/tests/integration/ui/conflict/layout_spec.lua similarity index 98% rename from tests/ui/conflict/conflict_layout_spec.lua rename to tests/integration/ui/conflict/layout_spec.lua index 9435055d..588e6044 100644 --- a/tests/ui/conflict/conflict_layout_spec.lua +++ b/tests/integration/ui/conflict/layout_spec.lua @@ -1,4 +1,4 @@ -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local path = require("codediff.core.path") describe("conflict editor layout", function() diff --git a/tests/ui/conflict/conflict_navigation_spec.lua b/tests/integration/ui/conflict/navigation_spec.lua similarity index 100% rename from tests/ui/conflict/conflict_navigation_spec.lua rename to tests/integration/ui/conflict/navigation_spec.lua diff --git a/tests/ui/conflict/conflict_resolution_spec.lua b/tests/integration/ui/conflict/resolution_spec.lua similarity index 100% rename from tests/ui/conflict/conflict_resolution_spec.lua rename to tests/integration/ui/conflict/resolution_spec.lua diff --git a/tests/ui/conflict/conflict_dedup_spec.lua b/tests/integration/ui/conflict/selection_dedup_spec.lua similarity index 100% rename from tests/ui/conflict/conflict_dedup_spec.lua rename to tests/integration/ui/conflict/selection_dedup_spec.lua diff --git a/tests/ui/conflict/conflict_signs_spec.lua b/tests/integration/ui/conflict/signs_spec.lua similarity index 100% rename from tests/ui/conflict/conflict_signs_spec.lua rename to tests/integration/ui/conflict/signs_spec.lua diff --git a/tests/ui/conflict/conflict_spec.lua b/tests/integration/ui/conflict/tracking_spec.lua similarity index 100% rename from tests/ui/conflict/conflict_spec.lua rename to tests/integration/ui/conflict/tracking_spec.lua diff --git a/tests/ui/explorer/explorer_spec.lua b/tests/integration/ui/explorer/creation_spec.lua similarity index 97% rename from tests/ui/explorer/explorer_spec.lua rename to tests/integration/ui/explorer/creation_spec.lua index 7559f932..29985fe2 100644 --- a/tests/ui/explorer/explorer_spec.lua +++ b/tests/integration/ui/explorer/creation_spec.lua @@ -3,7 +3,7 @@ local git = require('codediff.core.git') local config = require("codediff.config") -local h = dofile('tests/helpers.lua') +local h = require('tests.support') -- Setup CodeDiff command for tests local function setup_command() @@ -658,18 +658,10 @@ describe("Explorer Mode", function() -- Test 10: Commands.lua simplicity (no callbacks in commands) it("Commands.lua follows simple pattern", function() - -- This is a design validation test - -- Verify commands.lua doesn't contain on_file_select - local commands_path = vim.fn.fnamemodify(debug.getinfo(1).source:sub(2), ":h:h") - .. "/lua/vscode-diff/commands.lua" - - if vim.fn.filereadable(commands_path) == 1 then - local content = table.concat(vim.fn.readfile(commands_path), "\n") - -- Should NOT define on_file_select in commands.lua - local has_callback_def = content:match("local%s+function%s+on_file_select") - assert.is_nil(has_callback_def, - "Commands.lua should not define on_file_select callback") - end + local commands_path = h.project_root .. "/lua/codediff/commands/handlers/explorer.lua" + assert.equals(1, vim.fn.filereadable(commands_path), "the current command handler must exist") + local content = table.concat(vim.fn.readfile(commands_path), "\n") + assert.is_nil(content:match("local%s+function%s+on_file_select"), "commands must not define panel selection callbacks") end) end) diff --git a/tests/ui/explorer/issue_390_spec.lua b/tests/integration/ui/explorer/deleted_revision_spec.lua similarity index 99% rename from tests/ui/explorer/issue_390_spec.lua rename to tests/integration/ui/explorer/deleted_revision_spec.lua index 92e935b7..c403b6a3 100644 --- a/tests/ui/explorer/issue_390_spec.lua +++ b/tests/integration/ui/explorer/deleted_revision_spec.lua @@ -2,7 +2,7 @@ -- Selecting a deleted file in `:CodeDiff HEAD~N` mode must load its content -- from HEAD~N, not from `:0`/`HEAD` (where the file is already gone). -local h = require('tests.helpers') +local h = require('tests.support') describe('Issue #390 regression — deleted file shows content in revision mode', function() local repo diff --git a/tests/ui/explorer/file_select_branches_spec.lua b/tests/integration/ui/explorer/file_select_branches_spec.lua similarity index 99% rename from tests/ui/explorer/file_select_branches_spec.lua rename to tests/integration/ui/explorer/file_select_branches_spec.lua index 0fab78e7..6acd1021 100644 --- a/tests/ui/explorer/file_select_branches_spec.lua +++ b/tests/integration/ui/explorer/file_select_branches_spec.lua @@ -2,7 +2,7 @@ -- added in the revision being viewed, and directory comparison mode. Stubbing -- either left all 90 specs green. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local function open_explorer_on(dir, focus_file) local lifecycle = require("codediff.ui.lifecycle") diff --git a/tests/ui/explorer/hunk_operations_spec.lua b/tests/integration/ui/explorer/hunk_operations_spec.lua similarity index 98% rename from tests/ui/explorer/hunk_operations_spec.lua rename to tests/integration/ui/explorer/hunk_operations_spec.lua index 0ae833df..5c666f9e 100644 --- a/tests/ui/explorer/hunk_operations_spec.lua +++ b/tests/integration/ui/explorer/hunk_operations_spec.lua @@ -1,14 +1,8 @@ --- Test: Hunk-level staging, unstaging, and discard operations via real keymaps --- --- These are E2E tests that invoke actual keymap callbacks (stage_hunk, --- unstage_hunk, discard_hunk) on diff buffers, plus explorer-level --- stage_all / unstage_all, and verify that the diff view, highlights, --- and session state update correctly. --- --- Unlike stale_buffer_spec.lua (which calls refresh.refresh directly), --- these tests drive the full keymap → git apply → async refresh pipeline. - -local h = dofile("tests/helpers.lua") +-- Integration from registered keymap callbacks through Git and view refresh. +-- These invoke callbacks directly and inspect buffers/extmarks. Actual keyboard +-- and screen coverage lives in tests/e2e/view/hunk_actions_spec.lua. + +local h = require("tests.support") -- Ensure plugin is loaded (needed when the test framework isolates specs) h.ensure_plugin_loaded() diff --git a/tests/ui/explorer/line_formatters_spec.lua b/tests/integration/ui/explorer/line_formatters_spec.lua similarity index 100% rename from tests/ui/explorer/line_formatters_spec.lua rename to tests/integration/ui/explorer/line_formatters_spec.lua diff --git a/tests/ui/explorer/line_stats_spec.lua b/tests/integration/ui/explorer/line_stats_spec.lua similarity index 100% rename from tests/ui/explorer/line_stats_spec.lua rename to tests/integration/ui/explorer/line_stats_spec.lua diff --git a/tests/ui/explorer/refresh_keeps_view_spec.lua b/tests/integration/ui/explorer/refresh_keeps_view_spec.lua similarity index 99% rename from tests/ui/explorer/refresh_keeps_view_spec.lua rename to tests/integration/ui/explorer/refresh_keeps_view_spec.lua index 6c4a2554..19b734cb 100644 --- a/tests/ui/explorer/refresh_keeps_view_spec.lua +++ b/tests/integration/ui/explorer/refresh_keeps_view_spec.lua @@ -5,7 +5,7 @@ -- means the panel reshuffles under the user. Both were uncovered -- stubbing -- the collapse capture or the cursor capture left the whole suite green. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() describe("explorer refresh keeps the user's view", function() diff --git a/tests/ui/explorer/explorer_refresh_spec.lua b/tests/integration/ui/explorer/refresh_spec.lua similarity index 98% rename from tests/ui/explorer/explorer_refresh_spec.lua rename to tests/integration/ui/explorer/refresh_spec.lua index 53394b69..3a3c596c 100644 --- a/tests/ui/explorer/explorer_refresh_spec.lua +++ b/tests/integration/ui/explorer/refresh_spec.lua @@ -10,12 +10,12 @@ -- the window every time and the layout pass discarded any manual sizing. -- show_single_file now skips the rebuild when nothing changed. -- --- Split from tests/ui/explorer/explorer_spec.lua so the two describe blocks +-- Split from tests/integration/ui/explorer/creation_spec.lua so the two describe blocks -- (one for open/layout, one for refresh) can run as independent workers under -- the framework's per-file parallelism. local config = require("codediff.config") -local h = dofile("tests/helpers.lua") +local h = require("tests.support") -- Setup CodeDiff command for tests local function setup_command() diff --git a/tests/ui/explorer/reselect_spec.lua b/tests/integration/ui/explorer/reselect_spec.lua similarity index 99% rename from tests/ui/explorer/reselect_spec.lua rename to tests/integration/ui/explorer/reselect_spec.lua index 73337703..cbe57d93 100644 --- a/tests/ui/explorer/reselect_spec.lua +++ b/tests/integration/ui/explorer/reselect_spec.lua @@ -1,7 +1,7 @@ -- Re-selecting the file already on screen must not rebuild the diff: the -- rebuild repaints, the repaint fires another refresh. That is #317 and #401. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() describe("explorer re-selection", function() diff --git a/tests/ui/explorer/revision_explorer_spec.lua b/tests/integration/ui/explorer/revision_explorer_spec.lua similarity index 98% rename from tests/ui/explorer/revision_explorer_spec.lua rename to tests/integration/ui/explorer/revision_explorer_spec.lua index 8e23247b..0ea1438b 100644 --- a/tests/ui/explorer/revision_explorer_spec.lua +++ b/tests/integration/ui/explorer/revision_explorer_spec.lua @@ -5,7 +5,7 @@ -- test -- and it has to be one `-M` will report, hence a file long enough to -- stay recognisable after an edit. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") describe("explorer opened against a revision", function() local repo, saved_cwd diff --git a/tests/ui/explorer/explorer_scroll_independence_spec.lua b/tests/integration/ui/explorer/scroll_independence_spec.lua similarity index 99% rename from tests/ui/explorer/explorer_scroll_independence_spec.lua rename to tests/integration/ui/explorer/scroll_independence_spec.lua index ec33d90f..cabd5442 100644 --- a/tests/ui/explorer/explorer_scroll_independence_spec.lua +++ b/tests/integration/ui/explorer/scroll_independence_spec.lua @@ -1,7 +1,7 @@ -- Regression: the explorer pane must NOT scroll together with the side-by-side -- diff panes. Native scrollbind is enabled only on the diff windows. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") -- Ensure plugin is loaded (registers the :CodeDiff command for the subprocess). h.ensure_plugin_loaded() diff --git a/tests/ui/explorer/explorer_staging_spec.lua b/tests/integration/ui/explorer/staging_spec.lua similarity index 99% rename from tests/ui/explorer/explorer_staging_spec.lua rename to tests/integration/ui/explorer/staging_spec.lua index 5bc999b5..bb2b013d 100644 --- a/tests/ui/explorer/explorer_staging_spec.lua +++ b/tests/integration/ui/explorer/staging_spec.lua @@ -1,7 +1,7 @@ -- Test explorer staging/unstaging workflow with virtual files -- This tests buffer management during file switching in explorer mode -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local path = require("codediff.core.path") -- Ensure plugin is loaded (needed when the test framework isolates specs) diff --git a/tests/ui/explorer/stale_buffer_spec.lua b/tests/integration/ui/explorer/stale_buffer_spec.lua similarity index 98% rename from tests/ui/explorer/stale_buffer_spec.lua rename to tests/integration/ui/explorer/stale_buffer_spec.lua index 3397a591..f91e7d18 100644 --- a/tests/ui/explorer/stale_buffer_spec.lua +++ b/tests/integration/ui/explorer/stale_buffer_spec.lua @@ -1,10 +1,10 @@ -- Test: Welcome page after git operations (commit, stash) -- Validates that diff panes show welcome page when all changes are resolved. -- --- Staging/unstaging E2E tests are in hunk_operations_spec.lua (keymap-driven). +-- Callback-driven staging integration is in hunk_operations_spec.lua. -- These tests cover commit and stash operations that remove files from the tree. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") -- Ensure plugin is loaded (needed when the test framework isolates specs) h.ensure_plugin_loaded() diff --git a/tests/ui/explorer/toggle_staged_view_spec.lua b/tests/integration/ui/explorer/toggle_staged_view_spec.lua similarity index 99% rename from tests/ui/explorer/toggle_staged_view_spec.lua rename to tests/integration/ui/explorer/toggle_staged_view_spec.lua index d063d163..8c435ace 100644 --- a/tests/ui/explorer/toggle_staged_view_spec.lua +++ b/tests/integration/ui/explorer/toggle_staged_view_spec.lua @@ -4,7 +4,7 @@ -- currently reviewed file. Only meaningful in Status Mode; a no-op in -- revision, directory, or --staged modes. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") describe("toggle_staged_view (issue #352)", function() local repo diff --git a/tests/ui/explorer/explorer_tree_render_spec.lua b/tests/integration/ui/explorer/tree_render_spec.lua similarity index 99% rename from tests/ui/explorer/explorer_tree_render_spec.lua rename to tests/integration/ui/explorer/tree_render_spec.lua index 831f5f46..e7c9e5df 100644 --- a/tests/ui/explorer/explorer_tree_render_spec.lua +++ b/tests/integration/ui/explorer/tree_render_spec.lua @@ -1,6 +1,6 @@ -- Explorer tree content and file navigation. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() describe("Explorer tree render", function() diff --git a/tests/ui/explorer/issue_498_spec.lua b/tests/integration/ui/explorer/unborn_spec.lua similarity index 99% rename from tests/ui/explorer/issue_498_spec.lua rename to tests/integration/ui/explorer/unborn_spec.lua index 75e5915a..01178265 100644 --- a/tests/ui/explorer/issue_498_spec.lua +++ b/tests/integration/ui/explorer/unborn_spec.lua @@ -11,7 +11,7 @@ -- an AM file, future callers) just works without knowing about the unborn -- special case. -local h = require("tests.helpers") +local h = require("tests.support") describe("Issue #498 regression — unborn HEAD is treated as the empty tree", function() local repo diff --git a/tests/ui/explorer/explorer_visibility_spec.lua b/tests/integration/ui/explorer/visibility_spec.lua similarity index 98% rename from tests/ui/explorer/explorer_visibility_spec.lua rename to tests/integration/ui/explorer/visibility_spec.lua index c298a04a..493bca19 100644 --- a/tests/ui/explorer/explorer_visibility_spec.lua +++ b/tests/integration/ui/explorer/visibility_spec.lua @@ -1,6 +1,6 @@ -- Explorer hide/show (toggle visibility). -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() describe("Explorer toggle visibility", function() diff --git a/tests/ui/explorer/explorer_window_layout_spec.lua b/tests/integration/ui/explorer/window_layout_spec.lua similarity index 98% rename from tests/ui/explorer/explorer_window_layout_spec.lua rename to tests/integration/ui/explorer/window_layout_spec.lua index 6a8a1d3d..b6324b8f 100644 --- a/tests/ui/explorer/explorer_window_layout_spec.lua +++ b/tests/integration/ui/explorer/window_layout_spec.lua @@ -2,7 +2,7 @@ -- Verifies that :CodeDiff opens the explorer at the LEFTMOST column (not -- between the diff panes) and that the diff panes appear to its right. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() describe("Explorer window layout", function() diff --git a/tests/ui/filler_spec.lua b/tests/integration/ui/filler_spec.lua similarity index 100% rename from tests/ui/filler_spec.lua rename to tests/integration/ui/filler_spec.lua diff --git a/tests/ui/gutter_signs_spec.lua b/tests/integration/ui/gutter_signs_spec.lua similarity index 100% rename from tests/ui/gutter_signs_spec.lua rename to tests/integration/ui/gutter_signs_spec.lua diff --git a/tests/ui/highlights_spec.lua b/tests/integration/ui/highlights_spec.lua similarity index 100% rename from tests/ui/highlights_spec.lua rename to tests/integration/ui/highlights_spec.lua diff --git a/tests/ui/history/history_commit_files_spec.lua b/tests/integration/ui/history/commit_files_spec.lua similarity index 99% rename from tests/ui/history/history_commit_files_spec.lua rename to tests/integration/ui/history/commit_files_spec.lua index 5627fec6..a01346ed 100644 --- a/tests/ui/history/history_commit_files_spec.lua +++ b/tests/integration/ui/history/commit_files_spec.lua @@ -3,7 +3,7 @@ -- history_file_filter_spec covers filter.apply itself; this covers whether -- session data reaches the history view with the filter applied. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() --- Expand the newest commit and return the panel's rendered lines. diff --git a/tests/ui/history/history_initial_file_spec.lua b/tests/integration/ui/history/initial_file_spec.lua similarity index 98% rename from tests/ui/history/history_initial_file_spec.lua rename to tests/integration/ui/history/initial_file_spec.lua index 32748e84..8496d17a 100644 --- a/tests/ui/history/history_initial_file_spec.lua +++ b/tests/integration/ui/history/initial_file_spec.lua @@ -5,7 +5,7 @@ -- Neither had coverage: stubbing the selection, or the directory expansion, -- left the whole suite green. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() --- Wait until the history tab has a diff session with content on both sides. diff --git a/tests/ui/history/history_layout_spec.lua b/tests/integration/ui/history/layout_spec.lua similarity index 98% rename from tests/ui/history/history_layout_spec.lua rename to tests/integration/ui/history/layout_spec.lua index c241757f..1e90c85d 100644 --- a/tests/ui/history/history_layout_spec.lua +++ b/tests/integration/ui/history/layout_spec.lua @@ -1,6 +1,6 @@ -- History panel layout and content. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() describe("History layout", function() diff --git a/tests/ui/history/history_refresh_watcher_spec.lua b/tests/integration/ui/history/refresh_spec.lua similarity index 98% rename from tests/ui/history/history_refresh_watcher_spec.lua rename to tests/integration/ui/history/refresh_spec.lua index 84d61094..b8c09cd0 100644 --- a/tests/ui/history/history_refresh_watcher_spec.lua +++ b/tests/integration/ui/history/refresh_spec.lua @@ -1,4 +1,4 @@ -local h = require("tests.helpers") +local h = require("tests.support") local lifecycle = require("codediff.ui.lifecycle") local refresh = require("codediff.ui.refresh") local path = require("codediff.core.path") diff --git a/tests/ui/inline_spec.lua b/tests/integration/ui/inline_spec.lua similarity index 100% rename from tests/ui/inline_spec.lua rename to tests/integration/ui/inline_spec.lua diff --git a/tests/ui/inline_syntax_spec.lua b/tests/integration/ui/inline_syntax_spec.lua similarity index 100% rename from tests/ui/inline_syntax_spec.lua rename to tests/integration/ui/inline_syntax_spec.lua diff --git a/tests/ui/layout_spec.lua b/tests/integration/ui/layout_spec.lua similarity index 100% rename from tests/ui/layout_spec.lua rename to tests/integration/ui/layout_spec.lua diff --git a/tests/ui/lifecycle/close_spec.lua b/tests/integration/ui/lifecycle/close_spec.lua similarity index 100% rename from tests/ui/lifecycle/close_spec.lua rename to tests/integration/ui/lifecycle/close_spec.lua diff --git a/tests/ui/lifecycle/placeholder_paths_spec.lua b/tests/integration/ui/lifecycle/placeholder_paths_spec.lua similarity index 98% rename from tests/ui/lifecycle/placeholder_paths_spec.lua rename to tests/integration/ui/lifecycle/placeholder_paths_spec.lua index 26171ad5..21bdc7fe 100644 --- a/tests/ui/lifecycle/placeholder_paths_spec.lua +++ b/tests/integration/ui/lifecycle/placeholder_paths_spec.lua @@ -3,7 +3,7 @@ -- index a string, so those reads answered nil instead of failing. Both are -- path.empty() now; this pins that. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") describe("placeholder session paths", function() local repo, captured, restore diff --git a/tests/ui/lifecycle/lifecycle_spec.lua b/tests/integration/ui/lifecycle/session_spec.lua similarity index 100% rename from tests/ui/lifecycle/lifecycle_spec.lua rename to tests/integration/ui/lifecycle/session_spec.lua diff --git a/tests/ui/move_virtlines_spec.lua b/tests/integration/ui/move_virtlines_spec.lua similarity index 100% rename from tests/ui/move_virtlines_spec.lua rename to tests/integration/ui/move_virtlines_spec.lua diff --git a/tests/ui/explorer/native_watcher_spec.lua b/tests/integration/ui/refresh/controller_spec.lua similarity index 100% rename from tests/ui/explorer/native_watcher_spec.lua rename to tests/integration/ui/refresh/controller_spec.lua diff --git a/tests/ui/auto_refresh_spec.lua b/tests/integration/ui/refresh/inputs_spec.lua similarity index 100% rename from tests/ui/auto_refresh_spec.lua rename to tests/integration/ui/refresh/inputs_spec.lua diff --git a/tests/ui/render_core_spec.lua b/tests/integration/ui/render_spec.lua similarity index 100% rename from tests/ui/render_core_spec.lua rename to tests/integration/ui/render_spec.lua diff --git a/tests/scrollbind_spec.lua b/tests/integration/ui/scrollbind_spec.lua similarity index 100% rename from tests/scrollbind_spec.lua rename to tests/integration/ui/scrollbind_spec.lua diff --git a/tests/ui/view/autoscroll_spec.lua b/tests/integration/ui/view/autoscroll_spec.lua similarity index 100% rename from tests/ui/view/autoscroll_spec.lua rename to tests/integration/ui/view/autoscroll_spec.lua diff --git a/tests/ui/view/compact_spec.lua b/tests/integration/ui/view/compact_spec.lua similarity index 100% rename from tests/ui/view/compact_spec.lua rename to tests/integration/ui/view/compact_spec.lua diff --git a/tests/ui/view/view_spec.lua b/tests/integration/ui/view/creation_spec.lua similarity index 100% rename from tests/ui/view/view_spec.lua rename to tests/integration/ui/view/creation_spec.lua diff --git a/tests/ui/view/cycle_hunks_across_files_spec.lua b/tests/integration/ui/view/cycle_hunks_across_files_spec.lua similarity index 99% rename from tests/ui/view/cycle_hunks_across_files_spec.lua rename to tests/integration/ui/view/cycle_hunks_across_files_spec.lua index fbe083c6..d9a4801c 100644 --- a/tests/ui/view/cycle_hunks_across_files_spec.lua +++ b/tests/integration/ui/view/cycle_hunks_across_files_spec.lua @@ -3,7 +3,7 @@ -- hunk of file B (next in the explorer list); [c on the first hunk of file B -- jumps to the LAST hunk of file A (the natural backward walk). -local h = require("tests.helpers") +local h = require("tests.support") describe("cycle_hunks_across_files (#161)", function() local repo diff --git a/tests/ui/view/diffget_diffput_spec.lua b/tests/integration/ui/view/diffget_diffput_spec.lua similarity index 100% rename from tests/ui/view/diffget_diffput_spec.lua rename to tests/integration/ui/view/diffget_diffput_spec.lua diff --git a/tests/ui/view/hunk_textobject_spec.lua b/tests/integration/ui/view/hunk_textobject_spec.lua similarity index 100% rename from tests/ui/view/hunk_textobject_spec.lua rename to tests/integration/ui/view/hunk_textobject_spec.lua diff --git a/tests/ui/view/inline_explorer_spec.lua b/tests/integration/ui/view/inline_explorer_spec.lua similarity index 99% rename from tests/ui/view/inline_explorer_spec.lua rename to tests/integration/ui/view/inline_explorer_spec.lua index 1261ed51..c8e1e492 100644 --- a/tests/ui/view/inline_explorer_spec.lua +++ b/tests/integration/ui/view/inline_explorer_spec.lua @@ -395,7 +395,7 @@ describe("Inline diff with explorer", function() return end - local fixture = require("tests.framework.repository").new({ unborn = true }) + local fixture = require("tests.support.repository").new({ unborn = true }) local repo = fixture.dir local git = fixture.command diff --git a/tests/ui/view/inline_history_spec.lua b/tests/integration/ui/view/inline_history_spec.lua similarity index 99% rename from tests/ui/view/inline_history_spec.lua rename to tests/integration/ui/view/inline_history_spec.lua index 1212e473..96461b8e 100644 --- a/tests/ui/view/inline_history_spec.lua +++ b/tests/integration/ui/view/inline_history_spec.lua @@ -7,7 +7,7 @@ local inline = require("codediff.ui.inline") local diff = require("codediff.core.diff") local lifecycle = require("codediff.ui.lifecycle") local highlights = require("codediff.ui.highlights") -local test_helpers = require("tests.helpers") +local test_helpers = require("tests.support") local path = require("codediff.core.path") -- Helper to get OS-appropriate temp path diff --git a/tests/ui/view/inline_interaction_spec.lua b/tests/integration/ui/view/inline_interaction_spec.lua similarity index 100% rename from tests/ui/view/inline_interaction_spec.lua rename to tests/integration/ui/view/inline_interaction_spec.lua diff --git a/tests/ui/view/inline_standalone_spec.lua b/tests/integration/ui/view/inline_standalone_spec.lua similarity index 100% rename from tests/ui/view/inline_standalone_spec.lua rename to tests/integration/ui/view/inline_standalone_spec.lua diff --git a/tests/ui/view/layout_toggle_spec.lua b/tests/integration/ui/view/layout_toggle_spec.lua similarity index 99% rename from tests/ui/view/layout_toggle_spec.lua rename to tests/integration/ui/view/layout_toggle_spec.lua index bb40fd58..35881f13 100644 --- a/tests/ui/view/layout_toggle_spec.lua +++ b/tests/integration/ui/view/layout_toggle_spec.lua @@ -1,4 +1,4 @@ -local h = dofile("tests/helpers.lua") +local h = require("tests.support") h.ensure_plugin_loaded() diff --git a/tests/ui/view/move_keymap_spec.lua b/tests/integration/ui/view/move_keymap_spec.lua similarity index 100% rename from tests/ui/view/move_keymap_spec.lua rename to tests/integration/ui/view/move_keymap_spec.lua diff --git a/tests/ui/view/move_rendering_spec.lua b/tests/integration/ui/view/move_rendering_spec.lua similarity index 100% rename from tests/ui/view/move_rendering_spec.lua rename to tests/integration/ui/view/move_rendering_spec.lua diff --git a/tests/ui/view/pane_setup_spec.lua b/tests/integration/ui/view/pane_setup_spec.lua similarity index 98% rename from tests/ui/view/pane_setup_spec.lua rename to tests/integration/ui/view/pane_setup_spec.lua index 9d92d23d..15205856 100644 --- a/tests/ui/view/pane_setup_spec.lua +++ b/tests/integration/ui/view/pane_setup_spec.lua @@ -2,7 +2,7 @@ -- and the window options both panes get. Both were uncovered -- stubbing -- either left the whole suite green. -local h = dofile("tests/helpers.lua") +local h = require("tests.support") local path = require("codediff.core.path") local config = require("codediff.config") diff --git a/tests/ui/welcome_spec.lua b/tests/integration/ui/welcome_spec.lua similarity index 99% rename from tests/ui/welcome_spec.lua rename to tests/integration/ui/welcome_spec.lua index 484ca98e..abda0aca 100644 --- a/tests/ui/welcome_spec.lua +++ b/tests/integration/ui/welcome_spec.lua @@ -1,7 +1,7 @@ -- Test: Welcome page for empty diff panes -- Validates welcome buffer creation, detection, and integration with refresh -local helpers = require("tests.helpers") +local helpers = require("tests.support") -- Setup CodeDiff command for tests local function setup_command() diff --git a/tests/ui/lib/lib_spec.lua b/tests/integration/ui/widgets_spec.lua similarity index 100% rename from tests/ui/lib/lib_spec.lua rename to tests/integration/ui/widgets_spec.lua diff --git a/tests/integration_diagnostics_spec.lua b/tests/integration_diagnostics_spec.lua deleted file mode 100644 index 719acdb5..00000000 --- a/tests/integration_diagnostics_spec.lua +++ /dev/null @@ -1,103 +0,0 @@ --- Integration test: Verify virtual buffer diagnostics are disabled --- This is an end-to-end test that requires a real git repository - -local commands = require("codediff.commands") -local virtual_file = require("codediff.core.virtual_file") - --- Setup CodeDiff command for tests -local function setup_command() - if vim.fn.exists(':CodeDiff') ~= 2 then - vim.api.nvim_create_user_command("CodeDiff", function(opts) - commands.vscode_diff(opts) - end, { - nargs = "*", - bang = true, - complete = function() - return { "file", "install" } - end, - }) - end -end - -describe("Virtual buffer diagnostics integration", function() - before_each(function() - require("codediff").setup({ diff = { layout = "side-by-side" } }) - virtual_file.setup() - setup_command() - end) - - it("Disables diagnostics on virtual buffers in real CodeDiff usage", function() - -- Verify CodeDiff command exists - local has_command = vim.fn.exists(':CodeDiff') == 2 - assert.is_true(has_command, "CodeDiff command should be registered") - - -- This test runs the actual :CodeDiff command and verifies behavior - -- Skip if not in a git repo - local git_root = vim.fn.systemlist("git rev-parse --show-toplevel")[1] - if vim.v.shell_error ~= 0 then - pending("not in git repo") - return - end - - -- Navigate to git repo root - vim.cmd('cd ' .. git_root) - - -- Edit a file that exists in history - local test_file = git_root .. "/lua/codediff/core/git.lua" - if vim.fn.filereadable(test_file) == 0 then - pending("test file not found") - return - end - - vim.cmd('edit ' .. test_file) - - -- Try to find a valid revision - use HEAD first, or HEAD~1 if possible - local revision = "HEAD" - local commit_count = vim.fn.systemlist("git rev-list --count HEAD")[1] - if vim.v.shell_error == 0 and tonumber(commit_count) > 1 then - revision = "HEAD~1" - end - - -- Run CodeDiff with a valid revision (use new syntax with "file" subcommand) - local ok, err = pcall(function() - vim.cmd('CodeDiff file ' .. revision) - end) - - assert.is_true(ok, "CodeDiff command should execute successfully: " .. tostring(err)) - - -- Wait for diff view to be created - local view_created = vim.wait(2000, function() - return #vim.api.nvim_list_wins() > 1 - end, 100) - - assert.is_true(view_created, "Diff view should be created") - - -- Wait for async BufReadCmd callback to complete and disable diagnostics - vim.wait(1000) - - -- Check all windows and buffers - local wins = vim.api.nvim_list_wins() - local virtual_buf_found = false - local virtual_buf_diag_disabled = false - - for _, win in ipairs(wins) do - local buf = vim.api.nvim_win_get_buf(win) - local name = vim.api.nvim_buf_get_name(buf) - local is_virtual = name:match('^codediff://') - - if is_virtual then - virtual_buf_found = true - local diag_enabled = vim.diagnostic.is_enabled({bufnr = buf}) - if not diag_enabled then - virtual_buf_diag_disabled = true - end - - assert.is_false(diag_enabled, - string.format('Virtual buffer %d should have diagnostics disabled', buf)) - end - end - - assert.is_true(virtual_buf_found, "Should find at least one virtual buffer") - assert.is_true(virtual_buf_diag_disabled, "Virtual buffer should have diagnostics disabled") - end) -end) diff --git a/tests/run_tests.cmd b/tests/run_tests.cmd index f2a363a2..a6f8376a 100644 --- a/tests/run_tests.cmd +++ b/tests/run_tests.cmd @@ -1,20 +1,25 @@ @echo off -REM Test runner for codediff.nvim using the in-tree test framework -REM (tests/framework/), which replaces plenary.nvim. (Windows) -REM -REM Discovery, concurrency and output grouping all live in -REM tests/framework/supervisor.lua, so this script is a thin wrapper around a -REM single Neovim invocation and stays identical to tests/run_tests.sh. -REM -REM Env: -REM CODEDIFF_TEST_JOBS concurrent spec workers (default: 2x CPUs, max 16) -REM CODEDIFF_TEST_TIMEOUT per-spec timeout in ms (default: 300000) - +REM Selection and workers are shared with POSIX in framework/supervisor.lua. +REM CODEDIFF_TEST_TARGET is overridden by an explicit positional target. +REM CODEDIFF_TEST_JOBS and CODEDIFF_TEST_TIMEOUT control workers and timeouts. setlocal -pushd "%~dp0.." +if not "%~2"=="" goto usage_error +if "%~1"=="-h" goto usage +if "%~1"=="--help" goto usage +if not "%~1"=="" set "CODEDIFF_TEST_TARGET=%~1" + +pushd "%~dp0.." nvim --headless --noplugin -u tests/init.lua -c "lua require('tests.framework').run_all_and_exit()" set EXIT_CODE=%ERRORLEVEL% - popd exit /b %EXIT_CODE% + +:usage_error +call :usage +exit /b 2 + +:usage + echo Usage: %~nx0 [all^|unit^|integration^|e2e^|directory^|spec] + echo Examples: %~nx0 e2e; %~nx0 tests/integration/core/git +exit /b 0 diff --git a/tests/run_tests.sh b/tests/run_tests.sh index 1734fdcc..9a5eceef 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -1,21 +1,26 @@ #!/usr/bin/env bash -# Test runner for codediff.nvim using the in-tree test framework -# (tests/framework/), which replaces plenary.nvim. -# -# Discovery, concurrency and output grouping all live in -# tests/framework/supervisor.lua, so this script is a thin wrapper around a -# single Neovim invocation and stays identical to tests/run_tests.cmd. -# -# Env: -# CODEDIFF_TEST_JOBS concurrent spec workers (default: 2x CPUs, max 16) -# CODEDIFF_TEST_TIMEOUT per-spec timeout in ms (default: 300000) +# Discovery, selection and workers are shared with Windows in framework/supervisor.lua. +# CODEDIFF_TEST_TARGET is overridden by an explicit positional target. +# CODEDIFF_TEST_JOBS and CODEDIFF_TEST_TIMEOUT control workers and per-spec budgets. +set -euo pipefail -set -e +usage() { + printf 'Usage: %s [all|unit|integration|e2e|directory|spec]\n' "${0##*/}" + printf 'Examples: %s e2e; %s tests/integration/core/git\n' "${0##*/}" "${0##*/}" +} + +if (( $# > 1 )); then + usage + exit 2 +fi +case "${1:-}" in + -h|--help) usage; exit 0 ;; +esac SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" - cd "$PROJECT_ROOT" +export CODEDIFF_TEST_TARGET="${1:-${CODEDIFF_TEST_TARGET:-all}}" exec nvim --headless --noplugin -u tests/init.lua \ -c "lua require('tests.framework').run_all_and_exit()" diff --git a/tests/ui/refresh/helpers.lua b/tests/support/e2e.lua similarity index 100% rename from tests/ui/refresh/helpers.lua rename to tests/support/e2e.lua diff --git a/tests/ui/conflict/gutter_helpers.lua b/tests/support/gutter.lua similarity index 80% rename from tests/ui/conflict/gutter_helpers.lua rename to tests/support/gutter.lua index d77d9049..a85692d4 100644 --- a/tests/ui/conflict/gutter_helpers.lua +++ b/tests/support/gutter.lua @@ -114,43 +114,6 @@ function M.block_rows(case) } end --- A small real merge with an interior filler in incoming, plus a second file --- whose filler is on the opposite side. Expectations are authored below. -function M.create_repo() - local repo = require("tests.helpers").create_temp_git_repo() - repo.write_file("conf.txt", { "before", "base1", "base2", "base3", "after", "tail" }) - repo.write_file("other.txt", { "beforeB", "baseB", "afterB" }) - repo.write_file("deleted.txt", { "deleted one", "deleted two" }) - repo.git("add -A") - repo.git("commit -m base") - repo.git("checkout -b incoming") - repo.write_file("conf.txt", { "before", "base1", "THEIRS2", "THEIRS3", "after", "tail" }) - repo.write_file("other.txt", { "beforeB", "THEIRS_B", "extraB", "afterB" }) - repo.git("commit -am incoming") - repo.git("checkout main") - repo.write_file("conf.txt", { "before", "OURS1", "inserted", "OURS2", "base3", "after", "tail" }) - repo.write_file("other.txt", { "beforeB", "OURS_B", "afterB" }) - repo.git("commit -am current") - local _, code = repo.git("merge incoming --no-edit") - assert.equals(1, code, "fixture must produce a merge conflict") - repo.write_file("fresh.txt", { "fresh one", "fresh two" }) - repo.write_file("plain-left.txt", { "before", "same", "keep", "after" }) - repo.write_file("plain-right.txt", { "before", "same", "keep", "inserted", "after" }) - return repo -end - -M.merge_rows = { - original = { " before", "╭─base1", "│ THEIRS2", "│ ╱╱╱╱", "╰─THEIRS3", " after", " tail" }, - modified = { " before", "╭─OURS1", "│ inserted", "│ OURS2", "╰─base3", " after", " tail" }, - result = { " before", "╭─base1", "│ base2", "╰─base3", " after", " tail" }, -} - -M.other_merge_rows = { - original = { " beforeB", "╭─THEIRS_B", "╰─extraB", " afterB" }, - modified = { " beforeB", "╭─╱╱╱╱", "╰─OURS_B", " afterB" }, - result = { " beforeB", "[ baseB", " afterB" }, -} - function M.open_merge(screen, repo) screen:exec( [[ diff --git a/tests/helpers.lua b/tests/support/init.lua similarity index 94% rename from tests/helpers.lua rename to tests/support/init.lua index 86b75dda..1ec1271f 100644 --- a/tests/helpers.lua +++ b/tests/support/init.lua @@ -1,9 +1,10 @@ -- Cross-platform helpers shared by unit, integration and embedded UI tests. local M = {} +M.project_root = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h:h:h"):gsub("\\", "/") function M.ensure_plugin_loaded() if not vim.g.loaded_codediff then - local plugin_file = vim.fn.getcwd() .. "/plugin/codediff.lua" + local plugin_file = M.project_root .. "/plugin/codediff.lua" if vim.fn.filereadable(plugin_file) == 1 then dofile(plugin_file) end @@ -30,12 +31,12 @@ function M.create_temp_dir() end function M.git_cmd(dir, args) - return require("tests.framework.repository").git(dir, args) + return require("tests.support.repository").git(dir, args) end -- A fresh unborn main branch in an isolated TMP repository and worktree. function M.create_temp_git_repo() - return require("tests.framework.repository").new({ unborn = true }) + return require("tests.support.repository").new({ unborn = true }) end function M.wait_async(timeout_ms, condition_fn, interval_ms) diff --git a/tests/keymap_matrix.lua b/tests/support/keymaps.lua similarity index 100% rename from tests/keymap_matrix.lua rename to tests/support/keymaps.lua diff --git a/tests/framework/repository.lua b/tests/support/repository.lua similarity index 98% rename from tests/framework/repository.lua rename to tests/support/repository.lua index def1ae84..8d05ef78 100644 --- a/tests/framework/repository.lua +++ b/tests/support/repository.lua @@ -3,7 +3,7 @@ local M = {} local uv = vim.uv or vim.loop local seeds, owned = {}, {} -local project_root = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h:h:h") +local project_root = require("tests.support").project_root local function run(argv, opts) return vim.system(argv, vim.tbl_extend("force", { text = true }, opts or {})):wait() @@ -78,7 +78,7 @@ local function repository(dir) function repo.git_path(name) local value = vim.trim(repo.command({ "rev-parse", "--path-format=absolute", "--git-path", name })) - return value:gsub("\\", "/") + return (value:gsub("\\", "/")) end function repo.write_file(filename, lines) diff --git a/tests/core/argparse_spec.lua b/tests/unit/core/argparse_spec.lua similarity index 100% rename from tests/core/argparse_spec.lua rename to tests/unit/core/argparse_spec.lua diff --git a/tests/core/install_spec.lua b/tests/unit/core/installer_spec.lua similarity index 100% rename from tests/core/install_spec.lua rename to tests/unit/core/installer_spec.lua diff --git a/tests/core/path_spec.lua b/tests/unit/core/path_spec.lua similarity index 99% rename from tests/core/path_spec.lua rename to tests/unit/core/path_spec.lua index 79768b7e..7c63971f 100644 --- a/tests/core/path_spec.lua +++ b/tests/unit/core/path_spec.lua @@ -1,5 +1,5 @@ -- Tests for path reference resolution (core/path.lua make_ref) -local helpers = require("tests.helpers") +local helpers = require("tests.support") describe("core.path Path", function() local path diff --git a/tests/core/watcher_manager_spec.lua b/tests/unit/core/watcher/manager_spec.lua similarity index 100% rename from tests/core/watcher_manager_spec.lua rename to tests/unit/core/watcher/manager_spec.lua diff --git a/tests/core/watcher_protocol_spec.lua b/tests/unit/core/watcher/protocol_spec.lua similarity index 100% rename from tests/core/watcher_protocol_spec.lua rename to tests/unit/core/watcher/protocol_spec.lua diff --git a/tests/ui/merge_alignment_spec.lua b/tests/unit/ui/conflict/merge_alignment_spec.lua similarity index 100% rename from tests/ui/merge_alignment_spec.lua rename to tests/unit/ui/conflict/merge_alignment_spec.lua diff --git a/tests/ui/explorer/explorer_file_filter_spec.lua b/tests/unit/ui/explorer/filter_spec.lua similarity index 100% rename from tests/ui/explorer/explorer_file_filter_spec.lua rename to tests/unit/ui/explorer/filter_spec.lua diff --git a/tests/ui/explorer/flatten_dirs_spec.lua b/tests/unit/ui/explorer/flatten_dirs_spec.lua similarity index 100% rename from tests/ui/explorer/flatten_dirs_spec.lua rename to tests/unit/ui/explorer/flatten_dirs_spec.lua diff --git a/tests/ui/explorer/git_filter_spec.lua b/tests/unit/ui/explorer/git_filter_spec.lua similarity index 100% rename from tests/ui/explorer/git_filter_spec.lua rename to tests/unit/ui/explorer/git_filter_spec.lua diff --git a/tests/ui/history/history_date_format_spec.lua b/tests/unit/ui/history/date_format_spec.lua similarity index 100% rename from tests/ui/history/history_date_format_spec.lua rename to tests/unit/ui/history/date_format_spec.lua diff --git a/tests/ui/history/history_file_filter_spec.lua b/tests/unit/ui/history/file_filter_spec.lua similarity index 100% rename from tests/ui/history/history_file_filter_spec.lua rename to tests/unit/ui/history/file_filter_spec.lua diff --git a/tests/ui/refresh/policy_spec.lua b/tests/unit/ui/refresh/policy_spec.lua similarity index 100% rename from tests/ui/refresh/policy_spec.lua rename to tests/unit/ui/refresh/policy_spec.lua diff --git a/tests/ui/view/readiness_spec.lua b/tests/unit/ui/view/readiness_spec.lua similarity index 100% rename from tests/ui/view/readiness_spec.lua rename to tests/unit/ui/view/readiness_spec.lua From e6d66789f67e78dac5e6dfe5206d4de8685d8307 Mon Sep 17 00:00:00 2001 From: Yanuo Ma <41042490+esmuellert@users.noreply.github.com> Date: Mon, 14 Sep 2026 17:43:16 -0400 Subject: [PATCH 8/8] fix(refresh): let slow polling settle and harden CI fixtures Coalesce fallback ticks while a selection, read or real invalidation is pending, preserving the 500ms interval and classified repository events. Add controller regressions and real delayed-Git E2Es. Isolate hand-authored gutter projections from the comparison controller, write atomic index-only fixture changes, keep literal-arrow paths in Git rather than invalid Windows filenames, and retire fixture-owned sessions before removing watched directories. Retain the strict upstream scrollbind probe as an explicit opt-in after Neovim reverted #41519; test CodeDiff scrollbind setup unconditionally. Bound Windows worker concurrency and whole-spec runtime, and report active workers during long runs. --- .github/workflows/_platform-windows.yml | 7 ++ .../05-architecture/auto-refresh-strategy.md | 8 +- lua/codediff/ui/refresh/init.lua | 5 ++ tests/README.md | 15 +++- tests/e2e/COVERAGE.md | 10 ++- tests/e2e/refresh/lifecycle_spec.lua | 32 +++++++- tests/e2e/refresh/sources_spec.lua | 31 ++++--- tests/fixtures/README.md | 11 ++- tests/framework/reporter.lua | 81 +++++++++++++++---- tests/framework/supervisor.lua | 17 +++- tests/integration/support/repository_spec.lua | 49 ++++++++++- .../ui/conflict/gutter_grid_spec.lua | 12 +++ .../ui/refresh/controller_spec.lua | 50 ++++++++++++ tests/integration/ui/scrollbind_spec.lua | 10 ++- tests/support/gutter.lua | 13 ++- tests/support/init.lua | 25 +++++- tests/support/repository.lua | 11 +++ 17 files changed, 339 insertions(+), 48 deletions(-) diff --git a/.github/workflows/_platform-windows.yml b/.github/workflows/_platform-windows.yml index 297ba5ff..6cbcdf26 100644 --- a/.github/workflows/_platform-windows.yml +++ b/.github/workflows/_platform-windows.yml @@ -33,6 +33,7 @@ jobs: build: name: ${{ inputs.artifact }} runs-on: ${{ inputs.runs-on }} + timeout-minutes: 30 steps: - name: Checkout repository uses: actions/checkout@v5 @@ -60,6 +61,12 @@ jobs: - name: Run Neovim tests shell: bash + env: + # E2E specs create up to 120 isolated Git/Neovim instances. Avoid + # oversubscribing process startup and give the whole spec a budget; + # individual async assertions retain their bounded timeouts. + CODEDIFF_TEST_JOBS: '4' + CODEDIFF_TEST_TIMEOUT: '900000' run: ./tests/run_tests.sh - name: Upload build artifacts diff --git a/docs/development/05-architecture/auto-refresh-strategy.md b/docs/development/05-architecture/auto-refresh-strategy.md index beff914b..85dfd699 100644 --- a/docs/development/05-architecture/auto-refresh-strategy.md +++ b/docs/development/05-architecture/auto-refresh-strategy.md @@ -23,9 +23,11 @@ consume data changes rather than managing independent refresh loops. Removed the `auto_refresh` entry point, Explorer scheduler and per-panel refresh modules. The former `refresh/apply.lua` responsibilities now live in the existing view helpers and renderers; there is no separate refresh rendering pipeline. -Watcher categories remain intact, with a 500 ms polling fallback. Unchanged -inputs do not disturb the comparison, and changed merge inputs cannot overwrite -an edited Result. +Watcher categories remain intact, with a 500 ms polling fallback. Poll ticks +sample only when no selection, read or invalidation is pending; slow Git reads +must finish rather than accumulate an endless polling backlog. Actual repository +invalidations are still queued while a read is running. Unchanged inputs do not +disturb the comparison, and changed merge inputs cannot overwrite an edited Result. Regression coverage includes native watcher and polling screen-grid E2Es, data ownership, presentation-only list updates, navigation, hunk actions and stale diff --git a/lua/codediff/ui/refresh/init.lua b/lua/codediff/ui/refresh/init.lua index b47d9456..ec049c8a 100644 --- a/lua/codediff/ui/refresh/init.lua +++ b/lua/codediff/ui/refresh/init.lua @@ -218,6 +218,11 @@ function Controller:start_polling() 500, 500, vim.schedule_wrap(function() + -- Polling samples current state, unlike repository invalidations. A slow + -- read must finish before another sample is queued, or it never settles. + if not self.polling or self.closed or self.running or self.loading or next(self.pending) or #self.callbacks > 0 then + return + end self:request({ full = true }) end) ) diff --git a/tests/README.md b/tests/README.md index aa12224a..44ba93e0 100644 --- a/tests/README.md +++ b/tests/README.md @@ -81,7 +81,10 @@ nvim --headless --noplugin -u tests/init.lua \ Each spec gets its own child Neovim process. The supervisor discovers files recursively, runs a bounded worker pool and prints each child's output as one -block. New specs need no manifest or CI enumeration changes. +block. Start messages and a 30-second active-worker heartbeat distinguish long +specs from a stalled runner. New specs need no manifest or CI enumeration changes. +Windows CI uses four workers and a 15-minute per-spec budget for large E2E +matrices; individual asynchronous assertions retain their own bounded waits. | Environment variable | Default | Purpose | | --- | --- | --- | @@ -90,6 +93,7 @@ block. New specs need no manifest or CI enumeration changes. | `CODEDIFF_TEST_TIMEOUT` | `300000` | Per-spec timeout in milliseconds | | `NO_COLOR` / `CODEDIFF_TEST_NO_COLOR` | unset | Disable ANSI output | | `CODEDIFF_WATCHER_PATH` | installer default | Existing native watcher executable for offline E2Es | +| `CODEDIFF_TEST_UPSTREAM_SCROLLBIND` | unset | Opt into the strict tall-virtual-line regression on a Neovim build carrying the upstream fix | ## Fixtures and shared support @@ -138,10 +142,17 @@ silent fallback is not a native-test pass. Polling cases disable native startup and exercise the 500 ms fallback. Android skips native cases only. Race tests may delay delivery of real Git results, but do not fabricate their contents. +The tall-virtual-line monotonicity check is an upstream Neovim probe, not a +CodeDiff workaround. Neovim reverted #41519 in `0c9012f`, so a `0.13` version +check is insufficient. Its assertion remains opt-in on fixed builds; CodeDiff's +own scrollbind setup is checked unconditionally. Synthetic gutter fixtures +retire their comparison controller so periodic input reads cannot overwrite the +hand-authored projections; real merge E2Es keep the full controller active. + ## Behavioral coverage [e2e/COVERAGE.md](e2e/COVERAGE.md) maps the refresh changes against `main` to -scenario IDs and parameterized executions. Its 132 named scenarios / 544 +scenario IDs and parameterized executions. Its 133 named scenarios / 548 executions are a specific cross-feature matrix, **not the total E2E suite** and not a count of unit or integration tests. Additional command and working-file E2Es live alongside it. The runner reports the selected suite's actual counts. diff --git a/tests/e2e/COVERAGE.md b/tests/e2e/COVERAGE.md index 220cac91..4852d15b 100644 --- a/tests/e2e/COVERAGE.md +++ b/tests/e2e/COVERAGE.md @@ -24,6 +24,10 @@ notifications with a call to an internal refresh method. Race cases delay delivery of **real Git results**, without replacing their contents. The read-error case temporarily removes a real loose Git object. +Index-only changes are written directly to Git objects/index entries, without +exposing an unintended intermediate working-tree state. Literal-arrow path +cases keep entries in the real index with skip-worktree, allowing Windows to +exercise the same status parsing without trying to create an illegal `>` filename. Dialog cases answer Neovim's actual confirmation prompt. Expected file contents, Git blobs, paths, colors and navigation destinations come from the fixture or Git, not production diff/gutter calculators. @@ -35,7 +39,7 @@ are difficult to express through a Git merge. They are not counted below. ## Scenario matrix A named scenario is distinct from its parameterized executions. The matrix has -132 named scenarios and 544 E2E executions on a platform with a native watcher. +133 named scenarios and 548 E2E executions on a platform with a native watcher. This is the refresh change-audit matrix, not the entire E2E suite. Other command, working-file and diagnostic E2Es are additional coverage. Fixture self-tests, unit tests and component integrations are not included in these counts. @@ -45,7 +49,7 @@ unit tests and component integrations are not included in these counts. | [refresh/repository_spec.lua](refresh/repository_spec.lua) | 16 | 64 | native/polling × side-by-side/inline | | [conflict/refresh_spec.lua](conflict/refresh_spec.lua) | 10 | 20 | native/polling; three missing-stage shapes | | [refresh/files_spec.lua](refresh/files_spec.lua) | 3 | 6 | side-by-side/inline; plain-file polling | -| [refresh/lifecycle_spec.lua](refresh/lifecycle_spec.lua) | 17 | 66 | both transports/layouts; process exit is native-only | +| [refresh/lifecycle_spec.lua](refresh/lifecycle_spec.lua) | 18 | 70 | both transports/layouts; process exit is native-only | | [view/hunk_actions_spec.lua](view/hunk_actions_spec.lua) | 14 | 54 | both transports/layouts; manual-only mode runs per layout | | [explorer/actions_spec.lua](explorer/actions_spec.lua) | 20 | 80 | both transports/layouts | | [history/actions_spec.lua](history/actions_spec.lua) | 14 | 56 | both transports/layouts | @@ -166,6 +170,7 @@ Each ID is part of the test name, making failures and source searches traceable. | S15–S19 | Whitespace policy, whole-file highlights, original-right layout, moves, --repo | | T09–T12 | Hidden updates, hidden wipe, pane close, actual missing-object read/retry | | T13–T16 | Leaving/returning to Git, user keymaps, inlay hints, shared buffers across tabs | +| T17 | Real Git reads slower than the polling interval still settle and publish the correct inputs | | V01–V04 | Public revision URI, write protection, reversed load completions, wipe, missing file | The existing 38 scenarios cover unchanged-status worktree changes, unsaved @@ -185,6 +190,7 @@ hidden panels, shared subscriptions and native-process failover. | Y13–Y14 | Preserve line-range and reverse query options during history refresh | | T13 | Materialize a genuinely empty comparison side when following a file outside Git | | T15–T16 | Retain original buffer settings and respect buffers still owned by another session | +| T17 | Coalesce fallback samples while input reads are running, without dropping actual invalidations | ## Scope of the assurance diff --git a/tests/e2e/refresh/lifecycle_spec.lua b/tests/e2e/refresh/lifecycle_spec.lua index 74c6d266..7c2dc92c 100644 --- a/tests/e2e/refresh/lifecycle_spec.lua +++ b/tests/e2e/refresh/lifecycle_spec.lua @@ -99,9 +99,7 @@ for _, backend in ipairs({ "native", "polling" }) do write_a("working-B") h.open(screen, repo) h.hold_content(screen, "a.txt") - write_a("index-C") - repo.git("add a.txt") - write_a("working-B") + repo.write_index("a.txt", { "start", "index-C", "context", "end", "tail" }) wait_held() screen:exec("vim.api.nvim_set_current_win(refresh_session().modified_win); vim.api.nvim_win_set_cursor(0, { 2, 0 })") h.feed(screen, "ccUSER_LATEUSER_LATE_TWO") @@ -113,6 +111,34 @@ for _, backend in ipairs({ "native", "polling" }) do assert.equals(4, screen:exec("return refresh_session().stored_diff_result.changes[1].modified.end_line")) end) + it("[T17] settles slow Git reads without building an endless polling backlog", function() + write_a("index-A") + repo.git("add a.txt") + write_a("working-B") + h.open(screen, repo) + screen:exec([[ + local git = require('codediff.core.git') + local read = git.get_file_content + refresh_test.slow_reads = 0 + git.get_file_content = function(revision, root, path, done) + return read(revision, root, path, function(...) + local values, count = { ... }, select('#', ...) + vim.defer_fn(function() + refresh_test.slow_reads = refresh_test.slow_reads + 1 + done(unpack(values, 1, count)) + end, 700) + end) + end + ]]) + local before = h.checkpoint(screen) + repo.write_index("a.txt", { "start", "slow-index", "context", "end", "tail" }) + h.wait_event(screen, before) + h.expect_text(screen, "original", "slow-index") + h.expect_text(screen, "modified", "working-B") + h.idle(screen) + assert.is_true(screen:exec("return refresh_test.slow_reads > 0")) + end) + it("keeps the requested HEAD dependency when following a different working file", function() write_a("working-A") repo.write_file("b.txt", { "start", "working-B", "end" }) diff --git a/tests/e2e/refresh/sources_spec.lua b/tests/e2e/refresh/sources_spec.lua index 5ad19690..86331a79 100644 --- a/tests/e2e/refresh/sources_spec.lua +++ b/tests/e2e/refresh/sources_spec.lua @@ -144,22 +144,33 @@ for _, backend in ipairs({ "native", "polling" }) do it("[S12] a literal arrow in a filename is not parsed as a rename", function() repo = h.repo() local file = "literal -> name.txt" - repo.write_file(file, { "header", "old value", "tail" }) - repo.commit("literal arrow path") - repo.replace(file, 2, "new value") - h.open(screen, repo, "CodeDiff", file, file) + -- Git can store this path on Windows, but NTFS cannot check it out. + repo.command({ "config", "core.protectNTFS", "false" }) + repo.write_index(file, { "header", "old value", "tail" }) + repo.command({ "update-index", "--skip-worktree", file }) + repo.command({ "commit", "-m", "literal arrow path" }) + repo.write_index(file, { "header", "new value", "tail" }) + repo.command({ "update-index", "--skip-worktree", file }) + h.open(screen, repo, "CodeDiff", file) + h.expect_panel(screen, file) h.expect_lines(screen, "original", { "header", "old value", "tail" }) h.expect_text(screen, "modified", "new value") end) it("[S13] a renamed destination containing an arrow retains its complete path", function() repo = h.repo() - local file = "rename/target -> final.txt" - repo.command({ "mv", "rename/source file.txt", file }) - repo.replace(file, 3, "working arrow rename") - h.open(screen, repo, "CodeDiff", file, file) - h.expect_lines(screen, "original", fixture.files["rename/source file.txt"]) - h.expect_text(screen, "modified", "working arrow rename") + local source, file = "rename/source file.txt", "rename/target -> final.txt" + repo.command({ "config", "core.protectNTFS", "false" }) + local lines = vim.deepcopy(fixture.files[source]) + lines[3] = "index arrow rename" + repo.command({ "update-index", "--force-remove", source }) + assert.equals(0, vim.fn.delete(repo.path(source))) + repo.write_index(file, lines) + repo.command({ "update-index", "--skip-worktree", file }) + h.open(screen, repo, "CodeDiff", file) + h.expect_panel(screen, "target -> final.txt") + h.expect_lines(screen, "original", fixture.files[source]) + h.expect_text(screen, "modified", "index arrow rename") end) it("[S14] an unborn branch opens staged content against an empty base", function() diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index ab6d01dd..969b2199 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -27,7 +27,10 @@ a valid current directory when necessary. Call it after closing the embedded UI. A `VimLeavePre` fallback also removes seeds and abandoned cases. No fixture lives in the checked-out source tree. If an unavailable backend skips a case during setup, its cleanup hooks still run; cleanup failures are reported rather than -hidden by the skip. +hidden by the skip. The plugin-aware `tests.support.create_temp_git_repo()` +helper also retires matching in-process sessions before deletion so native +watchers release their directory handles. This does not replace closing an +embedded UI, which lives in a separate process. `tests/init.lua` removes inherited repository/index environment overrides and isolates global/system Git configuration. The factory also rejects inherited @@ -76,6 +79,7 @@ repo.command({ "diff", "--quiet" }, 1) -- explicit expected nonzero sta repo.write_file("a.txt", { "one", "two" }) repo.write_bytes("a.txt", "one\r\ntwo") repo.replace("a.txt", 2, "changed") +repo.write_index("a.txt", { "index-only content" }) -- working file is unchanged local index = repo.blob_lines(":0", "a.txt") local index_path = repo.git_path("index") repo.cleanup() @@ -83,7 +87,10 @@ repo.cleanup() Prefer argv-form `command` for new cases. `git` also accepts existing string-form commands; the refresh fixture checks their exit status, including merge failures -that must explicitly expect code 1. +that must explicitly expect code 1. `write_index` writes a real blob and index +entry directly; it can accept text or lines. Use it when only the index should +change, instead of writing/staging/restoring the working file and exposing +transient states to the watcher. The lower-level factory supports special states through the same lifecycle: diff --git a/tests/framework/reporter.lua b/tests/framework/reporter.lua index e42bd944..c9adb6c2 100644 --- a/tests/framework/reporter.lua +++ b/tests/framework/reporter.lua @@ -15,23 +15,39 @@ local M = {} -- --------------------------------------------------------------------------- local function tty_supports_color() - if vim.env.NO_COLOR and vim.env.NO_COLOR ~= "" then return false end - if vim.env.CODEDIFF_TEST_NO_COLOR and vim.env.CODEDIFF_TEST_NO_COLOR ~= "" then return false end + if vim.env.NO_COLOR and vim.env.NO_COLOR ~= "" then + return false + end + if vim.env.CODEDIFF_TEST_NO_COLOR and vim.env.CODEDIFF_TEST_NO_COLOR ~= "" then + return false + end -- CI environments (GitHub Actions) render ANSI colors in logs. return true end local use_color = tty_supports_color() local function color(s, code) - if not use_color then return s end + if not use_color then + return s + end return "\27[" .. code .. "m" .. s .. "\27[0m" end -local function red(s) return color(s, "31") end -local function green(s) return color(s, "32") end -local function yellow(s) return color(s, "33") end -local function cyan(s) return color(s, "36") end -local function dim(s) return color(s, "2") end +local function red(s) + return color(s, "31") +end +local function green(s) + return color(s, "32") +end +local function yellow(s) + return color(s, "33") +end +local function cyan(s) + return color(s, "36") +end +local function dim(s) + return color(s, "2") +end -- --------------------------------------------------------------------------- -- Output primitives @@ -47,7 +63,9 @@ end local function indent(prefix, block) local out = {} for line in tostring(block):gmatch("([^\n]*)\n?") do - if line ~= "" then table.insert(out, prefix .. line) end + if line ~= "" then + table.insert(out, prefix .. line) + end end return table.concat(out, "\n") end @@ -135,12 +153,18 @@ local BOX_WIDTH = 62 --- color codes (which occupy zero columns) don't skew the border alignment. local function box_row(text, plain) local pad = BOX_WIDTH - 1 - vim.fn.strdisplaywidth(plain or text) - if pad < 0 then pad = 0 end + if pad < 0 then + pad = 0 + end return "║ " .. text .. string.rep(" ", pad) .. "║" end -local function box_top() return "╔" .. string.rep("═", BOX_WIDTH) .. "╗" end -local function box_bottom() return "╚" .. string.rep("═", BOX_WIDTH) .. "╝" end +local function box_top() + return "╔" .. string.rep("═", BOX_WIDTH) .. "╗" +end +local function box_bottom() + return "╚" .. string.rep("═", BOX_WIDTH) .. "╝" +end --- Banner printed once, before any spec runs. -- @param spec_count number @@ -156,13 +180,32 @@ function M.print_suite_header(spec_count, mode, jobs, reason) detail = string.format("%d spec files, %d parallel workers", spec_count, jobs) else detail = string.format("%d spec files, sequential", spec_count) - if reason then detail = detail .. " (" .. reason .. ")" end + if reason then + detail = detail .. " (" .. reason .. ")" + end end write(box_row(dim(detail), detail)) write(box_bottom()) write("") end +function M.print_spec_start(spec) + write(cyan("▶ RUN ") .. spec) + io.stdout:flush() +end + +function M.print_running(active, now) + local names = {} + for spec, started in pairs(active) do + names[#names + 1] = string.format("%s (%.0fs)", spec, (now - started) / 1e9) + end + if #names > 0 then + table.sort(names) + write(dim("… running: " .. table.concat(names, ", "))) + io.stdout:flush() + end +end + --- Emit one spec's captured output as a single contiguous block. -- -- This is the whole anti-interleaving mechanism: a child's stdout is buffered @@ -188,7 +231,9 @@ function M.emit_block(spec, stdout, stderr) chunk = chunk:gsub("\n*$", "\n") .. dim(label) .. "\n" .. stderr end chunk = chunk:gsub("\n*$", "") - if chunk == "" then return end + if chunk == "" then + return + end write(chunk) end @@ -198,11 +243,15 @@ end function M.print_suite_summary(results, total_ms) local failures = {} for _, r in ipairs(results) do - if not r.ok then table.insert(failures, r) end + if not r.ok then + table.insert(failures, r) + end end -- Deterministic regardless of completion order, so CI logs stay diffable. - table.sort(failures, function(a, b) return a.spec < b.spec end) + table.sort(failures, function(a, b) + return a.spec < b.spec + end) write("") if #failures > 0 then diff --git a/tests/framework/supervisor.lua b/tests/framework/supervisor.lua index 8076851b..06741c15 100644 --- a/tests/framework/supervisor.lua +++ b/tests/framework/supervisor.lua @@ -131,7 +131,7 @@ local TIMEOUT_EXIT_CODE = 124 -- takes the next spec, so a slow spec never strands the remaining work and no -- hand-maintained ordering is required. local function run_parallel(specs, opts) - local results = {} + local results, active = {}, {} local next_index, emitted = 1, 0 local function spawn_next() @@ -140,8 +140,11 @@ local function run_parallel(specs, opts) end local spec = specs[next_index] next_index = next_index + 1 + active[spec] = uv.hrtime() + reporter.print_spec_start(spec) vim.system(child_argv(spec), { text = true, timeout = opts.timeout }, function(obj) + active[spec] = nil -- Keep the pool saturated before doing anything else. spawn_next() -- Emission is deferred to the main loop: the whole block is written by a @@ -162,11 +165,22 @@ local function run_parallel(specs, opts) spawn_next() end + local progress = uv.new_timer() + progress:start( + 30000, + 30000, + vim.schedule_wrap(function() + reporter.print_running(active, uv.hrtime()) + end) + ) + -- Every child is bounded by `opts.timeout`, so this is a true upper bound. local cap = opts.timeout * math.ceil(#specs / opts.jobs) + 60000 vim.wait(cap, function() return emitted >= #specs end, 20) + progress:stop() + progress:close() return results end @@ -179,6 +193,7 @@ end local function run_sequential(specs) local results = {} for _, spec in ipairs(specs) do + reporter.print_spec_start(spec) local out = vim.fn.system(child_argv(spec)) local code = vim.v.shell_error reporter.emit_block(spec, out, nil) diff --git a/tests/integration/support/repository_spec.lua b/tests/integration/support/repository_spec.lua index f4c88940..ecf70d9b 100644 --- a/tests/integration/support/repository_spec.lua +++ b/tests/integration/support/repository_spec.lua @@ -1,14 +1,20 @@ local repositories = require("tests.support.repository") describe("isolated fixture worktrees", function() - local repos + local repos, tabs before_each(function() - repos = {} + repos, tabs = {}, {} end) after_each(function() for _, repo in ipairs(repos) do repo.cleanup() end + for _, tab in ipairs(tabs) do + if vim.api.nvim_tabpage_is_valid(tab) then + vim.api.nvim_set_current_tabpage(tab) + vim.cmd("tabclose!") + end + end end) local function new(opts) local repo = repositories.new(opts) @@ -57,6 +63,45 @@ describe("isolated fixture worktrees", function() assert.equals("", second.command({ "ls-files", "staged.txt" })) end) + it("writes index content without exposing an intermediate working-tree change", function() + local repo = new() + repo.write_file("a.txt", { "working" }) + local oid = repo.write_index("a.txt", { "index" }) + assert.same({ "working" }, repo.read_file("a.txt")) + assert.same({ "index" }, repo.blob_lines(":0", "a.txt")) + assert.equals(oid, vim.trim(repo.command({ "rev-parse", ":0:a.txt" }))) + end) + + it("retires only a plugin-aware fixture's sessions before removing its directory", function() + local h = require("tests.support") + local lifecycle = require("codediff.ui.lifecycle") + local path = require("codediff.core.path") + local first, second = h.create_temp_git_repo(), h.create_temp_git_repo() + repos[#repos + 1], repos[#repos + 2] = first, second + local function open(repo) + repo.write_file("a.txt", { "content" }) + vim.cmd("tabnew") + local tab, win, buf = vim.api.nvim_get_current_tabpage(), vim.api.nvim_get_current_win(), vim.api.nvim_get_current_buf() + tabs[#tabs + 1] = tab + vim.api.nvim_buf_set_lines(buf, 0, -1, false, { "content" }) + lifecycle.create_session(tab, { + git_root = repo.dir, + original = path.make_ref("a.txt", repo.dir), + modified = path.make_ref("a.txt", repo.dir), + }, { original_bufnr = buf, modified_bufnr = buf, original_win = win, modified_win = win, lines_diff = { changes = {} } }) + return tab, require("codediff.ui.refresh").attach(tab) + end + local first_tab, first_controller = open(first) + local second_tab, second_controller = open(second) + first.cleanup() + assert.is_nil(lifecycle.get_session(first_tab)) + assert.is_true(first_controller.closed) + assert.equals(0, vim.fn.isdirectory(first.root)) + assert.is_not_nil(lifecycle.get_session(second_tab)) + assert.is_true(second_controller:valid()) + assert.equals(1, vim.fn.isdirectory(second.root)) + end) + it("also supplies regular Git-directory fixtures through the same factory", function() local repo = new({ worktree = false, unborn = true }) assert.equals(1, vim.fn.isdirectory(repo.path(".git"))) diff --git a/tests/integration/ui/conflict/gutter_grid_spec.lua b/tests/integration/ui/conflict/gutter_grid_spec.lua index 16e9fa33..77e65b7b 100644 --- a/tests/integration/ui/conflict/gutter_grid_spec.lua +++ b/tests/integration/ui/conflict/gutter_grid_spec.lua @@ -28,6 +28,18 @@ describe("conflict block gutter on the screen grid", function() end) end + it("keeps synthetic projections intact beyond the refresh polling interval", function() + screen = Screen.new(120, 24) + local panes = gutter.open_block(screen, 3) + vim.wait(650) + screen:flush() + local expected = gutter.block_rows(cases[3]) + for _, side in ipairs({ "original", "modified", "result" }) do + gutter.expect_pane(screen, panes[side], expected[side], "settled fixture: " .. side, panes.foreground) + end + assert.is_nil(screen:exec("return require('codediff.ui.lifecycle').get_session(...).refresh", { panes.tab })) + end) + it("keeps BOF offsets correct when only part of the leading filler is visible", function() screen = Screen.new(120, 24) local panes = gutter.open_block(screen, 13) diff --git a/tests/integration/ui/refresh/controller_spec.lua b/tests/integration/ui/refresh/controller_spec.lua index 311d8abd..c5619876 100644 --- a/tests/integration/ui/refresh/controller_spec.lua +++ b/tests/integration/ui/refresh/controller_spec.lua @@ -135,6 +135,56 @@ describe("session refresh scheduling", function() assert.same({ full = true }, reads[1].event) end) + it("does not queue redundant polling work while a slow read is running", function() + setup() + timers[2].callback() + vim.wait(10) + fire() + assert.is_true(controller.running) + assert.equals(500, timers[2].repeat_ms) + for _ = 1, 3 do + timers[2].callback() + vim.wait(10) + end + assert.same({}, controller.pending) + reads[1].done(nil, snapshot.capture(session)) + assert.is_false(controller.running) + assert.same({}, controller.pending) + timers[2].callback() + vim.wait(10) + fire() + assert.equals(2, #reads, "the next idle polling tick must still check data") + end) + + it("preserves real invalidations while redundant polling ticks are coalesced", function() + setup() + controller:request({ full = true }) + fire() + handlers.on_refresh({ index = true, worktree = true }) + timers[2].callback() + vim.wait(10) + assert.same({ index = true, worktree = true }, controller.pending) + reads[1].done(nil, snapshot.capture(session)) + fire() + assert.same({ index = true, worktree = true }, reads[2].event) + end) + + it("does not poll through an unfinished selection or a stopped transport", function() + setup() + refresh.begin(tab) + timers[2].callback() + vim.wait(10) + assert.same({}, controller.pending) + refresh.ready(tab) + vim.wait(10) + handlers.on_ready() + fire() + reads[1].done(nil, snapshot.capture(session)) + timers[2].callback() + vim.wait(10) + assert.same({}, controller.pending, "an already queued fallback tick must not outlive native readiness") + end) + it("discards an in-flight snapshot after retargeting", function() setup() controller:request({ index = true }) diff --git a/tests/integration/ui/scrollbind_spec.lua b/tests/integration/ui/scrollbind_spec.lua index 37a041c4..ec83669d 100644 --- a/tests/integration/ui/scrollbind_spec.lua +++ b/tests/integration/ui/scrollbind_spec.lua @@ -51,16 +51,18 @@ describe("native scrollbind", function() vim.cmd("rightbelow vsplit") local right = make_window({ "right" }) - vim.wo[left].scrollbind = true - vim.wo[right].scrollbind = true + require("codediff.ui.view.render").establish_scrollbind(left, right, vim.api.nvim_win_get_buf(left), vim.api.nvim_win_get_buf(right), { changes = {} }, { 1, 0 }, { 1, 0 }) assert.is_true(vim.wo[left].scrollbind) assert.is_true(vim.wo[right].scrollbind) end) it("keeps scrolling monotonic through a full-screen filler block", function() - if vim.fn.has("nvim-0.13") ~= 1 then - pending("requires Neovim's upstream tall virt_lines scrollbind fix") + -- Neovim reverted #41519 in 0c9012f; version 0.13 alone no longer + -- guarantees this upstream behavior. Keep the strict repro opt-in for + -- builds carrying its replacement, rather than hiding oscillation here. + if vim.env.CODEDIFF_TEST_UPSTREAM_SCROLLBIND ~= "1" then + pending("Neovim #41519 was reverted; opt in with CODEDIFF_TEST_UPSTREAM_SCROLLBIND=1 on a fixed build") end local left = make_window(make_content("C", 60), 30) diff --git a/tests/support/gutter.lua b/tests/support/gutter.lua index a85692d4..08c4fd9b 100644 --- a/tests/support/gutter.lua +++ b/tests/support/gutter.lua @@ -3,9 +3,10 @@ local M = {} -- Build a block with deliberately different buffer coordinates in each pane. -- Only the public conflict entry points render it; no calculator/backend calls. function M.open_block(screen, case_index) - return screen:exec( + local panes = screen:exec( [[ local case_index = ... + _G.gutter_fixture_ready = false local case = require('tests.fixtures.conflict_gutter')[case_index] local conflict = require('codediff.ui.conflict') local lifecycle = require('codediff.ui.lifecycle') @@ -64,6 +65,12 @@ function M.open_block(screen, case_index) conflict.attach_gutter(original_win, modified_win) conflict.setup_refresh_autocmd(tab, result_buf) conflict.refresh(lifecycle.get_session(tab)) + -- Synthetic projections are not a filesystem comparison. Let the scheduled + -- lifecycle attach complete, then retire it without disabling gutter edits. + vim.schedule(function() + require('codediff.ui.refresh').dispose(tab) + _G.gutter_fixture_ready = true + end) vim.api.nvim_win_call(original_win, function() vim.fn.winrestview({ topline = 1, topfill = case.fillers[0] or 0 }) end) @@ -74,6 +81,10 @@ function M.open_block(screen, case_index) ]], { case_index } ) + screen:await(function() + return screen:exec("return gutter_fixture_ready == true") + end, "synthetic gutter fixture did not finish setup") + return panes end function M.expect_pane(screen, win, rows, label, highlight) diff --git a/tests/support/init.lua b/tests/support/init.lua index 1ec1271f..647e6c36 100644 --- a/tests/support/init.lua +++ b/tests/support/init.lua @@ -34,9 +34,30 @@ function M.git_cmd(dir, args) return require("tests.support.repository").git(dir, args) end --- A fresh unborn main branch in an isolated TMP repository and worktree. +-- A plugin-aware fixture: retire its sessions before removing directories that +-- an active native watcher (especially on Windows) still has open. function M.create_temp_git_repo() - return require("tests.support.repository").new({ unborn = true }) + local repo = require("tests.support.repository").new({ unborn = true }) + local remove = repo.cleanup + repo.cleanup = function() + local sessions = package.loaded["codediff.ui.lifecycle.session"] + if sessions then + local function belongs(path) + if type(path) ~= "string" then + return false + end + path = path:gsub("\\", "/") + return path == repo.dir or path:sub(1, #repo.dir + 1) == repo.dir .. "/" + end + for tab, session in pairs(sessions.get_active_diffs()) do + if belongs(session.git_root) or belongs(session.original and session.original.absolute) or belongs(session.modified and session.modified.absolute) then + require("codediff.ui.lifecycle").cleanup(tab) + end + end + end + remove() + end + return repo end function M.wait_async(timeout_ms, condition_fn, interval_ms) diff --git a/tests/support/repository.lua b/tests/support/repository.lua index 8d05ef78..aa41347e 100644 --- a/tests/support/repository.lua +++ b/tests/support/repository.lua @@ -115,6 +115,17 @@ local function repository(dir) return value == "" and {} or vim.split(value:gsub("\n$", ""), "\n", { plain = true }) end + -- Update only the index: no intermediate working-tree state or checkout is + -- needed, including for Git paths that the host filesystem cannot represent. + function repo.write_index(filename, content) + if type(content) == "table" then + content = table.concat(content, "\n") .. (#content > 0 and "\n" or "") + end + local oid = vim.trim(repo.command({ "hash-object", "-w", "--stdin" }, 0, { stdin = content })) + repo.command({ "update-index", "--add", "--cacheinfo", "100644," .. oid .. "," .. filename }) + return oid + end + function repo.commit(message) commit_number = commit_number + 1 local date = string.format("2001-01-%02dT12:00:00+00:00", commit_number)