From aa05bb78af78330bb6fe1b0cba2dcdc95c39b3b5 Mon Sep 17 00:00:00 2001 From: zuqini Date: Sun, 25 Oct 2026 16:06:47 -0700 Subject: [PATCH 1/6] feat(merge): support opts_extend When several specs for one plugin set table-form `opts`, a list-valued option from a later spec replaces the earlier one. `opts_extend` names the keys whose lists are concatenated instead, so e.g. per-language files can each add to nvim-treesitter's `ensure_installed` without an opts function: { 'nvim-treesitter/nvim-treesitter', opts_extend = { 'ensure_installed' }, opts = { ensure_installed = { 'bash', 'c', 'diff' } } } { 'nvim-treesitter/nvim-treesitter', opts = { ensure_installed = { 'rust' } } } -- ensure_installed = { 'bash', 'c', 'diff', 'rust' } As in lazy.nvim, keys may be dotted to reach nested lists (`'sources.default'`), lists are concatenated without deduplication, and function-form opts receive the accumulated table and return its replacement. Deliberate divergences from lazy.nvim: - zpack unions `opts_extend` across every spec of the plugin. lazy.nvim reads only the nearest declaration at or before each fragment, so lists merged before the declaring fragment are replaced and a later fragment that redeclares fewer keys stops the rest from concatenating; with the union the result does not hinge on the order files are imported. - Where lazy.nvim loses data, zpack deep-merges instead: only plain lists concatenate, so a dict at an extend key (`servers = { lua_ls = ... }`) merges as usual rather than collapsing to `{}`, and `{ 'a', 'a.b' }` keeps `a`'s other keys. - Lists on an extend path are copied rather than aliased, so an opts function that appends in place (`vim.list_extend(opts.ensure_installed, ...)`) cannot edit a spec's own opts and duplicate entries on `:ZPack reload`. Also: - validate_spec checks opts_extend is a table of strings; resolve_opts skips non-string keys instead of throwing - LuaLS annotation, vimdoc field entry, spec blocks and a lazy.nvim migration note Refs #45 --- doc/zpack.txt | 25 ++++++ docs/spec.md | 1 + docs/tips.md | 1 + lua/zpack/merge.lua | 66 +++++++++++++- lua/zpack/types.lua | 1 + lua/zpack/validate.lua | 6 ++ tests/merge_test.lua | 193 ++++++++++++++++++++++++++++++++++++++++ tests/opts_test.lua | 23 +++++ tests/validate_test.lua | 15 ++++ 9 files changed, 330 insertions(+), 1 deletion(-) diff --git a/doc/zpack.txt b/doc/zpack.txt index 4dbfb24..908c6d7 100644 --- a/doc/zpack.txt +++ b/doc/zpack.txt @@ -612,6 +612,7 @@ parent's lazy trigger fires. -- Plugin configuration opts = {}, -- Options passed to setup() -- opts = function(plugin, opts) return {} end, + opts_extend = { "ensure_installed" }, -- Concatenate these opts lists -- Lifecycle hooks init = function(plugin) end, -- Runs before load @@ -748,6 +749,30 @@ opts (table|function(plugin, opts), optional) `opts` is passed as the second argument, but you are responsible for calling `setup()` yourself. + *zpack-Spec.opts_extend* +opts_extend (string[], optional) + Keys in `opts` whose lists get appended to instead of + replaced when several specs for the same plugin set `opts`. + Use dots for nested keys, e.g. `"sources.default"`. + Duplicates are kept. Only lists are appended; a table with + named keys at that path merges as usual. + + `opts_extend` from all specs of the plugin is combined, so + it only needs to be set on one of them. lazy.nvim parity, + with one difference: lazy.nvim only appends from the spec + that sets `opts_extend` onward, and lists from earlier + specs get replaced. +>lua + -- plugins/treesitter.lua + { 'nvim-treesitter/nvim-treesitter', + opts_extend = { 'ensure_installed' }, + opts = { ensure_installed = { 'bash', 'c' } } } + -- plugins/rust.lua + { 'nvim-treesitter/nvim-treesitter', + opts = { ensure_installed = { 'rust' } } } + -- ensure_installed ends up with bash, c and rust +< + *zpack-Spec.init* init (function(plugin), optional) Runs before the plugin loads. Receives |zpack.Plugin|. diff --git a/docs/spec.md b/docs/spec.md index a65bf86..2d8c341 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -28,6 +28,7 @@ -- Plugin configuration opts = {}, -- Options passed to setup(), triggers auto-setup -- opts = function(plugin, opts) return {} end, -- Can also be a function + opts_extend = { "ensure_installed" }, -- Opts keys whose lists are appended across specs, not replaced (lazy.nvim parity) -- Lifecycle hooks init = function(plugin) end, -- Runs before plugin loads, useful for certain vim plugins diff --git a/docs/tips.md b/docs/tips.md index 102394c..c89510c 100644 --- a/docs/tips.md +++ b/docs/tips.md @@ -17,6 +17,7 @@ Most of your lazy.nvim plugin specs will work as-is with zpack. However, zpack f - **profiling**: Use `nvim --startuptime startuptime.log`. Also refer to example [Neovim Profiler script](https://gist.github.com/zuqini/35993710f81983fbfa6baca67bdb32ed) - **default lazy plugins**: lazy.nvim's community specs silently default top-level specs for utility libraries like `plenary.nvim` to `lazy = true`, even without lazy triggers or a lazy parent. zpack respects your specs as-written, so set `lazy = true` explicitly on such specs if you want the same default — or set `defaults.lazy = true` in [`setup()`](../README.md#configurations) to apply it to every spec - **`enabled` vs `cond`**: lazy.nvim collapses both to a single "disabled" state. zpack splits them: `enabled = false` skips install entirely (the plugin is never cloned), while `cond = false` installs the plugin but skips its load (so it still shows up under `vim.pack`'s data dir). Use `enabled` when you want lazy.nvim's "don't install at all" behavior +- **`opts_extend`**: lazy.nvim only appends lists from the spec that sets `opts_extend` onward, so lists from earlier specs get replaced. zpack combines `opts_extend` from all specs of a plugin, so it doesn't matter which one sets it. If it's set on the plugin's first spec (LazyVim does this), both behave the same ## Gotchas diff --git a/lua/zpack/merge.lua b/lua/zpack/merge.lua index da0eba0..04c0819 100644 --- a/lua/zpack/merge.lua +++ b/lua/zpack/merge.lua @@ -265,13 +265,77 @@ function M.merge_spec_array(specs) return result end +---@class zpack.OptsExtendNode +---@field concat? boolean +---@field children table + +---Build a tree from the dotted `opts_extend` keys of every spec: `{ 'a', +---'a.b' }` marks `a` for concatenation and also descends into `a.b` for when +---`a` is a dict. Non-string keys are skipped; validate_spec reports them. +---@param specs zpack.Spec[] +---@return zpack.OptsExtendNode +local function extend_tree(specs) + local root = { children = {} } + for _, spec in ipairs(specs) do + for _, key in ipairs(type(spec.opts_extend) == "table" and spec.opts_extend or {}) do + if type(key) == "string" then + local node = root + for _, k in ipairs(vim.split(key, ".", { plain = true })) do + node.children[k] = node.children[k] or { children = {} } + node = node.children[k] + end + node.concat = true + end + end + end + return root +end + +---Mirrors vim.tbl_deep_extend: non-empty lists are leaves, not merged by index. +local function can_merge(v) + return type(v) == "table" and (next(v) == nil or not vim.islist(v)) +end + +---vim.tbl_deep_extend("force", base, value), except that a list at an +---`opts_extend` key is concatenated onto the base list (lazy.nvim's +---`opts_extend`). Values on an extend path are copied, never aliased, so +---function-form opts that edit them in place cannot reach a spec's own opts. +---@param base table +---@param value table +---@param node? zpack.OptsExtendNode +---@return table +local function merge_opts(base, value, node) + local result = {} + for k, v in pairs(base) do + result[k] = v + end + for k, v in pairs(value) do + local b = base[k] + local child = node and node.children[k] + if child and child.concat and vim.islist(v) and (b == nil or vim.islist(b)) then + result[k] = vim.list_extend(vim.list_slice(b or {}), v) + elseif can_merge(v) and (can_merge(b) or (child and b == nil)) then + result[k] = merge_opts(b or {}, v, child) + else + result[k] = v + end + end + return result +end + ---Resolve opts through all specs, supporting function-form opts. Throws ---if any function-form opts throws — callers must pcall. +--- +---`opts_extend` keys from every spec apply to every merge. lazy.nvim reads +---only the nearest `opts_extend` at or before each spec, so lists merged +---before the declaring spec are replaced; the union is a deliberate +---divergence so the result does not depend on import order. ---@param specs zpack.Spec[] ---@param plugin zpack.Plugin ---@return table function M.resolve_opts(specs, plugin) local accumulated = {} + local extend = extend_tree(specs) for _, spec in ipairs(specs) do local opts = spec.opts @@ -282,7 +346,7 @@ function M.resolve_opts(specs, plugin) accumulated = result end elseif type(opts) == "table" then - accumulated = vim.tbl_deep_extend("force", accumulated, opts) + accumulated = merge_opts(accumulated, opts, extend) end end end diff --git a/lua/zpack/types.lua b/lua/zpack/types.lua index ae8451d..c69ef04 100644 --- a/lua/zpack/types.lua +++ b/lua/zpack/types.lua @@ -62,6 +62,7 @@ ---@field keys? zpack.KeysValue|fun(plugin: zpack.Plugin?):zpack.KeysValue ---@field config? fun(plugin: zpack.Plugin?, opts: table)|true ---@field opts? table|fun(plugin: zpack.Plugin?, opts: table):table +---@field opts_extend? string[] Opts keys whose lists are appended across specs, not replaced. Dots reach nested keys (lazy.nvim parity) ---@field main? string ---@field event? zpack.EventValue|fun(plugin: zpack.Plugin?):zpack.EventValue ---@field pattern? string|string[] Global fallback pattern applied to all events (unless zpack.EventSpec specifies its own) diff --git a/lua/zpack/validate.lua b/lua/zpack/validate.lua index 444e54e..c613eb2 100644 --- a/lua/zpack/validate.lua +++ b/lua/zpack/validate.lua @@ -101,6 +101,7 @@ local SPEC_FIELD_TYPES = { build = { 'string', 'function', 'table', 'boolean' }, config = { 'function', 'boolean' }, opts = { 'table', 'function' }, + opts_extend = 'table', event = { 'string', 'table', 'function' }, cmd = { 'string', 'table', 'function' }, ft = { 'string', 'table', 'function' }, @@ -144,6 +145,11 @@ function M.validate_spec(spec) for _, field in ipairs(SORTED_SPEC_FIELDS) do check(errors, field, spec[field], SPEC_FIELD_TYPES[field]) end + if type(spec.opts_extend) == 'table' then + for i, key in ipairs(spec.opts_extend) do + check(errors, ('opts_extend[%d]'):format(i), key, 'string') + end + end -- Every field above is optional, so a spec with no source at all passes -- every type check yet cannot be loaded — `import.normalize_source` would diff --git a/tests/merge_test.lua b/tests/merge_test.lua index f56b5f8..265819d 100644 --- a/tests/merge_test.lua +++ b/tests/merge_test.lua @@ -343,6 +343,199 @@ describe("Merge Module Unit Tests", function() assert.are.equal(3, result.c) end) + it("resolve_opts concatenates opts_extend lists across specs", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 'ensure_installed' }, opts = { ensure_installed = { 'bash', 'c', 'diff' } } }, + { opts = { ensure_installed = { 'rust', 'ron' } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ 'bash', 'c', 'diff', 'rust', 'ron' }, result.ensure_installed) + end) + + it("resolve_opts applies opts_extend declared on a later spec to earlier lists", function() + local merge = require('zpack.merge') + + -- lazy.nvim only extends from the declaring spec onward and would drop + -- 'a'; zpack unions every spec's opts_extend so the result does not + -- hinge on the order plugin files are imported. + local specs = { + { opts = { ensure_installed = { 'a' } } }, + { opts = { ensure_installed = { 'b' } } }, + { opts_extend = { 'ensure_installed' }, opts = { ensure_installed = { 'c' } } }, + { opts = { ensure_installed = { 'd' } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ 'a', 'b', 'c', 'd' }, result.ensure_installed) + end) + + it("resolve_opts applies opts_extend declared on a spec without opts", function() + local merge = require('zpack.merge') + + local specs = { + { opts = { list = { 'a' } } }, + { opts_extend = { 'list' } }, + { opts = { list = { 'b' } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ 'a', 'b' }, result.list) + end) + + it("resolve_opts never drops a key another spec's opts_extend names", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 'first', 'second' }, opts = { first = { 1 }, second = { 1 } } }, + { opts_extend = { 'first' }, opts = { first = { 2 }, second = { 2 } } }, + { opts_extend = {}, opts = { first = { 3 }, second = { 3 } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ 1, 2, 3 }, result.first) + assert.are.same({ 1, 2, 3 }, result.second) + end) + + it("resolve_opts deep-merges an opts_extend key that holds a dict", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 'servers' }, opts = { servers = { lua_ls = { cmd = 'lua' } } } }, + { opts = { servers = { pyright = { cmd = 'py' } } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ lua_ls = { cmd = 'lua' }, pyright = { cmd = 'py' } }, result.servers) + end) + + it("resolve_opts keeps sibling keys when opts_extend names a dict and a list inside it", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 'a', 'a.b' }, opts = { a = { b = { 1 }, keep = true } } }, + { opts = { a = { b = { 2 } } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ b = { 1, 2 }, keep = true }, result.a) + end) + + it("resolve_opts skips non-string opts_extend keys instead of throwing", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 1, { 'x' }, 'list' }, opts = { list = { 'a' } } }, + { opts = { list = { 'b' } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ 'a', 'b' }, result.list) + end) + + it("resolve_opts follows dotted opts_extend keys into nested lists", function() + local merge = require('zpack.merge') + + local specs = { + { + opts_extend = { 'sources.default' }, + opts = { sources = { default = { 'lsp', 'path' }, providers = { lsp = { name = 'LSP' } } } }, + }, + { opts = { sources = { default = { 'snippets' }, providers = { snippets = { name = 'Snip' } } } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ 'lsp', 'path', 'snippets' }, result.sources.default) + assert.are.equal('LSP', result.sources.providers.lsp.name) + assert.are.equal('Snip', result.sources.providers.snippets.name) + end) + + it("resolve_opts still replaces lists not named in opts_extend", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 'extended' }, opts = { extended = { 1 }, replaced = { 1 } } }, + { opts = { extended = { 2 }, replaced = { 2 } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ 1, 2 }, result.extended) + assert.are.same({ 2 }, result.replaced) + end) + + it("resolve_opts without opts_extend merges like vim.tbl_deep_extend", function() + local merge = require('zpack.merge') + + local a = { list = { 1, 2 }, dict = { x = 1, nested = { y = 1 } }, empty = {}, mixed = { 1, k = 'a' }, s = 'a' } + local b = { list = { 3 }, dict = { nested = { z = 2 } }, empty = { q = 1 }, mixed = { 9 }, s = 'b', new = { 1 } } + local result = merge.resolve_opts({ { opts = a }, { opts = b } }, {}) + + assert.are.same(vim.tbl_deep_extend('force', a, b), result) + end) + + it("resolve_opts extends onto the table a function-form opts returns", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 'list' }, opts = { list = { 'a' } } }, + { + opts = function(_, acc) + table.insert(acc.list, 'b') + return acc + end, + }, + { opts = { list = { 'c' } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ 'a', 'b', 'c' }, result.list) + end) + + it("resolve_opts with opts_extend leaves spec opts untouched across resolves", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 'top', 'nested.list' }, opts = { top = { 'a' }, nested = { list = { 'x' } } } }, + { opts = { top = { 'b' }, nested = { list = { 'y' } } } }, + { opts = { top = { 'c' }, nested = { list = { 'z' } } } }, + } + local first = merge.resolve_opts(specs, {}) + local second = merge.resolve_opts(specs, {}) + + assert.are.same({ 'a', 'b', 'c' }, second.top) + assert.are.same({ 'x', 'y', 'z' }, second.nested.list) + assert.are.same(first, second) + assert.are.same({ top = { 'a' }, nested = { list = { 'x' } } }, specs[1].opts) + assert.are.same({ top = { 'b' }, nested = { list = { 'y' } } }, specs[2].opts) + assert.are.same({ top = { 'c' }, nested = { list = { 'z' } } }, specs[3].opts) + end) + + it("resolve_opts keeps function-form opts from editing a spec's opts_extend lists", function() + local merge = require('zpack.merge') + + local specs = { + { + opts_extend = { 'ensure_installed', 'sources.default' }, + opts = { ensure_installed = { 'bash' }, sources = { default = { 'lsp' } } }, + }, + { + opts = function(_, opts) + vim.list_extend(opts.ensure_installed, { 'lua' }) + table.insert(opts.sources.default, 'path') + end, + }, + { opts = { ensure_installed = { 'rust' } } }, + } + merge.resolve_opts(specs, {}) + local second = merge.resolve_opts(specs, {}) + + assert.are.same({ 'bash', 'lua', 'rust' }, second.ensure_installed) + assert.are.same({ 'lsp', 'path' }, second.sources.default) + assert.are.same({ ensure_installed = { 'bash' }, sources = { default = { 'lsp' } } }, specs[1].opts) + end) + it("keys with different modes are not deduplicated", function() require('zpack').setup({ spec = { diff --git a/tests/opts_test.lua b/tests/opts_test.lua index ebc1783..d482dee 100644 --- a/tests/opts_test.lua +++ b/tests/opts_test.lua @@ -108,6 +108,29 @@ describe("Plugin opts and auto-setup", function() assert.are.equal(42, received_opts.num) end) + it("opts_extend concatenates list opts from separate specs of one plugin", function() + local received_opts = nil + + require('zpack').setup({ + spec = { + { + 'test/plugin', + opts_extend = { 'ensure_installed' }, + opts = { ensure_installed = { 'bash', 'c', 'diff' } }, + config = function(_, opts) + received_opts = opts + end, + }, + { 'test/plugin', opts = { ensure_installed = { 'rust', 'ron' } } }, + }, + defaults = { confirm = false }, + }) + + helpers.flush_pending() + assert.is_not_nil(received_opts, "config should receive opts") + assert.are.same({ 'bash', 'c', 'diff', 'rust', 'ron' }, received_opts.ensure_installed) + end) + it("config function receives resolved opts from function", function() local received_opts = nil diff --git a/tests/validate_test.lua b/tests/validate_test.lua index a06eb3e..c72845a 100644 --- a/tests/validate_test.lua +++ b/tests/validate_test.lua @@ -120,11 +120,26 @@ describe("Spec Validation", function() cmd = { 'Foo', 'Bar' }, config = true, opts = {}, + opts_extend = { 'ensure_installed' }, enabled = function() return true end, }) assert.are.equal(0, #errors) end) + it("validate_spec flags a non-table opts_extend", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = 'ensure_installed' }) + assert.are.equal(1, #errors) + assert.is_truthy(errors[1]:find('opts_extend', 1, true) ~= nil, "error should name opts_extend") + end) + + it("validate_spec flags a non-string opts_extend key", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = { 'ok', 1 } }) + assert.are.equal(1, #errors) + assert.is_truthy(errors[1]:find('opts_extend[2]', 1, true) ~= nil, "error should name opts_extend[2]") + end) + it("validate_spec flags a non-boolean lazy", function() local validate = require('zpack.validate') local errors = validate.validate_spec({ 'user/plugin', lazy = 'yes' }) From 50272cd4d1889be5fde447c340d35e69300359a2 Mon Sep 17 00:00:00 2001 From: zuqini Date: Sun, 25 Oct 2026 17:11:46 -0700 Subject: [PATCH 2/6] fix(merge): copy spec opts instead of aliasing them resolve_opts handed tables from a spec's table-form opts to the merged result by reference (as vim.tbl_deep_extend and lazy.nvim's merge do), so an opts function that appends in place edited the spec itself: { opts = { sections = { lualine_x = { 'encoding' } } } } { opts = function(_, o) table.insert(o.sections.lualine_x, 'copilot') end } Each later resolve (`:ZPack reload`, or a retry after a failed load) started from the edited spec and added 'copilot' again. A plugin's setup() editing its opts had the same effect. merge_opts now copies plain tables as it merges them. Tables with a metatable, functions and userdata are kept by reference, so objects and vim.empty_dict() survive and vim.deepcopy's userdata error is avoided. The copy costs a few microseconds per plugin and runs when the plugin's config does. --- lua/zpack/merge.lua | 33 +++++++++++++++++++++++++++------ tests/merge_test.lua | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 6 deletions(-) diff --git a/lua/zpack/merge.lua b/lua/zpack/merge.lua index 04c0819..0e90965 100644 --- a/lua/zpack/merge.lua +++ b/lua/zpack/merge.lua @@ -296,10 +296,31 @@ local function can_merge(v) return type(v) == "table" and (next(v) == nil or not vim.islist(v)) end +---Copy the plain tables in `v`. Tables with a metatable (objects, +---vim.empty_dict()), functions and userdata are kept by reference. +---@param v any +---@param seen? table +---@return any +local function copy_plain(v, seen) + if type(v) ~= "table" or getmetatable(v) ~= nil then + return v + end + seen = seen or {} + if not seen[v] then + local copy = {} + seen[v] = copy + for k, x in pairs(v) do + copy[k] = copy_plain(x, seen) + end + end + return seen[v] +end + ---vim.tbl_deep_extend("force", base, value), except that a list at an ---`opts_extend` key is concatenated onto the base list (lazy.nvim's ----`opts_extend`). Values on an extend path are copied, never aliased, so ----function-form opts that edit them in place cannot reach a spec's own opts. +---`opts_extend`), and plain tables from `value` are copied rather than +---aliased, so function-form opts or a plugin's setup() that edit the +---result in place cannot reach a spec's own opts. ---@param base table ---@param value table ---@param node? zpack.OptsExtendNode @@ -313,11 +334,11 @@ local function merge_opts(base, value, node) local b = base[k] local child = node and node.children[k] if child and child.concat and vim.islist(v) and (b == nil or vim.islist(b)) then - result[k] = vim.list_extend(vim.list_slice(b or {}), v) - elseif can_merge(v) and (can_merge(b) or (child and b == nil)) then - result[k] = merge_opts(b or {}, v, child) + result[k] = vim.list_extend(vim.list_slice(b or {}), copy_plain(v)) + elseif can_merge(v) and can_merge(b) then + result[k] = merge_opts(b, v, child) else - result[k] = v + result[k] = copy_plain(v) end end return result diff --git a/tests/merge_test.lua b/tests/merge_test.lua index 265819d..fec8f67 100644 --- a/tests/merge_test.lua +++ b/tests/merge_test.lua @@ -536,6 +536,47 @@ describe("Merge Module Unit Tests", function() assert.are.same({ ensure_installed = { 'bash' }, sources = { default = { 'lsp' } } }, specs[1].opts) end) + it("resolve_opts keeps function-form opts from editing a spec's other tables", function() + local merge = require('zpack.merge') + + local specs = { + { opts = { sections = { lualine_x = { 'encoding' } } } }, + { opts = function(_, opts) table.insert(opts.sections.lualine_x, 'copilot') end }, + } + merge.resolve_opts(specs, {}) + local second = merge.resolve_opts(specs, {}) + + assert.are.same({ 'encoding', 'copilot' }, second.sections.lualine_x) + assert.are.same({ sections = { lualine_x = { 'encoding' } } }, specs[1].opts) + end) + + it("resolve_opts result can be edited without reaching a lone spec's opts", function() + local merge = require('zpack.merge') + + local specs = { { opts = { nested = { list = { 1 } } } } } + local result = merge.resolve_opts(specs, {}) + table.insert(result.nested.list, 2) + + assert.are.same({ nested = { list = { 1 } } }, specs[1].opts) + end) + + it("resolve_opts keeps functions, objects and cycles intact", function() + local merge = require('zpack.merge') + + local fn = function() end + local object = setmetatable({}, { __index = {} }) + local cyclic = { name = 'c' } + cyclic.self = cyclic + local specs = { { opts = { fn = fn, object = object, empty = vim.empty_dict(), cyclic = cyclic } } } + local result = merge.resolve_opts(specs, {}) + + assert.are.equal(fn, result.fn) + assert.are.equal(object, result.object) + assert.are.equal(getmetatable(vim.empty_dict()), getmetatable(result.empty)) + assert.are_not.equal(cyclic, result.cyclic) + assert.are.equal(result.cyclic, result.cyclic.self) + end) + it("keys with different modes are not deduplicated", function() require('zpack').setup({ spec = { From 98f30fcb0fcdb772233d66a431ebd5f94af76285 Mon Sep 17 00:00:00 2001 From: zuqini Date: Thu, 29 Oct 2026 16:32:39 -0700 Subject: [PATCH 3/6] fix(merge): address opts_extend review findings - Keep vim.empty_dict() a dict when specs merge it. merge_opts built every result as a plain `{}`, so two specs setting `settings = vim.empty_dict()` encoded as `[]` where vim.tbl_deep_extend gave `{}`. - Append the list entries of a table that also has named keys. which-key's `spec = { mode = { 'n', 'x' }, { ... } }` failed the list check and replaced every earlier entry; now the entries are appended and the named keys merge as usual. lazy.nvim keeps the list entries and drops the named keys. - Treat tables with a metatable (other than vim.empty_dict()'s) as objects when merging too: replaced, not flattened into a plain table. - Copy tables returned by function-form opts, so a setup() editing them cannot reach a module-level defaults table and duplicate entries on `:ZPack reload`. - Share one copy map per spec, so a table referenced from two opts keys stays one table, and guard merges in progress, so a cyclic table set by two specs no longer overflows the stack. - Leave opts_extend out of merge_specs like opts; resolve_opts reads it from every spec, while the OVERRIDE fallback kept only the last list. - validate_spec flags an opts_extend that is not a list and keys with an empty segment (`'ensure_installed.'`), both of which silently did nothing. - Correct the vimdoc and migration notes, which claimed parity with lazy.nvim beyond plain lists. --- doc/zpack.txt | 16 ++++-- docs/tips.md | 2 +- lua/zpack/merge.lua | 121 ++++++++++++++++++++++++++++++---------- lua/zpack/validate.lua | 6 ++ tests/merge_test.lua | 85 ++++++++++++++++++++++++++++ tests/validate_test.lua | 15 +++++ 6 files changed, 210 insertions(+), 35 deletions(-) diff --git a/doc/zpack.txt b/doc/zpack.txt index 908c6d7..5219d13 100644 --- a/doc/zpack.txt +++ b/doc/zpack.txt @@ -754,14 +754,18 @@ opts_extend (string[], optional) Keys in `opts` whose lists get appended to instead of replaced when several specs for the same plugin set `opts`. Use dots for nested keys, e.g. `"sources.default"`. - Duplicates are kept. Only lists are appended; a table with - named keys at that path merges as usual. + Duplicates are kept. Only list entries are appended; any + named keys in a table at that path merge as usual. `opts_extend` from all specs of the plugin is combined, so - it only needs to be set on one of them. lazy.nvim parity, - with one difference: lazy.nvim only appends from the spec - that sets `opts_extend` onward, and lists from earlier - specs get replaced. + it only needs to be set on one of them. For plain lists + this matches lazy.nvim, with two differences: + - lazy.nvim only appends from the spec that sets + `opts_extend` onward, and lists from earlier specs get + replaced. + - lazy.nvim keeps only the list entries of a table at that + path, so its named keys are dropped and a dict there + becomes an empty list. >lua -- plugins/treesitter.lua { 'nvim-treesitter/nvim-treesitter', diff --git a/docs/tips.md b/docs/tips.md index c89510c..15a235e 100644 --- a/docs/tips.md +++ b/docs/tips.md @@ -17,7 +17,7 @@ Most of your lazy.nvim plugin specs will work as-is with zpack. However, zpack f - **profiling**: Use `nvim --startuptime startuptime.log`. Also refer to example [Neovim Profiler script](https://gist.github.com/zuqini/35993710f81983fbfa6baca67bdb32ed) - **default lazy plugins**: lazy.nvim's community specs silently default top-level specs for utility libraries like `plenary.nvim` to `lazy = true`, even without lazy triggers or a lazy parent. zpack respects your specs as-written, so set `lazy = true` explicitly on such specs if you want the same default — or set `defaults.lazy = true` in [`setup()`](../README.md#configurations) to apply it to every spec - **`enabled` vs `cond`**: lazy.nvim collapses both to a single "disabled" state. zpack splits them: `enabled = false` skips install entirely (the plugin is never cloned), while `cond = false` installs the plugin but skips its load (so it still shows up under `vim.pack`'s data dir). Use `enabled` when you want lazy.nvim's "don't install at all" behavior -- **`opts_extend`**: lazy.nvim only appends lists from the spec that sets `opts_extend` onward, so lists from earlier specs get replaced. zpack combines `opts_extend` from all specs of a plugin, so it doesn't matter which one sets it. If it's set on the plugin's first spec (LazyVim does this), both behave the same +- **`opts_extend`**: lazy.nvim only appends lists from the spec that sets `opts_extend` onward, so lists from earlier specs get replaced, and it keeps only the list entries of a table at an `opts_extend` key, dropping its named keys. zpack combines `opts_extend` from all specs of a plugin, so it doesn't matter which one sets it, and merges named keys as usual. For plain lists with `opts_extend` set on the plugin's first spec (LazyVim does this), both give the same result ## Gotchas diff --git a/lua/zpack/merge.lua b/lua/zpack/merge.lua index 0e90965..14091c9 100644 --- a/lua/zpack/merge.lua +++ b/lua/zpack/merge.lua @@ -10,8 +10,9 @@ M.AND_LOGIC_ENABLED = "and_logic_enabled" -- `opts` is intentionally absent from this table. It is resolved lazily at -- load time by `resolve_opts` so that function-form opts (which receive the -- accumulated opts and may return a replacement) are handled with a single --- authoritative code path. `merge_specs` skips `opts` entirely; callers that --- need to know "does any spec contribute opts?" read `entry.has_opts`. +-- authoritative code path. `merge_specs` skips `opts` and `opts_extend` +-- (which `resolve_opts` reads from every spec); callers that need to know +-- "does any spec contribute opts?" read `entry.has_opts`. M.field_strategies = { name = M.OVERRIDE, main = M.OVERRIDE, @@ -202,9 +203,10 @@ function M.merge_specs(base, incoming) for k in pairs(incoming) do all_keys[k] = true end for key in pairs(all_keys) do - -- 'opts' is intentionally not merged here: it is resolved lazily via - -- resolve_opts at load time (see the comment above M.field_strategies). - if key ~= "opts" then + -- 'opts' and 'opts_extend' are intentionally not merged here: they are + -- resolved lazily via resolve_opts at load time (see the comment above + -- M.field_strategies). + if key ~= "opts" and key ~= "opts_extend" then if internal_fields[key] then result[key] = incoming[key] ~= nil and incoming[key] or base[key] else @@ -253,8 +255,9 @@ end ---Merge an array of specs in order (lowest priority first). ---Always returns a fresh table (never a reference to any input spec), and ----`opts` is always absent from the result — it is resolved at load time via ----`resolve_opts` so function-form opts are handled consistently. +---`opts` and `opts_extend` are always absent from the result — opts are +---resolved at load time via `resolve_opts` so function-form opts are handled +---consistently. ---@param specs zpack.Spec[] ---@return zpack.Spec function M.merge_spec_array(specs) @@ -291,23 +294,35 @@ local function extend_tree(specs) return root end +local EMPTY_DICT_MT = getmetatable(vim.empty_dict()) + +---Plain tables are copied and merged. Tables with any other metatable than +---vim.empty_dict()'s are objects: kept by reference and never merged into. +local function is_plain(v) + if type(v) ~= "table" then + return false + end + local mt = getmetatable(v) + return mt == nil or mt == EMPTY_DICT_MT +end + ---Mirrors vim.tbl_deep_extend: non-empty lists are leaves, not merged by index. local function can_merge(v) - return type(v) == "table" and (next(v) == nil or not vim.islist(v)) + return is_plain(v) and (next(v) == nil or not vim.islist(v)) end ----Copy the plain tables in `v`. Tables with a metatable (objects, ----vim.empty_dict()), functions and userdata are kept by reference. +---Copy the plain tables in `v`, keeping vim.empty_dict() marked as a dict. +---`seen` maps each source table to its copy, so shared and cyclic +---references stay shared in the copy. ---@param v any ----@param seen? table +---@param seen table ---@return any local function copy_plain(v, seen) - if type(v) ~= "table" or getmetatable(v) ~= nil then + if not is_plain(v) then return v end - seen = seen or {} if not seen[v] then - local copy = {} + local copy = setmetatable({}, getmetatable(v)) seen[v] = copy for k, x in pairs(v) do copy[k] = copy_plain(x, seen) @@ -316,31 +331,81 @@ local function copy_plain(v, seen) return seen[v] end ----vim.tbl_deep_extend("force", base, value), except that a list at an ----`opts_extend` key is concatenated onto the base list (lazy.nvim's ----`opts_extend`), and plain tables from `value` are copied rather than ----aliased, so function-form opts or a plugin's setup() that edit the ----result in place cannot reach a spec's own opts. +---@param t table +---@return any[] list the entries at 1..n +---@return table named every other key +local function split_list(t) + local list, named = {}, setmetatable({}, getmetatable(t)) + for i, x in ipairs(t) do + list[i] = x + end + for k, x in pairs(t) do + if list[k] == nil then + named[k] = x + end + end + return list, named +end + +---@class zpack.MergeState +---@field seen table copy_plain's source-to-copy map +---@field merging table results of the merges in progress, keyed by `value` + +local merge_opts + +---Append the list entries of `value` to those of `base` and merge their +---other keys as usual, so a which-key style `{ mode = 'x', { ... } }` keeps +---both the earlier entries and `mode`. +---@param base table +---@param value table +---@param node zpack.OptsExtendNode +---@param state zpack.MergeState +---@return table +local function concat(base, value, node, state) + local base_list, base_named = split_list(base) + local value_list, value_named = split_list(value) + local result = merge_opts(base_named, value_named, node, state) + for i, x in ipairs(base_list) do + result[i] = x + end + for i, x in ipairs(value_list) do + result[#base_list + i] = copy_plain(x, state.seen) + end + return result +end + +---vim.tbl_deep_extend("force", base, value), except that lists at an +---`opts_extend` key are concatenated (lazy.nvim's `opts_extend`), objects +---are replaced rather than merged into, and plain tables from `value` are +---copied rather than aliased, so function-form opts or a plugin's setup() +---that edit the result in place cannot reach a spec's own opts. ---@param base table ---@param value table ---@param node? zpack.OptsExtendNode +---@param state zpack.MergeState ---@return table -local function merge_opts(base, value, node) - local result = {} +function merge_opts(base, value, node, state) + if state.merging[value] then + return state.merging[value] + end + local dict = getmetatable(base) == EMPTY_DICT_MT or getmetatable(value) == EMPTY_DICT_MT + local result = dict and vim.empty_dict() or {} + state.merging[value] = result for k, v in pairs(base) do result[k] = v end for k, v in pairs(value) do local b = base[k] local child = node and node.children[k] - if child and child.concat and vim.islist(v) and (b == nil or vim.islist(b)) then - result[k] = vim.list_extend(vim.list_slice(b or {}), copy_plain(v)) + if child and child.concat and is_plain(v) and (b == nil or is_plain(b)) then + result[k] = concat(b or {}, v, child, state) elseif can_merge(v) and can_merge(b) then - result[k] = merge_opts(b, v, child) + result[k] = merge_opts(b, v, child, state) else - result[k] = copy_plain(v) + result[k] = copy_plain(v, state.seen) end end + state.merging[value] = nil return result end @@ -363,11 +428,11 @@ function M.resolve_opts(specs, plugin) if opts ~= nil then if type(opts) == "function" then local result = opts(plugin, accumulated) - if type(result) == "table" then - accumulated = result + if type(result) == "table" and result ~= accumulated then + accumulated = copy_plain(result, {}) end elseif type(opts) == "table" then - accumulated = merge_opts(accumulated, opts, extend) + accumulated = merge_opts(accumulated, opts, extend, { seen = {}, merging = {} }) end end end diff --git a/lua/zpack/validate.lua b/lua/zpack/validate.lua index c613eb2..9c03df2 100644 --- a/lua/zpack/validate.lua +++ b/lua/zpack/validate.lua @@ -146,8 +146,14 @@ function M.validate_spec(spec) check(errors, field, spec[field], SPEC_FIELD_TYPES[field]) end if type(spec.opts_extend) == 'table' then + if not vim.islist(spec.opts_extend) then + errors[#errors + 1] = 'opts_extend: expected a list of opts keys' + end for i, key in ipairs(spec.opts_extend) do check(errors, ('opts_extend[%d]'):format(i), key, 'string') + if type(key) == 'string' and vim.list_contains(vim.split(key, '.', { plain = true }), '') then + errors[#errors + 1] = ('opts_extend[%d] "%s" has an empty segment'):format(i, key) + end end end diff --git a/tests/merge_test.lua b/tests/merge_test.lua index fec8f67..7b9540c 100644 --- a/tests/merge_test.lua +++ b/tests/merge_test.lua @@ -577,6 +577,91 @@ describe("Merge Module Unit Tests", function() assert.are.equal(result.cyclic, result.cyclic.self) end) + it("resolve_opts keeps a table shared between two opts keys shared", function() + local merge = require('zpack.merge') + + local shared = { 'a' } + local result = merge.resolve_opts({ { opts = { x = shared, y = { z = shared } } } }, {}) + + assert.are_not.equal(shared, result.x) + assert.are.equal(result.x, result.y.z) + end) + + it("resolve_opts merges a cyclic table set by two specs", function() + local merge = require('zpack.merge') + + local mod = { name = 'm' } + mod.self = mod + local result = merge.resolve_opts({ { opts = { m = mod } }, { opts = { m = mod } } }, {}) + + assert.are.equal('m', result.m.name) + assert.are.equal(result.m, result.m.self) + end) + + it("resolve_opts keeps vim.empty_dict() a dict when specs merge it", function() + local merge = require('zpack.merge') + + local specs = { + { opts = { settings = vim.empty_dict(), init = vim.empty_dict() } }, + { opts = { settings = vim.empty_dict(), init = { a = 1 } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.equal('{}', vim.json.encode(result.settings)) + assert.are.equal(getmetatable(vim.empty_dict()), getmetatable(result.init)) + assert.are.equal(1, result.init.a) + end) + + it("resolve_opts replaces an object rather than merging into it", function() + local merge = require('zpack.merge') + + local class = { __index = { hi = function() return 'hi' end } } + local object = setmetatable({ f = 1 }, class) + local result = merge.resolve_opts({ { opts = { o = { g = 2 } } }, { opts = { o = object } } }, {}) + assert.are.equal(object, result.o) + + result = merge.resolve_opts({ { opts = { o = object } }, { opts = { o = { g = 2 } } } }, {}) + assert.are.same({ g = 2 }, result.o) + assert.are.equal('hi', object:hi()) + assert.are.equal(1, object.f) + end) + + it("resolve_opts appends the list entries of a table that also has named keys", function() + local merge = require('zpack.merge') + + local specs = { + { opts_extend = { 'spec' }, opts = { spec = { { 'f' }, { 'g' } } } }, + { opts = { spec = { mode = { 'n', 'x' }, { 'r' } } } }, + { opts = { spec = { { 't' }, icon = 'x' } } }, + } + local result = merge.resolve_opts(specs, {}) + + assert.are.same({ + { 'f' }, { 'g' }, { 'r' }, { 't' }, + mode = { 'n', 'x' }, icon = 'x', + }, result.spec) + end) + + it("resolve_opts keeps a table returned by function-form opts from being edited", function() + local merge = require('zpack.merge') + + local defaults = { list = { 'a' } } + local specs = { { opts = function() return defaults end } } + local result = merge.resolve_opts(specs, {}) + table.insert(result.list, 'b') + + assert.are.same({ list = { 'a' } }, defaults) + assert.are.same({ list = { 'a' } }, merge.resolve_opts(specs, {})) + end) + + it("merge_spec_array leaves opts_extend to resolve_opts", function() + local merge = require('zpack.merge') + + local merged = merge.merge_spec_array({ { opts_extend = { 'a' } }, { opts_extend = { 'b' } } }) + + assert.is_nil(merged.opts_extend) + end) + it("keys with different modes are not deduplicated", function() require('zpack').setup({ spec = { diff --git a/tests/validate_test.lua b/tests/validate_test.lua index c72845a..4f195a5 100644 --- a/tests/validate_test.lua +++ b/tests/validate_test.lua @@ -140,6 +140,21 @@ describe("Spec Validation", function() assert.is_truthy(errors[1]:find('opts_extend[2]', 1, true) ~= nil, "error should name opts_extend[2]") end) + it("validate_spec flags an opts_extend that is not a list", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = { ensure_installed = true } }) + assert.are.equal(1, #errors) + assert.is_truthy(errors[1]:find('opts_extend', 1, true) ~= nil, "error should name opts_extend") + end) + + it("validate_spec flags opts_extend keys with an empty segment", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = { 'a.', 'a..b', 'a.b' } }) + assert.are.equal(2, #errors) + assert.is_truthy(errors[1]:find('opts_extend[1]', 1, true) ~= nil, "error should name opts_extend[1]") + assert.is_truthy(errors[2]:find('opts_extend[2]', 1, true) ~= nil, "error should name opts_extend[2]") + end) + it("validate_spec flags a non-boolean lazy", function() local validate = require('zpack.validate') local errors = validate.validate_spec({ 'user/plugin', lazy = 'yes' }) From dc094de21fd3df1f8f544b13ebc450163adf64c8 Mon Sep 17 00:00:00 2001 From: zuqini Date: Thu, 29 Oct 2026 18:26:59 -0700 Subject: [PATCH 4/6] feat(merge): support opts_extend When several specs for one plugin set table-form `opts`, a list-valued option from a later spec replaces the earlier one. `opts_extend` names the keys whose lists are concatenated instead, so e.g. per-language files can each add to nvim-treesitter's `ensure_installed` without an opts function: { 'nvim-treesitter/nvim-treesitter', opts_extend = { 'ensure_installed' }, opts = { ensure_installed = { 'bash', 'c', 'diff' } } } { 'nvim-treesitter/nvim-treesitter', opts = { ensure_installed = { 'rust' } } } -- ensure_installed = { 'bash', 'c', 'diff', 'rust' } As in lazy.nvim, opts still merge through vim.tbl_deep_extend and the lists at each extend path are concatenated afterwards; keys may be dotted to reach nested lists (`'sources.default'`), lists are concatenated without deduplication, and function-form opts receive the accumulated table and return its replacement. Merging outside extend paths is unchanged. Deliberate divergences from lazy.nvim: - `opts_extend` merges like the other list fields (LIST_EXTEND), so the union over every spec of the plugin applies to every merge. lazy.nvim reads only the nearest declaration at or before each fragment, so lists merged before the first declaring fragment replace each other and a later fragment that redeclares fewer keys stops the rest from concatenating; with the union the result does not hinge on the order files are imported. - Where lazy.nvim loses data, zpack keeps it. Two dicts at an extend key (`servers = { lua_ls = ... }`) stay deep-merged rather than collapsing to `{}`, and `{ 'a', 'a.b' }` keeps `a`'s other keys. A table with named keys, such as which-key's `spec = { mode = 'x', { ... } }`, is appended as one entry, so its `mode` stays scoped to its own mappings instead of being dropped. - nil holes (`cond and 'x' or nil`) are dropped from extend lists, so ipairs-based installers see every entry, and an empty table counts as unset, so an empty default elsewhere does not change the result's shape. Also: - opts_extend also takes a single key (`opts_extend = 'ensure_installed'`), which merge_spec_array turns into a list; validate_spec checks it is a string or a list of strings without empty segments (`'ensure_installed.'`), and resolve_opts skips other non-string keys and paths through an object instead of throwing - LuaLS annotation, vimdoc field entry, spec blocks and a lazy.nvim migration note Refs #45 --- doc/zpack.txt | 42 ++++++ docs/spec.md | 1 + docs/tips.md | 1 + lua/zpack/merge.lua | 124 +++++++++++++++-- lua/zpack/plugin_loader.lua | 6 +- lua/zpack/types.lua | 1 + lua/zpack/validate.lua | 14 ++ tests/merge_test.lua | 262 +++++++++++++++++++++++++++++++++++- tests/opts_test.lua | 47 +++++++ tests/validate_test.lua | 42 ++++++ 10 files changed, 528 insertions(+), 12 deletions(-) diff --git a/doc/zpack.txt b/doc/zpack.txt index 4dbfb24..563db3c 100644 --- a/doc/zpack.txt +++ b/doc/zpack.txt @@ -612,6 +612,7 @@ parent's lazy trigger fires. -- Plugin configuration opts = {}, -- Options passed to setup() -- opts = function(plugin, opts) return {} end, + opts_extend = { "ensure_installed" }, -- Concatenate these opts lists -- Lifecycle hooks init = function(plugin) end, -- Runs before load @@ -748,6 +749,47 @@ opts (table|function(plugin, opts), optional) `opts` is passed as the second argument, but you are responsible for calling `setup()` yourself. + *zpack-Spec.opts_extend* +opts_extend (string|string[], optional) + Keys in `opts` whose lists get appended to instead of + replaced when several specs for the same plugin set `opts`. + Use dots for nested keys, e.g. `"sources.default"`. + Duplicates are kept, and nil holes in a list are dropped + when specs merge. A table with named keys at that path, + such as which-key's `{ mode = 'v', { ... } }`, is appended + as one entry, so its keys only apply to its own entries. + Two dicts at that path deep-merge as usual. + + `opts_extend` from all specs of the plugin is combined, so + it only needs to be set on one of them, and no spec can + turn it off. To replace an extended list, use function-form + opts, e.g. `function(_, o) o.ensure_installed = { 'x' } end`. + Lists are appended in merge order: specs pulled in as + `dependencies` first, then top-level specs in import order. + Specs listed under the `dependencies` of a plugin that is + disabled or skipped as `optional` are left out, as in + lazy.nvim. lazy.nvim differs: + - Each spec uses the nearest `opts_extend` at or before it. + A spec with none in effect replaces the lists before it, + so of the lists set before the first `opts_extend`, only + the last is kept, and a later `opts_extend` that leaves a + key out stops that key from appending. + - It keeps only the list entries of a table at that path, + so named keys are dropped and a dict there becomes an + empty list. + - It appends in import order, without putting + `dependencies` specs first. +>lua + -- plugins/treesitter.lua + { 'nvim-treesitter/nvim-treesitter', + opts_extend = { 'ensure_installed' }, + opts = { ensure_installed = { 'bash', 'c' } } } + -- plugins/rust.lua + { 'nvim-treesitter/nvim-treesitter', + opts = { ensure_installed = { 'rust' } } } + -- ensure_installed ends up with bash, c and rust +< + *zpack-Spec.init* init (function(plugin), optional) Runs before the plugin loads. Receives |zpack.Plugin|. diff --git a/docs/spec.md b/docs/spec.md index a65bf86..b4e915b 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -28,6 +28,7 @@ -- Plugin configuration opts = {}, -- Options passed to setup(), triggers auto-setup -- opts = function(plugin, opts) return {} end, -- Can also be a function + opts_extend = { "ensure_installed" }, -- Opts keys whose lists are appended across specs, not replaced -- Lifecycle hooks init = function(plugin) end, -- Runs before plugin loads, useful for certain vim plugins diff --git a/docs/tips.md b/docs/tips.md index 102394c..d575572 100644 --- a/docs/tips.md +++ b/docs/tips.md @@ -17,6 +17,7 @@ Most of your lazy.nvim plugin specs will work as-is with zpack. However, zpack f - **profiling**: Use `nvim --startuptime startuptime.log`. Also refer to example [Neovim Profiler script](https://gist.github.com/zuqini/35993710f81983fbfa6baca67bdb32ed) - **default lazy plugins**: lazy.nvim's community specs silently default top-level specs for utility libraries like `plenary.nvim` to `lazy = true`, even without lazy triggers or a lazy parent. zpack respects your specs as-written, so set `lazy = true` explicitly on such specs if you want the same default — or set `defaults.lazy = true` in [`setup()`](../README.md#configurations) to apply it to every spec - **`enabled` vs `cond`**: lazy.nvim collapses both to a single "disabled" state. zpack splits them: `enabled = false` skips install entirely (the plugin is never cloned), while `cond = false` installs the plugin but skips its load (so it still shows up under `vim.pack`'s data dir). Use `enabled` when you want lazy.nvim's "don't install at all" behavior +- **`opts_extend`**: in lazy.nvim each spec uses the nearest `opts_extend` at or before it, and a spec with none in effect replaces the lists before it, so of the lists set before the first `opts_extend` only the last is kept, and a later `opts_extend` that leaves a key out stops that key from appending. lazy.nvim also keeps only the list entries of a table at an `opts_extend` key, dropping its named keys. zpack combines `opts_extend` from all specs of a plugin, so it can be set on any of them, and appends a table with named keys (such as which-key's `{ mode = 'v', ... }`) as one entry. zpack appends `dependencies` specs' lists before top-level ones, while lazy.nvim appends in import order, so with plain lists the two match when only the plugin's first spec sets `opts_extend` (LazyVim does this) and no `dependencies` entry adds to the list ## Gotchas diff --git a/lua/zpack/merge.lua b/lua/zpack/merge.lua index da0eba0..2388274 100644 --- a/lua/zpack/merge.lua +++ b/lua/zpack/merge.lua @@ -31,6 +31,7 @@ M.field_strategies = { cmd = M.LIST_EXTEND, ft = M.LIST_EXTEND, keys = M.LIST_EXTEND, + opts_extend = M.LIST_EXTEND, cond = M.AND_LOGIC_COND, enabled = M.AND_LOGIC_ENABLED, @@ -41,7 +42,8 @@ local internal_fields = { _is_dependency = true, } ----Normalize value to array for LIST_EXTEND fields (event, cmd, ft, keys). +---Normalize value to array for LIST_EXTEND fields (event, cmd, ft, keys, +---opts_extend). ---Handles three cases: --- 1. nil -> empty array --- 2. Non-table (string) -> wrap in array: "BufRead" -> {"BufRead"} @@ -262,28 +264,130 @@ function M.merge_spec_array(specs) for i = 1, #specs do result = M.merge_specs(result, specs[i]) end + if result.opts_extend ~= nil then + result.opts_extend = to_array(result.opts_extend) + end + return result +end + +local EMPTY_DICT_MT = getmetatable(vim.empty_dict()) + +local function is_plain(v) + if type(v) ~= "table" then + return false + end + local mt = getmetatable(v) + return mt == nil or mt == EMPTY_DICT_MT +end + +local function has_index_keys(t) + for k in pairs(t) do + if type(k) == "number" then + return true + end + end + return false +end + +---Set `t[path]`, shallow-copying the tables on the way so a table that +---vim.tbl_deep_extend took by reference from a spec is never written to. +---Stops without setting when an object sits on the way; the copies made +---up to there equal the originals. +local function key_set(t, path, value) + for i = 1, #path - 1 do + local child = t[path[i]] + if not is_plain(child) then + return + end + local copy = setmetatable({}, getmetatable(child)) + for k, x in pairs(child) do + copy[k] = x + end + t[path[i]] = copy + t = copy + end + t[path[#path]] = value +end + +---A list contributes its entries, nil holes dropped. Any other table is +---appended as one entry, so the named keys of a which-key style +---`{ mode = 'x', { ... } }` only apply to its own entries. +---@param tables table[] +---@return any[] +local function concat(tables) + local list = {} + for _, t in ipairs(tables) do + if vim.isarray(t) then + for i = 1, table.maxn(t) do + list[#list + 1] = t[i] + end + else + list[#list + 1] = t + end + end + return list +end + +---vim.tbl_deep_extend("force", base, value), then concatenate the lists at +---each `opts_extend` path (lazy.nvim's `opts_extend`). Empty tables count +---as unset, two dicts stay deep-merged, and a path with a scalar or object +---on the incoming side keeps what vim.tbl_deep_extend made of it. +---@param base table +---@param value table +---@param paths string[][] +---@return table +local function merge_opts(base, value, paths) + local result = vim.tbl_deep_extend("force", base, value) + for _, path in ipairs(paths) do + local v = vim.tbl_get(value, unpack(path)) + if is_plain(v) then + local b = vim.tbl_get(base, unpack(path)) + local parts = {} + if is_plain(b) and next(b) ~= nil then + parts[#parts + 1] = b + end + if next(v) ~= nil then + parts[#parts + 1] = v + end + if #parts == 1 and vim.isarray(parts[1]) + or #parts == 2 and (has_index_keys(parts[1]) or has_index_keys(parts[2])) then + key_set(result, path, concat(parts)) + end + end + end return result end ---Resolve opts through all specs, supporting function-form opts. Throws ---if any function-form opts throws — callers must pcall. +--- +---`opts_extend` is the merged spec's: the union over every spec, applied to +---every merge. lazy.nvim reads only the nearest `opts_extend` at or before +---each spec, so lists merged before the first declaring spec replace each +---other; the union is a deliberate divergence so the result does not depend +---on import order. ---@param specs zpack.Spec[] ---@param plugin zpack.Plugin +---@param opts_extend? string|string[] ---@return table -function M.resolve_opts(specs, plugin) +function M.resolve_opts(specs, plugin, opts_extend) local accumulated = {} + local paths = {} + for _, key in ipairs(opts_extend and to_array(opts_extend) or {}) do + if type(key) == "string" then + paths[#paths + 1] = vim.split(key, ".", { plain = true }) + end + end for _, spec in ipairs(specs) do local opts = spec.opts - if opts ~= nil then - if type(opts) == "function" then - local result = opts(plugin, accumulated) - if type(result) == "table" then - accumulated = result - end - elseif type(opts) == "table" then - accumulated = vim.tbl_deep_extend("force", accumulated, opts) + if type(opts) == "function" then + local result = opts(plugin, accumulated) + if type(result) == "table" then + accumulated = result end + elseif type(opts) == "table" then + accumulated = merge_opts(accumulated, opts, paths) end end diff --git a/lua/zpack/plugin_loader.lua b/lua/zpack/plugin_loader.lua index 4417141..179fc12 100644 --- a/lua/zpack/plugin_loader.lua +++ b/lua/zpack/plugin_loader.lua @@ -39,7 +39,11 @@ function M.run_config(src, plugin, spec) local registry_entry = state.spec_registry[src] -- resolve_opts is the single authoritative path for opts; it walks -- sorted_specs fresh so function-form opts compose correctly. - local resolved_opts = merge.resolve_opts(registry_entry.sorted_specs or {}, plugin) + local resolved_opts = merge.resolve_opts( + registry_entry.sorted_specs or {}, + plugin, + registry_entry.merged_spec and registry_entry.merged_spec.opts_extend + ) local main = utils.resolve_main(plugin, spec) local label = (plugin and plugin.spec and plugin.spec.name) or src diff --git a/lua/zpack/types.lua b/lua/zpack/types.lua index ae8451d..1ea95b9 100644 --- a/lua/zpack/types.lua +++ b/lua/zpack/types.lua @@ -62,6 +62,7 @@ ---@field keys? zpack.KeysValue|fun(plugin: zpack.Plugin?):zpack.KeysValue ---@field config? fun(plugin: zpack.Plugin?, opts: table)|true ---@field opts? table|fun(plugin: zpack.Plugin?, opts: table):table +---@field opts_extend? string|string[] Opts keys whose lists are appended across specs, not replaced. Dots reach nested keys ---@field main? string ---@field event? zpack.EventValue|fun(plugin: zpack.Plugin?):zpack.EventValue ---@field pattern? string|string[] Global fallback pattern applied to all events (unless zpack.EventSpec specifies its own) diff --git a/lua/zpack/validate.lua b/lua/zpack/validate.lua index 444e54e..ce9e774 100644 --- a/lua/zpack/validate.lua +++ b/lua/zpack/validate.lua @@ -101,6 +101,7 @@ local SPEC_FIELD_TYPES = { build = { 'string', 'function', 'table', 'boolean' }, config = { 'function', 'boolean' }, opts = { 'table', 'function' }, + opts_extend = { 'string', 'table' }, event = { 'string', 'table', 'function' }, cmd = { 'string', 'table', 'function' }, ft = { 'string', 'table', 'function' }, @@ -144,6 +145,19 @@ function M.validate_spec(spec) for _, field in ipairs(SORTED_SPEC_FIELDS) do check(errors, field, spec[field], SPEC_FIELD_TYPES[field]) end + if type(spec.opts_extend) == 'string' and vim.list_contains(vim.split(spec.opts_extend, '.', { plain = true }), '') then + errors[#errors + 1] = ('opts_extend "%s" has an empty segment'):format(spec.opts_extend) + elseif type(spec.opts_extend) == 'table' then + if not vim.islist(spec.opts_extend) then + errors[#errors + 1] = 'opts_extend: expected a list of opts keys' + end + for i, key in ipairs(spec.opts_extend) do + check(errors, ('opts_extend[%d]'):format(i), key, 'string') + if type(key) == 'string' and vim.list_contains(vim.split(key, '.', { plain = true }), '') then + errors[#errors + 1] = ('opts_extend[%d] "%s" has an empty segment'):format(i, key) + end + end + end -- Every field above is optional, so a spec with no source at all passes -- every type check yet cannot be loaded — `import.normalize_source` would diff --git a/tests/merge_test.lua b/tests/merge_test.lua index f56b5f8..edbf2f3 100644 --- a/tests/merge_test.lua +++ b/tests/merge_test.lua @@ -1,5 +1,10 @@ local helpers = require('helpers') +local function resolve(specs) + local merge = require('zpack.merge') + return merge.resolve_opts(specs, {}, merge.merge_spec_array(specs).opts_extend) +end + describe("Spec Merging", function() before_each(helpers.setup_test_env) after_each(helpers.cleanup_test_env) @@ -231,7 +236,7 @@ describe("Merge Module Unit Tests", function() -- at load time by resolve_opts so function-form opts compose correctly -- with a single authoritative code path. See merge.lua field_strategies -- comment. Callers that need the deep-merged value should invoke - -- merge.resolve_opts(sorted_specs, plugin). + -- merge.resolve_opts(sorted_specs, plugin, merged_spec.opts_extend). local base = { opts = { a = 1, nested = { x = 1 } } } local incoming = { opts = { b = 2, nested = { y = 2 } } } local result = merge.merge_specs(base, incoming) @@ -343,6 +348,261 @@ describe("Merge Module Unit Tests", function() assert.are.equal(3, result.c) end) + it("resolve_opts concatenates opts_extend lists across specs", function() + local specs = { + { opts_extend = { 'ensure_installed' }, opts = { ensure_installed = { 'bash', 'c', 'diff' } } }, + { opts = { ensure_installed = { 'rust', 'ron' } } }, + } + local result = resolve(specs) + + assert.are.same({ 'bash', 'c', 'diff', 'rust', 'ron' }, result.ensure_installed) + end) + + it("resolve_opts applies opts_extend declared on a later spec to earlier lists", function() + -- lazy.nvim only extends from the declaring spec onward and would drop + -- 'a'; zpack unions every spec's opts_extend so the result does not + -- hinge on the order plugin files are imported. + local specs = { + { opts = { ensure_installed = { 'a' } } }, + { opts = { ensure_installed = { 'b' } } }, + { opts_extend = { 'ensure_installed' }, opts = { ensure_installed = { 'c' } } }, + { opts = { ensure_installed = { 'd' } } }, + } + local result = resolve(specs) + + assert.are.same({ 'a', 'b', 'c', 'd' }, result.ensure_installed) + end) + + it("resolve_opts applies opts_extend declared on a spec without opts", function() + local specs = { + { opts = { list = { 'a' } } }, + { opts_extend = { 'list' } }, + { opts = { list = { 'b' } } }, + } + local result = resolve(specs) + + assert.are.same({ 'a', 'b' }, result.list) + end) + + it("resolve_opts never drops a key another spec's opts_extend names", function() + local specs = { + { opts_extend = { 'first', 'second' }, opts = { first = { 1 }, second = { 1 } } }, + { opts_extend = { 'first' }, opts = { first = { 2 }, second = { 2 } } }, + { opts_extend = {}, opts = { first = { 3 }, second = { 3 } } }, + } + local result = resolve(specs) + + assert.are.same({ 1, 2, 3 }, result.first) + assert.are.same({ 1, 2, 3 }, result.second) + end) + + it("resolve_opts deep-merges an opts_extend key that holds a dict", function() + local specs = { + { opts_extend = { 'servers' }, opts = { servers = { lua_ls = { cmd = 'lua' } } } }, + { opts = { servers = { pyright = { cmd = 'py' } } } }, + } + local result = resolve(specs) + + assert.are.same({ lua_ls = { cmd = 'lua' }, pyright = { cmd = 'py' } }, result.servers) + end) + + it("resolve_opts keeps sibling keys when opts_extend names a dict and a list inside it", function() + local specs = { + { opts_extend = { 'a', 'a.b' }, opts = { a = { b = { 1 }, keep = true } } }, + { opts = { a = { b = { 2 } } } }, + } + local result = resolve(specs) + + assert.are.same({ b = { 1, 2 }, keep = true }, result.a) + end) + + it("resolve_opts skips non-string opts_extend keys instead of throwing", function() + local specs = { + { opts_extend = { 1, { 'x' }, 'list' }, opts = { list = { 'a' } } }, + { opts = { list = { 'b' } } }, + } + local result = resolve(specs) + + assert.are.same({ 'a', 'b' }, result.list) + end) + + it("resolve_opts follows dotted opts_extend keys into nested lists", function() + local specs = { + { + opts_extend = { 'sources.default' }, + opts = { sources = { default = { 'lsp', 'path' }, providers = { lsp = { name = 'LSP' } } } }, + }, + { opts = { sources = { default = { 'snippets' }, providers = { snippets = { name = 'Snip' } } } } }, + } + local result = resolve(specs) + + assert.are.same({ 'lsp', 'path', 'snippets' }, result.sources.default) + assert.are.equal('LSP', result.sources.providers.lsp.name) + assert.are.equal('Snip', result.sources.providers.snippets.name) + end) + + it("resolve_opts still replaces lists not named in opts_extend", function() + local specs = { + { opts_extend = { 'extended' }, opts = { extended = { 1 }, replaced = { 1 } } }, + { opts = { extended = { 2 }, replaced = { 2 } } }, + } + local result = resolve(specs) + + assert.are.same({ 1, 2 }, result.extended) + assert.are.same({ 2 }, result.replaced) + end) + + it("resolve_opts without opts_extend merges like vim.tbl_deep_extend", function() + local a = { list = { 1, 2 }, dict = { x = 1, nested = { y = 1 } }, empty = {}, mixed = { 1, k = 'a' }, s = 'a' } + local b = { list = { 3 }, dict = { nested = { z = 2 } }, empty = { q = 1 }, mixed = { 9 }, s = 'b', new = { 1 } } + local result = resolve({ { opts = a }, { opts = b } }) + + assert.are.same(vim.tbl_deep_extend('force', a, b), result) + end) + + it("resolve_opts extends onto the table a function-form opts returns", function() + local specs = { + { opts_extend = { 'list' }, opts = { list = { 'a' } } }, + { + opts = function(_, acc) + table.insert(acc.list, 'b') + return acc + end, + }, + { opts = { list = { 'c' } } }, + } + local result = resolve(specs) + + assert.are.same({ 'a', 'b', 'c' }, result.list) + end) + + it("resolve_opts with opts_extend leaves spec opts untouched across resolves", function() + local specs = { + { opts_extend = { 'top', 'nested.list' }, opts = { top = { 'a' }, nested = { list = { 'x' } } } }, + { opts = { top = { 'b' }, nested = { list = { 'y' } } } }, + { opts = { top = { 'c' }, nested = { list = { 'z' } } } }, + } + local first = resolve(specs) + local second = resolve(specs) + + assert.are.same({ 'a', 'b', 'c' }, second.top) + assert.are.same({ 'x', 'y', 'z' }, second.nested.list) + assert.are.same(first, second) + assert.are.same({ top = { 'a' }, nested = { list = { 'x' } } }, specs[1].opts) + assert.are.same({ top = { 'b' }, nested = { list = { 'y' } } }, specs[2].opts) + assert.are.same({ top = { 'c' }, nested = { list = { 'z' } } }, specs[3].opts) + end) + + it("resolve_opts keeps vim.empty_dict() a dict when specs merge it", function() + local specs = { + { opts = { settings = vim.empty_dict(), init = vim.empty_dict() } }, + { opts = { settings = vim.empty_dict(), init = { a = 1 } } }, + } + local result = resolve(specs) + + assert.are.equal('{}', vim.json.encode(result.settings)) + assert.are.equal(getmetatable(vim.empty_dict()), getmetatable(result.init)) + assert.are.equal(1, result.init.a) + end) + + it("resolve_opts merges into an object like vim.tbl_deep_extend", function() + local defaults = { d = 1 } + local object = setmetatable({ a = 1, b = 2 }, { __index = defaults }) + local result = resolve({ { opts = { cfg = object } }, { opts = { cfg = { b = 3 } } } }) + + assert.are.same({ a = 1, b = 3 }, result.cfg) + assert.are.equal(2, object.b) + end) + + it("resolve_opts drops nil holes from an opts_extend list only one spec sets", function() + local spec_opts = { sources = { default = { 'lsp', nil, 'path' } } } + local specs = { { opts_extend = { 'sources.default' }, opts = spec_opts } } + local result = resolve(specs) + + assert.are.same({ 'lsp', 'path' }, result.sources.default) + assert.are.equal(3, table.maxn(spec_opts.sources.default)) + end) + + it("resolve_opts keeps a table with named keys one spec sets at an opts_extend key as is", function() + local result = resolve({ { opts_extend = { 'spec' }, opts = { spec = { mode = 'n', { 'f' } } } } }) + + assert.are.same({ mode = 'n', { 'f' } }, result.spec) + end) + + it("resolve_opts takes a single opts_extend key", function() + local merge = require('zpack.merge') + + local specs = { { opts = { l = { 'a' } } }, { opts = { l = { 'b' } } } } + assert.are.same({ 'a', 'b' }, merge.resolve_opts(specs, {}, 'l').l) + end) + + it("resolve_opts accepts a single opts_extend key and ignores other non-tables", function() + assert.are.same({ 'a', 'b' }, resolve({ { opts_extend = 'l', opts = { l = { 'a' } } }, { opts = { l = { 'b' } } } }).l) + assert.are.same({ 'b' }, resolve({ { opts_extend = true, opts = { l = { 'a' } } }, { opts = { l = { 'b' } } } }).l) + end) + + it("resolve_opts drops nil holes from an opts_extend list that replaces a scalar", function() + local specs = { + { opts_extend = { 'ensure_installed' }, opts = { ensure_installed = 'all' } }, + { opts = { ensure_installed = { 'a', nil, 'c' } } }, + } + + assert.are.same({ 'a', 'c' }, resolve(specs).ensure_installed) + end) + + it("resolve_opts treats an empty table at an opts_extend key as unset", function() + local mixed = { mode = 'n', { 'a' } } + + assert.are.same(mixed, resolve({ + { opts_extend = { 'spec' }, opts = { spec = {} } }, + { opts = { spec = mixed } }, + }).spec) + assert.are.same({ 'x', 'y' }, resolve({ + { opts_extend = { 'l' }, opts = { l = { 'x', 'y' } } }, + { opts = { l = {} } }, + }).l) + end) + + it("resolve_opts leaves an opts_extend path that runs through an object alone", function() + local object = setmetatable({ default = { 'a' } }, { __metatable = 'locked' }) + local result = resolve({ { opts_extend = { 'sources.default' }, opts = { sources = object } } }) + + assert.are.equal(object, result.sources) + end) + + it("resolve_opts appends a table with named keys at an opts_extend key as one entry", function() + local specs = { + { opts_extend = { 'spec' }, opts = { spec = { mode = 'n', { 'f' } } } }, + { opts = { spec = { { 'g' } } } }, + { opts = { spec = { mode = { 'n', 'x' }, { 'r' } } } }, + } + local result = resolve(specs) + + assert.are.same({ + { mode = 'n', { 'f' } }, + { 'g' }, + { mode = { 'n', 'x' }, { 'r' } }, + }, result.spec) + end) + + it("resolve_opts drops nil holes when it concatenates opts_extend lists", function() + local specs = { + { opts_extend = { 'l' }, opts = { l = { 'a', nil, 'c' } } }, + { opts = { l = { 'd', nil, 'f' } } }, + } + local result = resolve(specs) + + assert.are.same({ 'a', 'c', 'd', 'f' }, result.l) + end) + + it("merge_spec_array unions opts_extend across specs", function() + local merge = require('zpack.merge') + + local merged = merge.merge_spec_array({ { opts_extend = { 'a', 'b' } }, { opts_extend = { 'b', 'c' } } }) + + assert.are.same({ 'a', 'b', 'c' }, merged.opts_extend) + end) + it("keys with different modes are not deduplicated", function() require('zpack').setup({ spec = { diff --git a/tests/opts_test.lua b/tests/opts_test.lua index ebc1783..e760115 100644 --- a/tests/opts_test.lua +++ b/tests/opts_test.lua @@ -108,6 +108,53 @@ describe("Plugin opts and auto-setup", function() assert.are.equal(42, received_opts.num) end) + it("opts_extend concatenates list opts from separate specs of one plugin", function() + local received_opts = nil + + require('zpack').setup({ + spec = { + { + 'test/plugin', + opts_extend = { 'ensure_installed' }, + opts = { ensure_installed = { 'bash', 'c', 'diff' } }, + config = function(_, opts) + received_opts = opts + end, + }, + { 'test/plugin', opts = { ensure_installed = { 'rust', 'ron' } } }, + }, + defaults = { confirm = false }, + }) + + helpers.flush_pending() + assert.is_not_nil(received_opts, "config should receive opts") + assert.are.same({ 'bash', 'c', 'diff', 'rust', 'ron' }, received_opts.ensure_installed) + end) + + it("opts_extend appends lists from dependencies specs before top-level ones", function() + local received_opts = nil + + require('zpack').setup({ + spec = { + { + 'test/plugin', + opts_extend = { 'ensure_installed' }, + opts = { ensure_installed = { 'top1' } }, + config = function(_, opts) + received_opts = opts + end, + }, + { 'test/other', dependencies = { { 'test/plugin', opts = { ensure_installed = { 'dep' } } } } }, + { 'test/plugin', opts = { ensure_installed = { 'top2' } } }, + }, + defaults = { confirm = false }, + }) + + helpers.flush_pending() + assert.is_not_nil(received_opts, "config should receive opts") + assert.are.same({ 'dep', 'top1', 'top2' }, received_opts.ensure_installed) + end) + it("config function receives resolved opts from function", function() local received_opts = nil diff --git a/tests/validate_test.lua b/tests/validate_test.lua index a06eb3e..5d85497 100644 --- a/tests/validate_test.lua +++ b/tests/validate_test.lua @@ -120,11 +120,53 @@ describe("Spec Validation", function() cmd = { 'Foo', 'Bar' }, config = true, opts = {}, + opts_extend = { 'ensure_installed' }, enabled = function() return true end, }) assert.are.equal(0, #errors) end) + it("validate_spec accepts a single opts_extend key", function() + local validate = require('zpack.validate') + assert.are.equal(0, #validate.validate_spec({ 'user/plugin', opts_extend = 'ensure_installed' })) + end) + + it("validate_spec flags an empty segment in a single opts_extend key", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = 'ensure_installed.' }) + assert.are.equal(1, #errors) + assert.is_truthy(errors[1]:find('empty segment', 1, true) ~= nil, "error should name the empty segment") + end) + + it("validate_spec flags an opts_extend that is neither a key nor a list", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = true }) + assert.are.equal(1, #errors) + assert.is_truthy(errors[1]:find('opts_extend', 1, true) ~= nil, "error should name opts_extend") + end) + + it("validate_spec flags a non-string opts_extend key", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = { 'ok', 1 } }) + assert.are.equal(1, #errors) + assert.is_truthy(errors[1]:find('opts_extend[2]', 1, true) ~= nil, "error should name opts_extend[2]") + end) + + it("validate_spec flags an opts_extend that is not a list", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = { ensure_installed = true } }) + assert.are.equal(1, #errors) + assert.is_truthy(errors[1]:find('opts_extend', 1, true) ~= nil, "error should name opts_extend") + end) + + it("validate_spec flags opts_extend keys with an empty segment", function() + local validate = require('zpack.validate') + local errors = validate.validate_spec({ 'user/plugin', opts_extend = { 'a.', 'a..b', 'a.b' } }) + assert.are.equal(2, #errors) + assert.is_truthy(errors[1]:find('opts_extend[1]', 1, true) ~= nil, "error should name opts_extend[1]") + assert.is_truthy(errors[2]:find('opts_extend[2]', 1, true) ~= nil, "error should name opts_extend[2]") + end) + it("validate_spec flags a non-boolean lazy", function() local validate = require('zpack.validate') local errors = validate.validate_spec({ 'user/plugin', lazy = 'yes' }) From a381f2106b693df7fae274905553cb02adc219dd Mon Sep 17 00:00:00 2001 From: zuqini Date: Thu, 29 Oct 2026 18:27:00 -0700 Subject: [PATCH 5/6] fix(merge): copy opts before handing them out resolve_opts handed tables from a spec's table-form opts to the merged result by reference (as vim.tbl_deep_extend and lazy.nvim's merge do), so an opts function that appends in place edited the spec itself: { opts = { sections = { lualine_x = { 'encoding' } } } } { opts = function(_, o) table.insert(o.sections.lualine_x, 'copilot') end } Each later resolve (`:ZPack reload`, or a retry after a failed load) started from the edited spec and added 'copilot' again. A table an opts function attaches (`o.ensure_installed = servers`) or returns, and a plugin's setup() editing its opts, had the same effect. resolve_opts now copies the plain tables of the accumulated opts once at each hand-off: before every opts function and before returning them for config/setup(). Copying where opts leave rather than where they are merged covers every way a reference gets in. One copy map per hand-off keeps a table shared between two keys, or a cycle, one table. Tables with a metatable (other than vim.empty_dict()'s), functions and userdata are kept by reference, which is also how a user passes a table whose identity matters. --- doc/zpack.txt | 5 +++ lua/zpack/merge.lua | 33 ++++++++++++++--- tests/merge_test.lua | 88 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 121 insertions(+), 5 deletions(-) diff --git a/doc/zpack.txt b/doc/zpack.txt index 563db3c..089f304 100644 --- a/doc/zpack.txt +++ b/doc/zpack.txt @@ -749,6 +749,11 @@ opts (table|function(plugin, opts), optional) `opts` is passed as the second argument, but you are responsible for calling `setup()` yourself. + Each opts function, `config` and `setup()` get their own copy + of the plain tables in opts, so editing opts in place never + reaches your specs. Tables with a metatable (other than + |vim.empty_dict()|'s) are not copied. + *zpack-Spec.opts_extend* opts_extend (string|string[], optional) Keys in `opts` whose lists get appended to instead of diff --git a/lua/zpack/merge.lua b/lua/zpack/merge.lua index 2388274..b074df6 100644 --- a/lua/zpack/merge.lua +++ b/lua/zpack/merge.lua @@ -280,6 +280,26 @@ local function is_plain(v) return mt == nil or mt == EMPTY_DICT_MT end +---Copy the plain tables in `v`, keeping vim.empty_dict() marked as a dict; +---objects are kept by reference. `seen` maps each source table to its copy, +---so shared and cyclic references stay shared in the copy. +---@param v any +---@param seen table +---@return any +local function copy_plain(v, seen) + if not is_plain(v) then + return v + end + if not seen[v] then + local copy = setmetatable({}, getmetatable(v)) + seen[v] = copy + for k, x in pairs(v) do + copy[k] = copy_plain(x, seen) + end + end + return seen[v] +end + local function has_index_keys(t) for k in pairs(t) do if type(k) == "number" then @@ -361,6 +381,10 @@ end ---Resolve opts through all specs, supporting function-form opts. Throws ---if any function-form opts throws — callers must pcall. --- +---Each opts function and the caller get their own copy of the plain tables, +---so editing opts in place (or setup() doing so) cannot reach a spec's or an +---earlier function's tables and pile up across `:ZPack reload`. +--- ---`opts_extend` is the merged spec's: the union over every spec, applied to ---every merge. lazy.nvim reads only the nearest `opts_extend` at or before ---each spec, so lists merged before the first declaring spec replace each @@ -382,16 +406,15 @@ function M.resolve_opts(specs, plugin, opts_extend) for _, spec in ipairs(specs) do local opts = spec.opts if type(opts) == "function" then - local result = opts(plugin, accumulated) - if type(result) == "table" then - accumulated = result - end + local copy = copy_plain(accumulated, {}) + local result = opts(plugin, copy) + accumulated = type(result) == "table" and result or copy elseif type(opts) == "table" then accumulated = merge_opts(accumulated, opts, paths) end end - return accumulated + return copy_plain(accumulated, {}) end local function entry_is_dep_only(entry) diff --git a/tests/merge_test.lua b/tests/merge_test.lua index edbf2f3..83072b4 100644 --- a/tests/merge_test.lua +++ b/tests/merge_test.lua @@ -493,6 +493,71 @@ describe("Merge Module Unit Tests", function() assert.are.same({ top = { 'c' }, nested = { list = { 'z' } } }, specs[3].opts) end) + it("resolve_opts keeps function-form opts from editing a spec's opts_extend lists", function() + local specs = { + { + opts_extend = { 'ensure_installed', 'sources.default' }, + opts = { ensure_installed = { 'bash' }, sources = { default = { 'lsp' } } }, + }, + { + opts = function(_, opts) + vim.list_extend(opts.ensure_installed, { 'lua' }) + table.insert(opts.sources.default, 'path') + end, + }, + { opts = { ensure_installed = { 'rust' } } }, + } + resolve(specs) + local second = resolve(specs) + + assert.are.same({ 'bash', 'lua', 'rust' }, second.ensure_installed) + assert.are.same({ 'lsp', 'path' }, second.sources.default) + assert.are.same({ ensure_installed = { 'bash' }, sources = { default = { 'lsp' } } }, specs[1].opts) + end) + + it("resolve_opts keeps function-form opts from editing a spec's other tables", function() + local specs = { + { opts = { sections = { lualine_x = { 'encoding' } } } }, + { opts = function(_, opts) table.insert(opts.sections.lualine_x, 'copilot') end }, + } + resolve(specs) + local second = resolve(specs) + + assert.are.same({ 'encoding', 'copilot' }, second.sections.lualine_x) + assert.are.same({ sections = { lualine_x = { 'encoding' } } }, specs[1].opts) + end) + + it("resolve_opts result can be edited without reaching a lone spec's opts", function() + local specs = { { opts = { nested = { list = { 1 } } } } } + local result = resolve(specs) + table.insert(result.nested.list, 2) + + assert.are.same({ nested = { list = { 1 } } }, specs[1].opts) + end) + + it("resolve_opts keeps functions, objects and cycles intact", function() + local fn = function() end + local object = setmetatable({}, { __index = {} }) + local cyclic = { name = 'c' } + cyclic.self = cyclic + local specs = { { opts = { fn = fn, object = object, empty = vim.empty_dict(), cyclic = cyclic } } } + local result = resolve(specs) + + assert.are.equal(fn, result.fn) + assert.are.equal(object, result.object) + assert.are.equal(getmetatable(vim.empty_dict()), getmetatable(result.empty)) + assert.are_not.equal(cyclic, result.cyclic) + assert.are.equal(result.cyclic, result.cyclic.self) + end) + + it("resolve_opts keeps a table shared between two opts keys shared", function() + local shared = { 'a' } + local result = resolve({ { opts = { x = shared, y = { z = shared } } } }) + + assert.are_not.equal(shared, result.x) + assert.are.equal(result.x, result.y.z) + end) + it("resolve_opts keeps vim.empty_dict() a dict when specs merge it", function() local specs = { { opts = { settings = vim.empty_dict(), init = vim.empty_dict() } }, @@ -595,6 +660,29 @@ describe("Merge Module Unit Tests", function() assert.are.same({ 'a', 'c', 'd', 'f' }, result.l) end) + it("resolve_opts keeps a table an opts function attaches in place from being edited", function() + local servers = { 'lua_ls' } + local specs = { + { opts = { x = 1 } }, + { opts = function(_, opts) opts.ensure_installed = servers end }, + } + for _ = 1, 2 do + table.insert(resolve(specs).ensure_installed, 'stylua') + end + + assert.are.same({ 'lua_ls' }, servers) + end) + + it("resolve_opts keeps a table returned by function-form opts from being edited", function() + local defaults = { list = { 'a' } } + local specs = { { opts = function() return defaults end } } + local result = resolve(specs) + table.insert(result.list, 'b') + + assert.are.same({ list = { 'a' } }, defaults) + assert.are.same({ list = { 'a' } }, resolve(specs)) + end) + it("merge_spec_array unions opts_extend across specs", function() local merge = require('zpack.merge') From d73de5693b8d1207f3f7c95bc6b8dd6f827f56b7 Mon Sep 17 00:00:00 2001 From: zuqini Date: Thu, 29 Oct 2026 19:52:35 -0700 Subject: [PATCH 6/6] fix(merge): drop specs declared under a removed plugin's dependencies When a plugin was disabled or skipped as `optional`, prune_disabled removed its registry entry and any dep-only plugin it orphaned, but specs it declared under `dependencies` for a plugin that stays (because other specs enable it) kept configuring that plugin. LazyVim's language extras do this, e.g. an optional nvim-dap carrying dependencies = { { 'mason-org/mason.nvim', opts = { ensure_installed = { 'delve' } } } } With `opts_extend = { 'ensure_installed' }` on mason, delve was installed even though dap was never enabled; the same spec's keys, event and other fields merged in too. lazy.nvim deletes a removed plugin's fragments together with their child fragments. Each dependency spec now records the specs that declared it, and pruning removes it (recursively) from the plugins that stay once all of them are removed, re-merging those plugins. One table listed under two plugins' `dependencies` stays while either plugin does. A plugin left with no specs, or with only optional ones, is removed as well, and edges into a removed plugin are cleared so no remaining parent points at it. Nested `specs` are peers in zpack and are unchanged. --- doc/zpack.txt | 5 +- lua/zpack/import.lua | 2 + lua/zpack/merge.lua | 150 +++++++++++++++++++++++++++---------- lua/zpack/types.lua | 1 + tests/lazy_parity_test.lua | 93 +++++++++++++++++++++++ 5 files changed, 210 insertions(+), 41 deletions(-) diff --git a/doc/zpack.txt b/doc/zpack.txt index 089f304..b243c68 100644 --- a/doc/zpack.txt +++ b/doc/zpack.txt @@ -707,7 +707,10 @@ dependencies (string|string[]|zpack.Spec|zpack.Spec[], optional) Can be a string (a `[1]` value, see |zpack-Spec|), array of strings, inline spec, or array of specs. Dependency specs can have their own configuration (opts, config, etc.) - and nested dependencies. + and nested dependencies. When the parent is disabled or + skipped as `optional`, its dependency specs are dropped with + it (lazy.nvim parity), including their configuration of a + plugin that other specs keep enabled. *zpack-Spec.enabled* enabled (boolean|function, optional) diff --git a/lua/zpack/import.lua b/lua/zpack/import.lua index 008016e..ca014df 100644 --- a/lua/zpack/import.lua +++ b/lua/zpack/import.lua @@ -239,6 +239,8 @@ local register_dependencies = function(spec, src, ctx) state.reverse_dependency_graph[dep_src] = state.reverse_dependency_graph[dep_src] or {} state.reverse_dependency_graph[dep_src][src] = true end + dep_spec._parent_specs = dep_spec._parent_specs or {} + dep_spec._parent_specs[spec] = true M.import_specs(dep_spec, dep_ctx) end end diff --git a/lua/zpack/merge.lua b/lua/zpack/merge.lua index b074df6..0d4e03a 100644 --- a/lua/zpack/merge.lua +++ b/lua/zpack/merge.lua @@ -40,6 +40,7 @@ M.field_strategies = { local internal_fields = { _import_order = true, _is_dependency = true, + _parent_specs = true, } ---Normalize value to array for LIST_EXTEND fields (event, cmd, ft, keys, @@ -478,10 +479,61 @@ local function propagate_enabled_disable(state, utils) end end ----Remove every enabled=false entry from the registry, plus any dep-only ----plugins that become orphaned as a side effect. After this runs, every ----remaining entry is guaranteed to reach vim.pack.add, which means the ----public API can rely on entry.plugin being populated by the load callback. +local function merge_entry(entry) + entry.sorted_specs = M.sort_specs(entry.specs) + entry.merged_spec = M.merge_spec_array(entry.sorted_specs) +end + +---`opts` is deliberately not stored on merged_spec; this boolean lets +---plugin_loader / startup answer "does any spec contribute opts?" without +---re-scanning. +local function contributes_opts(entry) + for _, s in ipairs(entry.sorted_specs) do + if s.opts ~= nil then + return true + end + end + return false +end + +---lazy.nvim spec parity (`optional = true`): a plugin is included only if +---referenced non-optionally somewhere. A dep declaration +---(`_is_dependency = true`) defeats `optional` — naming a plugin as a dep IS +---a non-optional reference. Without that, a table-form dep +---`{ 'foo/x', optional = true }` would prune `x` and cascade-disable its +---parent. +local function has_required_spec(entry) + for _, s in ipairs(entry.specs) do + if not s.optional or s._is_dependency then + return true + end + end + return false +end + +---A dependency spec goes with its parents only once every spec that declared +---it is gone; one table listed under two plugins' `dependencies` stays while +---either remains. +local function declared_only_by(removed, spec) + if not spec._parent_specs then + return false + end + for parent in pairs(spec._parent_specs) do + if not removed[parent] then + return false + end + end + return true +end + +---Remove every enabled=false entry from the registry, plus what lazy.nvim +---deletes along with a plugin: the specs its specs declared under +---`dependencies` (recursively), even where they configure a plugin that +---stays, and any dep-only plugin left orphaned. A plugin left with no specs, +---or only optional ones, is removed too; one that keeps others is re-merged +---without them. After this runs, every remaining entry is guaranteed to +---reach vim.pack.add, which means the public API can rely on entry.plugin +---being populated by the load callback. local function prune_disabled(state) local worklist = {} for src, entry in pairs(state.spec_registry) do @@ -490,14 +542,59 @@ local function prune_disabled(state) end end + local removed = {} while #worklist > 0 do - local src = table.remove(worklist) - local orphaned = strip_outgoing_edges(state, src) - state.spec_registry[src] = nil - for _, dep_src in ipairs(orphaned) do - local dep_entry = state.spec_registry[dep_src] - if dep_entry and entry_is_dep_only(dep_entry) then - table.insert(worklist, dep_src) + while #worklist > 0 do + local src = table.remove(worklist) + local entry = state.spec_registry[src] + if entry then + for _, spec in ipairs(entry.specs) do + removed[spec] = true + end + for parent_src in pairs(state.reverse_dependency_graph[src] or {}) do + local deps = state.dependency_graph[parent_src] + if deps then + deps[src] = nil + end + end + state.reverse_dependency_graph[src] = nil + local orphaned = strip_outgoing_edges(state, src) + state.spec_registry[src] = nil + for _, dep_src in ipairs(orphaned) do + local dep_entry = state.spec_registry[dep_src] + if dep_entry and entry_is_dep_only(dep_entry) then + table.insert(worklist, dep_src) + end + end + end + end + + local trimmed = {} + local changed = true + while changed do + changed = false + for src, entry in pairs(state.spec_registry) do + local kept = {} + for _, spec in ipairs(entry.specs) do + if removed[spec] or declared_only_by(removed, spec) then + removed[spec] = true + changed = true + else + kept[#kept + 1] = spec + end + end + if #kept < #entry.specs then + entry.specs = kept + trimmed[src] = entry + end + end + end + for src, entry in pairs(trimmed) do + if #entry.specs == 0 or not has_required_spec(entry) then + table.insert(worklist, src) + else + merge_entry(entry) + entry.has_opts = contributes_opts(entry) end end end @@ -553,11 +650,6 @@ local function rekey_graph_edges(state, old_src, new_src) end end -local function merge_entry(entry) - entry.sorted_specs = M.sort_specs(entry.specs) - entry.merged_spec = M.merge_spec_array(entry.sorted_specs) -end - ---Rank an entry for the coalesce fold as a (tier, import order) pair; compare ---tier first, then order. A `dev = true` fragment that did not fall back to ---its own `[1]` wins outright — dev outranks the whole explicit @@ -693,16 +785,7 @@ function M.resolve_all() for src, entry in pairs(state.spec_registry) do if entry.specs and #entry.specs > 0 then entry.enabled_result = utils.check_enabled(entry.merged_spec, src) - -- `opts` is deliberately not stored on merged_spec; compute a boolean - -- summary once here so existence checks in plugin_loader / startup can - -- answer "does any spec contribute opts?" without re-scanning. - entry.has_opts = false - for _, s in ipairs(entry.sorted_specs) do - if s.opts ~= nil then - entry.has_opts = true - break - end - end + entry.has_opts = contributes_opts(entry) -- cond_result is intentionally left nil here. It is written later by -- registration.register_all's vim.pack.add load callback (which needs -- the live plugin arg for function-form conds). Readers must treat @@ -711,22 +794,9 @@ function M.resolve_all() end end - -- lazy.nvim spec parity (`optional = true`): include the plugin only if - -- referenced non-optionally somewhere. A dep declaration - -- (`_is_dependency = true`) defeats `optional` — naming a plugin as a - -- dep IS a non-optional reference. Without that, a table-form dep - -- `{ 'foo/x', optional = true }` would prune `x` and cascade-disable - -- its parent. for src, entry in pairs(state.spec_registry) do if entry.specs and #entry.specs > 0 and entry.enabled_result ~= false then - local has_required = false - for _, s in ipairs(entry.specs) do - if not s.optional or s._is_dependency then - has_required = true - break - end - end - if not has_required then + if not has_required_spec(entry) then entry.enabled_result = false utils.schedule_notify( ("%s skipped: declared `optional = true` and never referenced elsewhere"):format(src), diff --git a/lua/zpack/types.lua b/lua/zpack/types.lua index 1ea95b9..203f88d 100644 --- a/lua/zpack/types.lua +++ b/lua/zpack/types.lua @@ -78,6 +78,7 @@ ---@field import? string|fun():zpack.Spec[] Module path string or function returning specs (lazy.nvim parity) ---@field _import_order? number Internal: Order in which spec was imported ---@field _is_dependency? boolean Internal: Whether spec was imported as a dependency +---@field _parent_specs? table Internal: The specs whose `dependencies` declared this one ---Plugin load lifecycle state. --- `pending` — next trigger will start a load. diff --git a/tests/lazy_parity_test.lua b/tests/lazy_parity_test.lua index 27a7140..38860b1 100644 --- a/tests/lazy_parity_test.lua +++ b/tests/lazy_parity_test.lua @@ -211,6 +211,99 @@ describe("optional = true (zpack_nvim-sg0)", function() end) end) +describe("specs declared under a removed plugin's dependencies", function() + before_each(helpers.setup_test_env) + after_each(helpers.cleanup_test_env) + + local function setup_with(parent) + local received = nil + require('zpack').setup({ + spec = { + { + 'test/mason', + opts_extend = { 'ensure_installed' }, + opts = { ensure_installed = { 'stylua' } }, + config = function(_, opts) received = opts end, + }, + parent, + }, + defaults = { confirm = false }, + }) + helpers.flush_pending() + return received + end + + it("are dropped from a plugin that stays when the parent is skipped as optional", function() + local opts = setup_with({ + 'test/dap', optional = true, + dependencies = { { 'test/mason', opts = { ensure_installed = { 'delve' } } } }, + }) + assert.are.same({ 'stylua' }, opts.ensure_installed) + end) + + it("are dropped from a plugin that stays when the parent is disabled", function() + local opts = setup_with({ + 'test/dap', enabled = false, + dependencies = { { 'test/mason', opts = { ensure_installed = { 'delve' } } } }, + }) + local state = require('zpack.state') + assert.are.same({ 'stylua' }, opts.ensure_installed) + assert.are.equal(1, #state.spec_registry['https://github.com/test/mason'].specs) + end) + + it("are dropped through a chain of dependencies", function() + local opts = setup_with({ + 'test/dap', optional = true, + dependencies = { + { 'test/dap-go', dependencies = { { 'test/mason', opts = { ensure_installed = { 'delve' } } } } }, + }, + }) + local state = require('zpack.state') + assert.are.same({ 'stylua' }, opts.ensure_installed) + assert.is_nil(state.spec_registry['https://github.com/test/dap-go']) + end) + + it("drop a plugin left with only optional specs", function() + require('zpack').setup({ + spec = { + { 'test/dap', enabled = false, dependencies = { 'test/ui' } }, + { 'test/ui', optional = true }, + }, + defaults = { confirm = false }, + }) + helpers.flush_pending() + local state = require('zpack.state') + assert.is_nil(state.spec_registry['https://github.com/test/ui']) + end) + + for _, order in ipairs({ 'before', 'after' }) do + it(("stay while another parent declaring the same table stays (disabled parent %s)"):format(order), function() + local mason = { 'test/mason', opts = { ensure_installed = { 'delve' } } } + local disabled = { 'test/dap', enabled = false, dependencies = { mason } } + local kept = { 'test/lsp', dependencies = { mason } } + require('zpack').setup({ + spec = order == 'before' and { disabled, kept } or { kept, disabled }, + defaults = { confirm = false }, + }) + helpers.flush_pending() + local state = require('zpack.state') + local entry = state.spec_registry['https://github.com/test/mason'] + assert.is_not_nil(entry) + assert.is_true(state.dependency_graph['https://github.com/test/lsp']['https://github.com/test/mason']) + local opts = require('zpack.merge').resolve_opts(entry.sorted_specs, nil, entry.merged_spec.opts_extend) + assert.are.same({ 'delve' }, opts.ensure_installed) + end) + end + + it("stay when the parent stays", function() + local opts = setup_with({ + 'test/dap', + dependencies = { { 'test/mason', opts = { ensure_installed = { 'delve' } } } }, + }) + assert.are.same({ 'delve', 'stylua' }, opts.ensure_installed) + end) +end) + describe("import = function() (zpack_nvim-fqs)", function() before_each(helpers.setup_test_env) after_each(helpers.cleanup_test_env)