robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
60.0 KiB1724 linesraw
1--- @brief
2---
3--- Install, update, and delete external plugins. WARNING: It is still considered
4--- experimental, yet should be stable enough for daily use.
5---
6---Manages plugins only in a dedicated [vim.pack-directory]() (see |packages|):
7---`site/pack/core/opt` subdirectory of "data" |standard-path|. Subdirectory `site` of "data"
8---standard path needs to be part of 'packpath'. It usually is, but might not be
9---in cases like |--clean| or setting |$XDG_DATA_HOME| during startup.
10---Plugin's subdirectory name matches plugin's name in specification.
11---It is assumed that all plugins in the directory are managed exclusively by `vim.pack`.
12---
13---Uses Git to manage plugins and requires present `git` executable.
14---Target plugins should be Git repositories with versions as named tags
15---following semver convention `v<major>.<minor>.<patch>` (with or without `v` prefix).
16---Like `v1.2.0` or `1.2.0`, but not `1.2` or `v1`.
17---
18---The latest state of all managed plugins is stored inside a [vim.pack-lockfile]()
19---located at |'packlockfile'|.
20---It is a JSON file that is used to persistently track data about plugins.
21---For a more robust config treat lockfile like its part: put under version control, etc.
22---In this case all plugins from the lockfile will be installed at once (in alphabetical order) and
23---at lockfile's revision (instead of inferring from `version`). This is done on the very first
24---`vim.pack` function call to ensure that lockfile is aligned with what is actually on the disk.
25---Lockfile should not be edited by hand. Corrupted data for installed plugins is repaired
26---(including after deleting whole file), but `version` fields will be missing
27---for not yet added plugins.
28---
29---[vim.pack-examples]()
30---
31---Basic install and management ~
32---
33---- Add |vim.pack.add()| call(s) to 'init.lua':
34---```lua
35---
36---vim.pack.add({
37---   -- Install "plugin1" and use default branch (usually `main` or `master`)
38---   'https://github.com/user/plugin1',
39---
40---   -- Same as above, but using a table (allows setting other options)
41---   { src = 'https://github.com/user/plugin1' },
42---
43---   -- Specify plugin's name (here the plugin will be called "plugin2"
44---   -- instead of "generic-name")
45---   { src = 'https://github.com/user/generic-name', name = 'plugin2' },
46---
47---   -- Specify version to follow during install and update
48---   {
49---     src = 'https://github.com/user/plugin3',
50---     -- Version constraint, see |vim.version.range()|
51---     version = vim.version.range('1.0'),
52---   },
53---   {
54---     src = 'https://github.com/user/plugin4',
55---     -- Git branch, tag, or commit hash
56---     version = 'main',
57---   },
58---})
59---
60----- Plugin's code can be used directly after `add()`
61---plugin1 = require('plugin1')
62---```
63---
64---- Restart Nvim (for example, with |:restart|). Plugins that were not yet
65---installed will be available on disk after `add()` call. Their revision is
66---taken from |vim.pack-lockfile| (if present) or inferred from the `version`.
67---
68---- To update all plugins with new changes:
69---    - Execute |:packupdate|. This will download updates from source and
70---      show confirmation buffer in a separate tabpage.
71---    - Review changes. To confirm all updates execute |:write|.
72---      To discard updates execute |:quit|.
73---    - (Optionally) |:restart| to start using code from updated plugins.
74---
75---Use shorter source ~
76---
77--- Create custom Lua helpers:
78---
79---```lua
80---
81---local gh = function(x) return 'https://github.com/' .. x end
82---local cb = function(x) return 'https://codeberg.org/' .. x end
83---vim.pack.add({ gh('user/plugin1'), cb('user/plugin2') })
84---```
85---
86---Another approach is to utilize Git's `insteadOf` configuration:
87---- `git config --global url."https://github.com/".insteadOf "gh:"`
88---- `git config --global url."https://codeberg.org/".insteadOf "cb:"`
89---- In 'init.lua': `vim.pack.add({ 'gh:user/plugin1', 'cb:user/plugin2' })`.
90---  These sources will be used verbatim in |vim.pack-lockfile|, so reusing
91---  the config on different machine will require the same Git configuration.
92---
93---Explore installed plugins ~
94---
95---- `:packupdate ++offline`
96---- Navigate between plugins with `[[` and `]]`. List them with `gO`
97---  (|vim.lsp.buf.document_symbol()|).
98---
99---Switch plugin's version and/or source ~
100---
101---- Update 'init.lua' for plugin to have desired `version` and/or `src`.
102---  Let's say, the switch is for plugin named 'plugin1'.
103---- |:restart|. The plugin's state on disk (revision and/or tracked source)
104---  is not yet changed. Only plugin's `version` in |vim.pack-lockfile| is updated.
105---- Execute `:packupdate plugin1`. The plugin's source is updated. If only
106---  switching version, also pass the `++offline` argument.
107---- Review changes and either confirm or discard them. If discarded, revert
108---  `version` change in 'init.lua' as well or you will be prompted again next time
109---  you run `:packupdate`.
110---
111---Freeze plugin from being updated ~
112---
113---- Update 'init.lua' for plugin to have `version` set to current revision.
114---Get it from |vim.pack-lockfile| (plugin's field `rev`; looks like `abc12345`).
115---- |:restart|.
116---
117---Unfreeze plugin to start receiving updates ~
118---
119---- Update 'init.lua' for plugin to have `version` set to whichever version
120---you want it to be updated.
121---- |:restart|.
122---
123---Revert plugin after an update ~
124---
125---- Revert the |vim.pack-lockfile| to the state before the update:
126---    - If Git tracked: `git checkout HEAD -- nvim-pack-lock.json`
127---    - If not tracked: examine log file ("nvim-pack.log" at "log" |standard-path|),
128---      locate the revisions before the latest update, and (carefully) adjust
129---      current lockfile to have those revisions.
130---- |:restart|.
131---- `:packupdate ++offline ++lockfile plugin`.
132---  Read and confirm.
133---
134---Synchronize config across machines ~
135---
136---- On main machine:
137---     - Add |vim.pack-lockfile| to VCS.
138---     - Push to the remote server.
139---- On secondary machine:
140---     - Pull from the server.
141---     - |:restart|. New plugins (not present locally, but present in the lockfile)
142---       are installed at proper revision. If some installation has failed but
143---       you know it should not (like due to bad Internet connection),
144---       revert |vim.pack-lockfile| and |:restart| again.
145---     - `:packupdate ++lockfile`. Read and confirm.
146---     - Manually delete outdated plugins (present locally, but were not present
147---       in the lockfile prior to restart) with `:packdel plugin`.
148---       They can be located by examining the VCS difference of the lockfile
149---       (`git diff -- nvim-pack-lock.json` for Git).
150---
151---Remove plugins from disk ~
152---
153---- Remove plugin specs from |vim.pack.add()| calls in 'init.lua' or they will be
154---  reinstalled later.
155---- |:restart|.
156---- Use |:packdel| with plugin names to remove. Use `:packdel ++all` to delete
157---  all inactive plugins.
158---
159---Check for pending updates ~
160---
161---- Run `vim.pack.get(nil, { offline = false })` and check the output for items
162---  with different `rev` and `rev_to` fields. To not download new updates
163---  from source, use plain `vim.pack.get()`.
164---
165---Check for issues ~
166---
167---- Run `:checkhealth vim.pack` and follow recommendations in case of detected issues.
168---
169--- <pre>help
170--- Commands                                             *vim.pack-commands* *E5807*
171---
172---                                                      *:packu* *:packupdate* *E5808*
173--- :packu[pdate][!] [++offline] [++lockfile] [name]
174---
175---     Interactively update the specified plugins. Skips confirmation when `!` is
176---     given. If no plugin names are provided, update all plugins.
177---
178---     When `++offline` is given, skip downloading new updates.
179---
180---     When `++lockfile` is given, use revisions from the lockfile.
181---
182---                                         *:packd* *:packdel* *E5809* *E5810* *E5811*
183--- :packd[el][!] {name}
184---
185---     Remove the specified plugins. Can only remove inactive plugins unless `!`
186---     is given.
187---
188--- :packd[el][!] ++all
189---
190---     Remove all inactive plugins. When `!` is given, instead remove all plugins.
191--- </pre>
192---
193---[vim.pack-events]()
194---
195---Performing actions via `vim.pack` functions can trigger these events:
196---- [PackChangedPre]() - before trying to change plugin's state.
197---- [PackChanged]() - after plugin's state has changed.
198---
199---Events are triggered in bulk respecting order of plugins in which they are supplied.
200---First all `PackChangedPre`, then perform all actions, and only after - all
201---`PackChanged` for successful actions. This provides more control for connected
202---plugins, like by specifying dependencies before the plugin itself.
203---
204---The |event-data| has these keys (type: `vim.event.packchanged.data`):
205---- `active` - whether plugin was added via |vim.pack.add()| to current session.
206---- `kind` - one of "install" (install on disk; before loading),
207---  "update" (update already installed plugin; might be not loaded),
208---  "delete" (delete from disk).
209---- `spec` - plugin's specification with defaults made explicit.
210---- `path` - full path to plugin's directory.
211---
212--- These events can be used to execute plugin hooks. For example:
213---```lua
214---local hooks = function(ev)
215---   -- Use available |event-data|
216---   local name, kind = ev.data.spec.name, ev.data.kind
217---
218---   -- Run build script after plugin's code has changed
219---   if name == 'plug-1' and (kind == 'install' or kind == 'update') then
220---     -- Append `:wait()` if you need synchronous execution
221---     vim.system({ 'make' }, { cwd = ev.data.path })
222---   end
223---
224---   -- If action relies on code from the plugin (like user command or
225---   -- Lua code), make sure to explicitly load it first
226---   if name == 'plug-2' and kind == 'update' then
227---     if not ev.data.active then
228---       vim.cmd.packadd('plug-2')
229---     end
230---     vim.cmd('PlugTwoUpdate')
231---     require('plug2').after_update()
232---   end
233---end
234---
235----- If hooks need to run on install, run this before `vim.pack.add()`
236----- To act on install from lockfile, run before very first `vim.pack.add()`
237---vim.api.nvim_create_autocmd('PackChanged', { callback = hooks })
238---```
239---[vim.pack-manifest]()
240---
241---Plugins can come with a special top level `pkg.json` manifest file with extra
242---information. If present, `vim.pack` uses it for improved user experience:
243---- Apply |:source| for scripts after triggering corresponding |vim.pack-events|.
244---  This allows plugins to define hooks that will be executed during plugin's lifetime.
245---  Sourcing is done with special context:
246---    - The |current-directory| is temporarily set to plugin's root (to make
247---      it easier to run |vim.system()| commands).
248---    - Plugin's path is temporarily ensured to be inside |'runtimepath'| (so script
249---      can use |require()| with plugin's module, possibly with explicit |package.loaded|
250---      reset inside `"update"` scripts).
251---- Running |:checkhealth| for `vim.pack` will perform extra checks to ensure
252---  healthy plugin installation.
253---
254---Full specification see at https://packspec.org/. See also |vim.pack.Manifest|.
255---A simple example:
256---```json
257---{
258---  "name": "best-plugin.nvim",
259---  "description": "The best plugin for Neovim",
260---  "engines": {
261---      "nvim": ">=0.13.0",
262---      "vim": ">=9.1.0"
263---  },
264---  "scripts": {
265---    "install": "scripts/install.lua",
266---    "preupdate": "scripts/preupdate.vim",
267---    "update": "scripts/update.vim",
268---    "preuninstall": "scripts/preuninstall.lua"
269---  }
270---}
271---```
272
273local api = vim.api
274local uv = vim.uv
275---@diagnostic disable-next-line: no-unknown
276local async = require('vim.async')
277local util = require('vim._core.util')
278local nvim_on = util.nvim_on
279local N_ = vim.fn.gettext
280
281local M = {}
282
283--- @nodoc
284--- @class vim.pack.LockData
285--- @field rev string Latest recorded revision.
286--- @field src string Plugin source.
287--- @field version? string|vim.VersionRange Plugin `version`, as supplied in `spec`.
288
289--- @nodoc
290--- @class vim.pack.Lock
291--- @field plugins table<string, vim.pack.LockData> Map from plugin name to its lock data.
292
293--- @type vim.pack.Lock
294local plugin_lock
295
296--- @return string
297local function get_plug_dir()
298  return vim.fs.joinpath(vim.fn.stdpath('data'), 'site', 'pack', 'core', 'opt')
299end
300
301-- Git ------------------------------------------------------------------------
302
303--- @async
304--- @param cmd string[]
305--- @param cwd? string
306--- @return string
307local function git_cmd(cmd, cwd)
308  -- Use '-c gc.auto=0' to disable `stderr` "Auto packing..." messages
309  cmd = vim.list_extend({ 'git', '-c', 'gc.auto=0' }, cmd)
310  local env = vim.fn.environ() --- @type table<string,string>
311  env.GIT_DIR, env.GIT_WORK_TREE, env.GIT_INDEX_FILE = nil, nil, nil
312  local sys_opts = { cwd = cwd, text = true, env = env, clear_env = true }
313  local out = async.await(3, vim.system, cmd, sys_opts) --- @type vim.SystemCompleted
314  async.await(1, vim.schedule)
315  local stderr = out.stderr or ''
316  if out.code ~= 0 then
317    error(stderr)
318  end
319  if stderr ~= '' then
320    vim.schedule(function()
321      vim.notify(stderr:gsub('\n+$', ''), vim.log.levels.WARN)
322    end)
323  end
324  return (assert(out.stdout):gsub('\n+$', ''))
325end
326
327--- @param x string
328local function parse_semver(x)
329  return vim.version.parse(x, { strict = true })
330end
331
332--- @type vim.Version
333local git_version
334
335local function git_ensure_exec()
336  local ok, sys = pcall(vim.system, { 'git', 'version' })
337  if not ok then
338    error('No `git` executable')
339  end
340  git_version = vim.version.parse(assert(sys:wait().stdout)) --[[@as vim.Version]]
341end
342
343--- @async
344--- @param url string
345--- @param path string
346local function git_clone(url, path)
347  local cmd = { 'clone', '--quiet', '--no-checkout' }
348
349  if vim.startswith(url, 'file://') then
350    cmd[#cmd + 1] = '--no-hardlinks'
351  elseif git_version >= parse_semver('2.27.0') then
352    cmd[#cmd + 1] = '--filter=blob:none'
353  end
354
355  vim.list_extend(cmd, { '--origin', 'origin', url, path })
356  git_cmd(cmd, uv.cwd())
357end
358
359--- @async
360--- @param ref string
361--- @param cwd string
362--- @return string
363local function git_get_hash(ref, cwd)
364  -- Using `rev-list -1` shows a commit of reference, while `rev-parse` shows
365  -- hash of reference. Those are different for annotated tags.
366  return git_cmd({ 'rev-list', '-1', ref }, cwd)
367end
368
369--- @async
370--- @param cwd string
371local function git_fetch(cwd)
372  -- Using '--tags --force' means conflicting tags will be synced with remote
373  local args = { 'fetch', '--quiet', '--tags', '--force', '--recurse-submodules=yes', 'origin' }
374  git_cmd(args, cwd)
375end
376
377--- @async
378--- @param cwd string
379--- @return string
380local function git_get_default_branch(cwd)
381  local res = git_cmd({ 'rev-parse', '--abbrev-ref', 'origin/HEAD' }, cwd)
382  return (res:gsub('^origin/', ''))
383end
384
385--- @async
386--- @param cwd string
387--- @return string[]
388local function git_get_branches(cwd)
389  local def_branch = git_get_default_branch(cwd)
390  local cmd = { 'branch', '--remote', '--list', '--format=%(refname:short)', '--', 'origin/**' }
391  local stdout = git_cmd(cmd, cwd)
392  local res = {} --- @type string[]
393  for l in vim.gsplit(stdout, '\n') do
394    local branch = l:match('^origin/(.+)$')
395    local pos = branch == def_branch and 1 or (#res + 1)
396    table.insert(res, pos, branch)
397  end
398  return res
399end
400
401--- @async
402--- @param cwd string
403--- @return string[]
404local function git_get_tags(cwd)
405  local tags = git_cmd({ 'tag', '--list', '--sort=-v:refname' }, cwd)
406  return tags == '' and {} or vim.split(tags, '\n')
407end
408
409-- Plugin operations ----------------------------------------------------------
410
411--- @param msg string|string[]
412--- @param level ('DEBUG'|'TRACE'|'INFO'|'WARN'|'ERROR')?
413local function notify(msg, level)
414  msg = type(msg) == 'table' and table.concat(msg, '\n') or msg
415  vim.notify('vim.pack: ' .. msg, vim.log.levels[level or 'INFO'])
416  vim.cmd.redraw()
417end
418
419--- @param x string|vim.VersionRange
420--- @return boolean
421local function is_version(x)
422  return type(x) == 'string' or (type(x) == 'table' and pcall(x.has, x, '1'))
423end
424
425--- @param x string
426--- @return boolean
427local function is_semver(x)
428  return parse_semver(x) ~= nil
429end
430
431--- @param x any
432local function is_nonempty_string(x)
433  return type(x) == 'string' and x ~= ''
434end
435
436--- @return string
437local function get_timestamp()
438  return vim.fn.strftime('%Y-%m-%d %H:%M:%S')
439end
440
441--- @class vim.pack.Spec
442---
443--- URI from which to install and pull updates. Any format supported by `git clone` is allowed.
444--- @field src string
445---
446--- Name of plugin. Will be used as directory name. Default: `src` repository name.
447--- @field name? string
448---
449--- Version to use for install and updates. Can be:
450--- - `nil` (no value, default) to use repository's default branch (usually `main` or `master`).
451--- - String to use specific branch, tag, or commit hash.
452--- - Output of |vim.version.range()| to install the greatest/last semver tag
453---   inside the version constraint.
454--- @field version? string|vim.VersionRange
455---
456--- @field data? any Arbitrary data associated with a plugin.
457
458--- @alias vim.pack.SpecResolved { src: string, name: string, version: nil|string|vim.VersionRange, data: any|nil }
459
460--- @param spec string|vim.pack.Spec
461--- @return vim.pack.SpecResolved
462local function normalize_spec(spec)
463  -- and/or narrowing: EmmyLuaLs/emmylua-analyzer-rust#1260
464  spec = (type(spec) == 'string' and { src = spec } or spec) --[[@as vim.pack.Spec]]
465  vim.validate('spec', spec, 'table')
466  vim.validate('spec.src', spec.src, is_nonempty_string, false, 'non-empty string')
467  local name = spec.name or spec.src:gsub('%.git$', '')
468  name = (type(name) == 'string' and name or ''):match('[^/]+$') or ''
469  vim.validate('spec.name', name, is_nonempty_string, true, 'non-empty string')
470  vim.validate('spec.version', spec.version, is_version, true, 'string or vim.VersionRange')
471  return { src = spec.src, name = name, version = spec.version, data = spec.data }
472end
473
474--- @class (private) vim.pack.PlugInfo
475--- @field err string The latest error when working on plugin. If non-empty,
476---   all further actions should not be done (including triggering events).
477--- @field installed? boolean Whether plugin was successfully installed.
478--- @field updated? boolean Whether plugin was successfully updated.
479--- @field version_str? string `spec.version` with resolved version range.
480--- @field version_ref? string Resolved version as Git reference (if different
481---   from `version_str`).
482--- @field sha_head? string Git hash of HEAD.
483--- @field sha_target? string Git hash of `version_ref`.
484--- @field update_details? string Details about the update:: changelog if HEAD
485---   and target are different, available newer tags otherwise.
486
487--- @class (private) vim.pack.Plug
488--- @field spec vim.pack.SpecResolved
489--- @field path string
490--- @field info vim.pack.PlugInfo Gathered information about plugin.
491
492--- @param spec string|vim.pack.Spec
493--- @param plug_dir string?
494--- @return vim.pack.Plug
495local function new_plug(spec, plug_dir)
496  local spec_resolved = normalize_spec(spec)
497  local path = vim.fs.joinpath(plug_dir or get_plug_dir(), spec_resolved.name)
498  local info = { err = '', installed = plugin_lock.plugins[spec_resolved.name] ~= nil }
499  return { spec = spec_resolved, path = path, info = info }
500end
501
502--- Normalize plug array: gather non-conflicting data from duplicated entries.
503--- @param plugs vim.pack.Plug[]
504--- @return vim.pack.Plug[]
505local function normalize_plugs(plugs)
506  --- @type table<string, { plug: vim.pack.Plug, id: integer }>
507  local plug_map = {}
508  local n = 0
509  for _, p in ipairs(plugs) do
510    -- Collect
511    if not plug_map[p.path] then
512      n = n + 1
513      plug_map[p.path] = { plug = p, id = n }
514    end
515    local p_data = plug_map[p.path]
516    -- TODO(echasnovski): if both versions are `vim.VersionRange`, collect as
517    -- their intersection. Needs `vim.version.intersect`.
518    p_data.plug.spec.version = vim.nonnil(p_data.plug.spec.version, p.spec.version)
519
520    -- Ensure no conflicts
521    local spec_ref = p_data.plug.spec
522    local spec = p.spec
523    if spec_ref.src ~= spec.src then
524      local src_1 = tostring(spec_ref.src)
525      local src_2 = tostring(spec.src)
526      error(('Conflicting `src` for `%s`:\n%s\n%s'):format(spec.name, src_1, src_2))
527    end
528    if spec_ref.version ~= spec.version then
529      local ver_1 = tostring(spec_ref.version)
530      local ver_2 = tostring(spec.version)
531      error(('Conflicting `version` for `%s`:\n%s\n%s'):format(spec.name, ver_1, ver_2))
532    end
533  end
534
535  --- @type vim.pack.Plug[]
536  local res = {}
537  for _, p_data in pairs(plug_map) do
538    res[p_data.id] = p_data.plug
539  end
540  assert(#res == n)
541  return res
542end
543
544--- @param names? string[]
545--- @return vim.pack.Plug[]
546local function plug_list_from_names(names)
547  local p_data_list = M.get(names, { info = false })
548  local plug_dir = get_plug_dir()
549  local plugs = {} --- @type vim.pack.Plug[]
550  for _, p_data in ipairs(p_data_list) do
551    plugs[#plugs + 1] = new_plug(p_data.spec, plug_dir)
552  end
553  return plugs
554end
555
556--- Map from plugin path to its data.
557--- Use map and not array to avoid linear lookup during startup.
558--- @type table<string, { plug: vim.pack.Plug, id: integer }?>
559local active_plugins = {}
560local n_active_plugins = 0
561
562--- @class vim.pack.ManifestEngines
563--- @inlinedoc
564--- @field nvim? string Version range for Nvim.
565--- @field vim? string Version range for Vim.
566
567--- @class vim.pack.ManifestScripts
568--- @inlinedoc
569--- @field install? string Post install script.
570--- @field preupdate? string Pre update script.
571--- @field update? string Post update script.
572--- @field preuninstall? string Pre delete script.
573
574--- @class vim.pack.Manifest
575--- @field name? string Plugin name
576--- @field description? string Plugin description
577--- Supported engine versions. Values should be |vim.version.range()| compatible specs.
578--- @field engines? vim.pack.ManifestEngines
579--- Script locations (relative to plugin's root) to |:source| after triggering
580--- corresponding |vim.pack-events|.
581--- @field scripts? vim.pack.ManifestScripts
582
583--- @param path string
584--- @return vim.pack.Manifest?
585local function manifest_read(path)
586  local manifest_path = vim.fs.joinpath(path, 'pkg.json')
587  local stat = uv.fs_stat(manifest_path)
588  if not stat then
589    return nil
590  end
591
592  local fd = uv.fs_open(manifest_path, 'r', 438)
593  if not fd then
594    return {}
595  end
596
597  local data = assert(uv.fs_read(fd, stat.size, 0))
598  assert(uv.fs_close(fd))
599  local ok, res = pcall(vim.json.decode, data)
600  return (ok and type(res) == 'table') and res or {}
601end
602
603--- @param p vim.pack.Plug
604--- @param name string
605local function source_manifest_script(p, name)
606  local manifest = manifest_read(p.path)
607  if not (type(manifest) == 'table' and (manifest.scripts or {})[name]) then
608    return
609  end
610
611  local script_path = vim.fs.joinpath(p.path, (manifest.scripts or {})[name])
612  vim._with({ cwd = p.path, o = { runtimepath = vim.o.runtimepath } }, function()
613    vim.cmd.packadd({ p.spec.name, bang = true })
614    ---@diagnostic disable-next-line: no-unknown
615    local ok, err = pcall(vim.cmd.source, { script_path, magic = { file = false, bar = false } })
616    if not ok then
617      notify(err, 'WARN')
618    end
619  end)
620end
621
622local manifest_script_name_map = {
623  PackChangedPre = { update = 'preupdate', delete = 'preuninstall' },
624  PackChanged = { install = 'install', update = 'update' },
625}
626
627--- @param plugs vim.pack.Plug[]
628--- @param event_name 'PackChangedPre'|'PackChanged'
629--- @param kind 'install'|'update'|'delete'
630local function trigger_events(plugs, event_name, kind)
631  local manifest_script_name = manifest_script_name_map[event_name][kind]
632  for _, p in ipairs(plugs) do
633    local active = active_plugins[p.path] ~= nil
634    local data = { active = active, kind = kind, spec = vim.deepcopy(p.spec), path = p.path }
635    api.nvim_exec_autocmds(event_name, { pattern = p.path, data = data })
636
637    if manifest_script_name then
638      source_manifest_script(p, manifest_script_name)
639    end
640  end
641end
642
643--- @param action string
644--- @return fun(kind: 'begin'|'report'|'end', percent: integer, fmt: string, ...:any): nil
645local function new_progress_report(action)
646  local progress = { kind = 'progress', source = 'vim.pack', title = 'vim.pack' }
647  local headless = #api.nvim_list_uis() == 0
648
649  return vim.schedule_wrap(function(kind, percent, fmt, ...)
650    progress.status = kind == 'end' and 'success' or 'running'
651    progress.percent = percent
652    local msg = ('%s %s'):format(action, fmt:format(...))
653    progress.id = api.nvim_echo({ { msg } }, kind ~= 'report', progress)
654    -- Force redraw to show installation progress during startup
655    -- TODO: redraw! not needed with ui2.
656    if not headless then
657      vim.cmd.redraw({ bang = true })
658    end
659  end)
660end
661
662local copcall = package.loaded.jit and pcall or require('coxpcall').pcall
663local max_timeout = 120000
664
665--- @param funs (async fun())[]
666local function async_join_run_wait(funs)
667  local n_threads = 2 * (uv.available_parallelism() or 1)
668  --- @async
669  local function joined_f()
670    ---@diagnostic disable-next-line: no-unknown
671    local semaphore = async.semaphore(n_threads)
672    ---@param f async fun()
673    local function run_one(f)
674      -- Isolate job failures. Task return still observes cancellation.
675      copcall(semaphore.with, semaphore, f)
676    end
677    for _, f in ipairs(funs) do
678      async.run(run_one, f)
679    end
680  end
681  async.run(joined_f):wait(max_timeout)
682end
683
684--- Execute function in parallel for each non-errored plugin in the list
685--- @param plug_list vim.pack.Plug[]
686--- @param f async fun(p: vim.pack.Plug)
687--- @param progress_action string
688local function run_list(plug_list, f, progress_action)
689  local report_progress = new_progress_report(progress_action)
690
691  -- Construct array of functions to execute in parallel
692  local n_finished = 0
693  local funs = {} --- @type (async fun())[]
694  for _, p in ipairs(plug_list) do
695    -- Run only for plugins which didn't error before
696    if p.info.err == '' then
697      --- @async
698      funs[#funs + 1] = function()
699        ---@diagnostic disable-next-line: no-unknown
700        local ok, err = async.pawait(async.run(f, p))
701        if not ok then
702          p.info.err = err --- @as string
703        end
704
705        -- Show progress
706        n_finished = n_finished + 1
707        local percent = math.floor(100 * n_finished / #funs)
708        report_progress('report', percent, '(%d/%d) - %s', n_finished, #funs, p.spec.name)
709      end
710    end
711  end
712
713  if #funs == 0 then
714    return
715  end
716
717  -- Run async in parallel but wait for all to finish/timeout
718  report_progress('begin', 0, '(0/%d)', #funs)
719  async_join_run_wait(funs)
720  report_progress('end', 100, '(%d/%d)', #funs, #funs)
721end
722
723local confirm_all = false
724
725--- @param plug_list vim.pack.Plug[]
726--- @return boolean
727local function confirm_install(plug_list)
728  if confirm_all then
729    return true
730  end
731
732  -- Gather pretty aligned list of plugins to install
733  local name_width, name_max_width = {}, 0 --- @type integer[], integer
734  for i, p in ipairs(plug_list) do
735    name_width[i] = api.nvim_strwidth(p.spec.name)
736    name_max_width = math.max(name_max_width, name_width[i])
737  end
738  local lines = {} --- @type string[]
739  for i, p in ipairs(plug_list) do
740    local pad = (' '):rep(name_max_width - assert(name_width[i]) + 1)
741    lines[i] = ('%s%sfrom %s'):format(p.spec.name, pad, p.spec.src)
742  end
743
744  local text = table.concat(lines, '\n')
745  local confirm_msg = ('These plugins will be installed:\n\n%s\n'):format(text)
746  local choice = vim.fn.confirm(confirm_msg, 'Proceed? &Yes\n&No\n&Always', 1, 'Question')
747  confirm_all = choice == 3
748  vim.cmd.redraw()
749  return choice ~= 2
750end
751
752--- @param tags string[]
753--- @param version_range vim.VersionRange
754local function get_last_semver_tag(tags, version_range)
755  local last_tag, last_ver_tag --- @type string, vim.Version
756  for _, tag in ipairs(tags) do
757    local ver_tag = parse_semver(tag)
758    if ver_tag then
759      if version_range:has(ver_tag) and (not last_ver_tag or ver_tag > last_ver_tag) then
760        last_tag, last_ver_tag = tag, ver_tag
761      end
762    end
763  end
764  return last_tag
765end
766
767--- @async
768--- @param p vim.pack.Plug
769local function resolve_version(p)
770  --- @param name string
771  --- @param list string[]
772  local function list_in_line(name, list)
773    return ('\n%s: %s'):format(name, table.concat(list, ', '))
774  end
775
776  -- Resolve only once
777  if p.info.version_str then
778    return
779  end
780  local version = p.spec.version
781
782  -- Default branch
783  if not version then
784    p.info.version_str = git_get_default_branch(p.path)
785    p.info.version_ref = 'origin/' .. p.info.version_str
786    return
787  end
788
789  -- Non-version-range like version: branch, tag, or commit hash
790  local branches = git_get_branches(p.path)
791  local tags = git_get_tags(p.path)
792  if type(version) == 'string' then
793    local is_branch = vim.tbl_contains(branches, version)
794    ---@diagnostic disable-next-line: no-unknown
795    local is_tag_or_hash = async.pawait(async.run(git_get_hash, version, p.path))
796    if not (is_branch or is_tag_or_hash) then
797      local err = ('`%s` is not a branch/tag/commit. Available:'):format(version)
798        .. list_in_line('Tags', tags)
799        .. list_in_line('Branches', branches)
800      error(err)
801    end
802
803    p.info.version_str = version
804    p.info.version_ref = (is_branch and 'origin/' or '') .. version
805    return
806  end
807  --- @cast version vim.VersionRange
808
809  -- Choose the greatest/last version among all matching semver tags
810  p.info.version_str = get_last_semver_tag(tags, version)
811  if p.info.version_str == nil then
812    local semver_tags = vim.tbl_filter(is_semver, tags)
813    table.sort(semver_tags, vim.version.gt)
814    local err = 'No versions fit constraint. Relax it or switch to branch. Available:'
815      .. list_in_line('Versions', semver_tags)
816      .. list_in_line('Branches', branches)
817    error(err)
818  end
819end
820
821--- @async
822--- @param p vim.pack.Plug
823local function infer_revisions(p)
824  p.info.sha_head = p.info.sha_head or git_get_hash('HEAD', p.path)
825
826  resolve_version(p)
827  local target_ref = p.info.version_ref or p.info.version_str --[[@as string]]
828  p.info.sha_target = p.info.sha_target or git_get_hash(target_ref, p.path)
829end
830
831--- Keep repos in detached HEAD state. Infer commit from resolved version.
832--- No local branches are created, branches from "origin" remote are used directly.
833--- @async
834--- @param p vim.pack.Plug
835--- @param timestamp string
836--- @param skip_stash? boolean
837local function checkout(p, timestamp, skip_stash)
838  infer_revisions(p)
839
840  if not skip_stash then
841    local stash_cmd = { 'stash' }
842    if git_version > parse_semver('2.13.0') then
843      -- Use 'push' to avoid a 'stash -m' bug in versions prior to git v2.26
844      stash_cmd[#stash_cmd + 1] = 'push'
845      stash_cmd[#stash_cmd + 1] = '--message'
846      stash_cmd[#stash_cmd + 1] = ('vim.pack: %s Stash before checkout'):format(timestamp)
847    end
848    stash_cmd[#stash_cmd + 1] = '--quiet'
849    git_cmd(stash_cmd, p.path)
850  end
851
852  git_cmd({ 'checkout', '--quiet', p.info.sha_target }, p.path)
853
854  local submodule_cmd = { 'submodule', 'update', '--init', '--recursive' }
855  if git_version >= parse_semver('2.36.0') then
856    submodule_cmd[#submodule_cmd + 1] = '--filter=blob:none'
857  end
858  git_cmd(submodule_cmd, p.path)
859
860  plugin_lock.plugins[p.spec.name].rev = p.info.sha_target
861
862  -- (Re)Generate help tags according to the current help files.
863  -- Also use `pcall()` because `:helptags` errors if 'doc/' has no help files.
864  local doc_dir = vim.fs.joinpath(p.path, 'doc')
865  vim.fn.delete(vim.fs.joinpath(doc_dir, 'tags'))
866  if vim.fn.isdirectory(doc_dir) == 1 then
867    copcall(vim.cmd.helptags, { doc_dir, magic = { file = false } })
868  end
869end
870
871--- @param plug_list vim.pack.Plug[]
872--- @param confirm? boolean
873local function install_list(plug_list, confirm)
874  local timestamp = get_timestamp()
875  --- @async
876  --- @param p vim.pack.Plug
877  local function do_install(p)
878    git_clone(p.spec.src, p.path)
879
880    plugin_lock.plugins[p.spec.name].src = p.spec.src
881
882    -- Prefer revision from the lockfile instead of using `version`
883    p.info.sha_target = (plugin_lock.plugins[p.spec.name] or {}).rev
884
885    checkout(p, timestamp, true)
886    p.info.installed = true
887  end
888
889  -- Install possibly after user confirmation
890  if not confirm or confirm_install(plug_list) then
891    trigger_events(plug_list, 'PackChangedPre', 'install')
892    run_list(plug_list, do_install, 'Installing plugins')
893    local installed = vim.tbl_filter(function(p)
894      return p.info.installed == true
895    end, plug_list)
896    trigger_events(installed, 'PackChanged', 'install')
897  end
898
899  -- Ensure that not fully installed plugins are absent on disk and in lockfile
900  for _, p in ipairs(plug_list) do
901    if not (p.info.installed and uv.fs_stat(p.path) ~= nil) then
902      plugin_lock.plugins[p.spec.name] = nil
903      vim.fs.rm(p.path, { recursive = true, force = true })
904    end
905  end
906end
907
908--- @async
909--- @param p vim.pack.Plug
910local function infer_update_details(p)
911  p.info.update_details = ''
912  infer_revisions(p)
913  local sha_head = assert(p.info.sha_head)
914  local sha_target = assert(p.info.sha_target)
915
916  -- Try showing log of changes (if any)
917  if sha_head ~= sha_target then
918    local range = sha_head .. '...' .. sha_target
919    local format = '--pretty=format:%m %h │ %s%d'
920    -- Show only tags near commits (not `origin/main`, etc.)
921    local decorate = '--decorate-refs=refs/tags'
922    -- `--topo-order` makes showing divergent branches nicer, but by itself
923    -- doesn't ensure that reverted ("left", shown with `<`) and added
924    -- ("right", shown with `>`) commits have fixed order.
925    local l = git_cmd({ 'log', format, '--topo-order', '--left-only', decorate, range }, p.path)
926    local r = git_cmd({ 'log', format, '--topo-order', '--right-only', decorate, range }, p.path)
927    p.info.update_details = l == '' and r or (r == '' and l or (l .. '\n' .. r))
928    return
929  end
930
931  -- Suggest newer semver tags (i.e. greater than greatest past semver tag)
932  local all_semver_tags = vim.tbl_filter(is_semver, git_get_tags(p.path))
933  if #all_semver_tags == 0 then
934    return
935  end
936
937  local older_tags = ''
938  if git_version >= parse_semver('2.13.0') then
939    older_tags = git_cmd({ 'tag', '--list', '--no-contains', sha_head }, p.path)
940  end
941  local cur_tags = git_cmd({ 'tag', '--list', '--points-at', sha_head }, p.path)
942  local past_tags = vim.split(older_tags, '\n')
943  vim.list_extend(past_tags, vim.split(cur_tags, '\n'))
944
945  local any_version = vim.version.range('*') --[[@as vim.VersionRange]]
946  local last_version = get_last_semver_tag(past_tags, any_version)
947
948  local newer_semver_tags = vim.tbl_filter(function(x)
949    return vim.version.gt(x, last_version)
950  end, all_semver_tags)
951
952  table.sort(newer_semver_tags, vim.version.gt)
953  p.info.update_details = table.concat(newer_semver_tags, '\n')
954end
955
956--- @param plug vim.pack.Plug
957--- @param load? boolean|fun(plug_data: {spec: vim.pack.Spec, path: string})
958local function pack_add(plug, load)
959  -- Add plugin only once, i.e. no overriding of spec. This allows users to put
960  -- plugin first to fully control its spec.
961  if active_plugins[plug.path] then
962    return
963  end
964
965  n_active_plugins = n_active_plugins + 1
966  active_plugins[plug.path] = { plug = plug, id = n_active_plugins }
967
968  if vim.is_callable(load) then
969    ---@cast load -boolean, -nil
970    load({ spec = vim.deepcopy(plug.spec), path = plug.path })
971    return
972  end
973
974  -- NOTE: The `:packadd` specifically seems to not handle spaces in dir name
975  vim.cmd.packadd({ vim.fn.escape(plug.spec.name, ' '), bang = not load, magic = { file = false } })
976
977  -- The `:packadd` only sources plain 'plugin/' files. Execute 'after/' scripts
978  -- if not during startup (when they will be sourced later, even if
979  -- `vim.pack.add` is inside user's 'plugin/')
980  -- See https://github.com/vim/vim/issues/15584
981  -- Deliberately do so after executing all currently known 'plugin/' files.
982  if vim.v.vim_did_enter == 1 and load then
983    local after_paths = vim.fn.glob(plug.path .. '/after/plugin/**/*.{vim,lua}', false, true)
984    --- @param path string
985    vim.tbl_map(function(path)
986      vim.cmd.source({ path, magic = { file = false } })
987    end, after_paths)
988  end
989end
990
991local function lock_write()
992  -- Serialize `version`
993  local lock = vim.deepcopy(plugin_lock)
994  for _, l_data in pairs(lock.plugins) do
995    local version = l_data.version
996    if version then
997      l_data.version = type(version) == 'string' and ("'%s'"):format(version) or tostring(version)
998    end
999  end
1000
1001  vim.fn.mkdir(vim.fs.dirname(M._plugin_lock_path), 'p')
1002  local fd = assert(uv.fs_open(M._plugin_lock_path, 'w', 438))
1003
1004  local data = vim.json.encode(lock, { indent = '  ', sort_keys = true })
1005  assert(uv.fs_write(fd, data .. '\n'))
1006  assert(uv.fs_close(fd))
1007end
1008
1009--- @param names string[]
1010--- @param plug_dir string
1011local function lock_repair(names, plug_dir)
1012  --- @async
1013  local function f()
1014    for _, name in ipairs(names) do
1015      local path = vim.fs.joinpath(plug_dir, name)
1016      -- Try reusing existing table to preserve maybe present `version`
1017      local data = plugin_lock.plugins[name] or {}
1018      data.rev = git_get_hash('HEAD', path)
1019      data.src = git_cmd({ 'remote', 'get-url', 'origin' }, path)
1020      plugin_lock.plugins[name] = data
1021    end
1022  end
1023  async.run(f):wait(max_timeout)
1024end
1025
1026--- Sync lockfile data and installed plugins:
1027--- - Install plugins that have proper lockfile data but are not on disk.
1028--- - Repair corrupted lock data for installed plugins.
1029--- - Remove unrepairable corrupted lock data and plugins.
1030--- @param confirm boolean
1031--- @param specs (string|vim.pack.Spec)[] Plugin specs provided by the user. Can contain
1032--- fields outside of what is in the lockfile to be passed down to events.
1033local function lock_sync(confirm, specs)
1034  if type(plugin_lock.plugins) ~= 'table' then
1035    plugin_lock.plugins = {}
1036  end
1037
1038  -- Compute installed plugins
1039  local plug_dir = get_plug_dir()
1040  if uv.fs_stat(plug_dir) == nil then
1041    vim.fn.mkdir(plug_dir, 'p')
1042  end
1043
1044  -- NOTE: The directory traversal is done on every startup, but it is very fast.
1045  -- Also, single `vim.fs.dir()` scales better than on demand `uv.fs_stat()` checks.
1046  local installed = {} --- @type table<string,string>
1047  for name, fs_type in vim.fs.dir(plug_dir) do
1048    installed[name] = fs_type
1049    plugin_lock.plugins[name] = plugin_lock.plugins[name] or {}
1050  end
1051
1052  -- Traverse once optimizing for "regular startup" (no repair, no install)
1053  local to_install = {} --- @type vim.pack.Plug[]
1054  local to_repair = {} --- @type string[]
1055  local to_remove = {} --- @type string[]
1056  for name, data in pairs(plugin_lock.plugins) do
1057    if type(data) ~= 'table' then
1058      data = {} ---@diagnostic disable-line: missing-fields
1059      plugin_lock.plugins[name] = data
1060    end
1061
1062    -- Deserialize `version`
1063    local version = data.version
1064    if type(version) == 'string' then
1065      data.version = version:match("^'(.+)'$") or vim.version.range(version)
1066    end
1067
1068    -- Synchronize
1069    local is_bad_lock = type(data.rev) ~= 'string' or type(data.src) ~= 'string'
1070    local is_bad_plugin = installed[name] and installed[name] ~= 'directory'
1071    if is_bad_lock or is_bad_plugin then
1072      local t = installed[name] == 'directory' and to_repair or to_remove
1073      t[#t + 1] = name
1074    elseif not installed[name] then
1075      local spec ---@type vim.pack.Spec
1076      -- Try reusing spec from user's `vim.pack.add()` (matters for events)
1077      -- Delay until this point when shaving milliseconds shouldn't matter much
1078      for _, s in ipairs(specs) do
1079        local ok, s_norm = pcall(normalize_spec, s)
1080        if ok and s_norm.name == name then
1081          spec = vim.deepcopy(s_norm)
1082        end
1083      end
1084
1085      -- Force fields relevant to actual installation, try to preserve others
1086      spec = spec or {}
1087      spec.src = data.src
1088      spec.name = name
1089      spec.version = spec.version or data.version
1090
1091      to_install[#to_install + 1] = new_plug(spec, plug_dir)
1092    end
1093  end
1094
1095  -- Perform actions if needed
1096  if #to_install > 0 then
1097    table.sort(to_install, function(a, b)
1098      return a.spec.name < b.spec.name
1099    end)
1100    git_ensure_exec()
1101    install_list(to_install, confirm)
1102  end
1103
1104  if #to_repair > 0 then
1105    lock_repair(to_repair, plug_dir)
1106    table.sort(to_repair)
1107    notify('Repaired corrupted lock data for plugins: ' .. table.concat(to_repair, ', '), 'WARN')
1108    lock_write()
1109  end
1110
1111  if #to_remove > 0 then
1112    for _, name in ipairs(to_remove) do
1113      plugin_lock.plugins[name] = nil
1114      vim.fs.rm(vim.fs.joinpath(plug_dir, name), { recursive = true, force = true })
1115    end
1116    table.sort(to_remove)
1117    notify('Removed corrupted lock data for plugins: ' .. table.concat(to_remove, ', '), 'WARN')
1118    lock_write()
1119  end
1120end
1121
1122--- @param confirm? boolean
1123--- @param specs? (string|vim.pack.Spec)[]
1124local function lock_read(confirm, specs)
1125  if plugin_lock then
1126    return
1127  end
1128
1129  M._plugin_lock_path = vim.go.packlockfile
1130  local fd = uv.fs_open(M._plugin_lock_path, 'r', 438)
1131  if fd then
1132    local stat = assert(uv.fs_fstat(fd))
1133    local data = assert(uv.fs_read(fd, stat.size, 0))
1134    assert(uv.fs_close(fd))
1135    plugin_lock = vim.json.decode(data)
1136  else
1137    plugin_lock = { plugins = {} }
1138  end
1139
1140  lock_sync(confirm ~= false, specs or {})
1141end
1142
1143--- @class vim.pack.keyset.add
1144--- @inlinedoc
1145--- Load `plugin/` files and `ftdetect/` scripts. If `false`, works like `:packadd!`.
1146--- If function, called with plugin data and is fully responsible for loading plugin.
1147--- Default `false` during |init.lua| sourcing and `true` afterwards.
1148--- @field load? boolean|fun(plug_data: {spec: vim.pack.Spec, path: string})
1149---
1150--- @field confirm? boolean Whether to ask user to confirm initial install. Default `true`.
1151
1152--- Add plugin to current session
1153---
1154--- - For each specification check that plugin exists on disk in |vim.pack-directory|:
1155---     - If exists, check if its `src` is the same as input. If not - delete
1156---       immediately to clean install from the new source. Otherwise do nothing.
1157---     - If doesn't exist, install it by downloading from `src` into `name`
1158---       subdirectory (via partial blobless `git clone`) and update revision
1159---       to match `version` (via `git checkout`). Plugin will not be on disk if
1160---       any step resulted in an error.
1161--- - For each plugin execute |:packadd| (or customizable `load` function) making
1162---   it reachable by Nvim.
1163---
1164--- Notes:
1165--- - Installation is done in parallel, but waits for all to finish before
1166---   continuing next code execution.
1167--- - If plugin is already present on disk, there are no checks about its current revision.
1168---   The specified `version` can be not the one actually present on disk.
1169---   Execute |vim.pack.update()| to synchronize.
1170--- - Adding plugin second and more times during single session does nothing:
1171---   only the data from the first adding is registered.
1172---
1173--- @param specs (string|vim.pack.Spec)[] List of plugin specifications. String item
1174--- is treated as `src`.
1175--- @param opts? vim.pack.keyset.add
1176function M.add(specs, opts)
1177  vim.validate('specs', specs, vim.islist, false, 'list')
1178  opts = vim.tbl_extend('force', { load = vim.v.vim_did_init == 1, confirm = true }, opts or {})
1179  vim.validate('opts', opts, 'table')
1180
1181  lock_read(opts.confirm, specs)
1182
1183  local plug_dir = get_plug_dir()
1184  local plugs = {} --- @type vim.pack.Plug[]
1185  for i = 1, #specs do
1186    plugs[i] = new_plug(specs[i], plug_dir)
1187  end
1188  plugs = normalize_plugs(plugs)
1189
1190  -- Pre-process
1191  local plugs_to_install = {} --- @type vim.pack.Plug[]
1192  local needs_lock_write = false
1193  for _, p in ipairs(plugs) do
1194    -- Detect `version` change
1195    local p_lock = plugin_lock.plugins[p.spec.name] or {}
1196    needs_lock_write = needs_lock_write or p_lock.version ~= p.spec.version
1197    p_lock.version = p.spec.version
1198    plugin_lock.plugins[p.spec.name] = p_lock
1199
1200    -- Register for install
1201    if not p.info.installed then
1202      plugs_to_install[#plugs_to_install + 1] = p
1203      needs_lock_write = true
1204    end
1205  end
1206
1207  -- Install
1208  if #plugs_to_install > 0 then
1209    git_ensure_exec()
1210    install_list(plugs_to_install, opts.confirm)
1211  end
1212
1213  if needs_lock_write then
1214    lock_write()
1215  end
1216
1217  -- Register and load those actually on disk while collecting errors
1218  -- Delay showing all errors to have "good" plugins added first
1219  local errors = {} --- @type string[]
1220  for _, p in ipairs(plugs) do
1221    if p.info.installed then
1222      local ok, err = pcall(pack_add, p, opts.load) --[[@as string]]
1223      if not ok then
1224        p.info.err = err
1225      end
1226    end
1227    if p.info.err ~= '' then
1228      errors[#errors + 1] = ('`%s`:\n%s'):format(p.spec.name, p.info.err)
1229    end
1230  end
1231
1232  if #errors > 0 then
1233    local error_str = table.concat(errors, '\n\n')
1234    error(('vim.pack:\n\n%s'):format(error_str))
1235  end
1236end
1237
1238--- @param p vim.pack.Plug
1239--- @return string
1240local function compute_feedback_lines_single(p)
1241  local active_suffix = active_plugins[p.path] ~= nil and '' or ' (not active)'
1242  if p.info.err ~= '' then
1243    return ('## %s%s\n\n %s'):format(p.spec.name, active_suffix, p.info.err:gsub('\n', '\n  '))
1244  end
1245
1246  local parts = { ('## %s%s\n'):format(p.spec.name, active_suffix) }
1247  local version_suffix = p.info.version_str == '' and '' or (' (%s)'):format(p.info.version_str)
1248
1249  if p.info.sha_head == p.info.sha_target then
1250    parts[#parts + 1] = table.concat({
1251      'Path:     ' .. p.path,
1252      'Source:   ' .. p.spec.src,
1253      'Revision: ' .. p.info.sha_target .. version_suffix,
1254    }, '\n')
1255
1256    local update_details = assert(p.info.update_details)
1257    if update_details ~= '' then
1258      local details = update_details:gsub('\n', '\n• ')
1259      parts[#parts + 1] = '\n\nAvailable newer versions:\n• ' .. details
1260    end
1261  else
1262    parts[#parts + 1] = table.concat({
1263      'Path:            ' .. p.path,
1264      'Source:          ' .. p.spec.src,
1265      'Revision before: ' .. p.info.sha_head,
1266      'Revision after:  ' .. p.info.sha_target .. version_suffix,
1267      '',
1268      'Pending updates:',
1269      p.info.update_details,
1270    }, '\n')
1271  end
1272
1273  return table.concat(parts, '')
1274end
1275
1276--- @param plug_list vim.pack.Plug[]
1277--- @param skip_same_sha boolean
1278--- @return string[]
1279local function compute_feedback_lines(plug_list, skip_same_sha)
1280  -- Construct plugin line groups for better report
1281  local report_err, report_update, report_same = {}, {}, {}
1282  for _, p in ipairs(plug_list) do
1283    --- @type string[]
1284    local group_arr = p.info.err ~= '' and report_err
1285      or (p.info.sha_head ~= p.info.sha_target and report_update or report_same)
1286    group_arr[#group_arr + 1] = compute_feedback_lines_single(p)
1287  end
1288
1289  local lines = {}
1290  --- @param header string
1291  --- @param arr string[]
1292  local function append_report(header, arr)
1293    if #arr == 0 then
1294      return
1295    end
1296    header = header .. ' ' .. string.rep('─', 79 - header:len())
1297    table.insert(lines, header)
1298    vim.list_extend(lines, arr)
1299  end
1300  append_report('# Error', report_err)
1301  append_report('# Update', report_update)
1302  if not skip_same_sha then
1303    append_report('# Same', report_same)
1304  end
1305
1306  return vim.split(table.concat(lines, '\n\n'), '\n')
1307end
1308
1309--- @param plug_list vim.pack.Plug[]
1310local function feedback_log(plug_list)
1311  local lines = { ('========== Update %s =========='):format(get_timestamp()) }
1312  vim.list_extend(lines, compute_feedback_lines(plug_list, true))
1313  lines[#lines + 1] = ''
1314
1315  local log_path = vim.fn.stdpath('log') .. '/nvim-pack.log'
1316  vim.fn.mkdir(vim.fs.dirname(log_path), 'p')
1317  vim.fn.writefile(lines, log_path, 'a')
1318end
1319
1320--- @param lines string[]
1321--- @param on_finish fun(bufnr: integer)
1322local function show_confirm_buf(lines, on_finish)
1323  -- Show buffer in a separate tabpage
1324  local bufnr = api.nvim_create_buf(true, true)
1325  api.nvim_buf_set_name(bufnr, 'nvim-pack://confirm#' .. bufnr)
1326  api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)
1327  vim.cmd.sbuffer({ bufnr, mods = { tab = vim.fn.tabpagenr() } })
1328  local win_id = api.nvim_get_current_win()
1329
1330  local delete_buffer = vim.schedule_wrap(function()
1331    pcall(api.nvim_win_close, win_id, true)
1332    pcall(api.nvim_buf_delete, bufnr, { force = true })
1333    vim.cmd.redraw()
1334  end)
1335
1336  -- Define action on accepting confirm
1337  local function finish()
1338    on_finish(bufnr)
1339    delete_buffer()
1340  end
1341  -- - Use `nested` to allow other events (useful for statuslines)
1342  nvim_on('BufWriteCmd', nil, { buf = bufnr, nested = true }, finish)
1343
1344  -- Define action to cancel confirm
1345  --- @type integer
1346  local cancel_au_id
1347  --- @param data vim.api.keyset.create_autocmd.callback_args
1348  local function on_cancel(data)
1349    if vim._tointeger(data.match) ~= win_id then
1350      return
1351    end
1352    pcall(api.nvim_del_autocmd, cancel_au_id)
1353    delete_buffer()
1354  end
1355  cancel_au_id = nvim_on('WinClosed', nil, { nested = true }, on_cancel)
1356
1357  -- Set buffer-local options last (so that user autocmmands could override)
1358  vim.bo[bufnr].modified = false
1359  vim.bo[bufnr].modifiable = false
1360  vim.bo[bufnr].buftype = 'acwrite'
1361  vim.bo[bufnr].filetype = 'nvim-pack'
1362
1363  -- Attach in-process LSP for more capabilities
1364  vim.lsp.buf_attach_client(bufnr, require('vim.pack._lsp').client_id)
1365end
1366
1367--- Get map of plugin names that need update based on confirmation buffer
1368--- content: all plugin sections present in "# Update" section.
1369--- @param bufnr integer
1370--- @return table<string,boolean>
1371local function get_update_map(bufnr)
1372  local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false)
1373  --- @type table<string,boolean>, boolean
1374  local res, is_in_update = {}, false
1375  for _, l in ipairs(lines) do
1376    local name = l:match('^## (.+)$')
1377    if name and is_in_update then
1378      res[name:gsub(' %(not active%)$', '')] = true
1379    end
1380
1381    local group = l:match('^# (%S+)')
1382    if group then
1383      is_in_update = group == 'Update'
1384    end
1385  end
1386  return res
1387end
1388
1389--- Checkout plugins to the update target
1390--- @param plug_list vim.pack.Plug[]
1391local function update_list(plug_list)
1392  trigger_events(plug_list, 'PackChangedPre', 'update')
1393
1394  local timestamp = get_timestamp()
1395  --- @async
1396  --- @param p vim.pack.Plug
1397  local function do_update(p)
1398    checkout(p, timestamp)
1399    p.info.updated = true
1400  end
1401  run_list(plug_list, do_update, 'Applying updates')
1402
1403  local updated = vim.tbl_filter(function(p)
1404    return p.info.updated == true
1405  end, plug_list)
1406  trigger_events(updated, 'PackChanged', 'update')
1407end
1408
1409--- @class vim.pack.keyset.update
1410--- @inlinedoc
1411--- @field package _ex? boolean
1412--- @field force? boolean Whether to skip confirmation and make updates immediately. Default `false`.
1413---
1414--- @field offline? boolean Whether to skip downloading new updates. Default: `false`.
1415---
1416--- How to compute a new plugin revision. One of:
1417---   - "version" (default): use latest revision matching `version` from plugin specification.
1418---   - "lockfile": use revision from the lockfile. For reverting or performing controlled update.
1419--- @field target? string
1420
1421--- Update plugins
1422---
1423--- - Download new changes from source.
1424--- - Infer update info (current/target revisions, changelog, etc.).
1425--- - If `force` is `false` (default), show confirmation buffer.
1426---   If `force` is `true`, make updates right away.
1427---
1428--- Notes:
1429--- - Every actual update is logged in "nvim-pack.log" file inside "log" |standard-path|.
1430--- - It doesn't update source's default branch if it has changed (like from `master` to `main`).
1431---   To have `version = nil` point to a new default branch, re-install the plugin
1432---   (|vim.pack.del()| + |vim.pack.add()|).
1433---
1434--- Confirmation buffer ~
1435---
1436--- The goal of the confirmation buffer is to show update details for the user to read, confirm
1437--- (execute |:write|) or deny (execute |:quit|) the update.
1438---
1439--- Pending changes starting with `>` will be applied while the ones starting with `<` will be
1440--- reverted.
1441---
1442--- There are convenience buffer-local mappings:
1443--- - |]]| and |[[| to navigate through plugin sections.
1444---
1445--- Some features are provided via LSP:
1446--- - 'textDocument/documentLink' - compute links for plugin paths, sources,
1447---   commits, and tags. Makes a best effort educated guess about a link structure.
1448---   Use |gx| to open a link to an object at cursor.
1449--- - 'textDocument/documentSymbol' (`gO` via |lsp-defaults| or |vim.lsp.buf.document_symbol()|) -
1450---   show structure of the buffer.
1451--- - 'textDocument/hover' (`K` via |lsp-defaults| or |vim.lsp.buf.hover()|) - show more
1452---   information at cursor. Like details of particular pending change or newer tag.
1453--- - 'textDocument/codeAction' (`gra` via |lsp-defaults| or |vim.lsp.buf.code_action()|) - show
1454---   code actions relevant for "plugin at cursor". Like "delete" (after extra confirmation for
1455---   active plugins), "update" or "skip updating" (if there are pending updates).
1456---
1457--- @param names? string[] List of plugin names to update. Must be managed
1458--- by |vim.pack|, not necessarily already added to current session.
1459--- Default: names of all plugins managed by |vim.pack|.
1460--- @param opts? vim.pack.keyset.update
1461function M.update(names, opts)
1462  vim.validate('names', names, vim.islist, true, 'list')
1463  opts = vim.tbl_extend('force', { force = false, offline = false, target = 'version' }, opts or {})
1464
1465  local plug_list = plug_list_from_names(names)
1466  if #plug_list == 0 then
1467    if opts._ex then
1468      util.echo_err(N_('E5808: Nothing to update'))
1469    end
1470    return
1471  end
1472  git_ensure_exec()
1473  lock_read()
1474
1475  -- Infer update details
1476  local needs_lock_write = opts.force or false
1477
1478  --- @async
1479  --- @param p vim.pack.Plug
1480  local function infer_details(p)
1481    local l_data = plugin_lock.plugins[p.spec.name]
1482    -- Ensure proper `origin` if needed
1483    if l_data.src ~= p.spec.src then
1484      git_cmd({ 'remote', 'set-url', 'origin', p.spec.src }, p.path)
1485      plugin_lock.plugins[p.spec.name].src = p.spec.src
1486      needs_lock_write = true
1487    end
1488
1489    -- Fetch
1490    if not opts.offline then
1491      git_fetch(p.path)
1492    end
1493
1494    -- Compute change info: changelog if any, new tags if nothing to update
1495    if opts.target == 'lockfile' then
1496      p.info.version_str = '*lockfile*'
1497      p.info.sha_target = l_data.rev
1498    end
1499    infer_update_details(p)
1500  end
1501  local infer_title = opts.offline and 'Computing updates' or 'Downloading updates'
1502  run_list(plug_list, infer_details, infer_title)
1503
1504  -- Update and show report
1505  if opts.force then
1506    local plugs_to_update = vim.tbl_filter(function(p)
1507      return p.info.sha_head ~= p.info.sha_target
1508    end, plug_list)
1509    update_list(plugs_to_update)
1510  end
1511
1512  if needs_lock_write then
1513    lock_write()
1514  end
1515
1516  if opts.force then
1517    feedback_log(plug_list)
1518    return
1519  end
1520
1521  -- Show report in new buffer in separate tabpage
1522  local lines = compute_feedback_lines(plug_list, false)
1523  show_confirm_buf(lines, function(bufnr)
1524    local to_update = get_update_map(bufnr)
1525    if not next(to_update) then
1526      notify('Nothing to update', 'WARN')
1527      return
1528    end
1529
1530    --- @param p vim.pack.Plug
1531    local plugs_to_update = vim.tbl_filter(function(p)
1532      return to_update[p.spec.name]
1533    end, plug_list)
1534    update_list(plugs_to_update)
1535
1536    lock_write()
1537    feedback_log(plugs_to_update)
1538  end)
1539end
1540
1541--- @class vim.pack.keyset.del
1542--- @inlinedoc
1543--- @field package _ex? boolean
1544--- @field force? boolean Whether to allow deleting an active plugin. Default `false`.
1545
1546--- Remove plugins from disk
1547---
1548--- @param names string[] List of plugin names to remove from disk. Must be managed
1549--- by |vim.pack|, not necessarily already added to current session.
1550--- @param opts? vim.pack.keyset.del
1551function M.del(names, opts)
1552  vim.validate('names', names, vim.islist, false, 'list')
1553  opts = vim.tbl_extend('force', { force = false }, opts or {})
1554
1555  local plug_list = plug_list_from_names(names)
1556  if #plug_list == 0 then
1557    if opts._ex then
1558      util.echo_err(N_('E5809: Nothing to remove'))
1559    end
1560    return
1561  end
1562
1563  lock_read()
1564
1565  trigger_events(plug_list, 'PackChangedPre', 'delete')
1566
1567  local deleted = {} --- @type vim.pack.Plug[]
1568  local deleted_names = {} --- @type string[]
1569  local not_deleted_names = {} --- @type string[]
1570  for _, p in ipairs(plug_list) do
1571    if not active_plugins[p.path] or opts.force then
1572      vim.fs.rm(p.path, { recursive = true, force = true })
1573      active_plugins[p.path] = nil
1574      plugin_lock.plugins[p.spec.name] = nil
1575
1576      deleted[#deleted + 1] = p
1577      deleted_names[#deleted_names + 1] = p.spec.name
1578    else
1579      not_deleted_names[#not_deleted_names + 1] = p.spec.name
1580    end
1581  end
1582  trigger_events(deleted, 'PackChanged', 'delete')
1583
1584  lock_write()
1585
1586  if #deleted_names > 0 then
1587    local suffix = #deleted_names == 1 and '' or 's'
1588    local plugs = table.concat(deleted_names, ', ')
1589    notify(('Removed plugin%s: %s'):format(suffix, plugs), 'INFO')
1590  end
1591
1592  if #not_deleted_names > 0 then
1593    local plugs = table.concat(not_deleted_names, ', ')
1594    if opts._ex then
1595      util.echo_err(N_('E5810: Some plugins are active and were not deleted: %s'):format(plugs))
1596      return
1597    else
1598      local msg = ('Some plugins are active and were not deleted: %s.'):format(plugs)
1599        .. ' Remove them from init.lua, restart, and try again.'
1600      error(msg)
1601    end
1602  end
1603end
1604
1605--- @inlinedoc
1606--- @class vim.pack.PlugData
1607--- @field active boolean Whether plugin was added via |vim.pack.add()| to current session.
1608--- @field branches? string[] Available Git branches (first is default). Missing if `info=false`.
1609--- Data from the |vim.pack-manifest|. Empty in case of reading error. Missing if `info=false`.
1610--- @field manifest? vim.pack.Manifest
1611--- @field path string Plugin's path on disk.
1612--- @field rev string Current Git revision. Taken from |vim.pack-lockfile| if `info=false`.
1613--- Git revision of a pending update. The same as used during |vim.pack.update()| and which
1614--- points to a resolved `spec.version`. Missing if `info=false`.
1615--- @field rev_to? string
1616--- @field spec vim.pack.SpecResolved A |vim.pack.Spec| with resolved `name`.
1617--- @field tags? string[] Available Git tags. Missing if `info=false`.
1618
1619--- @class vim.pack.keyset.get
1620--- @inlinedoc
1621--- @field info? boolean Whether to include extra plugin info. Default `true`.
1622--- Whether to skip downloading new updates. Requires `info=true`. Default: `true`.
1623--- @field offline? boolean
1624
1625--- @param p_data_list vim.pack.PlugData[]
1626--- @param offline? boolean
1627local function add_p_data_info(p_data_list, offline)
1628  local funs = {} --- @type (async fun())[]
1629  local plug_dir = get_plug_dir()
1630  for i, p_data in ipairs(p_data_list) do
1631    local plug = new_plug(p_data.spec, plug_dir)
1632    local path = p_data.path
1633    --- @async
1634    funs[i] = function()
1635      p_data.branches = git_get_branches(path)
1636      p_data.tags = git_get_tags(path)
1637      p_data.manifest = manifest_read(path)
1638
1639      if not offline then
1640        git_fetch(path)
1641      end
1642
1643      infer_revisions(plug)
1644      p_data.rev = plug.info.sha_head
1645      p_data.rev_to = plug.info.sha_target
1646    end
1647  end
1648  async_join_run_wait(funs)
1649end
1650
1651--- Gets |vim.pack| plugin info, optionally filtered by `names`.
1652--- @param names? string[] List of plugin names. Default: all plugins managed by |vim.pack|.
1653--- @param opts? vim.pack.keyset.get
1654--- @return vim.pack.PlugData[]
1655function M.get(names, opts)
1656  vim.validate('names', names, vim.islist, true, 'list')
1657  opts = vim.tbl_extend('force', { info = true, offline = true }, opts or {})
1658
1659  -- Process active plugins in order they were added. Take into account that
1660  -- there might be "holes" after `vim.pack.del()`.
1661  local active = {} --- @type table<integer,vim.pack.Plug?>
1662  for _, p_active in pairs(active_plugins) do
1663    active[p_active.id] = p_active.plug
1664  end
1665
1666  lock_read()
1667  local res = {} --- @type vim.pack.PlugData[]
1668  local used_names = {} --- @type table<string,boolean>
1669  for i = 1, n_active_plugins do
1670    if active[i] and (not names or vim.tbl_contains(names, active[i].spec.name)) then
1671      local name = active[i].spec.name
1672      local spec = vim.deepcopy(active[i].spec)
1673      local rev = (plugin_lock.plugins[name] or {}).rev
1674      res[#res + 1] = { spec = spec, path = active[i].path, rev = rev, active = true }
1675      used_names[name] = true
1676    end
1677  end
1678
1679  local plug_dir = get_plug_dir()
1680  for name, l_data in vim.spairs(plugin_lock.plugins) do
1681    local path = vim.fs.joinpath(plug_dir, name)
1682    local is_in_names = not names or vim.tbl_contains(names, name)
1683    if not active_plugins[path] and is_in_names then
1684      local spec = { name = name, src = l_data.src, version = l_data.version }
1685      res[#res + 1] = { spec = spec, path = path, rev = l_data.rev, active = false }
1686      used_names[name] = true
1687    end
1688  end
1689
1690  if names ~= nil then
1691    -- Align result with input
1692    local names_order = {} --- @type table<string,integer>
1693    for i, n in ipairs(names) do
1694      if not used_names[n] then
1695        error(('Plugin `%s` is not installed'):format(tostring(n)))
1696      end
1697      names_order[n] = i
1698    end
1699    table.sort(res, function(a, b)
1700      return names_order[a.spec.name] < names_order[b.spec.name]
1701    end)
1702  end
1703
1704  if opts.info then
1705    git_ensure_exec()
1706    add_p_data_info(res, opts.offline)
1707  end
1708
1709  return res
1710end
1711
1712--- @param skip_inactive? boolean
1713--- @return string[] plugin_names
1714function M._get_names(skip_inactive)
1715  local names = {} --- @type string[]
1716  for _, plugin_data in ipairs(vim.pack.get(nil, { info = false })) do
1717    if not (skip_inactive and plugin_data.active) then
1718      names[#names + 1] = plugin_data.spec.name
1719    end
1720  end
1721  return names
1722end
1723
1724return M