robin/lynn.nvim

native-first neovim plugin manager with charm

git clone https://git.robinwobin.dev/robin/lynn.nvim

robinfeat: add `ensure` fieldb0bc793

main
10.4 KiB463 linesraw
1---@module 'lynn'
2
3local nonnil = vim.nonnil or vim.F.if_nil
4
5local lzrq = function(modname)
6  return setmetatable({
7    modname = modname,
8  }, {
9    __index = function(t, k)
10      local m = rawget(t, "modname")
11      if not m then
12        return
13      end
14      return require(m)[k]
15    end,
16  })
17end
18
19local utils = lzrq("lynn.utils")
20
21local lynn = {}
22
23-- utils --
24
25local did_ui_enter = false
26local notif_queue = nil
27local function notify(...)
28  if did_ui_enter then
29    return vim.notify(...)
30  end
31
32  notif_queue = notif_queue or {}
33  notif_queue[#notif_queue + 1] = { ... }
34end
35
36lynn.do_notify = function()
37  did_ui_enter = true
38
39  if not notif_queue then
40    return
41  end
42
43  vim.schedule(function()
44    for _, v in ipairs(notif_queue) do
45      notify(unpack(v))
46    end
47    notif_queue = nil
48  end)
49end
50
51---@param v any
52---@return string
53local function inspect(v)
54  if type(v) == "table" and not vim.islist(v) then
55    return table.concat(
56      vim
57        .iter(pairs(v))
58        :map(function(key, value)
59          return string.format("%s=%q", inspect(key), inspect(value))
60        end)
61        :totable(),
62      " "
63    )
64  end
65
66  return type(v) ~= "string" and vim.inspect(v) or v
67end
68
69---@param ... any
70---@return string
71local function logfmt(...)
72  local c = { ... }
73  local t = vim
74    .iter(ipairs(c))
75    :map(function(_, item)
76      return inspect(item)
77    end)
78    :totable()
79  return table.concat(t, " ")
80end
81
82---@param ... any
83local function logdebug(...)
84  if vim.o.debug ~= "" then
85    notify(logfmt(...), vim.log.levels.DEBUG)
86  end
87end
88
89---@param ... any
90---@return string?
91local function logerr(...)
92  local l = logfmt(...)
93
94  notify(l, vim.log.levels.ERROR)
95
96  if vim.o.debug == "throw" then
97    return error(l)
98  end
99end
100
101---@param msg string
102---@param trace string
103---@return string?
104local function logtrace(msg, trace)
105  return logerr(string.format("lynn: %s:\n\t%s", msg, trace))
106end
107
108---@class lynn.plug
109---@field name string
110---@field url string
111---@field path string
112---@field version? string|vim.VersionRange
113---@field lazy? boolean
114---@field event? string|string[]
115---@field init? function function run before loading the plugin
116---@field load? function function run to load the plugin
117---@field config? function function run after loading the plugin
118---@field build? string|function
119---@field ensure? boolean defaults to true, ensure the package is installed
120---@field deps? string[]
121
122---@class lynn.plug.spec : lynn.plug
123---@field [1] string
124---@field name? string
125---@field url? string
126---@field path? string
127
128--- { [path]: { plug: <plug>, id: <id> } }
129---@type table<string, { plug: lynn.plug, id: number }>
130lynn.loaded = {}
131
132lynn.packdir = vim.fs.joinpath(vim.fn.stdpath("data"), "site", "pack", "core", "opt")
133
134lynn.group = vim.api.nvim_create_augroup("@lynn.lazy", { clear = true })
135
136local n_loaded = 0
137
138--- { [name]: <plug> }
139---@class table<string, lynn.plug>
140lynn.plugins = {}
141
142-- hooks --
143
144---@alias lynn.hook fun(spec: lynn.plug)
145---@alias lynn.hook.builtin
146---|'init'
147---|'load'
148---|'config'
149---|'build'
150
151---@type table<lynn.hook.builtin, lynn.hook>
152lynn.default_hooks = {
153  init = function(_) end,
154  load = function(spec)
155    local ok, result = pcall(vim.cmd.packadd, { spec.name, bang = vim.v.vim_did_init == 0 })
156    if not ok then
157      logerr("error running |:packadd|", { ["spec.name"] = spec.name })
158      return logtrace("load", result)
159    end
160
161    if not vim.v.vim_did_init == 0 then
162      local after_paths = vim.fn.glob(spec.path .. "/after/plugin/**/*.{vim,lua}", false, true)
163      vim.tbl_map(function(path)
164        pcall(vim.cmd.source, vim.fn.fnameescape(path))
165      end, after_paths)
166    end
167  end,
168  config = function(spec)
169    vim.cmd.runtime({ "config/" .. spec.name .. ".lua", bang = true })
170  end,
171  build = function(spec)
172    if type(spec.build) ~= "string" then
173      return
174    end
175    ---@type string
176    ---@diagnostic disable-next-line: assign-type-mismatch
177    local buildstr = spec.build
178    if not buildstr or buildstr == "" then
179      return
180    end
181
182    if string.sub(buildstr, 0, 1) == ":" then
183      vim.cmd(string.sub(buildstr, 2))
184      return
185    end
186
187    local result = vim
188      .system(vim.split(buildstr, " "), {
189        cwd = spec.path,
190      })
191      :wait()
192    if result.code == 0 then
193      return
194    end
195
196    logerr("error running build command", { ["spec.name"] = spec.name })
197    return logtrace("build", result.stderr)
198  end,
199}
200
201---@param plug lynn.plug
202---@param hook string
203---@param fn function
204local function wraphook(plug, hook, fn)
205  if not fn or type(fn) ~= "function" then
206    return
207  end
208
209  logdebug("running hook", { hook = hook, ["plug.name"] = plug.name })
210  do
211    local ok, result = pcall(fn, plug)
212    if not ok then
213      logerr("error running hook", { hook = hook, ["plug.name"] = plug.name })
214      return logtrace("wraphook", result)
215    end
216  end
217end
218
219---@param plug lynn.plug
220---@param hook string
221---@param use_default? boolean
222function lynn.runhook(plug, hook, use_default)
223  if type(hook) ~= "string" then
224    return
225  end
226  local fn = plug[hook]
227  if not fn or type(fn) ~= "function" then
228    if not use_default then
229      return
230    end
231    wraphook(plug, hook, lynn.default_hooks[hook])
232    return
233  end
234
235  wraphook(plug, hook, fn)
236end
237
238---@param plug lynn.plug
239---@return integer id
240local function pack_lazy(plug)
241  if type(plug.event) == "string" then
242    local event = vim.split(plug.event, " ")
243    return vim.api.nvim_create_autocmd(event[1], {
244      group = lynn.group,
245      pattern = event[2],
246      once = true,
247      callback = function()
248        lynn.plugadd(plug)
249      end,
250    })
251  end
252
253  return vim.api.nvim_create_autocmd(plug.event, {
254    group = lynn.group,
255    once = true,
256    callback = function()
257      lynn.plugadd(plug)
258    end,
259  })
260end
261
262--- load a plugin
263--- - add the plugin to the loaded list
264--- - check deps
265--- - run |:packadd|
266--- - run init/config hooks
267--- - check if `after/` dirs should be loaded
268---@param plug lynn.plug
269function lynn.plugadd(plug)
270  if type(plug) == "string" then
271    plug = lynn.plugins[plug]
272  end
273  if lynn.loaded[plug.path] then
274    return
275  end
276
277  -- add dependencies
278  if plug.deps then
279    vim.tbl_map(lynn.load, plug.deps)
280  end
281
282  -- add to loaded
283  n_loaded = n_loaded + 1
284  lynn.loaded[plug.path] = { plug = plug, id = n_loaded }
285
286  lynn.runhook(plug, "init", true)
287  lynn.runhook(plug, "load", true)
288  lynn.runhook(plug, "config", true)
289end
290
291---@param plug lynn.plug.spec|string
292---@return lynn.plug
293function lynn.norm(plug)
294  if type(plug) == "string" then
295    plug = { plug }
296  end
297  plug.url = plug.url or plug[1]
298  if plug.path and not plug.url then
299    plug.url = "file://" .. vim.fs.normalize(plug.path)
300  end
301  plug.url = utils.norm_url(plug.url)
302  plug.name = plug.name or utils.get_name(plug.url)
303  plug.path = plug.path or vim.fs.joinpath(lynn.packdir, plug.name)
304  ---@diagnostic disable-next-line: cast-type-mismatch
305  ---@cast plug lynn.plug
306
307  plug.ensure = nonnil(plug.ensure, true)
308  return plug
309end
310
311--- translate lynn.plug to vim.pack.Spec format
312---@param plug lynn.plug
313---@return vim.pack.Spec
314function lynn.translate(plug)
315  return {
316    src = plug.url,
317    name = plug.name,
318    version = plug.version,
319    data = {
320      init = plug.init,
321      load = plug.load,
322      config = plug.config,
323      build = plug.build,
324      ensure = plug.ensure,
325    },
326  }
327end
328
329--- register a plugin
330---@param plug lynn.plug.spec|string
331function lynn.register(plug)
332  local p = lynn.norm(plug)
333
334  lynn.plugins[p.name] = vim.tbl_extend("keep", p, lynn.plugins[p.name] or {})
335  if p.ensure then
336    vim.pack.add({ lynn.translate(p) }, { load = false })
337  end
338end
339
340--- load a plugin by either running `lynn.plugadd` or wrapping the callback in
341--- an autocmd
342---@param name string
343function lynn.load(name)
344  local plug = lynn.plugins[name]
345  if not plug then
346    return logerr("plugin not found", { name = name })
347  end
348
349  if lynn.loaded[plug.path] then
350    return
351  end
352
353  if not plug.lazy and not plug.event then
354    return lynn.plugadd(plug)
355  elseif plug.event then
356    return pack_lazy(plug)
357  end
358end
359
360--- load all plugins
361function lynn.loadall()
362  vim.iter(pairs(lynn.plugins)):each(function(name, _)
363    local ok, result = pcall(lynn.load, name)
364    if not ok then
365      logerr("error while loading plugin", { name = name })
366      return logtrace("load", result)
367    end
368  end)
369end
370
371--- import a list of plugins from a module
372---@param plugins lynn.plug.spec[]|string plugins|modname
373---@param nopack? boolean avoid adding the plugin to `vim.pack` until later
374function lynn.import(plugins, nopack)
375  if type(plugins) == "string" then
376    logdebug("importing plugins", { modname = plugins, nopack = not not nopack })
377
378    local ok, result = pcall(require, plugins)
379    if not ok then
380      logerr("failed to import module", { modname = plugins })
381      return logtrace("import", result)
382    end
383    return lynn.import(result, nopack)
384  end
385
386  local packspecs = vim
387    .iter(ipairs(plugins))
388    :map(function(_, p)
389      p = lynn.norm(p)
390      if nopack then
391        p.ensure = false
392      end
393      return p
394    end)
395    :map(function(p)
396      local ok, result = pcall(lynn.register, p)
397      if not ok then
398        logerr("error while registering plugin", { ["plug.name"] = p.name })
399        return logtrace("register", result or "")
400      end
401      return lynn.translate(p)
402    end)
403    :filter(function(p)
404      return p.ensure
405    end)
406    :totable()
407
408  if #packspecs == 0 then
409    return
410  end
411
412  vim.pack.add(packspecs, { load = false })
413end
414
415--- run |lynn.import()| and run packload for all plugins
416---@param plugins? lynn.plug.spec[]|string plugins|modname
417---@param nopack? boolean avoid adding the plugin to `vim.pack` until later
418function lynn.setup(plugins, nopack)
419  if plugins then
420    lynn.import(plugins, nopack)
421  end
422
423  lynn.loadall()
424
425  vim.api.nvim_exec_autocmds("User", {
426    pattern = "PackDone",
427  })
428end
429
430function lynn.sync()
431  -- update
432  vim.pack.update()
433end
434
435--- delete inactive plugins.
436--- these include all plugin directories that are not in `vim.pack`.
437function lynn.clean()
438  local inactive = utils.get_inactive()
439
440  if #inactive == 0 then
441    return
442  end
443
444  local pluglist = vim
445    .iter(inactive)
446    :map(function(p)
447      return " - " .. p.spec.name .. "\n\t" .. p.path
448    end)
449    :totable()
450  local plugstr = table.concat(pluglist, "\n")
451
452  vim.ui.input({
453    prompt = "Delete inactive plugins? (y/N)\n" .. plugstr .. "\n",
454  }, function(input)
455    if string.lower(input) == "y" then
456      vim.tbl_map(function(p)
457        vim.fs.rm(p.path, { recursive = true })
458      end, inactive)
459    end
460  end)
461end
462
463return lynn