diff --git a/.github/agents/codediff-developer.agent.md b/.github/agents/codediff-developer.agent.md index 7bc690e2..1c750dd6 100644 --- a/.github/agents/codediff-developer.agent.md +++ b/.github/agents/codediff-developer.agent.md @@ -11,28 +11,48 @@ You are a specialist developer for the **codediff.nvim** Neovim plugin - a VSCod - Lua programming for Neovim plugins - Neovim APIs (vim.api, vim.fn, autocmds, extmarks) - Git operations and diff algorithms -- The nui.nvim UI library (Tree, Split components) -- Async patterns in Lua (callbacks, vim.schedule) +- The in-tree UI library `lua/codediff/ui/lib/` (Tree, Split, Line) — a drop-in + replacement for nui.nvim, so the plugin has no external Lua dependencies +- The in-tree test framework `tests/framework/` — a drop-in replacement for + plenary.nvim providing `describe/it/before_each/after_each/assert.*` +- Async patterns in Lua (callbacks, vim.schedule, vim.system) ## Repository Structure ``` lua/codediff/ -├── init.lua -- Main entry, setup() -├── config.lua -- Configuration options -├── commands.lua -- :CodeDiff command handling +├── init.lua -- Main entry, setup() + navigation API +├── config.lua -- Configuration options and keymaps +├── commands.lua -- :CodeDiff command handling + completion +├── version.lua -- Version info +├── scrollsync.lua -- Scroll synchronization between panes ├── core/ +│ ├── argparse/ -- Declarative command parser for :CodeDiff +│ ├── compat.lua -- Neovim version compatibility shims │ ├── diff.lua -- FFI diff computation (C library) │ ├── git.lua -- Async git operations │ ├── dir.lua -- Directory comparison +│ ├── installer.lua -- Automatic native library installation +│ ├── path.lua -- Path normalization helpers │ └── virtual_file.lua -- Virtual buffer handling └── ui/ ├── explorer/ -- File explorer sidebar - ├── view/ -- Diff view management - ├── lifecycle/ -- Session tracking - └── highlights.lua -- Syntax highlighting + ├── history/ -- Commit history sidebar + ├── conflict/ -- Merge conflict resolution + ├── view/ -- Diff view management (side-by-side, inline) + ├── lifecycle/ -- Session tracking and cleanup + ├── lib/ -- In-tree Tree/Split/Line (replaces nui.nvim) + ├── inline.lua -- Inline diff virtual-line rendering + ├── move.lua -- Moved-code rendering + ├── filler.lua -- Filler line alignment + ├── layout.lua -- Window layout + ├── auto_refresh.lua -- Buffer-change driven diff refresh + └── highlights.lua -- Highlight groups ``` +`lua/vscode-diff/` only contains deprecated compatibility shims for the old +plugin name — never add new functionality there. + ## Workflow for Fixing Issues ### 1. Understand the Issue @@ -48,7 +68,8 @@ return { setup = function(ctx, e2e) ctx.repo = e2e.create_temp_git_repo() ctx.repo.write_file("test.txt", {"original"}) - ctx.repo.git("add . && git commit -m 'initial'") + ctx.repo.git("add .") + ctx.repo.git("commit -m 'initial'") ctx.repo.write_file("test.txt", {"modified"}) vim.cmd("edit " .. ctx.repo.path("test.txt")) end, @@ -70,11 +91,17 @@ return { } ``` +`repo.git(args)` runs `git -C `, so pass one git subcommand per +call. Chaining (`"add . && git commit -m 'x'"`) runs the second command in +Neovim's own cwd, not the temp repo. + Run with: ```bash SCENARIO_FILE=/tmp/repro.lua nvim --headless -u tests/init.lua -c "luafile scripts/nvim-e2e.lua" -c "qa!" 2>&1 ``` +Committed scenarios in `tests/e2e/` are working examples and run the same way. + ### 3. Implement the Fix - Make minimal, focused changes - Follow existing code patterns @@ -82,52 +109,112 @@ SCENARIO_FILE=/tmp/repro.lua nvim --headless -u tests/init.lua -c "luafile scrip ### 4. Validate - Run the repro scenario again (should now pass) -- Run full test suite: `./tests/run_plenary_tests.sh` +- Run full test suite: `./tests/run_tests.sh` (or `make test-lua`) +- Run a single spec while iterating: + ```bash + nvim --headless --noplugin -u tests/init.lua \ + -c "lua require('tests.framework').run_and_exit('tests/ui/explorer/explorer_spec.lua')" + ``` +- Lint Lua changes: `make lint` (stylua), format with `make format` + +Specs are auto-discovered under `tests/`, each runs in its own child Neovim, and +`tests/framework/supervisor.lua` runs them concurrently. Tune with +`CODEDIFF_TEST_JOBS` (default 2x CPUs, capped at 16; `1` forces sequential) and +`CODEDIFF_TEST_TIMEOUT` (per-spec ms, default 300000). ## E2E Helper Functions ```lua -- Git repo local repo = e2e.create_temp_git_repo() +repo.dir -- Repo root path repo.write_file("path", {"lines"}) -repo.git("add .") +repo.read_file("path") +repo.git("add .") -- One subcommand per call repo.path("file.txt") -- Full path repo.cleanup() -- Waiting +e2e.wait(timeout_ms, condition_fn) e2e.wait_for_explorer(timeout_ms) e2e.wait_for_diff_ready(timeout_ms) +e2e.wait_for_new_tab(timeout_ms) +e2e.wait_for_buffer_content(bufnr, text, timeout_ms) --- Windows -e2e.find_window_by_filetype("codediff-explorer") +-- Windows and buffers +e2e.find_window_by_filetype("codediff-explorer") -- also "codediff-history" +e2e.get_all_windows() +e2e.focus_window(winid) e2e.focus_explorer() e2e.get_buffer_lines(bufnr) - --- Navigation -e2e.next_file() -- ]f -e2e.prev_file() -- [f -e2e.next_hunk() -- ]c -e2e.toggle_stage() -- - +e2e.get_buffer_content(bufnr) +e2e.get_cursor_position() +e2e.set_cursor_position(line, col) + +-- Diff session +e2e.get_diff_buffers() -- orig_buf, mod_buf +e2e.get_diff_session() +e2e.get_original_content() +e2e.get_modified_content() + +-- Explorer +e2e.get_explorer_files() +e2e.select_explorer_item(line_num) + +-- Navigation and actions +e2e.next_file() -- ]f +e2e.prev_file() -- [f +e2e.next_hunk() -- ]c +e2e.prev_hunk() -- [c +e2e.toggle_stage() -- - +e2e.toggle_explorer()-- b +e2e.next_conflict() -- ]x +e2e.accept_incoming()-- ct +e2e.diff_get() -- do +e2e.press("]c", 200) + +-- Git state and assertions +e2e.get_git_status(repo.dir) +e2e.is_file_staged(repo.dir, "file.txt") +e2e.assert_contains(str, substr, msg) +e2e.assert_equals(expected, actual, msg) +e2e.assert_true(value, msg) -- Commands e2e.exec("CodeDiff HEAD~1") ``` +In explorer mode the diff panes are placeholders until a file is selected, so +`get_modified_content()` returns an empty string right after +`wait_for_diff_ready()`. Select a file first (`e2e.next_file()` or +`e2e.select_explorer_item(line)`) before asserting on diff content. + ## Key Files for Common Issues | Issue Type | Key Files | |------------|-----------| -| Explorer display | `ui/explorer/render.lua`, `ui/explorer/nodes.lua` | -| File navigation | `ui/explorer/actions.lua` | -| Diff rendering | `ui/view/render.lua`, `core/diff.lua` | +| Explorer display | `ui/explorer/render.lua`, `ui/explorer/nodes.lua`, `ui/explorer/line_layout.lua` | +| File navigation | `ui/explorer/actions.lua`, `ui/view/navigation.lua` | +| Diff rendering | `ui/view/render.lua`, `ui/view/side_by_side.lua`, `core/diff.lua` | +| Inline view | `ui/inline.lua`, `ui/view/inline_view.lua` | +| Moved code | `ui/move.lua`, `ui/filler.lua` | | Git operations | `core/git.lua` | -| Staging/unstaging | `ui/explorer/actions.lua` | -| Keymaps | `ui/explorer/keymaps.lua`, `ui/view/keymaps.lua` | +| Staging/unstaging | `ui/explorer/actions.lua` (files), `ui/view/keymaps.lua` (hunks) | +| Merge conflicts | `ui/conflict/` | +| Commit history | `ui/history/` | +| Command parsing | `commands.lua`, `core/argparse/` | +| Keymaps | `ui/explorer/keymaps.lua`, `ui/view/keymaps.lua`, `config.lua` | | Session lifecycle | `ui/lifecycle/init.lua` | +| Window layout | `ui/layout.lua`, `ui/scroll.lua`, `scrollsync.lua` | ## Important Notes - The plugin module is `codediff` (not `vscode-diff`) - Always use the test init: `nvim --headless -u tests/init.lua` -- Create scenario files in `/tmp/`, never in the repo +- No external Lua dependencies: nui.nvim and plenary.nvim are replaced by + in-tree `lua/codediff/ui/lib/` and `tests/framework/` +- Create ad-hoc repro scenario files in `/tmp/`, never in the repo; only add a + scenario to `tests/e2e/` when it is worth keeping - Clean up temp repos in the cleanup phase +- Tests must use current production APIs — never reintroduce removed APIs for + backward compatibility diff --git a/.github/instructions/tests.instructions.md b/.github/instructions/tests.instructions.md index 635e28d5..b5ee558d 100644 --- a/.github/instructions/tests.instructions.md +++ b/.github/instructions/tests.instructions.md @@ -7,5 +7,5 @@ applyTo: "tests/**" When working with tests in this directory: - **Extend existing tests**: Add new test cases to existing test files whenever possible; only create new test files when covering genuinely distinct functionality -- **Update test runner**: Always add newly created test files to `tests/run_tests.sh` script to ensure they run in CI +- **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 - **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/skills/nvim-e2e-workflow/SKILL.md b/.github/skills/nvim-e2e-workflow/SKILL.md index e84d84c7..69fbcd22 100644 --- a/.github/skills/nvim-e2e-workflow/SKILL.md +++ b/.github/skills/nvim-e2e-workflow/SKILL.md @@ -12,7 +12,7 @@ This skill enables end-to-end investigation and fixing of Lua plugin issues usin - **Plugin name**: codediff (formerly vscode-diff) - **Type**: Neovim Lua plugin with native C bindings - **Main module**: `require("codediff")` -- **Test framework**: plenary.nvim +- **Test framework**: in-tree `tests/framework/` (no external test deps) --- @@ -93,7 +93,7 @@ SCENARIO_FILE=/tmp/repro.lua nvim --headless -u tests/init.lua -c "luafile scrip Then run the full test suite: ```bash -./tests/run_plenary_tests.sh +./tests/run_tests.sh ``` --- @@ -321,13 +321,13 @@ nvim --headless -u tests/init.lua -c "lua print(vim.inspect(require('codediff.co **Run all tests:** ```bash -./tests/run_plenary_tests.sh +./tests/run_tests.sh ``` **Run single test file:** ```bash nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('plenary.test_harness').test_file('tests/explorer_spec.lua', { minimal_init = 'tests/init.lua' })" + -c "lua require('tests.framework').run_and_exit('tests/explorer_spec.lua')" ``` --- diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index a9dc444a..7753d87e 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -148,7 +148,7 @@ jobs: - name: Run Neovim tests (Windows) if: startsWith(matrix.runs-on, 'windows') shell: bash - run: ./tests/run_plenary_tests.sh + run: ./tests/run_tests.sh - name: Upload build artifacts if: success() diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index 553c7ec2..4372e103 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -59,23 +59,8 @@ jobs: echo "$HOME/nvim/bin" >> "$GITHUB_PATH" "$HOME/nvim/bin/nvim" --version | head -n 1 - # Preinstall plenary.nvim so the coding agent doesn't need github.com at task time. - # tests/init.lua expects it under vim.fn.stdpath("data")/plenary.nvim, which on - # Linux resolves to $HOME/.local/share/nvim/plenary.nvim. - # nui.nvim is not a runtime or test dependency (verified: zero require("nui...") in lua/). - - name: Cache plenary.nvim - id: cache-plenary - uses: actions/cache@v5 - with: - path: ~/.local/share/nvim/plenary.nvim - key: plenary-nvim-${{ runner.os }}-v1 - - - name: Install plenary.nvim - if: steps.cache-plenary.outputs.cache-hit != 'true' - run: | - mkdir -p "$HOME/.local/share/nvim" - git clone --depth=1 https://github.com/nvim-lua/plenary.nvim \ - "$HOME/.local/share/nvim/plenary.nvim" + # The test framework is in-tree at tests/framework/ — no external clone needed. + # nui.nvim is installed on-demand by tests/init.lua only if a test actually requires it. - name: Build native library run: make build diff --git a/.github/workflows/standalone-build-test.yml b/.github/workflows/standalone-build-test.yml index dcf2e805..7b31ab14 100644 --- a/.github/workflows/standalone-build-test.yml +++ b/.github/workflows/standalone-build-test.yml @@ -83,10 +83,10 @@ jobs: if: matrix.os != 'windows-latest' run: | nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('plenary.test_harness').test_file('tests/full_integration_spec.lua', { minimal_init = vim.fn.getcwd() .. '/tests/init.lua' })" + -c "lua require('tests.framework').run_and_exit('tests/full_integration_spec.lua')" - name: Run integration test (Windows) if: matrix.os == 'windows-latest' shell: pwsh run: | - nvim --headless --noplugin -u tests/init.lua -c "lua require('plenary.test_harness').test_file('tests/full_integration_spec.lua', { minimal_init = vim.fn.getcwd() .. '/tests/init.lua' })" + nvim --headless --noplugin -u tests/init.lua -c "lua require('tests.framework').run_and_exit('tests/full_integration_spec.lua')" diff --git a/.gitignore b/.gitignore index 999c4c60..996e60d0 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,5 @@ example/ .DS_Store Thumbs.db .cache/ -tests/plenary.nvim compile_commands.json build/include/version.h diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 054d67fd..8651c46c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -286,13 +286,6 @@ The following dependencies are not bundled but are required for full functionali **Source**: https://github.com/MunifTanjim/nui.nvim **Purpose**: UI components for file explorer -### plenary.nvim - -**License**: MIT License -**Maintainers**: nvim-lua community -**Source**: https://github.com/nvim-lua/plenary.nvim -**Purpose**: Test framework (development only) - --- ## Architectural Inspiration diff --git a/CMakeLists.txt b/CMakeLists.txt index 9b7d9a08..9e01e009 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -65,7 +65,7 @@ test-c: build \t@cd build && ctest --output-on-failure test-lua: -\t@./tests/run_plenary_tests.sh +\t@./tests/run_tests.sh lint: \t@stylua --check lua @@ -119,7 +119,7 @@ test-c: build \tctest --test-dir build --output-on-failure -C Release test-lua: -\ttests\\run_plenary_tests.cmd +\ttests\\run_tests.cmd lint: \tstylua --check lua diff --git a/Makefile b/Makefile index 99ec60bf..19019255 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ test-c: build @cd build && ctest --output-on-failure test-lua: - @./tests/run_plenary_tests.sh + @./tests/run_tests.sh lint: @stylua --check lua diff --git a/Makefile.win b/Makefile.win index b17d2a7e..893a3c78 100644 --- a/Makefile.win +++ b/Makefile.win @@ -20,7 +20,7 @@ test-c: build ctest --test-dir build --output-on-failure -C Release test-lua: - tests\run_plenary_tests.cmd + tests\run_tests.cmd lint: stylua --check lua diff --git a/README.md b/README.md index 381c0153..e0f81c91 100644 --- a/README.md +++ b/README.md @@ -817,7 +817,7 @@ codediff.nvim/ │ └── vscode-diff/ # Backward compatibility shims ├── plugin/ # Plugin entry point │ └── codediff.lua # Auto-loaded on startup -├── tests/ # Test suite (plenary.nvim) +├── tests/ # Test suite (in-tree tests/framework/) ├── docs/ # Documentation and development history ├── Makefile # Build automation └── README.md @@ -835,7 +835,7 @@ codediff.nvim/ - [x] Syntax highlighting preservation (LSP semantic tokens + TreeSitter) - [x] Read-only buffers with virtual filler lines for alignment - [x] Flexible highlight configuration (colorscheme-aware) -- [x] Integration tests (C + Lua with plenary.nvim) +- [x] Integration tests (C + Lua via in-tree `tests/framework/` runner) - [x] File history mode (per-commit review, similar to DiffviewFileHistory) ### Future Enhancements diff --git a/VERSION b/VERSION index e7a9ca6a..54bbd78d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.59.0 +2.60.0 diff --git a/docs/development/05-architecture/timeout-mechanism.md b/docs/development/05-architecture/timeout-mechanism.md index fd7f9023..3ee9d2eb 100644 --- a/docs/development/05-architecture/timeout-mechanism.md +++ b/docs/development/05-architecture/timeout-mechanism.md @@ -85,7 +85,7 @@ Coverage: - 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('plenary.test_harness').test_file('tests/timeout_spec.lua')"` +Run: `nvim --headless -u tests/init.lua -c "lua require('tests.framework').run_and_exit('tests/timeout_spec.lua')"` ## Files Modified @@ -97,7 +97,7 @@ Run: `nvim --headless -u tests/init.lua -c "lua require('plenary.test_harness'). 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_plenary_tests.sh` - Added to test runner +9. `tests/run_tests.sh` - Added to test runner --- diff --git a/lua/codediff/core/argparse/README.md b/lua/codediff/core/argparse/README.md index c34cd39f..6b6a9358 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('plenary.test_harness').test_file('tests/core/argparse_spec.lua', { minimal_init = 'tests/init.lua' })" + -c "lua require('tests.framework').run_and_exit('tests/core/argparse_spec.lua')" ``` diff --git a/lua/codediff/core/git.lua b/lua/codediff/core/git.lua index a16451a5..beeeceee 100644 --- a/lua/codediff/core/git.lua +++ b/lua/codediff/core/git.lua @@ -105,6 +105,25 @@ end local function run_git_async(args, opts, callback) opts = opts or {} + local argv = { "git" } + if opts.no_optional_locks then + -- `--no-optional-locks` (git 2.15+) tells git to skip the *optional* index + -- refresh that read-only queries perform, which takes `.git/index.lock`. + -- Required locks (e.g. the one `git add` needs) are unaffected. + -- + -- The explorer polls status every 500ms. Without this, a poll landing while + -- the user stages or discards a hunk owns index.lock just long enough to + -- make the staging command fail with + -- `Unable to create '.../.git/index.lock': File exists`. + -- + -- `git status` and `git ls-files` honor it; `git diff` refreshes the index + -- regardless, so it is passed there for intent and forward-compatibility + -- only. Reads never fail on a contended lock either way — git falls back to + -- not refreshing. + table.insert(argv, "--no-optional-locks") + end + vim.list_extend(argv, args) + -- Use vim.system if available (Neovim 0.10+) if vim.system then -- On Windows, vim.system requires that cwd exists before running the command @@ -114,7 +133,7 @@ local function run_git_async(args, opts, callback) return end - vim.system(vim.list_extend({ "git" }, args), { + vim.system(argv, { cwd = opts.cwd, text = true, }, function(result) @@ -141,7 +160,9 @@ local function run_git_async(args, opts, callback) ---@diagnostic disable-next-line: missing-fields handle = vim.loop.spawn("git", { - args = args, + -- `argv` already carries `--no-optional-locks` when requested; `spawn` + -- takes the arguments *after* argv[0], so drop the leading "git". + args = vim.list_slice(argv, 2, #argv), cwd = opts.cwd, stdio = { nil, stdout, stderr }, }, function(code) @@ -349,7 +370,7 @@ function M.get_status(git_root, callback, pathspec) -- `-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 - { cwd = git_root }, + { cwd = git_root, no_optional_locks = true }, function(err, output) if err then callback(err, nil) @@ -413,7 +434,7 @@ end -- callback: function(err, status_result) where status_result has same format as get_status function M.get_diff_revision(revision, git_root, callback, pathspec) -- First get tracked file changes (trailing `-- ` scopes to a pathspec) - run_git_async(vim.list_extend({ "diff", "--name-status", "-M", revision, "--" }, pathspec or {}), { cwd = git_root }, function(err, output) + run_git_async(vim.list_extend({ "diff", "--name-status", "-M", revision, "--" }, pathspec or {}), { cwd = git_root, no_optional_locks = true }, function(err, output) if err then callback(err, nil) return @@ -462,7 +483,7 @@ function M.get_diff_revision(revision, git_root, callback, pathspec) table.insert(ls_args, "--directory") end table.insert(ls_args, "--") - run_git_async(vim.list_extend(ls_args, pathspec or {}), { cwd = git_root }, function(err_untracked, output_untracked) + run_git_async(vim.list_extend(ls_args, pathspec or {}), { cwd = git_root, no_optional_locks = true }, function(err_untracked, output_untracked) if err_untracked then -- If getting untracked files fails, just return what we have callback(nil, result) @@ -491,7 +512,7 @@ end -- git_root: absolute path to git repository root -- callback: function(err, status_result) function M.get_diff_revisions(rev1, rev2, git_root, callback, pathspec) - run_git_async(vim.list_extend({ "diff", "--name-status", "-M", rev1, rev2, "--" }, pathspec or {}), { cwd = git_root }, function(err, output) + run_git_async(vim.list_extend({ "diff", "--name-status", "-M", rev1, rev2, "--" }, pathspec or {}), { cwd = git_root, no_optional_locks = true }, function(err, output) if err then callback(err, nil) return diff --git a/lua/codediff/ui/history/refresh.lua b/lua/codediff/ui/history/refresh.lua index b0991c45..d8e350eb 100644 --- a/lua/codediff/ui/history/refresh.lua +++ b/lua/codediff/ui/history/refresh.lua @@ -69,6 +69,18 @@ function M.setup_auto_refresh(history, tabpage) {}, 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 diff --git a/lua/codediff/ui/view/helpers.lua b/lua/codediff/ui/view/helpers.lua index 345547dc..fac843c3 100644 --- a/lua/codediff/ui/view/helpers.lua +++ b/lua/codediff/ui/view/helpers.lua @@ -76,4 +76,56 @@ function M.prepare_buffer(is_virtual, git_root, revision, ref) end end +--- Display a real-file buffer in a window, re-syncing it with disk first. +--- +--- Neovim runs a timestamp check whenever a buffer becomes visible. When the +--- file was deleted behind our back (branch switch, `git stash`, external `rm`) +--- that check emits `E211: File ... no longer available`; worse, it can surface +--- as an error out of `nvim_win_set_buf` and abort view construction halfway. +--- +--- Running the check ourselves beforehand reloads the buffer when the file +--- really did change and clears the pending check either way, so the display +--- below stays quiet. `:checktime {buf}` is scoped to this buffer — a bare +--- `:checktime` walks every loaded buffer and would reload unrelated files. +--- `silent!` is required on top of `pcall`: for a buffer that is (or is about +--- to be) displayed, `:checktime` *reports* `E211` rather than raising it, so +--- `pcall` alone does not suppress it. A missing file has nothing to reload; +--- the deletion is picked up by the refresh that follows. +---@param win number Window handle +---@param bufnr number Buffer handle backed by a real file on disk +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) + end + vim.api.nvim_win_set_buf(win, bufnr) +end + +--- Load a real file into a buffer and display it in `win`. +--- +--- Uses `:edit` rather than `bufload()` for a not-yet-loaded buffer on purpose: +--- a buffer loaded outside of any window and then displayed comes back marked +--- `'modified'`, which makes Neovim refuse to ever reload it from disk (W12). +--- +--- When the buffer already exists it is reused as-is: `bufadd` resolves +--- `target` to the exact buffer Neovim would pick even when the path is spelled +--- differently (a symlinked directory such as macOS `/tmp`, a `./` segment), +--- which is precisely the case where `:edit` would fail with `E211` for a file +--- that has since been deleted. +---@param win number Window handle +---@param target string Absolute path of the file to load +---@return number bufnr +function M.open_real_file(win, target) + local bufnr = vim.fn.bufadd(target) + if vim.api.nvim_buf_is_loaded(bufnr) then + M.show_real_file_buffer(win, bufnr) + return bufnr + end + + vim.api.nvim_set_current_win(win) + vim.cmd("edit " .. vim.fn.fnameescape(target)) + return vim.api.nvim_get_current_buf() +end + return M diff --git a/lua/codediff/ui/view/inline_view.lua b/lua/codediff/ui/view/inline_view.lua index 825b768d..4fb43071 100644 --- a/lua/codediff/ui/view/inline_view.lua +++ b/lua/codediff/ui/view/inline_view.lua @@ -17,6 +17,8 @@ local helpers = require("codediff.ui.view.helpers") local panel = require("codediff.ui.view.panel") 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 function disable_refresh_and_clear_highlights(session) for _, bufnr in pairs({ session.original_bufnr, session.modified_bufnr }) do @@ -183,12 +185,17 @@ function M.create(session_config, filetype, on_ready) local modified_info = prepare_buffer(modified_is_virtual, session_config.git_root, session_config.modified_revision, session_config.modified) -- Load modified buffer into the visible window - if modified_info.needs_edit then - local cmd = modified_is_virtual and "edit! " or "edit " - vim.cmd(cmd .. vim.fn.fnameescape(modified_info.target)) - modified_info.bufnr = vim.api.nvim_get_current_buf() + if modified_is_virtual then + if modified_info.needs_edit then + vim.cmd("edit! " .. vim.fn.fnameescape(modified_info.target)) + modified_info.bufnr = vim.api.nvim_get_current_buf() + else + vim.api.nvim_win_set_buf(modified_win, modified_info.bufnr) + end + elseif modified_info.needs_edit then + modified_info.bufnr = open_real_file(modified_win, modified_info.target) else - vim.api.nvim_win_set_buf(modified_win, modified_info.bufnr) + show_real_file_buffer(modified_win, modified_info.bufnr) end welcome_window.sync(modified_win) @@ -382,16 +389,11 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) else local modified_info = prepare_buffer(false, session_config.git_root, nil, session_config.modified) if modified_info.needs_edit then - local bufnr = vim.fn.bufadd(modified_info.target) - vim.fn.bufload(bufnr) - mod_buf = bufnr + mod_buf = open_real_file(modified_win, modified_info.target) else mod_buf = modified_info.bufnr - vim.api.nvim_buf_call(mod_buf, function() - vim.cmd("checktime") - end) + show_real_file_buffer(modified_win, mod_buf) end - vim.api.nvim_win_set_buf(modified_win, mod_buf) end welcome_window.sync(modified_win) @@ -577,9 +579,7 @@ function M.show_single_file(tabpage, file_path, opts) welcome_window.sync(mod_win) else -- Real file - file_bufnr = vim.fn.bufadd(file_path) - vim.fn.bufload(file_bufnr) - vim.api.nvim_win_set_buf(mod_win, file_bufnr) + file_bufnr = open_real_file(mod_win, file_path) welcome_window.sync(mod_win) end diff --git a/lua/codediff/ui/view/side_by_side.lua b/lua/codediff/ui/view/side_by_side.lua index fb0f518d..92a300a4 100644 --- a/lua/codediff/ui/view/side_by_side.lua +++ b/lua/codediff/ui/view/side_by_side.lua @@ -24,6 +24,8 @@ local welcome_window = require("codediff.ui.view.welcome_window") 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 compute_and_render = render.compute_and_render local compute_and_render_conflict = render.compute_and_render_conflict local setup_auto_refresh = render.setup_auto_refresh @@ -92,24 +94,34 @@ function M.create(session_config, filetype, on_ready) original_win = vim.api.nvim_get_current_win() -- Load original buffer - if original_info.needs_edit then - local cmd = original_is_virtual and "edit! " or "edit " - vim.cmd(cmd .. vim.fn.fnameescape(original_info.target)) - original_info.bufnr = vim.api.nvim_get_current_buf() + if original_is_virtual then + if original_info.needs_edit then + vim.cmd("edit! " .. vim.fn.fnameescape(original_info.target)) + original_info.bufnr = vim.api.nvim_get_current_buf() + else + vim.api.nvim_win_set_buf(original_win, original_info.bufnr) + end + elseif original_info.needs_edit then + original_info.bufnr = open_real_file(original_win, original_info.target) else - vim.api.nvim_win_set_buf(original_win, original_info.bufnr) + show_real_file_buffer(original_win, original_info.bufnr) end vim.cmd(split_cmd) modified_win = vim.api.nvim_get_current_win() -- Load modified buffer - if modified_info.needs_edit then - local cmd = modified_is_virtual and "edit! " or "edit " - vim.cmd(cmd .. vim.fn.fnameescape(modified_info.target)) - modified_info.bufnr = vim.api.nvim_get_current_buf() + if modified_is_virtual then + if modified_info.needs_edit then + vim.cmd("edit! " .. vim.fn.fnameescape(modified_info.target)) + modified_info.bufnr = vim.api.nvim_get_current_buf() + else + vim.api.nvim_win_set_buf(modified_win, modified_info.bufnr) + end + elseif modified_info.needs_edit then + modified_info.bufnr = open_real_file(modified_win, modified_info.target) else - vim.api.nvim_win_set_buf(modified_win, modified_info.bufnr) + show_real_file_buffer(modified_win, modified_info.bufnr) end welcome_window.sync(original_win) welcome_window.sync(modified_win) @@ -598,18 +610,14 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) original_info.bufnr = vim.api.nvim_get_current_buf() end else - local bufnr = vim.fn.bufadd(original_info.target) - vim.fn.bufload(bufnr) - original_info.bufnr = bufnr - vim.api.nvim_win_set_buf(original_win, original_info.bufnr) + original_info.bufnr = open_real_file(original_win, original_info.target) end else if vim.api.nvim_buf_is_valid(original_info.bufnr) then - vim.api.nvim_win_set_buf(original_win, original_info.bufnr) - if not original_is_virtual then - vim.api.nvim_buf_call(original_info.bufnr, function() - vim.cmd("checktime") - end) + if original_is_virtual then + vim.api.nvim_win_set_buf(original_win, original_info.bufnr) + else + show_real_file_buffer(original_win, original_info.bufnr) end else if original_is_virtual then @@ -617,10 +625,7 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) vim.cmd("edit! " .. vim.fn.fnameescape(original_info.target)) original_info.bufnr = vim.api.nvim_get_current_buf() else - local bufnr = vim.fn.bufadd(original_info.target) - vim.fn.bufload(bufnr) - original_info.bufnr = bufnr - vim.api.nvim_win_set_buf(original_win, original_info.bufnr) + original_info.bufnr = open_real_file(original_win, original_info.target) end end end @@ -638,18 +643,14 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) modified_info.bufnr = vim.api.nvim_get_current_buf() end else - local bufnr = vim.fn.bufadd(modified_info.target) - vim.fn.bufload(bufnr) - modified_info.bufnr = bufnr - vim.api.nvim_win_set_buf(modified_win, modified_info.bufnr) + modified_info.bufnr = open_real_file(modified_win, modified_info.target) end else if vim.api.nvim_buf_is_valid(modified_info.bufnr) then - vim.api.nvim_win_set_buf(modified_win, modified_info.bufnr) - if not modified_is_virtual then - vim.api.nvim_buf_call(modified_info.bufnr, function() - vim.cmd("checktime") - end) + if modified_is_virtual then + vim.api.nvim_win_set_buf(modified_win, modified_info.bufnr) + else + show_real_file_buffer(modified_win, modified_info.bufnr) end else if modified_is_virtual then @@ -657,10 +658,7 @@ function M.update(tabpage, session_config, auto_scroll_to_first_hunk) vim.cmd("edit! " .. vim.fn.fnameescape(modified_info.target)) modified_info.bufnr = vim.api.nvim_get_current_buf() else - local bufnr = vim.fn.bufadd(modified_info.target) - vim.fn.bufload(bufnr) - modified_info.bufnr = bufnr - vim.api.nvim_win_set_buf(modified_win, modified_info.bufnr) + modified_info.bufnr = open_real_file(modified_win, modified_info.target) end end end @@ -789,7 +787,7 @@ local function show_single_file(tabpage, opts) -- Load the file into the kept window if keep_win and vim.api.nvim_win_is_valid(keep_win) then - vim.api.nvim_win_set_buf(keep_win, opts.load_bufnr) + show_real_file_buffer(keep_win, opts.load_bufnr) welcome_window.sync(keep_win) if opts.keep == "original" then diff --git a/tests/README.md b/tests/README.md index fd3cc378..6527a436 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,6 +1,8 @@ # Test Suite -Integration tests for codediff.nvim using [plenary.nvim](https://github.com/nvim-lua/plenary.nvim). +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 @@ -53,15 +55,54 @@ LSP integration and rendering: ### All tests: ```bash -./tests/run_plenary_tests.sh +./tests/run_tests.sh # or: make test-lua ``` +Spec files are auto-discovered under `tests/`, so a new `*_spec.lua` is picked +up with no runner changes. + ### Individual spec: ```bash nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('plenary.test_harness').test_directory('tests/ffi_integration_spec.lua')" + -c "lua require('tests.framework').run_and_exit('tests/core/ffi_integration_spec.lua')" ``` +### 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, which cuts the suite from ~150s to +~35s on a 4-core machine. + +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. + +### 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). + +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. + +| 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. | + ## Test Philosophy Focus on **integration points** that C tests cannot validate: @@ -70,8 +111,6 @@ Focus on **integration points** that C tests cannot validate: - System integration (git) - UI behavior (scrolling, rendering) -**Total: 46 tests** across 5 spec files using industry-standard plenary.nvim framework. - ## What's NOT Covered ❌ **Diff algorithm** - Validated by C tests in `c-diff-core/tests/` (3,490 lines) diff --git a/tests/command_e2e_spec.lua b/tests/command_e2e_spec.lua index 25dc5267..83f95af1 100644 --- a/tests/command_e2e_spec.lua +++ b/tests/command_e2e_spec.lua @@ -3,7 +3,7 @@ -- (diff buffer contents, explorer file list, history commits, layout) — not just -- that dispatch routed correctly. -- --- Scope note: the plenary harness cannot drive the async codediff:// virtual-file +-- 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 diff --git a/tests/core/git_integration_spec.lua b/tests/core/git_integration_spec.lua index 12f2a359..cb4b1ed5 100644 --- a/tests/core/git_integration_spec.lua +++ b/tests/core/git_integration_spec.lua @@ -407,3 +407,116 @@ describe("Git untracked policy (#389)", function() 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.dir .. "/.git/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.dir .. "/.git/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/framework/assert.lua b/tests/framework/assert.lua new file mode 100644 index 00000000..d4bd68d8 --- /dev/null +++ b/tests/framework/assert.lua @@ -0,0 +1,268 @@ +-- tests/framework/assert.lua +-- +-- Assertion library that mirrors the subset of luassert used across the spec files. +-- +-- Design: this module returns a callable table. Assigning it to `_G.assert` +-- keeps stdlib behavior intact (`assert(cond)` / `assert(cond, msg)` / passthrough +-- of extra return values from expressions like `assert(fn())`) via `__call`, while +-- exposing the rich `.equals`, `.is_true`, `.are.same`, `.has_no.errors`, etc. +-- helpers used by the specs. + +local M = {} + +-- --------------------------------------------------------------------------- +-- Formatting helpers +-- --------------------------------------------------------------------------- + +local function fmt(v) + local ok, s = pcall(vim.inspect, v) + if ok then return s end + return tostring(v) +end + +local function fail(msg, level) + error(msg, (level or 2) + 1) +end + +-- --------------------------------------------------------------------------- +-- Deep equality (delegates to vim.deep_equal, which handles nested tables, +-- mixed keys and cycles). +-- --------------------------------------------------------------------------- + +local function deep_equal(a, b) + if a == b then return true end + if type(a) ~= type(b) then return false end + if type(a) ~= "table" then return false end + return vim.deep_equal(a, b) +end + +-- Strict equality follows luassert's `assert.equal`: for tables this is +-- reference identity, for primitives it degenerates to `==`. This distinction +-- matters: several specs rely on `assert.are_not.equal` to check that two +-- table results are separate copies even when their content is identical +-- (e.g. LRU cache tests). +local function strict_equal(a, b) + return a == b +end + +-- --------------------------------------------------------------------------- +-- Core assertion helpers +-- --------------------------------------------------------------------------- + +function M.equals(expected, actual, msg) + if not strict_equal(expected, actual) then + fail(string.format( + "%s\nExpected: %s\nActual: %s", + msg or "Values are not equal", + fmt(expected), + fmt(actual) + ), 2) + end +end +M.equal = M.equals + +function M.same(expected, actual, msg) + if not deep_equal(expected, actual) then + fail(string.format( + "%s\nExpected: %s\nActual: %s", + msg or "Values are not the same", + fmt(expected), + fmt(actual) + ), 2) + end +end + +function M.not_equal(a, b, msg) + if strict_equal(a, b) then + fail(string.format( + "%s\nExpected values to differ, both were:\n %s", + msg or "Values are equal but should differ", + fmt(a) + ), 2) + end +end + +function M.not_same(a, b, msg) + if deep_equal(a, b) then + fail(string.format( + "%s\nExpected values to differ, both were:\n %s", + msg or "Values are the same but should differ", + fmt(a) + ), 2) + end +end + +function M.is_true(v, msg) + if v ~= true then + fail(string.format( + "%s\nExpected: true\nActual: %s", + msg or "Expected value to be true", + fmt(v) + ), 2) + end +end + +function M.is_false(v, msg) + if v ~= false then + fail(string.format( + "%s\nExpected: false\nActual: %s", + msg or "Expected value to be false", + fmt(v) + ), 2) + end +end + +function M.is_nil(v, msg) + if v ~= nil then + fail(string.format( + "%s\nExpected: nil\nActual: %s", + msg or "Expected value to be nil", + fmt(v) + ), 2) + end +end + +function M.is_not_nil(v, msg) + if v == nil then + fail(msg or "Expected value to be non-nil, got nil", 2) + end +end + +function M.is_truthy(v, msg) + if not v then + fail(string.format( + "%s\nExpected truthy value, got: %s", + msg or "Expected value to be truthy", + fmt(v) + ), 2) + end +end + +function M.is_falsy(v, msg) + if v then + fail(string.format( + "%s\nExpected falsy value, got: %s", + msg or "Expected value to be falsy", + fmt(v) + ), 2) + end +end + +local function type_check(expected_type) + return function(v, msg) + if type(v) ~= expected_type then + fail(string.format( + "%s\nExpected type: %s\nActual type: %s\nValue: %s", + msg or ("Expected value to be a " .. expected_type), + expected_type, + type(v), + fmt(v) + ), 2) + end + end +end + +M.is_function = type_check("function") +M.is_table = type_check("table") +M.is_number = type_check("number") +M.is_string = type_check("string") +M.is_boolean = type_check("boolean") + +function M.matches(pattern, s, msg) + if type(s) ~= "string" or not s:find(pattern) then + fail(string.format( + "%s\nExpected string matching: %s\nActual: %s", + msg or "Value does not match pattern", + fmt(pattern), + fmt(s) + ), 2) + end +end + +function M.has_no_errors(fn, msg) + local ok, err = pcall(fn) + if not ok then + fail(string.format( + "%s\nExpected no error, got: %s", + msg or "Function raised an error", + tostring(err) + ), 2) + end +end + +function M.has_error(fn, expected, msg) + local ok, err = pcall(fn) + if ok then + fail(msg or "Expected function to raise an error, but it did not", 2) + end + if expected ~= nil and not deep_equal(expected, err) then + if type(expected) ~= "string" or type(err) ~= "string" or not err:find(expected, 1, true) then + fail(string.format( + "%s\nExpected error: %s\nActual error: %s", + msg or "Error did not match expected", + fmt(expected), + fmt(err) + ), 2) + end + end +end + +-- --------------------------------------------------------------------------- +-- Chainable sub-tables (`assert.are.equal`, `assert.is_not.equal`, etc.) +-- --------------------------------------------------------------------------- + +M.are = { + equal = M.equals, + equals = M.equals, + same = M.same, +} + +M.are_not = { + equal = M.not_equal, + equals = M.not_equal, + same = M.not_same, +} + +M.is_not = { + equal = M.not_equal, + equals = M.not_equal, + same = M.not_same, + ["nil"] = M.is_not_nil, +} + +M.is = { + equal = M.equals, + equals = M.equals, + same = M.same, + truthy = M.is_truthy, + falsy = M.is_falsy, + ["true"] = M.is_true, + ["false"] = M.is_false, + ["nil"] = M.is_nil, +} + +M.has_no = { + errors = M.has_no_errors, + error = M.has_no_errors, +} + +M.has = { + errors = M.has_error, + error = M.has_error, + no = M.has_no, +} + +-- --------------------------------------------------------------------------- +-- Callable table: keeps stdlib `assert(cond[, msg, ...])` behavior and passes +-- through all return values (needed for patterns like `local m = assert(fn())`). +-- --------------------------------------------------------------------------- + +return setmetatable(M, { + __call = function(_, v, ...) + if not v then + local msg = ... + error(msg or "assertion failed!", 2) + end + return v, ... + end, +}) diff --git a/tests/framework/busted.lua b/tests/framework/busted.lua new file mode 100644 index 00000000..7e2c9988 --- /dev/null +++ b/tests/framework/busted.lua @@ -0,0 +1,184 @@ +-- tests/framework/busted.lua +-- +-- Minimal busted-compatible test collector. Installs the `describe`, `it`, +-- `before_each`, `after_each` and `pending` globals. Test execution is handled +-- by tests/framework/runner.lua. + +local M = {} + +-- Sentinel error raised by `pending()` inside a running test to unwind the +-- stack cleanly. The runner treats a test with `state.pending == true` as +-- pending regardless of whether the sentinel is what surfaced from xpcall. +local PENDING_SENTINEL = {} +M.PENDING_SENTINEL = PENDING_SENTINEL + +-- --------------------------------------------------------------------------- +-- State +-- --------------------------------------------------------------------------- + +local root, current, all_tests +local runtime_state + +local function make_group(name, parent) + return { + name = name, + parent = parent, + before_each = {}, + after_each = {}, + tests = {}, + children = {}, + } +end + +local function reset() + root = make_group("", nil) + current = root + all_tests = {} + runtime_state = { current_test = nil } +end + +reset() + +M.reset = reset + +-- --------------------------------------------------------------------------- +-- Test/group registration +-- --------------------------------------------------------------------------- + +local function add_test(name, fn, opts) + opts = opts or {} + local test = { + name = name, + fn = fn, + group = current, + pending = opts.pending or false, + pending_msg = opts.pending_msg, + } + table.insert(current.tests, test) + table.insert(all_tests, test) + return test +end + +local function do_describe(name, fn) + local group = make_group(name, current) + table.insert(current.children, group) + local prev = current + current = group + local ok, err = xpcall(fn, function(e) + return debug.traceback(tostring(e), 2) + end) + current = prev + if not ok then + -- describe body itself raised — surface it as a failing pseudo-test so the + -- runner reports it rather than dying silently during collection. + add_test("", function() + error(err, 0) + end) + end +end + +local function do_it(name, fn) + return add_test(name, fn) +end + +local function do_pending(name_or_msg, fn) + if fn then + -- describe-level pending placeholder: `pending("name", function() ... end)` + return add_test(name_or_msg or "pending", fn, { pending = true, pending_msg = name_or_msg }) + end + + if runtime_state.current_test then + -- Called mid-test: mark the running test pending and unwind via sentinel. + runtime_state.current_test.pending = true + runtime_state.current_test.pending_msg = name_or_msg + error(PENDING_SENTINEL, 2) + end + + -- Called at describe body level with no fn: create a body-less pending entry. + return add_test(name_or_msg or "pending", nil, { pending = true, pending_msg = name_or_msg }) +end + +-- --------------------------------------------------------------------------- +-- Installation of globals +-- --------------------------------------------------------------------------- + +local installed = false + +function M.install() + if installed then return end + installed = true + + _G.describe = do_describe + _G.it = do_it + _G.pending = do_pending + + _G.before_each = function(fn) + table.insert(current.before_each, fn) + end + + _G.after_each = function(fn) + table.insert(current.after_each, fn) + end +end + +-- --------------------------------------------------------------------------- +-- Query API used by the runner +-- --------------------------------------------------------------------------- + +function M.get_tests() + return all_tests +end + +--- Return the ordered describe-block names from root down to the test. +function M.describe_chain(test) + local names = {} + local node = test.group + while node and node.parent do + table.insert(names, 1, node.name) + node = node.parent + end + return names +end + +--- Return the flat list of hooks that should run for a test. +-- @param test any +-- @param kind "before_each" or "after_each" +-- Ordering: +-- before_each: outer -> inner (root's first, test's group last) +-- after_each: inner -> outer (test's group first, root's last) +function M.hooks_for(test, kind) + local chain = {} + local node = test.group + while node do + table.insert(chain, 1, node) -- prepend so root ends up first + node = node.parent + end + + local hooks = {} + if kind == "before_each" then + for _, group in ipairs(chain) do + for _, h in ipairs(group.before_each) do + table.insert(hooks, h) + end + end + else -- after_each + for i = #chain, 1, -1 do + local group = chain[i] + for _, h in ipairs(group.after_each) do + table.insert(hooks, h) + end + end + end + return hooks +end + +--- Runtime state accessor used by the runner to mark the currently executing test. +function M.set_current(test) + runtime_state.current_test = test +end + +function M.get_current() + return runtime_state.current_test +end + +return M diff --git a/tests/framework/init.lua b/tests/framework/init.lua new file mode 100644 index 00000000..6c628939 --- /dev/null +++ b/tests/framework/init.lua @@ -0,0 +1,63 @@ +-- tests/framework/init.lua +-- +-- Public entry point for the codediff.nvim test framework. This module owns +-- the process-level setup: augmenting the global `assert`, installing the +-- 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. + +local M = {} + +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 + installed = true + + -- Assertion library replaces `_G.assert`. It is a callable table so the + -- stdlib form `assert(cond[, msg, ...])` continues to work with full + -- passthrough of extra return values. + local a = require("tests.framework.assert") + _G.assert = a + + -- 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 + + -- describe/it/before_each/after_each/pending globals + require("tests.framework.busted").install() +end + +--- Run a single spec file. Returns (ok, counts). +function M.run_file(spec_file) + return require("tests.framework.runner").run_file(spec_file) +end + +--- Run a single spec file and exit Neovim with the appropriate exit code. +--- Used by the child processes the supervisor spawns. +function M.run_and_exit(spec_file) + return require("tests.framework.runner").run_and_exit(spec_file) +end + +--- Run every discovered spec file. Returns (ok, results). +--- Concurrency and output grouping live in the supervisor; see its header. +function M.run_all(opts) + return require("tests.framework.supervisor").run(opts) +end + +--- Run every discovered spec file and exit with the appropriate exit code. +--- This is the single entry point used by tests/run_tests.{sh,cmd}. +function M.run_all_and_exit(opts) + return require("tests.framework.supervisor").run_and_exit(opts) +end + +return M diff --git a/tests/framework/reporter.lua b/tests/framework/reporter.lua new file mode 100644 index 00000000..e42bd944 --- /dev/null +++ b/tests/framework/reporter.lua @@ -0,0 +1,234 @@ +-- tests/framework/reporter.lua +-- +-- Stdout reporter used by tests/framework/runner.lua. Prints one line per test +-- (with color prefix), a failure block with traceback when tests fail, and a +-- summary line per spec file. +-- +-- It also owns the suite-level output used by tests/framework/supervisor.lua +-- (banner, per-spec block emission, aggregate summary) so that every byte the +-- test suite prints is formatted in exactly one place. + +local M = {} + +-- --------------------------------------------------------------------------- +-- Colors +-- --------------------------------------------------------------------------- + +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 + -- 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 + 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 + +-- --------------------------------------------------------------------------- +-- Output primitives +-- --------------------------------------------------------------------------- + +local function write(line) + -- Use io.write + "\n" so output is line-buffered and shows up in `nvim + -- --headless` runs immediately (Neovim's `print` also works, but io.write + -- integrates better with shell pipes on Windows). + io.write(line, "\n") +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 + end + return table.concat(out, "\n") +end + +-- --------------------------------------------------------------------------- +-- Public API +-- --------------------------------------------------------------------------- + +function M.print_header(spec_file) + write(cyan("┌─ " .. spec_file)) +end + +--- Print one test's result. +-- @param names table describe-name chain (outermost first, may be empty) +-- @param test_name string +-- @param status "pass" | "fail" | "pending" +-- @param message string|nil (failure traceback or pending reason) +-- @param duration_ms number|nil +function M.print_test(names, test_name, status, message, duration_ms) + local prefix + if status == "pass" then + prefix = green(" ✓") + elseif status == "fail" then + prefix = red(" ✗") + else + prefix = yellow(" -") + end + + local desc_str = "" + if #names > 0 then + desc_str = dim(table.concat(names, " › ") .. " › ") + end + + local dur = "" + if status == "pass" and duration_ms and duration_ms > 0 then + dur = " " .. dim("(" .. duration_ms .. "ms)") + end + + write(prefix .. " " .. desc_str .. test_name .. dur) + + if message and message ~= "" then + write(indent(" " .. (status == "fail" and red("│ ") or yellow("│ ")), message)) + end +end + +function M.print_summary(spec_file, pass, fail, pending, total_ms) + local parts = {} + table.insert(parts, green(pass .. " passed")) + if fail > 0 then + table.insert(parts, red(fail .. " failed")) + else + table.insert(parts, fail .. " failed") + end + if pending > 0 then + table.insert(parts, yellow(pending .. " pending")) + else + table.insert(parts, pending .. " pending") + end + + local prefix + if fail > 0 then + prefix = red("└─ FAIL ") + elseif pass == 0 and pending == 0 then + prefix = yellow("└─ EMPTY ") + else + prefix = green("└─ OK ") + end + + write(prefix .. spec_file .. " " .. table.concat(parts, ", ") .. dim(" (" .. total_ms .. "ms)")) +end + +function M.print_load_error(spec_file, err) + write(red("┌─ LOAD ERROR ") .. spec_file) + write(indent(" " .. red("│ "), err)) + write(red("└─ FAIL ") .. spec_file) +end + +-- --------------------------------------------------------------------------- +-- Suite-level output (used by tests/framework/supervisor.lua) +-- --------------------------------------------------------------------------- + +local BOX_WIDTH = 62 + +--- Draw one `║ ... ║` row, padded to BOX_WIDTH by *display* width so that ANSI +--- 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 + 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 + +--- Banner printed once, before any spec runs. +-- @param spec_count number +-- @param mode "parallel"|"sequential" +-- @param jobs number concurrent workers (1 in sequential mode) +-- @param reason string|nil why sequential mode was chosen +function M.print_suite_header(spec_count, mode, jobs, reason) + write("") + write(box_top()) + write(box_row("codediff.nvim Test Suite", "codediff.nvim Test Suite")) + local detail + if mode == "parallel" then + 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 + end + write(box_row(dim(detail), detail)) + write(box_bottom()) + write("") +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 +-- in full by the supervisor and handed here, so no other spec's output can +-- land in the middle of it. Child processes must therefore never share this +-- process's stdout. +-- +-- Trailing newlines are normalized to exactly one: Neovim writes some messages +-- (e.g. `E211: File ... no longer available`) without a trailing newline, which +-- would otherwise glue the next block's header onto the last line. +-- +-- stderr is appended after stdout because the two streams are captured +-- separately, so it lands after the block's `└─` footer. It is labelled with +-- the spec name, otherwise those incidental Neovim messages read as +-- unattributed noise sitting between two blocks. +-- @param spec string spec path, used to label the stderr section +-- @param stdout string captured child stdout (framework output) +-- @param stderr string|nil captured child stderr (incidental Neovim messages) +function M.emit_block(spec, stdout, stderr) + local chunk = stdout or "" + if stderr and stderr ~= "" then + local label = "── stderr from " .. spec .. " ──" + chunk = chunk:gsub("\n*$", "\n") .. dim(label) .. "\n" .. stderr + end + chunk = chunk:gsub("\n*$", "") + if chunk == "" then return end + write(chunk) +end + +--- Aggregate summary printed once, after every spec has finished. +-- @param results table list of { spec, ok, timed_out } +-- @param total_ms number wall-clock time for the whole suite +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 + end + + -- Deterministic regardless of completion order, so CI logs stay diffable. + table.sort(failures, function(a, b) return a.spec < b.spec end) + + write("") + if #failures > 0 then + write(red("Failed spec files:")) + for _, r in ipairs(failures) do + write(red(" ✗ ") .. r.spec .. (r.timed_out and dim(" (timed out)") or "")) + end + write("") + end + + local seconds = string.format("%.1fs", total_ms / 1000) + write(box_top()) + if #results == 0 then + -- An empty run is a failure, never a pass: it means discovery broke, which + -- would otherwise silently disable the whole suite in CI. + local plain = "✗ NO SPEC FILES FOUND" + write(box_row(red(plain), plain)) + elseif #failures == 0 then + local plain = string.format("✓ ALL TESTS PASSED (%d spec files, %s)", #results, seconds) + write(box_row(green(plain), plain)) + else + local plain = string.format("✗ %d OF %d SPEC FILE(S) FAILED (%s)", #failures, #results, seconds) + write(box_row(red(plain), plain)) + end + write(box_bottom()) + write("") +end + +return M diff --git a/tests/framework/runner.lua b/tests/framework/runner.lua new file mode 100644 index 00000000..0753f0f7 --- /dev/null +++ b/tests/framework/runner.lua @@ -0,0 +1,164 @@ +-- tests/framework/runner.lua +-- +-- Executes tests collected by tests/framework/busted.lua and dispatches them +-- through tests/framework/reporter.lua. + +local busted = require("tests.framework.busted") +local reporter = require("tests.framework.reporter") + +local M = {} + +-- --------------------------------------------------------------------------- +-- Helpers +-- --------------------------------------------------------------------------- + +local function hrtime_ms() + -- `vim.uv` is 0.10+; `vim.loop` is the pre-0.10 spelling. + return math.floor((vim.uv or vim.loop).hrtime() / 1e6) +end + +local function traceback(e) + -- Preserve pending sentinel intact so the runner can detect it. + if e == busted.PENDING_SENTINEL then return e end + return debug.traceback(tostring(e), 2) +end + +--- Run a function with xpcall + traceback; returns ok, err. +local function guarded(fn) + return xpcall(fn, traceback) +end + +-- --------------------------------------------------------------------------- +-- Test execution +-- --------------------------------------------------------------------------- + +local function run_test(test) + local desc = busted.describe_chain(test) + local test_start = hrtime_ms() + + -- Registered as pending — via `pending("name", fn)` or body-less + -- `pending("msg")` at describe level. Skip hooks and body entirely. + -- (Mid-test `pending()` toggles this flag from inside the body, but we've + -- already dispatched by then so this branch is only for pre-registered + -- pending tests.) + if test.pending then + reporter.print_test(desc, test.name, "pending", test.pending_msg) + return "pending" + end + + -- Run before_each hooks (outer -> inner) + busted.set_current(test) + local before_err + for _, hook in ipairs(busted.hooks_for(test, "before_each")) do + local ok, err = guarded(hook) + if not ok then + before_err = err + break + end + end + + -- Run the test body + local test_err + if not before_err then + local ok, err = guarded(test.fn) + if not ok and err ~= busted.PENDING_SENTINEL then + test_err = err + end + end + + -- Run after_each hooks (inner -> outer). Always run, even on failure. + local after_errs = {} + for _, hook in ipairs(busted.hooks_for(test, "after_each")) do + local ok, err = guarded(hook) + if not ok then + table.insert(after_errs, err) + end + end + busted.set_current(nil) + + local duration_ms = hrtime_ms() - test_start + + -- Compose result + if before_err then + local msg = "[before_each] " .. tostring(before_err) + if #after_errs > 0 then + msg = msg .. "\n[after_each] " .. table.concat(after_errs, "\n[after_each] ") + end + reporter.print_test(desc, test.name, "fail", msg, duration_ms) + return "fail" + end + + if test.pending then + -- pending() was called inside the running body + reporter.print_test(desc, test.name, "pending", test.pending_msg) + return "pending" + end + + if test_err then + local msg = tostring(test_err) + if #after_errs > 0 then + msg = msg .. "\n[after_each] " .. table.concat(after_errs, "\n[after_each] ") + end + reporter.print_test(desc, test.name, "fail", msg, duration_ms) + return "fail" + end + + if #after_errs > 0 then + reporter.print_test(desc, test.name, "fail", + "[after_each] " .. table.concat(after_errs, "\n[after_each] "), duration_ms) + return "fail" + end + + reporter.print_test(desc, test.name, "pass", nil, duration_ms) + return "pass" +end + +-- --------------------------------------------------------------------------- +-- Public API +-- --------------------------------------------------------------------------- + +--- Run a single spec file. Returns (ok, counts) where counts is a table with +-- `pass`, `fail`, `pending`. +function M.run_file(spec_file) + busted.reset() + + reporter.print_header(spec_file) + + local total_start = hrtime_ms() + + -- Load the spec; this triggers describe/it registration. + local load_ok, load_err = xpcall(function() + return dofile(spec_file) + end, function(e) + return debug.traceback(tostring(e), 2) + end) + + if not load_ok then + reporter.print_load_error(spec_file, load_err) + return false, { pass = 0, fail = 1, pending = 0 } + end + + local counts = { pass = 0, fail = 0, pending = 0 } + for _, test in ipairs(busted.get_tests()) do + local status = run_test(test) + counts[status] = counts[status] + 1 + end + + local total_ms = hrtime_ms() - total_start + reporter.print_summary(spec_file, counts.pass, counts.fail, counts.pending, total_ms) + + return counts.fail == 0, counts +end + +--- Convenience entry point used by the shell scripts: +--- runs the file and exits Neovim with the appropriate exit code. +function M.run_and_exit(spec_file) + local ok = M.run_file(spec_file) + if ok then + vim.cmd("qa!") + else + vim.cmd("cq 1") + end +end + +return M diff --git a/tests/framework/supervisor.lua b/tests/framework/supervisor.lua new file mode 100644 index 00000000..6a98ee5e --- /dev/null +++ b/tests/framework/supervisor.lua @@ -0,0 +1,252 @@ +-- tests/framework/supervisor.lua +-- +-- Runs the whole spec suite from a single parent Neovim process. +-- +-- Each spec file still executes in its own child `nvim --headless` process, so +-- process isolation is byte-for-byte what the old shell loop provided. What +-- changes is that the *parent* owns discovery, concurrency and output: +-- +-- * Concurrency lives here, not in the shell, so `run_tests.sh` and +-- `run_tests.cmd` become identical thin wrappers and Windows gets the same +-- behavior as POSIX without needing `xargs -P` or GNU parallel. +-- +-- * Output is grouped. Children never inherit this process's stdout; their +-- output is buffered in full and emitted as one contiguous block when they +-- exit (see reporter.emit_block). Letting N concurrent children share one +-- fd interleaves their output — block-wise, because stdout is fully +-- buffered when it is not a tty, and even line-wise, because Neovim writes +-- some messages without a trailing newline. +-- +-- * Concurrency requires `vim.system()` (Neovim 0.10+). On older versions the +-- suite falls back to running the same children one at a time via +-- `vim.fn.system()`, which produces identical output, just slower. + +local reporter = require("tests.framework.reporter") + +local M = {} + +-- `vim.uv` is 0.10+; `vim.loop` is the pre-0.10 spelling. Resolved here so the +-- sequential fallback below is actually reachable on the versions it targets. +local uv = vim.uv or vim.loop + +-- --------------------------------------------------------------------------- +-- Configuration +-- --------------------------------------------------------------------------- + +-- Per-spec wall-clock budget. Deliberately generous: it exists to stop a hung +-- spec from hanging CI forever, not to police slow specs. +local DEFAULT_TIMEOUT_MS = 300000 + +local function env_number(name) + local raw = vim.env[name] + if not raw or raw == "" then return nil end + local n = tonumber(raw) + if not n or n < 1 then return nil end + return math.floor(n) +end + +--- Default worker count. +-- +-- The suite is dominated by specs blocked in `vim.wait` on async git/render +-- work rather than by CPU, so oversubscribing cores measurably helps. Capped +-- so a many-core machine doesn't spawn dozens of Neovim processes. +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 + return math.max(2, math.min(cpus * 2, 16)) +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" + local root = vim.fn.getcwd():gsub("\\", "/") + + local matches = vim.fn.globpath(dir, "**/*_spec.lua", true, true) + + local specs = {} + for _, path in ipairs(matches) do + local norm = path: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 + norm = norm:sub(#root + 2) + end + table.insert(specs, norm) + end + + table.sort(specs) + return specs +end + +-- --------------------------------------------------------------------------- +-- Child process +-- --------------------------------------------------------------------------- + +--- Argument vector for the child that runs exactly one spec file. +-- Mirrors the invocation the shell loop used, so a spec sees the same +-- environment it always has. +local function child_argv(spec) + return { + vim.v.progpath, + "--headless", + "--noplugin", + "-u", + "tests/init.lua", + "-c", + string.format("lua require('tests.framework').run_and_exit(%q)", spec), + } +end + +-- `vim.system` reports a timed-out child as exit code 124 (it sends SIGTERM). +local TIMEOUT_EXIT_CODE = 124 + +-- --------------------------------------------------------------------------- +-- Execution strategies +-- --------------------------------------------------------------------------- + +--- Parallel execution via a fixed-size worker pool (Neovim 0.10+). +-- +-- A pull-based queue rather than a static split: whenever a worker finishes it +-- 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 next_index, emitted = 1, 0 + + local function spawn_next() + if next_index > #specs then return end + local spec = specs[next_index] + next_index = next_index + 1 + + vim.system(child_argv(spec), { text = true, timeout = opts.timeout }, function(obj) + -- Keep the pool saturated before doing anything else. + spawn_next() + -- Emission is deferred to the main loop: the whole block is written by a + -- single writer, so blocks cannot interleave with each other. + vim.schedule(function() + reporter.emit_block(spec, obj.stdout, obj.stderr) + table.insert(results, { + spec = spec, + ok = obj.code == 0, + timed_out = obj.code == TIMEOUT_EXIT_CODE, + }) + emitted = emitted + 1 + end) + end) + end + + for _ = 1, math.min(opts.jobs, #specs) do + spawn_next() + 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) + + return results +end + +--- Sequential fallback for Neovim without `vim.system()` (pre-0.10). +-- +-- Same child processes and the same grouped output, just one at a time. +-- `vim.fn.system()` is blocking and captures the child's output in full, so +-- interleaving is impossible here by construction. +local function run_sequential(specs) + local results = {} + for _, spec in ipairs(specs) do + local out = vim.fn.system(child_argv(spec)) + local code = vim.v.shell_error + reporter.emit_block(spec, out, nil) + table.insert(results, { spec = spec, ok = code == 0, timed_out = false }) + end + return results +end + +-- --------------------------------------------------------------------------- +-- Public API +-- --------------------------------------------------------------------------- + +--- Run every discovered spec file. Returns (ok, results). +-- @param opts table|nil { dir, jobs, timeout } +function M.run(opts) + opts = opts or {} + local specs = M.discover(opts.dir) + + 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() + + -- Concurrency needs vim.system(); without it we still run every spec, just + -- serially, so an older Neovim loses speed but never coverage. + local parallel = vim.system ~= nil and jobs > 1 + local reason + if not parallel then + reason = vim.system == nil and "vim.system() unavailable" or nil + end + + reporter.print_suite_header(#specs, parallel and "parallel" or "sequential", jobs, reason) + + if #specs == 0 then + -- Never report success for an empty run: it almost certainly means + -- discovery broke, which would silently disable the suite in CI. + reporter.print_suite_summary({}, 0) + return false, {} + end + + local started = uv.hrtime() + local results + if parallel then + results = run_parallel(specs, { jobs = jobs, timeout = timeout }) + else + results = run_sequential(specs) + end + local total_ms = math.floor((uv.hrtime() - started) / 1e6) + + -- A spec with no result never reported back (parent wait cap hit). Treat it + -- as a failure rather than silently dropping it from the totals. + local seen = {} + for _, r in ipairs(results) do + seen[r.spec] = true + end + for _, spec in ipairs(specs) do + if not seen[spec] then + table.insert(results, { spec = spec, ok = false, timed_out = true }) + end + end + + reporter.print_suite_summary(results, total_ms) + + for _, r in ipairs(results) do + if not r.ok then return false, results end + end + return true, results +end + +--- Run every spec file and exit Neovim with the appropriate exit code. +--- Used by tests/run_tests.{sh,cmd}. +function M.run_and_exit(opts) + local ok = M.run(opts) + if ok then + vim.cmd("qa!") + else + vim.cmd("cq 1") + end +end + +return M diff --git a/tests/helpers.lua b/tests/helpers.lua index 44af509d..02b76762 100644 --- a/tests/helpers.lua +++ b/tests/helpers.lua @@ -4,7 +4,7 @@ local M = {} -- Ensure the plugin is loaded --- This is needed because PlenaryBustedFile spawns a subprocess that may not have loaded our plugin +-- 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' @@ -12,7 +12,7 @@ function M.ensure_plugin_loaded() dofile(plugin_file) end end - -- Also ensure virtual_file autocmds are set up (plenary may clear them between tests) + -- 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 diff --git a/tests/init.lua b/tests/init.lua index e292fbb5..3a64183b 100644 --- a/tests/init.lua +++ b/tests/init.lua @@ -1,5 +1,8 @@ --- Test init file for plenary tests --- This loads the plugin and plenary.nvim +-- Test bootstrap for codediff.nvim +-- +-- Loads the plugin and installs the in-tree test framework (tests/framework/), +-- which fully replaces plenary.nvim. See tests/framework/init.lua for design +-- notes. -- Disable auto-installation in tests (library is already built by CI) vim.env.VSCODE_DIFF_NO_AUTO_INSTALL = "1" @@ -7,32 +10,61 @@ vim.env.VSCODE_DIFF_NO_AUTO_INSTALL = "1" -- Disable ShaDa (fixes Windows permission issues in CI) vim.opt.shadafile = "NONE" +-- 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 +-- git prints +-- warning: in the working copy of '', LF will be replaced by CRLF ... +-- on stderr whenever it touches a file the specs wrote with LF endings. +-- `vim.fn.system()` folds stderr into its return value ('shellredir' defaults to +-- `>%s 2>&1`), so that warning lands inside strings specs compare against git's +-- 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, +-- global and repository config files. +vim.env.GIT_CONFIG_COUNT = "1" +vim.env.GIT_CONFIG_KEY_0 = "core.autocrlf" +vim.env.GIT_CONFIG_VALUE_0 = "false" + -- Add current directory to runtimepath local cwd = vim.fn.getcwd() vim.opt.rtp:prepend(cwd) --- Ensure lua/ directory is in package.path for direct requires -package.path = package.path .. ";" .. cwd .. "/lua/?.lua;" .. cwd .. "/lua/?/init.lua" +-- 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" vim.opt.swapfile = false --- Setup plenary.nvim in Neovim's data directory (proper location) -local plenary_dir = vim.fn.stdpath("data") .. "/plenary.nvim" -if vim.fn.isdirectory(plenary_dir) == 0 then - -- Clone plenary if not found - print("Installing plenary.nvim for tests...") - vim.fn.system({ - "git", - "clone", - "--depth=1", - "https://github.com/nvim-lua/plenary.nvim", - plenary_dir, - }) -end -vim.opt.rtp:prepend(plenary_dir) +-- Opt out of Neovim's file-watcher backing for 'autoread' (its documented +-- `g:loaded_autoread` guard, see $VIMRUNTIME/plugin/autoread.lua). The option +-- itself stays on, so `:checktime` still reloads buffers silently; only the +-- `uv_fs_event` handle that Neovim attaches to every loaded file buffer goes +-- away. +-- +-- Specs open files inside throwaway git repos and then delete those repos, which +-- leaves watchers pointing at paths that no longer exist. On Linux that only +-- prints `E211: File ... no longer available`, but on Windows the fs_event +-- callback is handed EPERM repeatedly and Neovim's own callback asserts on it, so +-- the error is re-raised forever: stderr fills with tracebacks and the spec's +-- event loop never makes progress until the per-spec timeout kills it. +-- +-- Must be set before the `runtime! plugin/*.lua` below, which is what sources +-- Neovim's runtime plugins despite `--noplugin`. +vim.g.loaded_autoread = 1 -- Load plugin files (for integration tests that need commands) vim.cmd('runtime! plugin/*.lua plugin/*.vim') -- Setup plugin require("codediff").setup() + +-- Install the in-tree test framework: augments `_G.assert` and installs the +-- `describe`, `it`, `before_each`, `after_each`, `pending` globals. +require("tests.framework").setup() diff --git a/tests/run_plenary_tests.cmd b/tests/run_plenary_tests.cmd deleted file mode 100644 index b751fbde..00000000 --- a/tests/run_plenary_tests.cmd +++ /dev/null @@ -1,30 +0,0 @@ -@echo off -REM Test runner for codediff.nvim using plenary.nvim (Windows) -setlocal enabledelayedexpansion - -set FAILED=0 - -echo. -echo ================================================================ -echo codediff.nvim Test Suite (Plenary) -echo ================================================================ -echo. - -for /r tests %%f in (*_spec.lua) do ( - echo Running: %%f - nvim --headless --noplugin -u tests/init.lua -c "lua require('plenary.test_harness').test_file('%%f', { minimal_init = vim.fn.getcwd() .. '/tests/init.lua' })" - if errorlevel 1 ( - echo FAILED: %%f - set /a FAILED+=1 - ) - echo. -) - -echo ================================================================ -if !FAILED! equ 0 ( - echo ALL TESTS PASSED - exit /b 0 -) else ( - echo !FAILED! TEST(S^) FAILED - exit /b 1 -) diff --git a/tests/run_plenary_tests.sh b/tests/run_plenary_tests.sh deleted file mode 100755 index eea2193f..00000000 --- a/tests/run_plenary_tests.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env bash -# Test runner for codediff.nvim using plenary.nvim - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" - -# Colors -GREEN='\033[0;32m' -RED='\033[0;31m' -CYAN='\033[0;36m' -NC='\033[0m' - -echo "" -echo "╔══════════════════════════════════════════════════════════════╗" -echo "║ codediff.nvim Test Suite (Plenary) ║" -echo "╚══════════════════════════════════════════════════════════════╝" -echo "" - -cd "$PROJECT_ROOT" - -# Run all spec files -FAILED=0 - -# Auto-discover all *_spec.lua files (POSIX-compatible) -SPEC_FILES=() -while IFS= read -r file; do - SPEC_FILES+=("$file") -done < <(find tests -name '*_spec.lua' -type f | sort) - -for spec_file in "${SPEC_FILES[@]}"; do - echo -e "${CYAN}Running: $spec_file${NC}" - if nvim --headless --noplugin -u tests/init.lua \ - -c "lua require('plenary.test_harness').test_file('$spec_file', { minimal_init = '$PROJECT_ROOT/tests/init.lua' })" 2>&1; then - echo "" - else - echo -e "${RED}✗ $spec_file failed${NC}" - FAILED=$((FAILED + 1)) - echo "" - fi -done - -# Summary -echo "╔══════════════════════════════════════════════════════════════╗" -if [ $FAILED -eq 0 ]; then - echo -e "║ ${GREEN}✓ ALL TESTS PASSED${NC} ║" - echo "╚══════════════════════════════════════════════════════════════╝" - exit 0 -else - echo -e "║ ${RED}✗ $FAILED TEST(S) FAILED${NC} ║" - echo "╚══════════════════════════════════════════════════════════════╝" - exit 1 -fi diff --git a/tests/run_tests.cmd b/tests/run_tests.cmd new file mode 100644 index 00000000..f2a363a2 --- /dev/null +++ b/tests/run_tests.cmd @@ -0,0 +1,20 @@ +@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) + +setlocal +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% diff --git a/tests/run_tests.sh b/tests/run_tests.sh new file mode 100755 index 00000000..1734fdcc --- /dev/null +++ b/tests/run_tests.sh @@ -0,0 +1,21 @@ +#!/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) + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + +cd "$PROJECT_ROOT" + +exec nvim --headless --noplugin -u tests/init.lua \ + -c "lua require('tests.framework').run_all_and_exit()" diff --git a/tests/ui/explorer/explorer_staging_spec.lua b/tests/ui/explorer/explorer_staging_spec.lua index 011320a3..829d089f 100644 --- a/tests/ui/explorer/explorer_staging_spec.lua +++ b/tests/ui/explorer/explorer_staging_spec.lua @@ -4,7 +4,7 @@ local h = dofile('tests/helpers.lua') local path = require("codediff.core.path") --- Ensure plugin is loaded (needed for PlenaryBustedFile subprocess) +-- Ensure plugin is loaded (needed when the test framework isolates specs) h.ensure_plugin_loaded() describe("Explorer Buffer Management", function() diff --git a/tests/ui/explorer/hunk_operations_spec.lua b/tests/ui/explorer/hunk_operations_spec.lua index 8c68a847..03cf1505 100644 --- a/tests/ui/explorer/hunk_operations_spec.lua +++ b/tests/ui/explorer/hunk_operations_spec.lua @@ -10,7 +10,7 @@ local h = dofile("tests/helpers.lua") --- Ensure plugin is loaded (needed for PlenaryBustedFile subprocess) +-- Ensure plugin is loaded (needed when the test framework isolates specs) h.ensure_plugin_loaded() -- Setup CodeDiff user command for tests diff --git a/tests/ui/explorer/stale_buffer_spec.lua b/tests/ui/explorer/stale_buffer_spec.lua index 23c501ed..0a89e133 100644 --- a/tests/ui/explorer/stale_buffer_spec.lua +++ b/tests/ui/explorer/stale_buffer_spec.lua @@ -6,7 +6,7 @@ local h = dofile("tests/helpers.lua") --- Ensure plugin is loaded (needed for PlenaryBustedFile subprocess) +-- Ensure plugin is loaded (needed when the test framework isolates specs) h.ensure_plugin_loaded() -- Setup CodeDiff command for tests diff --git a/tests/ui/history/history_refresh_watcher_spec.lua b/tests/ui/history/history_refresh_watcher_spec.lua new file mode 100644 index 00000000..bdf4bb71 --- /dev/null +++ b/tests/ui/history/history_refresh_watcher_spec.lua @@ -0,0 +1,93 @@ +-- 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 + + before_each(function() + original_new_fs_event = uv.new_fs_event + repo = h.create_temp_git_repo() + end) + + after_each(function() + uv.new_fs_event = original_new_fs_event + if repo then + repo.cleanup() + repo = nil + end + 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 = { + 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 + end) +end) diff --git a/tests/ui/view/view_spec.lua b/tests/ui/view/view_spec.lua index e6add181..e04f9949 100644 --- a/tests/ui/view/view_spec.lua +++ b/tests/ui/view/view_spec.lua @@ -427,4 +427,69 @@ describe("Render View", function() vim.fn.delete(right_path) end end) + + -- Test 16: Re-opening a diff whose file was deleted behind our back must stay + -- quiet. Neovim timestamp-checks a buffer whenever it becomes visible, and + -- both `:edit` and displaying an already-loaded buffer surface that as + -- `E211: File ... no longer available` — a bare `pcall` does not suppress it, + -- and on some platforms it aborts view construction outright. + it("Does not report E211 when a diffed file is deleted behind the view", function() + local original = { "line 1", "line 2" } + local modified = { "line 1", "changed" } + + local left_path = get_temp_path("test_view_left_16.txt") + local right_path = get_temp_path("test_view_right_16.txt") + vim.fn.writefile(original, left_path) + vim.fn.writefile(modified, right_path) + + -- First create loads both real files into buffers displayed in windows. + create_test_diff_view(original, modified, left_path, right_path) + vim.wait(200) + + -- Both files vanish (external `rm`, `git stash`, branch switch, ...). + vim.fn.delete(left_path) + vim.fn.delete(right_path) + + -- Second create finds those buffers by name and re-displays them. + vim.cmd("messages clear") + create_test_diff_view(original, modified, left_path, right_path) + vim.wait(200) + + local messages = vim.fn.execute("messages") + assert.is_nil(messages:find("E211", 1, true), "Re-displaying a loaded buffer for a deleted file should not report E211, got: " .. messages) + end) + + -- Test 17: Same situation, but reached through the "no buffer found, load it" + -- branch. A path that is spelled differently from the buffer's name (here an + -- extra "." segment; on macOS the real trigger is /tmp being a symlink to + -- /private/tmp) misses the by-name lookup, yet still resolves to the very + -- same buffer once loaded. + it("Does not report E211 when loading a deleted file whose buffer is already open", function() + local original = { "line 1", "line 2" } + local modified = { "line 1", "changed" } + + local left_path = get_temp_path("test_view_left_17.txt") + local right_path = get_temp_path("test_view_right_17.txt") + vim.fn.writefile(original, left_path) + vim.fn.writefile(modified, right_path) + + create_test_diff_view(original, modified, left_path, right_path) + vim.wait(200) + + vim.fn.delete(left_path) + vim.fn.delete(right_path) + + local sep = package.config:sub(1, 1) + local function indirect(p) + local dir, name = p:match("^(.*)[/\\]([^/\\]+)$") + return dir .. sep .. "." .. sep .. name + end + + vim.cmd("messages clear") + create_test_diff_view(original, modified, indirect(left_path), indirect(right_path)) + vim.wait(200) + + local messages = vim.fn.execute("messages") + assert.is_nil(messages:find("E211", 1, true), "Loading a deleted file that is already open should not report E211, got: " .. messages) + end) end)