From 6a31b97e3729af3710207642968e1492071a7dbc Mon Sep 17 00:00:00 2001 From: Folke Lemaitre Date: Sun, 8 Jan 2023 14:58:17 +0100 Subject: [PATCH] feat(util): better deep merging with `Util.merge` --- lua/lazy/core/util.lua | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/lua/lazy/core/util.lua b/lua/lazy/core/util.lua index 5111566..70c1eb8 100644 --- a/lua/lazy/core/util.lua +++ b/lua/lazy/core/util.lua @@ -286,4 +286,31 @@ function M.debug(msg, level, opts) end end +local function can_merge(v) + return type(v) == "table" and (vim.tbl_isempty(v) or not M.is_list(v)) +end + +--- Merges the values similar to vim.tbl_deep_extend with the **force** behavior, +--- but the values can be any type, in which case they override the values on the left. +--- Values will me merged in-place in the first left-most table. If you want the result to be in +--- a new table, then simply pass an empty table as the first argument `vim.merge({}, ...)` +--- Supports clearing values by setting a key to `vim.NIL` +function M.merge(...) + local values = { ... } + local ret = values[1] + for i = 2, #values, 1 do + local value = values[i] + if can_merge(ret) and can_merge(value) then + for k, v in pairs(value) do + ret[k] = M.merge(ret[k], v) + end + elseif value == vim.NIL then + ret = nil + else + ret = value + end + end + return ret +end + return M