robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
103.2 KiB2709 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4local describe, it, before_each, after_each, setup, teardown =
5  t.describe, t.it, t.before_each, t.after_each, t.setup, t.teardown
6local skip_integ = os.getenv('NVIM_TEST_INTEG') ~= '1'
7
8local api = n.api
9local fn = n.fn
10
11local eq = t.eq
12local matches = t.matches
13local pcall_err = t.pcall_err
14local exec_lua = n.exec_lua
15
16-- Helpers ====================================================================
17-- Installed plugins ----------------------------------------------------------
18
19local function pack_get_dir()
20  return vim.fs.joinpath(fn.stdpath('data'), 'site', 'pack', 'core', 'opt')
21end
22
23local function pack_get_plug_path(plug_name)
24  return vim.fs.joinpath(pack_get_dir(), plug_name)
25end
26
27local function pack_exists(plug_name)
28  local path = vim.fs.joinpath(pack_get_dir(), plug_name)
29  return vim.uv.fs_stat(path) ~= nil
30end
31
32--- Assert content from the main Lua file inside installed plugin.
33--- Used as a proxy for checking plugin state on disk.
34local function pack_assert_content(plug_name, content)
35  local full_path = vim.fs.joinpath(pack_get_plug_path(plug_name), 'lua', plug_name .. '.lua')
36  eq(content, fn.readblob(full_path))
37end
38
39-- Test repos (to be installed) -----------------------------------------------
40
41local repos_dir = vim.fs.abspath('test/functional/lua/pack-test-repos')
42
43--- Map from repo name to its proper `src` used in plugin spec
44--- @type table<string,string>
45local repos_src = {}
46
47local function repo_get_path(repo_name)
48  vim.validate('repo_name', repo_name, 'string')
49  return vim.fs.joinpath(repos_dir, repo_name)
50end
51
52local function repo_write_file(repo_name, rel_path, text, no_dedent, append)
53  local path = vim.fs.joinpath(repo_get_path(repo_name), rel_path)
54  fn.mkdir(vim.fs.dirname(path), 'p')
55  t.write_file(path, text, no_dedent, append)
56end
57
58local function git_cmd(cmd, repo_name)
59  local git_cmd_prefix = {
60    'git',
61    '-c',
62    'gc.auto=0',
63    '-c',
64    'user.name=Marvim',
65    '-c',
66    'user.email=marvim@neovim.io',
67    '-c',
68    'init.defaultBranch=main',
69  }
70
71  cmd = vim.list_extend(git_cmd_prefix, cmd)
72  local cwd = repo_get_path(repo_name)
73  local sys_opts = { cwd = cwd, text = true, clear_env = true }
74  local out = n.system_sync(cmd, sys_opts)
75  if out.code ~= 0 then
76    error(out.stderr)
77  end
78  return (out.stdout:gsub('\n+$', ''))
79end
80
81local function init_test_repo(repo_name)
82  local path = repo_get_path(repo_name)
83  fn.mkdir(path, 'p')
84  repos_src[repo_name] = 'file://' .. path
85
86  git_cmd({ 'init' }, repo_name)
87  if t.is_arch('s390x') then
88    -- Ensure default branch is 'main' even if git is too old for `init.defaultBranch`.
89    git_cmd({ 'symbolic-ref', 'HEAD', 'refs/heads/main' }, repo_name)
90  end
91end
92
93local function git_add_commit(msg, repo_name)
94  git_cmd({ 'add', '*' }, repo_name)
95  git_cmd({ 'commit', '-m', msg }, repo_name)
96end
97
98local function git_get_hash(rev, repo_name)
99  return git_cmd({ 'rev-list', '-1', rev }, repo_name)
100end
101
102local function git_get_short_hash(rev, repo_name)
103  -- Pin `--abbrev`. Git's default abbrev differs across environments, which would shift the
104  -- hard-coded column alignment and LSP link positions in the confirmation-buffer tests.
105  return git_cmd({ 'rev-list', '-1', '--abbrev=7', '--abbrev-commit', rev }, repo_name)
106end
107
108-- Common test repos ----------------------------------------------------------
109--- @type table<string,function>
110local repos_setup = {}
111
112function repos_setup.basic()
113  init_test_repo('basic')
114
115  repo_write_file('basic', 'lua/basic.lua', 'return "basic init"')
116  git_add_commit('Initial commit for "basic"', 'basic')
117  repo_write_file('basic', 'lua/basic.lua', 'return "basic main"')
118  git_add_commit('Commit in `main` but not in `feat-branch`', 'basic')
119
120  git_cmd({ 'checkout', 'main~' }, 'basic')
121  git_cmd({ 'checkout', '-b', 'feat-branch' }, 'basic')
122
123  repo_write_file('basic', 'lua/basic.lua', 'return "basic some-tag"')
124  git_add_commit('Add commit for some tag', 'basic')
125  git_cmd({ 'tag', 'some-tag' }, 'basic')
126
127  repo_write_file('basic', 'lua/basic.lua', 'return "basic feat-branch"')
128  git_add_commit('Add important feature', 'basic')
129
130  -- Make sure that `main` is the default remote branch
131  git_cmd({ 'checkout', 'main' }, 'basic')
132end
133
134function repos_setup.plugindirs()
135  init_test_repo('plugindirs')
136
137  -- Add semver tag
138  repo_write_file('plugindirs', 'lua/plugindirs.lua', 'return "plugindirs v0.0.1"')
139  git_add_commit('Add version v0.0.1', 'plugindirs')
140  git_cmd({ 'tag', 'v0.0.1' }, 'plugindirs')
141
142  -- Add various 'plugin/' files
143  repo_write_file('plugindirs', 'lua/plugindirs.lua', 'return "plugindirs main"')
144  repo_write_file('plugindirs', 'plugin/dirs.lua', 'vim.g._plugin = true')
145  repo_write_file('plugindirs', 'plugin/dirs_log.lua', '_G.DL = _G.DL or {}; DL[#DL+1] = "p"')
146  repo_write_file('plugindirs', 'plugin/dirs.vim', 'let g:_plugin_vim=v:true')
147  repo_write_file('plugindirs', 'plugin/sub/dirs.lua', 'vim.g._plugin_sub = true')
148  repo_write_file('plugindirs', 'plugin/bad % name.lua', 'vim.g._plugin_bad = true')
149  repo_write_file('plugindirs', 'after/plugin/dirs.lua', 'vim.g._after_plugin = true')
150  repo_write_file('plugindirs', 'after/plugin/dirs_log.lua', '_G.DL = _G.DL or {}; DL[#DL+1] = "a"')
151  repo_write_file('plugindirs', 'after/plugin/dirs.vim', 'let g:_after_plugin_vim=v:true')
152  repo_write_file('plugindirs', 'after/plugin/sub/dirs.lua', 'vim.g._after_plugin_sub = true')
153  repo_write_file('plugindirs', 'after/plugin/bad % name.lua', 'vim.g._after_plugin_bad = true')
154  git_add_commit('Initial commit for "plugindirs"', 'plugindirs')
155end
156
157function repos_setup.helptags()
158  init_test_repo('helptags')
159  repo_write_file('helptags', 'lua/helptags.lua', 'return "helptags main"')
160  repo_write_file('helptags', 'doc/my-test-help.txt', '*my-test-help*')
161  repo_write_file('helptags', 'doc/bad % name.txt', '*my-test-help-bad*')
162  repo_write_file('helptags', 'doc/bad % dir/file.txt', '*my-test-help-sub-bad*')
163  git_add_commit('Initial commit for "helptags"', 'helptags')
164end
165
166function repos_setup.pluginerr()
167  init_test_repo('pluginerr')
168
169  repo_write_file('pluginerr', 'lua/pluginerr.lua', 'return "pluginerr main"')
170  repo_write_file('pluginerr', 'plugin/err.lua', 'error("Wow, an error")')
171  git_add_commit('Initial commit for "pluginerr"', 'pluginerr')
172end
173
174function repos_setup.defbranch()
175  init_test_repo('defbranch')
176
177  repo_write_file('defbranch', 'lua/defbranch.lua', 'return "defbranch main"')
178  git_add_commit('Initial commit for "defbranch"', 'defbranch')
179
180  -- Make `dev` the default remote branch
181  git_cmd({ 'checkout', '-b', 'dev' }, 'defbranch')
182
183  repo_write_file('defbranch', 'lua/defbranch.lua', 'return "defbranch dev"')
184  git_add_commit('Add to new default branch', 'defbranch')
185end
186
187function repos_setup.gitsuffix()
188  init_test_repo('gitsuffix.git')
189
190  repo_write_file('gitsuffix.git', 'lua/gitsuffix.lua', 'return "gitsuffix main"')
191  git_add_commit('Initial commit for "gitsuffix"', 'gitsuffix.git')
192end
193
194function repos_setup.semver()
195  init_test_repo('semver')
196
197  local function add_tag(name)
198    repo_write_file('semver', 'lua/semver.lua', 'return "semver ' .. name .. '"')
199    git_add_commit('Add version ' .. name, 'semver')
200    git_cmd({ 'tag', name }, 'semver')
201  end
202
203  add_tag('v0.0.1')
204  add_tag('v0.0.2')
205  add_tag('v0.1.0')
206  add_tag('v0.1.1')
207  add_tag('v0.2.0-dev')
208  add_tag('v0.2.0')
209  add_tag('v0.3.0')
210  repo_write_file('semver', 'lua/semver.lua', 'return "semver middle-commit')
211  git_add_commit('Add middle commit', 'semver')
212  add_tag('0.3.1') -- Semver even without `v` prefix
213  add_tag('v0.4') -- Not semver since it requires all three version numbers
214  add_tag('non-semver')
215  add_tag('v0.2.1') -- Intentionally add version not in order
216  add_tag('v1.0.0')
217end
218
219function repos_setup.with_subs()
220  -- To-be-submodule repo
221  init_test_repo('sub')
222
223  repo_write_file('sub', 'sub.lua', 'return "sub init"')
224  git_add_commit('Initial commit for "sub"', 'sub')
225
226  -- With-submodules repo with submodule recorded at its initial commit
227  init_test_repo('with_subs')
228
229  repo_write_file('with_subs', 'lua/with_subs.lua', 'return "with_subs init"')
230  local sub_src = 'file://' .. repo_get_path('sub')
231  git_cmd({ '-c', 'protocol.file.allow=always', 'submodule', 'add', sub_src, 'sub' }, 'with_subs')
232  git_add_commit('Initial commit for "with_subs"', 'with_subs')
233  git_cmd({ 'tag', 'init-commit' }, 'with_subs')
234
235  -- Advance both submodule and with-submodules repos by one commit
236  repo_write_file('sub', 'sub.lua', 'return "sub main"')
237  git_add_commit('Second commit for "sub"', 'sub')
238
239  repo_write_file('with_subs', 'lua/with_subs.lua', 'return "with_subs main"')
240  git_cmd(
241    { '-c', 'protocol.file.allow=always', 'submodule', 'update', '--remote', 'sub' },
242    'with_subs'
243  )
244  git_add_commit('Second commit for "with_subs"', 'with_subs')
245end
246
247function repos_setup.with_manifest()
248  init_test_repo('manifest')
249
250  repo_write_file('manifest', 'lua/manifest.lua', 'return "manifest init"')
251
252  local manifest_tbl = {
253    name = 'plug',
254    description = 'Nvim plugin',
255    engine = { nvim = '>=0.12.0', vim = '>=9.1.0' },
256    -- Should handle both `*.lua` and `*.vim` files
257    scripts = {
258      install = 'scripts/install.lua',
259      preupdate = 'scripts/preupdate.vim',
260      update = 'scripts/update.lua',
261      preuninstall = 'scirpts/preuninstall.vim',
262    },
263  }
264  repo_write_file('manifest', 'pkg.json', vim.json.encode(manifest_tbl))
265
266  -- Create scripts that use Lua module from the same plugin
267  local hook_module_text = [[
268    return {
269      hook = function(script_name)
270        -- NOTE: share the log with the one used for watching events to test
271        -- relative order of events and script
272        _G.event_log = _G.event_log or {}
273        local rtp = vim.api.nvim_list_runtime_paths()
274        local data = { kind = script_name, cwd = vim.fs.normalize(vim.uv.cwd()), rtp = rtp }
275        table.insert(_G.event_log, { event = 'script', data = data })
276
277        -- Should handle errors during script exectuion
278        error('Error in ' .. script_name .. ' script')
279      end
280    }
281  ]]
282  repo_write_file('manifest', 'lua/manifest-hook.lua', hook_module_text)
283
284  for name, script_path in pairs(manifest_tbl.scripts) do
285    local text = ("require('manifest-hook').hook('%s')"):format(name)
286    if vim.endswith(script_path, '.vim') then
287      text = 'lua << EOF\n' .. text .. '\nEOF'
288    end
289    repo_write_file('manifest', script_path, text)
290  end
291
292  git_add_commit('Initial commit', 'manifest')
293
294  -- Add extra branch to test script execution in `vim.pack.update()`
295  git_cmd({ 'checkout', '-b', 'other-branch' }, 'manifest')
296  repo_write_file('manifest', 'lua/manifest.lua', 'return "manifest other-branch"')
297  local other_script = "_G.other_script = true\nrequire('manifest-hook').hook('update')"
298  repo_write_file('manifest', 'scripts/update.lua', other_script)
299  git_add_commit('Other commit', 'manifest')
300
301  git_cmd({ 'checkout', 'main' }, 'manifest')
302end
303
304-- Utility --------------------------------------------------------------------
305
306--- Execute `vim.pack.add()` inside `testnvim` instance
307local function vim_pack_add(specs, opts)
308  exec_lua(function()
309    vim.pack.add(specs, opts)
310  end)
311end
312
313local function watch_events(event)
314  exec_lua(function()
315    _G.event_log = _G.event_log or {} --- @type table[]
316    vim.api.nvim_create_autocmd(event, {
317      callback = function(ev)
318        table.insert(_G.event_log, { event = ev.event, match = ev.match, data = ev.data })
319      end,
320    })
321  end)
322end
323
324--- Input is array of  { suffix, kind, name, version, active, user_data }
325--- @param log_compact ([string,string,string,string,boolean,any])[]
326local function assert_packchanged(log_compact)
327  local log = exec_lua('return _G.event_log')
328  local expected = {} --- @type table[]
329  for i, l in ipairs(log_compact) do
330    local path = pack_get_plug_path(l[3])
331    local spec = { name = l[3], src = repos_src[l[3]], version = l[4], data = l[6] }
332    local data = { active = l[5], kind = l[2], path = path, spec = spec }
333    expected[i] = { event = 'PackChanged' .. l[1], match = vim.fs.abspath(path), data = data }
334  end
335  eq(expected, log)
336end
337
338local function assert_manifest_scripts(plug_path, ref_log_trimmed)
339  -- Should be sourced in particular order relative to `PackChanged` events
340  local log_trimmed = {} --- @type table[]
341  for i, tbl in ipairs(exec_lua('return _G.event_log')) do
342    local rtp_has_plug = tbl.data.rtp and vim.tbl_contains(tbl.data.rtp, plug_path) or nil
343    local kind, cwd = tbl.data.kind, tbl.data.cwd
344    log_trimmed[i] = { event = tbl.event, kind = kind, cwd = cwd, rtp_has_plug = rtp_has_plug }
345  end
346  eq(ref_log_trimmed, log_trimmed)
347end
348
349local function track_nvim_echo()
350  exec_lua(function()
351    _G.echo_log = {}
352    local nvim_echo_orig = vim.api.nvim_echo
353    ---@diagnostic disable-next-line: duplicate-set-field
354    vim.api.nvim_echo = function(...)
355      table.insert(_G.echo_log, vim.deepcopy({ ... }))
356      return nvim_echo_orig(...)
357    end
358  end)
359end
360
361local function is_in_echo_log(chunk_substring, chunk_hl)
362  ---@diagnostic disable-next-line: no-unknown
363  for _, msg in ipairs(exec_lua('return _G.echo_log')) do
364    local chunk = msg[1][1] --- @type [string, string]
365    if chunk[1]:find(chunk_substring, 0, true) and chunk[2] == chunk_hl then
366      return true
367    end
368  end
369  return false
370end
371
372--- @param echo_log table[]?
373local function assert_progress_report(echo_log, action, step_names)
374  echo_log = echo_log or exec_lua('return _G.echo_log')
375  local n_steps = #step_names
376  eq(n_steps + 2, #echo_log)
377
378  local progress =
379    { kind = 'progress', source = 'vim.pack', title = 'vim.pack', status = 'running', percent = 0 }
380  local init_step = { { { ('%s (0/%d)'):format(action, n_steps) } }, true, progress }
381  eq(init_step, echo_log[1])
382
383  local steps_seen = {} --- @type table<string,boolean>
384  for i = 1, n_steps do
385    local echo_args = echo_log[i + 1]
386
387    -- NOTE: There is no guaranteed order (as it is async), so check that some
388    -- expected step name is used in the message
389    local msg = ('%s (%d/%d)'):format(action, i, n_steps)
390    local pattern = '^' .. vim.pesc(msg) .. ' %- (%S+)$'
391    local step = echo_args[1][1][1]:match(pattern) ---@type string
392    eq(true, vim.tbl_contains(step_names, step))
393    steps_seen[step] = true
394
395    -- Should not add intermediate progress report to history
396    eq(false, echo_args[2])
397
398    -- Should update a single message by its id (computed after first call)
399    progress.id = progress.id or echo_args[3].id ---@type integer
400    progress.percent = math.floor(100 * i / n_steps)
401    eq(progress, echo_args[3])
402  end
403
404  -- Should report all steps
405  eq(n_steps, vim.tbl_count(steps_seen))
406
407  progress.percent, progress.status = 100, 'success'
408  local final_step = { { { ('%s (%d/%d)'):format(action, n_steps, n_steps) } }, true, progress }
409  eq(final_step, echo_log[n_steps + 2])
410end
411
412local function mock_confirm(output_value)
413  exec_lua(function()
414    _G.confirm_log = _G.confirm_log or {}
415
416    ---@diagnostic disable-next-line: duplicate-set-field
417    vim.fn.confirm = function(...)
418      table.insert(_G.confirm_log, { ... })
419      return output_value
420    end
421  end)
422end
423
424local function mock_git_file_transport()
425  -- HACK: mock `vim.system()` to have `git` commands be executed
426  -- with temporarily set 'protocol.file.allow=always' option.
427  -- Otherwise performing `git` operations with submodules from `vim.pack`
428  -- itself will fail with `fatal: transport 'file' not allowed`.
429  -- Directly adding `-c protocol.file.allow=always` to `git_cmd` in `vim.pack`
430  -- itself is too much and might be bad for security.
431  exec_lua(function()
432    local vim_system_orig = vim.system
433    vim.system = function(cmd, opts, on_exit)
434      if cmd[1] == 'git' then
435        table.insert(cmd, 2, '-c')
436        table.insert(cmd, 3, 'protocol.file.allow=always')
437      end
438      return vim_system_orig(cmd, opts, on_exit)
439    end
440  end)
441end
442
443local function is_jit()
444  return exec_lua('return package.loaded.jit ~= nil')
445end
446
447local function get_lock_path()
448  return vim.fs.joinpath(fn.stdpath('config'), 'nvim-pack-lock.json')
449end
450
451local function get_other_lock_path()
452  return vim.fs.joinpath(fn.stdpath('state'), 'test-pack-lock')
453end
454
455--- @return {plugins:table<string, {rev:string, src:string, version?:string}>}
456local function get_lock_tbl()
457  return vim.json.decode(fn.readblob(get_lock_path()))
458end
459
460-- Tests ======================================================================
461
462describe('vim.pack', function()
463  setup(function()
464    n.clear()
465    for _, r_setup in pairs(repos_setup) do
466      r_setup()
467    end
468  end)
469
470  before_each(function()
471    n.clear()
472  end)
473
474  after_each(function()
475    local pack_dir = pack_get_dir()
476    local lock_path = get_lock_path()
477    local other_lock_path = get_other_lock_path()
478    local log_path = vim.fs.joinpath(fn.stdpath('log'), 'nvim-pack.log')
479
480    -- Wait for neovim to close before removing directories so it can release
481    -- the file handles it has open. We don't want to conflict with open files
482    -- when we remove dirs below.
483    n.check_close()
484
485    n.rmdir(pack_dir)
486    pcall(vim.fs.rm, lock_path, { force = true })
487    pcall(vim.fs.rm, other_lock_path, { force = true })
488    pcall(vim.fs.rm, log_path, { force = true })
489  end)
490
491  teardown(function()
492    n.rmdir(repos_dir)
493  end)
494
495  describe('add()', function()
496    it('installs only once', function()
497      vim_pack_add({ repos_src.basic })
498      n.clear()
499
500      watch_events({ 'PackChanged' })
501      vim_pack_add({ repos_src.basic })
502      eq(0, exec_lua('return #_G.event_log'))
503
504      -- Should not create redundant stash entry
505      local basic_path = pack_get_plug_path('basic')
506      local stash_list = n.system_sync({ 'git', 'stash', 'list' }, { cwd = basic_path }).stdout
507        or ''
508      eq('', stash_list)
509    end)
510
511    it('passes `data` field through to `opts.load`', function()
512      local out = exec_lua(function()
513        local map = {} ---@type table<string,boolean>
514        local function load(p)
515          local name = p.spec.name ---@type string
516          map[name] = name == 'basic' and (p.spec.data.test == 'value') or (p.spec.data == 'value')
517        end
518        vim.pack.add({
519          { src = repos_src.basic, data = { test = 'value' } },
520          { src = repos_src.defbranch, data = 'value' },
521        }, { load = load })
522        return map
523      end)
524      eq({ basic = true, defbranch = true }, out)
525    end)
526
527    it('asks for installation confirmation', function()
528      -- Do not confirm installation to see what happens (should not error)
529      mock_confirm(2)
530
531      vim_pack_add({ repos_src.basic, { src = repos_src.defbranch, name = 'other-name' } })
532      eq(false, pack_exists('basic'))
533      eq(false, pack_exists('defbranch'))
534      eq({ plugins = {} }, get_lock_tbl())
535
536      local confirm_msg_lines = ([[
537        These plugins will be installed:
538
539        basic      from %s
540        other-name from %s]]):format(repos_src.basic, repos_src.defbranch)
541      local confirm_msg = vim.trim(vim.text.indent(0, confirm_msg_lines))
542      local ref_log = { { confirm_msg .. '\n', 'Proceed? &Yes\n&No\n&Always', 1, 'Question' } }
543      eq(ref_log, exec_lua('return _G.confirm_log'))
544
545      -- Should remove lock data if not confirmed during lockfile sync
546      n.clear()
547      vim_pack_add({ repos_src.basic })
548      eq(true, pack_exists('basic'))
549      eq('table', type(get_lock_tbl().plugins.basic))
550
551      n.rmdir(pack_get_dir())
552      n.clear()
553      mock_confirm(2)
554
555      vim_pack_add({ repos_src.basic })
556      eq(false, pack_exists('basic'))
557      eq({ plugins = {} }, get_lock_tbl())
558
559      -- Should ask for confirm twice: during lockfile sync and inside
560      -- `vim.pack.add()` (i.e. not confirming during lockfile sync has
561      -- an immediate effect on whether a plugin is installed or not)
562      eq(2, exec_lua('return #_G.confirm_log'))
563    end)
564
565    it('respects `opts.confirm`', function()
566      mock_confirm(1)
567      vim_pack_add({ repos_src.basic }, { confirm = false })
568
569      eq(0, exec_lua('return #_G.confirm_log'))
570      eq(true, pack_exists('basic'))
571
572      -- Should also respect `confirm` when installing during lockfile sync
573      n.rmdir(pack_get_dir())
574      n.clear()
575      mock_confirm(1)
576      eq('table', type(get_lock_tbl().plugins.basic))
577
578      vim_pack_add({}, { confirm = false })
579      eq(0, exec_lua('return #_G.confirm_log'))
580      eq(true, pack_exists('basic'))
581    end)
582
583    it('can always confirm in current session', function()
584      mock_confirm(3)
585
586      vim_pack_add({ repos_src.basic })
587      eq(1, exec_lua('return #_G.confirm_log'))
588      eq('basic main', exec_lua('return require("basic")'))
589
590      vim_pack_add({ repos_src.defbranch })
591      eq(1, exec_lua('return #_G.confirm_log'))
592      eq('defbranch dev', exec_lua('return require("defbranch")'))
593
594      -- Should still ask in next session
595      n.clear()
596      mock_confirm(3)
597      vim_pack_add({ repos_src.plugindirs })
598      eq(1, exec_lua('return #_G.confirm_log'))
599      eq('plugindirs main', exec_lua('return require("plugindirs")'))
600    end)
601
602    it('creates lockfile', function()
603      local helptags_rev = git_get_hash('HEAD', 'helptags')
604      exec_lua(function()
605        vim.pack.add({
606          { src = repos_src.basic, version = 'some-tag' },
607          { src = repos_src.defbranch, version = 'main' },
608          { src = repos_src.helptags, version = helptags_rev },
609          { src = repos_src.plugindirs },
610          { src = repos_src.semver, version = vim.version.range('*') },
611        })
612      end)
613
614      local basic_rev = git_get_hash('some-tag', 'basic')
615      local defbranch_rev = git_get_hash('main', 'defbranch')
616      local plugindirs_rev = git_get_hash('HEAD', 'plugindirs')
617      local semver_rev = git_get_hash('v1.0.0', 'semver')
618
619      -- Should properly format as indented JSON. Notes:
620      -- - Branch, tag, and commit should be serialized like `'value'` to be
621      --   distinguishable from version ranges.
622      -- - Absent `version` should be missing and not autoresolved.
623      local ref_lockfile_lines = ([[
624        {
625          "plugins": {
626            "basic": {
627              "rev": "%s",
628              "src": "%s",
629              "version": "'some-tag'"
630            },
631            "defbranch": {
632              "rev": "%s",
633              "src": "%s",
634              "version": "'main'"
635            },
636            "helptags": {
637              "rev": "%s",
638              "src": "%s",
639              "version": "'%s'"
640            },
641            "plugindirs": {
642              "rev": "%s",
643              "src": "%s"
644            },
645            "semver": {
646              "rev": "%s",
647              "src": "%s",
648              "version": ">=0.0.0"
649            }
650          }
651        }
652        ]]):format(
653        basic_rev,
654        repos_src.basic,
655        defbranch_rev,
656        repos_src.defbranch,
657        helptags_rev,
658        repos_src.helptags,
659        helptags_rev,
660        plugindirs_rev,
661        repos_src.plugindirs,
662        semver_rev,
663        repos_src.semver
664      )
665      eq(vim.text.indent(0, ref_lockfile_lines), fn.readblob(get_lock_path()))
666    end)
667
668    it('updates lockfile', function()
669      vim_pack_add({ repos_src.basic })
670      local ref_lockfile = {
671        plugins = {
672          basic = { rev = git_get_hash('main', 'basic'), src = repos_src.basic },
673        },
674      }
675      eq(ref_lockfile, get_lock_tbl())
676
677      n.clear()
678      vim_pack_add({ { src = repos_src.basic, version = 'main' } })
679
680      ref_lockfile.plugins.basic.version = "'main'"
681      eq(ref_lockfile, get_lock_tbl())
682    end)
683
684    it('uses lockfile during install', function()
685      vim_pack_add({ { src = repos_src.basic, version = 'feat-branch' }, repos_src.defbranch })
686
687      -- Mock clean initial install, but with lockfile present
688      n.rmdir(pack_get_dir())
689      n.clear()
690      watch_events({ 'PackChangedPre', 'PackChanged' })
691
692      local basic_rev = git_get_hash('feat-branch', 'basic')
693      local defbranch_rev = git_get_hash('HEAD', 'defbranch')
694      local ref_lockfile = {
695        plugins = {
696          basic = { rev = basic_rev, src = repos_src.basic, version = "'feat-branch'" },
697          defbranch = { rev = defbranch_rev, src = repos_src.defbranch },
698        },
699      }
700      eq(ref_lockfile, get_lock_tbl())
701
702      mock_confirm(1)
703      -- Should use revision from lockfile (pointing at latest 'feat-branch'
704      -- commit) and not use latest `main` commit. Although should report
705      -- `version = 'main'` inside event data and write it to the lockfile as
706      -- to preserve user input as much as possible.
707      -- Should also preserve `data` field in event data.
708      vim_pack_add({ { src = repos_src.basic, version = 'main', data = { 'd' } } })
709      pack_assert_content('basic', 'return "basic feat-branch"')
710      ref_lockfile.plugins.basic.version = "'main'"
711      eq(ref_lockfile, get_lock_tbl())
712
713      local confirm_log = exec_lua('return _G.confirm_log')
714      eq(1, #confirm_log)
715      matches('basic.*defbranch', confirm_log[1][1])
716
717      -- Should install `defbranch` (as it is in lockfile), but not load it
718      eq(true, pack_exists('defbranch'))
719      eq(false, exec_lua('return pcall(require, "defbranch")'))
720
721      -- Should trigger `kind=install` events in a pre-defined order
722      assert_packchanged({
723        { 'Pre', 'install', 'basic', 'main', false, { 'd' } },
724        { 'Pre', 'install', 'defbranch', nil, false },
725        { '', 'install', 'basic', 'main', false, { 'd' } },
726        { '', 'install', 'defbranch', nil, false },
727      })
728
729      -- Running `update()` should still update to use `main`
730      exec_lua(function()
731        vim.pack.update({ 'basic' }, { force = true })
732      end)
733      pack_assert_content('basic', 'return "basic main"')
734
735      ref_lockfile.plugins.basic.rev = git_get_hash('main', 'basic')
736      ref_lockfile.plugins.basic.version = "'main'"
737      eq(ref_lockfile, get_lock_tbl())
738
739      -- Improper or string spec input should not interfere with initial install
740      n.rmdir(pack_get_dir())
741      n.clear()
742
743      mock_confirm(1)
744      pcall_err(vim_pack_add, { repos_src.basic, 1 })
745      eq(true, pack_exists('basic'))
746      eq(true, pack_exists('defbranch'))
747
748      -- Direct install from the lockfile should not write to it
749      n.rmdir(pack_get_dir())
750      n.clear()
751      local lockfile_fs_stat = vim.uv.fs_stat(get_lock_path())
752      vim_pack_add({})
753      eq(lockfile_fs_stat, vim.uv.fs_stat(get_lock_path()))
754    end)
755
756    it('handles lockfile during install errors', function()
757      local repo_not_exist = 'file://' .. repo_get_path('does-not-exist')
758      pcall_err(exec_lua, function()
759        vim.pack.add({
760          repo_not_exist,
761          { src = repos_src.basic, version = 'not-exist' },
762          { src = repos_src.pluginerr, version = 'main' },
763        })
764      end)
765
766      local pluginerr_hash = git_get_hash('main', 'pluginerr')
767      local ref_lockfile = {
768        -- Should be no entry for `repo_not_exist` and `basic` as they did not
769        -- fully install
770        plugins = {
771          -- Error during sourcing 'plugin/' should not affect lockfile
772          pluginerr = { rev = pluginerr_hash, src = repos_src.pluginerr, version = "'main'" },
773        },
774      }
775      eq(ref_lockfile, get_lock_tbl())
776    end)
777
778    it('regenerates manually deleted lockfile', function()
779      vim_pack_add({
780        { src = repos_src.basic, name = 'other', version = 'feat-branch' },
781        repos_src.defbranch,
782      })
783      local lock_path = get_lock_path()
784      eq(true, vim.uv.fs_stat(lock_path) ~= nil)
785
786      local basic_rev = git_get_hash('feat-branch', 'basic')
787      local plugindirs_rev = git_get_hash('dev', 'defbranch')
788
789      -- Should try its best to regenerate lockfile based on installed plugins
790      fn.delete(get_lock_path())
791      n.clear()
792      vim_pack_add({})
793      local ref_lockfile = {
794        plugins = {
795          -- No `version = 'feat-branch'` as there is no way to get that info
796          -- (lockfile was the only source of that on disk)
797          other = { rev = basic_rev, src = repos_src.basic },
798          defbranch = { rev = plugindirs_rev, src = repos_src.defbranch },
799        },
800      }
801      eq(ref_lockfile, get_lock_tbl())
802
803      local ref_messages = 'vim.pack: Repaired corrupted lock data for plugins: defbranch, other'
804      eq(ref_messages, n.exec_capture('messages'))
805
806      -- Calling `add()` with `version` should still add it to lockfile
807      vim_pack_add({ { src = repos_src.basic, name = 'other', version = 'feat-branch' } })
808      eq("'feat-branch'", get_lock_tbl().plugins.other.version)
809    end)
810
811    it('repairs corrupted lock data for installed plugins', function()
812      vim_pack_add({
813        -- Should preserve present `version`
814        { src = repos_src.basic, version = 'feat-branch' },
815        repos_src.defbranch,
816        repos_src.semver,
817        repos_src.helptags,
818      })
819
820      local lock_tbl = get_lock_tbl()
821      local ref_lock_tbl = vim.deepcopy(lock_tbl)
822      local assert = function()
823        vim_pack_add({})
824        eq(ref_lock_tbl, get_lock_tbl())
825        eq(true, pack_exists('basic'))
826        eq(true, pack_exists('defbranch'))
827        eq(true, pack_exists('semver'))
828        eq(true, pack_exists('helptags'))
829      end
830
831      -- Missing lock data required field
832      lock_tbl.plugins.basic.rev = nil
833      -- Wrong lock data field type
834      lock_tbl.plugins.defbranch.src = 1 ---@diagnostic disable-line: assign-type-mismatch
835      -- Wrong lock data type
836      lock_tbl.plugins.semver = 1 ---@diagnostic disable-line: assign-type-mismatch
837
838      local lockfile_text = vim.json.encode(lock_tbl, { indent = '  ', sort_keys = true })
839      fn.writefile(vim.split(lockfile_text, '\n'), get_lock_path())
840
841      n.clear()
842      assert()
843
844      local ref_messages =
845        'vim.pack: Repaired corrupted lock data for plugins: basic, defbranch, semver'
846      eq(ref_messages, n.exec_capture('messages'))
847
848      -- Should work even for badly corrupted lockfile
849      lockfile_text = vim.json.encode({ plugins = 1 }, { indent = '  ', sort_keys = true })
850      fn.writefile(vim.split(lockfile_text, '\n'), get_lock_path())
851
852      n.clear()
853      -- Can not preserve `version` if it was deleted from the lockfile
854      ref_lock_tbl.plugins.basic.version = nil
855      assert()
856    end)
857
858    it("respects 'packlockfile'", function()
859      local other_lock_path = get_other_lock_path()
860      api.nvim_set_option_value('packlockfile', other_lock_path, { scope = 'global' })
861      exec_lua(function()
862        vim.pack.add({ repos_src.basic })
863      end)
864      local ref_lockfile = {
865        plugins = {
866          basic = { rev = git_get_hash('main', 'basic'), src = repos_src.basic },
867        },
868      }
869      eq(ref_lockfile, vim.json.decode(fn.readblob(other_lock_path)))
870      eq(false, vim.uv.fs_stat(get_lock_path()) ~= nil)
871
872      n.clear()
873      api.nvim_set_option_value('packlockfile', other_lock_path, { scope = 'global' })
874      exec_lua(function()
875        vim.pack.add({ { src = repos_src.basic, version = 'feat-branch' } })
876      end)
877      ref_lockfile.plugins.basic.version = "'feat-branch'"
878      eq(ref_lockfile, vim.json.decode(fn.readblob(other_lock_path)))
879    end)
880
881    it('removes unrepairable corrupted data and plugins', function()
882      vim_pack_add({ repos_src.basic, repos_src.defbranch, repos_src.semver, repos_src.helptags })
883
884      local lock_tbl = get_lock_tbl()
885      local ref_lock_tbl = vim.deepcopy(lock_tbl)
886
887      -- Corrupted data for missing plugin
888      vim.fs.rm(pack_get_plug_path('basic'), { recursive = true, force = true })
889      lock_tbl.plugins.basic.rev = nil
890
891      -- Good data for corrupted plugin
892      local defbranch_path = pack_get_plug_path('defbranch')
893      vim.fs.rm(defbranch_path, { recursive = true, force = true })
894      fn.writefile({ 'File and not directory' }, defbranch_path)
895
896      -- Corrupted data for corrupted plugin
897      local semver_path = pack_get_plug_path('semver')
898      vim.fs.rm(semver_path, { recursive = true, force = true })
899      fn.writefile({ 'File and not directory' }, semver_path)
900      lock_tbl.plugins.semver.rev = 1 ---@diagnostic disable-line: assign-type-mismatch
901
902      local lockfile_text = vim.json.encode(lock_tbl, { indent = '  ', sort_keys = true })
903      fn.writefile(vim.split(lockfile_text, '\n'), get_lock_path())
904
905      n.clear()
906      vim_pack_add({})
907      ref_lock_tbl.plugins.basic = nil
908      ref_lock_tbl.plugins.defbranch = nil
909      ref_lock_tbl.plugins.semver = nil
910      eq(ref_lock_tbl, get_lock_tbl())
911
912      eq(false, pack_exists('basic'))
913      eq(false, pack_exists('defbranch'))
914      eq(false, pack_exists('semver'))
915      eq(true, pack_exists('helptags'))
916    end)
917
918    it('installs at proper version', function()
919      local out = exec_lua(function()
920        vim.pack.add({ { src = repos_src.basic, version = 'feat-branch' } })
921        -- Should have plugin available immediately (not even on the next loop)
922        return require('basic')
923      end)
924
925      eq('basic feat-branch', out)
926
927      local rtp = api.nvim_list_runtime_paths()
928      local plug_path = pack_get_plug_path('basic')
929      local after_dir = vim.fs.joinpath(plug_path, 'after')
930      eq(true, vim.tbl_contains(rtp, plug_path))
931      -- No 'after/' directory in runtimepath because it is not present in plugin
932      eq(false, vim.tbl_contains(rtp, after_dir))
933    end)
934
935    it('installs with submodules', function()
936      mock_git_file_transport()
937      vim_pack_add({ repos_src.with_subs })
938
939      local sub_lua_file = vim.fs.joinpath(pack_get_plug_path('with_subs'), 'sub', 'sub.lua')
940      eq('return "sub main"', fn.readblob(sub_lua_file))
941    end)
942
943    it('does not install on bad `version`', function()
944      local err = pcall_err(exec_lua, function()
945        vim.pack.add({ { src = repos_src.basic, version = 'not-exist' } })
946      end)
947      matches('`not%-exist` is not a branch/tag/commit', err)
948      eq(false, pack_exists('basic'))
949    end)
950
951    it('can install from the Internet', function()
952      t.skip(skip_integ, 'NVIM_TEST_INTEG not set (network integration test)')
953      vim_pack_add({ 'https://github.com/neovim/nvim-lspconfig' })
954      eq(true, exec_lua('return pcall(require, "lspconfig")'))
955    end)
956
957    describe('startup', function()
958      local config_dir, pack_add_cmd = '', ''
959
960      before_each(function()
961        config_dir = fn.stdpath('config')
962        fn.mkdir(vim.fs.joinpath(config_dir, 'plugin'), 'p')
963
964        pack_add_cmd = ('vim.pack.add({ %s })'):format(vim.inspect(repos_src.plugindirs))
965      end)
966
967      after_each(function()
968        n.rmdir(config_dir)
969      end)
970
971      local function assert_loaded()
972        eq('plugindirs main', exec_lua('return require("plugindirs")'))
973
974        -- Should source 'plugin/' and 'after/plugin/' exactly once
975        eq({ true, true }, n.exec_lua('return { vim.g._plugin, vim.g._after_plugin }'))
976        eq({ 'p', 'a' }, n.exec_lua('return _G.DL'))
977      end
978
979      local function assert_works()
980        -- Should auto-install but wait before executing code after it
981        n.clear({ args_rm = { '-u' } })
982        t.retry(nil, t.is_os('win') and 30000 or 5000, function()
983          eq(true, exec_lua('return _G.done'))
984        end)
985        assert_loaded()
986
987        -- Should only `:packadd!`/`:packadd` already installed plugin
988        n.clear({ args_rm = { '-u' } })
989        assert_loaded()
990      end
991
992      it('works in init.lua', function()
993        local init_lua = vim.fs.joinpath(config_dir, 'init.lua')
994        fn.writefile({ pack_add_cmd, '_G.done = true' }, init_lua)
995        assert_works()
996
997        -- Should not load plugins if `--noplugin`, only adjust 'runtimepath'
998        n.clear({ args = { '--noplugin' }, args_rm = { '-u' } })
999        eq('plugindirs main', exec_lua('return require("plugindirs")'))
1000        eq({}, n.exec_lua('return { vim.g._plugin, vim.g._after_plugin }'))
1001        eq(vim.NIL, n.exec_lua('return _G.DL'))
1002      end)
1003
1004      it('works in plugin/', function()
1005        local plugin_file = vim.fs.joinpath(config_dir, 'plugin', 'mine.lua')
1006        fn.writefile({ pack_add_cmd, '_G.done = true' }, plugin_file)
1007        -- Should source plugin's 'plugin/' files without explicit `load=true`
1008        assert_works()
1009      end)
1010    end)
1011
1012    it('shows progress report during installation', function()
1013      track_nvim_echo()
1014      vim_pack_add({ repos_src.basic, repos_src.defbranch })
1015      assert_progress_report(nil, 'Installing plugins', { 'basic', 'defbranch' })
1016    end)
1017
1018    it('triggers relevant events', function()
1019      watch_events({ 'PackChangedPre', 'PackChanged' })
1020
1021      -- Should provide event-data respecting manual `version` without inferring default
1022      -- Should order events as they were supplied in `vim.pack.add`
1023      vim_pack_add({ repos_src.defbranch, { src = repos_src.basic, version = 'feat-branch' } })
1024      assert_packchanged({
1025        { 'Pre', 'install', 'defbranch', nil, false },
1026        { 'Pre', 'install', 'basic', 'feat-branch', false },
1027        { '', 'install', 'defbranch', nil, false },
1028        { '', 'install', 'basic', 'feat-branch', false },
1029      })
1030    end)
1031
1032    it('sources relevant manifest scripts', function()
1033      watch_events({ 'PackChangedPre', 'PackChanged' })
1034      track_nvim_echo()
1035      local cwd = fn.getcwd()
1036      exec_lua(function()
1037        vim.pack.add({ repos_src.manifest }, { load = function() end })
1038      end)
1039
1040      -- Should not have side effects after executing script in special context
1041      eq(cwd, fn.getcwd())
1042      local plug_path = pack_get_plug_path('manifest')
1043      eq(false, vim.tbl_contains(api.nvim_list_runtime_paths(), plug_path))
1044
1045      -- Should execute script in special context after triggering events
1046      assert_manifest_scripts(plug_path, {
1047        { event = 'PackChangedPre', kind = 'install' },
1048        { event = 'PackChanged', kind = 'install' },
1049        { event = 'script', kind = 'install', cwd = plug_path, rtp_has_plug = true },
1050      })
1051
1052      -- Should warn on errors during script execution
1053      eq(true, is_in_echo_log('Error in install script', 'WarningMsg'))
1054    end)
1055
1056    it('recognizes several `version` types', function()
1057      local prev_commit = git_get_hash('HEAD~', 'defbranch')
1058      exec_lua(function()
1059        vim.pack.add({
1060          { src = repos_src.basic, version = 'some-tag' }, -- Tag
1061          { src = repos_src.defbranch, version = prev_commit }, -- Commit hash
1062          { src = repos_src.semver, version = vim.version.range('<1') }, -- Semver constraint
1063        })
1064      end)
1065
1066      eq('basic some-tag', exec_lua('return require("basic")'))
1067      eq('defbranch main', exec_lua('return require("defbranch")'))
1068      eq('semver 0.3.1', exec_lua('return require("semver")'))
1069    end)
1070
1071    it('respects plugin/ and after/plugin/ scripts', function()
1072      local function assert(load, ref)
1073        vim_pack_add({ { src = repos_src.plugindirs, name = 'plugin % dirs' } }, { load = load })
1074        -- Should handle bad plugin directory name
1075        local out = exec_lua(function()
1076          return {
1077            vim.g._plugin,
1078            vim.g._plugin_vim,
1079            vim.g._plugin_sub,
1080            vim.g._plugin_bad,
1081            vim.g._after_plugin,
1082            vim.g._after_plugin_vim,
1083            vim.g._after_plugin_sub,
1084            vim.g._after_plugin_bad,
1085          }
1086        end)
1087        eq(ref, out)
1088
1089        -- Should add necessary directories to runtimepath regardless of `opts.load`
1090        local rtp = api.nvim_list_runtime_paths()
1091        local plug_path = pack_get_plug_path('plugin % dirs')
1092        local after_dir = vim.fs.joinpath(plug_path, 'after')
1093        eq(true, vim.tbl_contains(rtp, plug_path))
1094        eq(true, vim.tbl_contains(rtp, after_dir))
1095      end
1096
1097      assert(nil, { true, true, true, true, true, true, true, true })
1098
1099      n.clear()
1100      assert(false, {})
1101    end)
1102
1103    it('can use function `opts.load`', function()
1104      local function assert()
1105        n.exec_lua(function()
1106          _G.load_log = {}
1107          local function load(...)
1108            table.insert(_G.load_log, { ... })
1109          end
1110          vim.pack.add({ repos_src.plugindirs, repos_src.basic }, { load = load })
1111        end)
1112
1113        -- Order of execution should be the same as supplied in `add()`
1114        local plugindirs_data = {
1115          spec = { src = repos_src.plugindirs, name = 'plugindirs' },
1116          path = pack_get_plug_path('plugindirs'),
1117        }
1118        local basic_data = {
1119          spec = { src = repos_src.basic, name = 'basic' },
1120          path = pack_get_plug_path('basic'),
1121        }
1122        -- - Only single table argument should be supplied to `load`
1123        local ref_log = { { plugindirs_data }, { basic_data } }
1124        eq(ref_log, n.exec_lua('return _G.load_log'))
1125
1126        -- Should not add plugin to the session in any way
1127        eq(false, exec_lua('return pcall(require, "plugindirs")'))
1128        eq(false, exec_lua('return pcall(require, "basic")'))
1129
1130        -- Should not source 'plugin/'
1131        eq({}, n.exec_lua('return { vim.g._plugin, vim.g._after_plugin }'))
1132
1133        -- Plugins should still be marked as "active", since they were added
1134        eq(true, exec_lua('return vim.pack.get({ "plugindirs" })[1].active'))
1135        eq(true, exec_lua('return vim.pack.get({ "basic" })[1].active'))
1136      end
1137
1138      -- Works on initial install
1139      assert()
1140
1141      -- Works when loading already installed plugin
1142      n.clear()
1143      assert()
1144    end)
1145
1146    it('generates help tags', function()
1147      vim_pack_add({ { src = repos_src.helptags, name = 'help tags' } })
1148      local target_tags = fn.getcompletion('my-test', 'help')
1149      table.sort(target_tags)
1150      eq({ 'my-test-help', 'my-test-help-bad', 'my-test-help-sub-bad' }, target_tags)
1151    end)
1152
1153    it('reports install/load errors after loading all input', function()
1154      t.skip(not is_jit(), "Non LuaJIT reports errors differently due to 'coxpcall'")
1155      local function assert(err_pat)
1156        local err = pcall_err(exec_lua, function()
1157          vim.pack.add({
1158            { src = repos_src.basic, version = 'wrong-version' }, -- Error during initial checkout
1159            { src = repos_src.semver, version = vim.version.range('>=2.0.0') }, -- Missing version
1160            { src = repos_src.plugindirs, version = 'main' },
1161            { src = repos_src.pluginerr, version = 'main' }, -- Error during 'plugin/' source
1162          })
1163        end)
1164
1165        matches(err_pat, err)
1166
1167        -- Should have processed non-errored 'plugin/' and add to 'rtp'
1168        eq('plugindirs main', exec_lua('return require("plugindirs")'))
1169        eq(true, exec_lua('return vim.g._plugin'))
1170
1171        -- Should add plugin to 'rtp' even if 'plugin/' has error
1172        eq('pluginerr main', exec_lua('return require("pluginerr")'))
1173      end
1174
1175      -- During initial install
1176      local err_pat_parts = {
1177        'vim%.pack',
1178        '`basic`:\n',
1179        -- Should report available branches and tags if revision is absent
1180        '`wrong%-version`',
1181        -- Should list default branch first
1182        'Available:\nTags: some%-tag\nBranches: main, feat%-branch',
1183        -- Should report available branches and versions if no constraint match
1184        '`semver`',
1185        'Available:\nVersions: v1%.0%.0, 0%.3%.1, v0%.3%.0.*\nBranches: main\n',
1186        '`pluginerr`:\n',
1187        'Wow, an error',
1188      }
1189      assert(table.concat(err_pat_parts, '.*'))
1190
1191      -- During loading already installed plugin.
1192      n.clear()
1193      -- NOTE: There is no error for wrong `version`, because there is no check
1194      -- for already installed plugins. Might change in the future.
1195      assert('vim%.pack.*`pluginerr`:\n.*Wow, an error')
1196    end)
1197
1198    it('normalizes each spec', function()
1199      vim_pack_add({
1200        repos_src.basic, -- String should be inferred as `{ src = ... }`
1201        { src = repos_src.defbranch }, -- Default `version` is remote's default branch
1202        { src = repos_src['gitsuffix.git'] }, -- Default `name` comes from `src` repo name
1203        { src = repos_src.plugindirs, name = 'plugin/dirs' }, -- Ensure proper directory name
1204      })
1205
1206      eq('basic main', exec_lua('return require("basic")'))
1207      eq('defbranch dev', exec_lua('return require("defbranch")'))
1208      eq('gitsuffix main', exec_lua('return require("gitsuffix")'))
1209      eq(true, exec_lua('return vim.g._plugin'))
1210
1211      eq(true, pack_exists('gitsuffix'))
1212      eq(true, pack_exists('dirs'))
1213    end)
1214
1215    it('handles problematic names', function()
1216      vim_pack_add({ { src = repos_src.basic, name = 'bad % name' } })
1217      eq('basic main', exec_lua('return require("basic")'))
1218    end)
1219
1220    it('is not affected by special environment variables', function()
1221      fn.setenv('GIT_WORK_TREE', t.paths.test_source_path)
1222      fn.setenv('GIT_DIR', vim.fs.joinpath(t.paths.test_source_path, '.git'))
1223      local index_path = vim.fs.joinpath(repo_get_path('defbranch'), '.git', 'index')
1224      local index = fn.readblob(index_path)
1225      fn.setenv('GIT_INDEX_FILE', index_path)
1226      local ref_environ = fn.environ()
1227
1228      vim_pack_add({ repos_src.basic })
1229      eq('basic main', exec_lua('return require("basic")'))
1230
1231      eq(ref_environ, fn.environ())
1232      eq(index, fn.readblob(index_path))
1233    end)
1234
1235    it('validates input', function()
1236      local function assert(err_pat, input)
1237        local function add_input()
1238          vim.pack.add(input)
1239        end
1240        matches(err_pat, pcall_err(exec_lua, add_input))
1241      end
1242
1243      -- Separate spec entries
1244      assert('list', repos_src.basic)
1245      assert('spec:.*table', { 1 })
1246      assert('spec%.src:.*string', { { src = 1 } })
1247      assert('spec%.src:.*non%-empty string', { { src = '' } })
1248      assert('spec%.name:.*string', { { src = repos_src.basic, name = 1 } })
1249      assert('spec%.name:.*non%-empty string', { { src = repos_src.basic, name = '' } })
1250      assert(
1251        'spec%.version:.*string or vim%.VersionRange',
1252        { { src = repos_src.basic, version = 1 } }
1253      )
1254
1255      -- Conflicts in input array
1256      local version_conflict = {
1257        { src = repos_src.basic, version = 'feat-branch' },
1258        { src = repos_src.basic, version = 'main' },
1259      }
1260      assert('Conflicting `version` for `basic`.*feat%-branch.*main', version_conflict)
1261
1262      local src_conflict = {
1263        { src = repos_src.basic, name = 'my-plugin' },
1264        { src = repos_src.semver, name = 'my-plugin' },
1265      }
1266      assert('Conflicting `src` for `my%-plugin`.*basic.*semver', src_conflict)
1267    end)
1268  end)
1269
1270  describe('update()', function()
1271    -- Tables with hashes used to test confirmation buffer and log content
1272    local hashes --- @type table<string,string>
1273    local short_hashes --- @type table<string,string>
1274
1275    before_each(function()
1276      -- Create a dedicated clean repo for which "push changes" will be mocked
1277      init_test_repo('fetch')
1278
1279      repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch init"')
1280      git_add_commit('Initial commit for "fetch"', 'fetch')
1281
1282      repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch main"')
1283      git_add_commit('Commit from `main` to be removed', 'fetch')
1284
1285      hashes = { fetch_head = git_get_hash('HEAD', 'fetch') }
1286      short_hashes = { fetch_head = git_get_short_hash('HEAD', 'fetch') }
1287
1288      -- Install initial versions of tested plugins
1289      vim_pack_add({
1290        { src = repos_src.fetch, version = 'main' },
1291        { src = repos_src.semver, version = 'v0.3.0' },
1292        repos_src.defbranch,
1293      })
1294      n.clear()
1295
1296      -- Pin git's short-hash length so the confirmation buffer's `%h` columns are deterministic.
1297      exec_lua([[
1298        vim.env.GIT_CONFIG_COUNT = '1'
1299        vim.env.GIT_CONFIG_KEY_0 = 'core.abbrev'
1300        vim.env.GIT_CONFIG_VALUE_0 = '7'
1301      ]])
1302
1303      -- Mock remote repo update
1304      -- - Force push
1305      repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch new"')
1306      git_cmd({ 'add', '*' }, 'fetch')
1307      git_cmd({ 'commit', '--amend', '-m', 'Commit to be added 1' }, 'fetch')
1308
1309      -- - Presence of a tag (should be shown in changelog)
1310      git_cmd({ 'tag', 'dev-tag' }, 'fetch')
1311
1312      repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch new 2"')
1313      git_add_commit('Commit to be added 2', 'fetch')
1314
1315      -- Make `dev` default remote branch to check that `version` is respected
1316      git_cmd({ 'checkout', '-b', 'dev' }, 'fetch')
1317      repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch dev"')
1318      git_add_commit('Commit from default `dev` branch', 'fetch')
1319    end)
1320
1321    after_each(function()
1322      n.rmdir(repo_get_path('fetch'))
1323      local log_path = vim.fs.joinpath(fn.stdpath('log'), 'nvim-pack.log')
1324      pcall(vim.fs.rm, log_path, { force = true })
1325    end)
1326
1327    describe('confirmation buffer', function()
1328      it('works', function()
1329        vim_pack_add({
1330          repos_src.fetch,
1331          { src = repos_src.semver, version = 'v0.3.0' },
1332          { src = repos_src.defbranch, version = 'does-not-exist' },
1333        })
1334        pack_assert_content('fetch', 'return "fetch main"')
1335
1336        exec_lua(function()
1337          -- Enable highlighting of special filetype
1338          vim.cmd('filetype plugin on')
1339          vim.pack.update()
1340        end)
1341
1342        -- Buffer should be special and shown in a separate tabpage
1343        eq(2, #api.nvim_list_tabpages())
1344        eq(2, fn.tabpagenr())
1345        eq('nvim-pack', api.nvim_get_option_value('filetype', {}))
1346        eq(false, api.nvim_get_option_value('modifiable', {}))
1347        eq('acwrite', api.nvim_get_option_value('buftype', {}))
1348        local confirm_bufnr = api.nvim_get_current_buf()
1349        local confirm_winnr = api.nvim_get_current_win()
1350        local confirm_tabpage = api.nvim_get_current_tabpage()
1351        eq('nvim-pack://confirm#' .. confirm_bufnr, api.nvim_buf_get_name(0))
1352
1353        -- Adjust lines for a more robust screenshot testing
1354        local fetch_src = repos_src.fetch
1355        local fetch_path = pack_get_plug_path('fetch')
1356        local semver_src = repos_src.semver
1357        local semver_path = pack_get_plug_path('semver')
1358        local pack_runtime = '/lua/vim/pack.lua'
1359
1360        exec_lua(function()
1361          -- Replace matches in line to preserve extmark highlighting
1362          local function replace_in_line(i, pattern, repl)
1363            local line = vim.api.nvim_buf_get_lines(0, i - 1, i, false)[1]
1364            local from, to = line:find(pattern)
1365            while from and to do
1366              vim.api.nvim_buf_set_text(0, i - 1, from - 1, i - 1, to, { repl })
1367              line = vim.api.nvim_buf_get_lines(0, i - 1, i, false)[1]
1368              from, to = line:find(pattern)
1369            end
1370          end
1371
1372          vim.bo.modifiable = true
1373          local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
1374          -- NOTE: replace path to `vim.pack` in error traceback accounting for
1375          -- pcall source truncation and possibly different slashes on Windows
1376          local pack_runtime_pesc = vim.pesc(pack_runtime):gsub('/', '[\\/]')
1377          local pack_runtime_pattern = ('%%S.+%s:%%d+'):format(pack_runtime_pesc)
1378          for i = 1, #lines do
1379            replace_in_line(i, pack_runtime_pattern, 'VIM_PACK_RUNTIME')
1380            replace_in_line(i, vim.pesc(fetch_path), 'FETCH_PATH')
1381            replace_in_line(i, vim.pesc(fetch_src), 'FETCH_SRC')
1382            replace_in_line(i, vim.pesc(semver_path), 'SEMVER_PATH')
1383            replace_in_line(i, vim.pesc(semver_src), 'SEMVER_SRC')
1384          end
1385          vim.bo.modified = false
1386          vim.bo.modifiable = false
1387        end)
1388
1389        -- Use screenshot to test highlighting, otherwise prefer text matching.
1390        -- This requires computing target hashes on each test run because they
1391        -- change due to source repos being cleanly created on each file test.
1392        local screen
1393        screen = Screen.new(85, 34)
1394
1395        hashes.fetch_new = git_get_hash('main', 'fetch')
1396        short_hashes.fetch_new = git_get_short_hash('main', 'fetch')
1397        short_hashes.fetch_new_prev = git_get_short_hash('main~', 'fetch')
1398        hashes.semver_head = git_get_hash('v0.3.0', 'semver')
1399
1400        local tab_name = 'n' .. (t.is_os('win') and ':' or '') .. '//confirm#2'
1401
1402        local ref_screen_lines = ([[
1403          {24: [No Name] }{5: %s }{2:%s                                                          }{24:X}|
1404          {19:^# Error ────────────────────────────────────────────────────────────────────────}     |
1405                                                                                               |
1406          {19:## defbranch}                                                                         |
1407                                                                                               |
1408           VIM_PACK_RUNTIME: `does-not-exist` is not a branch/tag/commit. Available:           |
1409            Tags:                                                                              |
1410            Branches: dev, main                                                                |
1411                                                                                               |
1412          {101:# Update ───────────────────────────────────────────────────────────────────────}     |
1413                                                                                               |
1414          {101:## fetch}                                                                             |
1415          Path:            {103:FETCH_PATH}                                                          |
1416          Source:          {103:FETCH_SRC}                                                           |
1417          Revision before: {103:%s}                            |
1418          Revision after:  {103:%s} {102:(main)}                     |
1419                                                                                               |
1420          Pending updates:                                                                     |
1421          {19:< %s │ Commit from `main` to be removed}                                         |
1422          {104:> %s │ Commit to be added 2}                                                     |
1423          {104:> %s │ Commit to be added 1 (tag: dev-tag)}                                      |
1424                                                                                               |
1425          {102:# Same ─────────────────────────────────────────────────────────────────────────}     |
1426                                                                                               |
1427          {102:## semver}                                                                            |
1428          Path:     {103:SEMVER_PATH}                                                                |
1429          Source:   {103:SEMVER_SRC}                                                                 |
1430          Revision: {103:%s} {102:(v0.3.0)}                          |
1431                                                                                               |
1432          Available newer versions:                                                            |
1433          • {102:v1.0.0}                                                                             |
1434          • {102:0.3.1}                                                                              |
1435          {1:~                                                                                    }|
1436                                                                                               |
1437        ]]):format(
1438          tab_name,
1439          t.is_os('win') and '' or ' ',
1440          hashes.fetch_head,
1441          hashes.fetch_new,
1442          short_hashes.fetch_head,
1443          short_hashes.fetch_new,
1444          short_hashes.fetch_new_prev,
1445          hashes.semver_head
1446        )
1447
1448        screen:add_extra_attr_ids({
1449          [101] = { foreground = Screen.colors.Orange },
1450          [102] = { foreground = Screen.colors.LightGray },
1451          [103] = { foreground = Screen.colors.LightBlue },
1452          [104] = { foreground = Screen.colors.SeaGreen },
1453        })
1454        -- NOTE: Non LuaJIT reports errors differently due to 'coxpcall'
1455        if is_jit() then
1456          local ref_screen = vim.text.indent(0, ref_screen_lines)
1457          screen:expect(ref_screen)
1458        end
1459
1460        -- `:write` should confirm
1461        n.exec('write')
1462
1463        -- - Apply changes immediately
1464        pack_assert_content('fetch', 'return "fetch new 2"')
1465
1466        -- - Clean up buffer+window+tabpage
1467        eq(false, api.nvim_buf_is_valid(confirm_bufnr))
1468        eq(false, api.nvim_win_is_valid(confirm_winnr))
1469        eq(false, api.nvim_tabpage_is_valid(confirm_tabpage))
1470
1471        -- - Write to log file
1472        local log_path = vim.fs.joinpath(fn.stdpath('log'), 'nvim-pack.log')
1473        local log_text = fn.readblob(log_path)
1474        local log_1, log_rest = log_text:match('^(.-)\n(.*)$') --- @type string, string
1475        matches('========== Update %d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d ==========', log_1)
1476        local ref_log_lines = ([[
1477          # Update ───────────────────────────────────────────────────────────────────────
1478
1479          ## fetch
1480          Path:            %s
1481          Source:          %s
1482          Revision before: %s
1483          Revision after:  %s (main)
1484
1485          Pending updates:
1486          < %s │ Commit from `main` to be removed
1487          > %s │ Commit to be added 2
1488          > %s │ Commit to be added 1 (tag: dev-tag)]]):format(
1489          fetch_path,
1490          fetch_src,
1491          hashes.fetch_head,
1492          hashes.fetch_new,
1493          short_hashes.fetch_head,
1494          short_hashes.fetch_new,
1495          short_hashes.fetch_new_prev
1496        )
1497        eq(vim.text.indent(0, ref_log_lines), vim.trim(log_rest))
1498      end)
1499
1500      it('can be dismissed with `:quit`', function()
1501        vim_pack_add({ repos_src.fetch })
1502        exec_lua('vim.pack.update({ "fetch" })')
1503        eq('nvim-pack', api.nvim_get_option_value('filetype', {}))
1504
1505        -- Should not apply updates
1506        n.exec('quit')
1507        pack_assert_content('fetch', 'return "fetch main"')
1508      end)
1509
1510      it('closes full tabpage', function()
1511        vim_pack_add({ repos_src.fetch })
1512        exec_lua('vim.pack.update()')
1513
1514        -- Confirm with `:write`
1515        local confirm_tabpage = api.nvim_get_current_tabpage()
1516        n.exec('-tab split other-tab')
1517        local other_tabpage = api.nvim_get_current_tabpage()
1518        n.exec('tabnext')
1519        n.exec('write')
1520        eq(true, api.nvim_get_current_tabpage() == other_tabpage)
1521        eq(false, api.nvim_tabpage_is_valid(confirm_tabpage))
1522
1523        -- Not confirm with `:quit`
1524        n.exec('tab split other-tab-2')
1525        local other_tabpage_2 = api.nvim_get_current_tabpage()
1526        exec_lua('vim.pack.update()')
1527        confirm_tabpage = api.nvim_get_current_tabpage()
1528
1529        -- - Temporary split window in tabpage should prevent from closing
1530        n.exec('vsplit other-buf')
1531        n.exec('wincmd w')
1532
1533        n.exec('tabclose ' .. api.nvim_tabpage_get_number(other_tabpage_2))
1534        eq(confirm_tabpage, api.nvim_get_current_tabpage())
1535        n.exec('quit')
1536        eq(confirm_tabpage, api.nvim_get_current_tabpage())
1537        n.exec('quit')
1538        eq(false, api.nvim_tabpage_is_valid(confirm_tabpage))
1539
1540        -- Should work even if it is the last tabpage
1541        exec_lua('vim.pack.update()')
1542        n.exec('tabonly')
1543        n.exec('write')
1544        eq('', n.eval('v:errmsg'))
1545
1546        -- Should cleanly close tabpage even if there are only scratch buffers
1547        n.exec('%bwipeout')
1548        local init_buf = api.nvim_get_current_buf()
1549        api.nvim_set_current_buf(api.nvim_create_buf(false, true))
1550        api.nvim_buf_delete(init_buf, { force = true })
1551        exec_lua('vim.pack.update()')
1552        n.exec('write')
1553        eq(1, #api.nvim_list_tabpages())
1554        eq(1, #api.nvim_list_bufs())
1555      end)
1556
1557      it('has in-process LSP features', function()
1558        t.skip(not is_jit(), "Non LuaJIT reports errors differently due to 'coxpcall'")
1559        track_nvim_echo()
1560        vim_pack_add({
1561          repos_src.fetch,
1562          -- No `semver` to test with non-active plugins
1563          { src = repos_src.defbranch, version = 'does-not-exist' },
1564        })
1565        exec_lua('vim.pack.update()')
1566
1567        eq(1, exec_lua('return #vim.lsp.get_clients({ bufnr = 0 })'))
1568
1569        -- textDocument/documentLink
1570        --- @param ref ([number, number, number, number, string])[]
1571        local assert_links = function(ref)
1572          --- @type table[]
1573          local out_links = exec_lua(function()
1574            local params = { textDocument = vim.lsp.util.make_text_document_params(0) }
1575            local response = vim.lsp.buf_request_sync(0, 'textDocument/documentLink', params)
1576            return response[1].result
1577          end)
1578
1579          --- @type table[]
1580          local ref_links = {}
1581          for i, r in ipairs(ref) do
1582            local start = { line = r[1], character = r[2] }
1583            local end_ = { line = r[3], character = r[4] }
1584            ref_links[i] = { range = { start = start, ['end'] = end_ }, target = r[5] }
1585          end
1586
1587          eq(ref_links, out_links)
1588        end
1589
1590        local fetch_src = repos_src.fetch
1591        local fetch_path = pack_get_plug_path('fetch')
1592        local fetch_path_uri = vim.uri_from_fname(fetch_path)
1593        local semver_src = repos_src.semver
1594        local semver_path = pack_get_plug_path('semver')
1595        local semver_path_uri = vim.uri_from_fname(semver_path)
1596
1597        -- With `file://` sources it can only return "Path:" and "Source:" links
1598        local ref_file_links = {
1599          { 11, 17, 11, 17 + fetch_path:len() - 1, fetch_path_uri }, -- Path: ...
1600          { 12, 17, 12, 17 + fetch_src:len() - 1, fetch_src }, -- Source: ...
1601          { 24, 10, 24, 10 + semver_path:len() - 1, semver_path_uri }, -- Path: ...
1602          { 25, 10, 25, 10 + semver_src:len() - 1, semver_src }, -- Source: ...
1603        }
1604        assert_links(ref_file_links)
1605
1606        -- Mock using common sources which should provide all links
1607        local fetch_github = 'https://github.com/user/fetch'
1608        local semver_codeberg = 'https://codeberg.org/user/semver'
1609        local lines = api.nvim_buf_get_lines(0, 0, -1, false)
1610        lines[13] = lines[13]:gsub('^(Source: +)(.+)$', '%1' .. fetch_github)
1611        lines[26] = lines[26]:gsub('^(Source: +)(.+)$', '%1' .. semver_codeberg)
1612        api.nvim_set_option_value('modifiable', true, { buf = 0 })
1613        api.nvim_buf_set_lines(0, 0, -1, false, lines)
1614        api.nvim_set_option_value('modifiable', false, { buf = 0 })
1615
1616        local ref_github_links = {
1617          { 11, 17, 11, 17 + fetch_path:len() - 1, fetch_path_uri }, -- Path: ...
1618          { 12, 17, 12, 45, fetch_github }, -- Source: ...
1619          { 13, 17, 13, 56, fetch_github .. '/commit/' .. lines[14]:match('%S+$') }, -- Revision before: ...
1620          { 14, 17, 14, 56, fetch_github .. '/commit/' .. lines[15]:match('(%S+) %b()$') }, -- Revision before: ...
1621          { 17, 2, 17, 8, fetch_github .. '/commit/' .. lines[18]:match('^< (%S+)') },
1622          { 18, 2, 18, 8, fetch_github .. '/commit/' .. lines[19]:match('^> (%S+)') },
1623          { 19, 2, 19, 8, fetch_github .. '/commit/' .. lines[20]:match('^> (%S+)') },
1624          { 24, 10, 24, 10 + semver_path:len() - 1, semver_path_uri }, -- Path: ...
1625          { 25, 10, 25, 41, semver_codeberg }, -- Source: ...
1626          { 26, 10, 26, 49, semver_codeberg .. '/commit/' .. lines[27]:match('(%S+) %b()$') }, -- Revision: ...
1627          -- Should use UTF index
1628          { 29, 2, 29, 7, semver_codeberg .. '/src/tag/v1.0.0' },
1629          { 30, 2, 30, 6, semver_codeberg .. '/src/tag/0.3.1' },
1630        }
1631        assert_links(ref_github_links)
1632
1633        n.exec('quit')
1634
1635        -- textDocument/documentSymbol
1636        exec_lua('vim.pack.update()')
1637        exec_lua('vim.lsp.buf.document_symbol()')
1638        local loclist = vim.tbl_map(function(x) --- @param x table
1639          return {
1640            lnum = x.lnum, --- @type integer
1641            col = x.col, --- @type integer
1642            end_lnum = x.end_lnum, --- @type integer
1643            end_col = x.end_col, --- @type integer
1644            text = x.text, --- @type string
1645          }
1646        end, fn.getloclist(0))
1647        local ref_loclist = {
1648          { lnum = 1, col = 1, end_lnum = 9, end_col = 1, text = '[Namespace] Error' },
1649          { lnum = 3, col = 1, end_lnum = 9, end_col = 1, text = '[Module] defbranch' },
1650          { lnum = 9, col = 1, end_lnum = 22, end_col = 1, text = '[Namespace] Update' },
1651          { lnum = 11, col = 1, end_lnum = 22, end_col = 1, text = '[Module] fetch' },
1652          { lnum = 22, col = 1, end_lnum = 31, end_col = 1, text = '[Namespace] Same' },
1653          { lnum = 24, col = 1, end_lnum = 31, end_col = 1, text = '[Module] semver (not active)' },
1654        }
1655        eq(ref_loclist, loclist)
1656
1657        n.exec('lclose')
1658
1659        -- textDocument/hover
1660        local confirm_winnr = api.nvim_get_current_win()
1661        local function assert_hover(pos, commit_msg)
1662          -- Should not be affected by special environment variables
1663          fn.setenv('GIT_WORK_TREE', t.paths.test_source_path)
1664          fn.setenv('GIT_DIR', vim.fs.joinpath(t.paths.test_source_path, '.git'))
1665          fn.setenv('GIT_INDEX_FILE', vim.fs.joinpath(repo_get_path('defbranch'), '.git', 'index'))
1666          api.nvim_win_set_cursor(0, pos)
1667          exec_lua(function()
1668            vim.lsp.buf.hover()
1669            -- Default hover is async shown in floating window
1670            vim.wait(1000, function()
1671              return #vim.api.nvim_tabpage_list_wins(0) > 1
1672            end)
1673          end)
1674
1675          local all_wins = api.nvim_tabpage_list_wins(0)
1676          eq(2, #all_wins)
1677          local float_winnr = all_wins[1] == confirm_winnr and all_wins[2] or all_wins[1]
1678          eq(true, api.nvim_win_get_config(float_winnr).relative ~= '')
1679
1680          local float_buf = api.nvim_win_get_buf(float_winnr)
1681          local text = table.concat(api.nvim_buf_get_lines(float_buf, 0, -1, false), '\n')
1682
1683          local ref_pattern = 'Marvim <marvim@neovim%.io>\nDate:.*' .. vim.pesc(commit_msg)
1684          matches(ref_pattern, text)
1685
1686          exec_lua('vim.uv.os_unsetenv("GIT_WORK_TREE")')
1687          exec_lua('vim.uv.os_unsetenv("GIT_DIR")')
1688          exec_lua('vim.uv.os_unsetenv("GIT_INDEX_FILE")')
1689        end
1690
1691        assert_hover({ 14, 0 }, 'Commit from `main` to be removed')
1692        assert_hover({ 15, 0 }, 'Commit to be added 2')
1693        assert_hover({ 18, 0 }, 'Commit from `main` to be removed')
1694        assert_hover({ 19, 0 }, 'Commit to be added 2')
1695        assert_hover({ 20, 0 }, 'Commit to be added 1')
1696        assert_hover({ 27, 0 }, 'Add version v0.3.0')
1697        assert_hover({ 30, 0 }, 'Add version v1.0.0')
1698        assert_hover({ 31, 0 }, 'Add version 0.3.1')
1699
1700        -- textDocument/codeAction
1701        n.exec_lua(function()
1702          -- Mock `vim.ui.select()` which is a default code action selection
1703          _G.select_idx = 0
1704
1705          ---@diagnostic disable-next-line: duplicate-set-field
1706          vim.ui.select = function(items, _, on_choice)
1707            _G.select_items = items
1708            local idx = _G.select_idx
1709            if idx > 0 then
1710              on_choice(items[idx], idx)
1711              -- Minor delay before continue because LSP cmd execution is async
1712              vim.wait(10)
1713            end
1714          end
1715        end)
1716
1717        local ref_lockfile = get_lock_tbl() --- @type vim.pack.Lock
1718
1719        local function assert_action(pos, action_titles, select_idx, should_preserve_lines)
1720          api.nvim_win_set_cursor(0, pos)
1721
1722          local buf_lines = api.nvim_buf_get_lines(0, 0, -1, false)
1723          n.exec_lua(function()
1724            _G.select_items = nil
1725            _G.select_idx = select_idx
1726            vim.lsp.buf.code_action()
1727          end)
1728          local titles = vim.tbl_map(function(x) --- @param x table
1729            return x.action.title
1730          end, n.exec_lua('return _G.select_items or {}'))
1731          eq(titles, action_titles)
1732
1733          -- If no action is asked (like via cancel), should not delete lines
1734          if select_idx <= 0 or should_preserve_lines then
1735            eq(buf_lines, api.nvim_buf_get_lines(0, 0, -1, false))
1736          end
1737        end
1738
1739        -- - Should not include "namespace" header as "plugin at cursor"
1740        assert_action({ 1, 1 }, {}, 0)
1741        assert_action({ 2, 0 }, {}, 0)
1742        -- - "Delete" action should be present for active plugins
1743        local defbranch_actions = { 'Delete `defbranch`' }
1744        assert_action({ 3, 1 }, defbranch_actions, 0)
1745        assert_action({ 7, 0 }, defbranch_actions, 0)
1746        -- - Should not include separator blank line as "plugin at cursor"
1747        assert_action({ 8, 0 }, {}, 0)
1748        assert_action({ 9, 0 }, {}, 0)
1749        assert_action({ 10, 0 }, {}, 0)
1750        -- - Should suggest updating related actions if updates available
1751        local fetch_actions = { 'Update `fetch`', 'Skip updating `fetch`', 'Delete `fetch`' }
1752        assert_action({ 11, 0 }, fetch_actions, 0)
1753        assert_action({ 14, 0 }, fetch_actions, 0)
1754        assert_action({ 20, 0 }, fetch_actions, 0)
1755        assert_action({ 21, 0 }, {}, 0)
1756        assert_action({ 22, 0 }, {}, 0)
1757        assert_action({ 23, 0 }, {}, 0)
1758        -- - "Delete" action should be present for not active plugin
1759        local semver_actions = { 'Delete `semver`' }
1760        assert_action({ 24, 0 }, semver_actions, 0)
1761        assert_action({ 28, 0 }, semver_actions, 0)
1762        assert_action({ 31, 0 }, semver_actions, 0)
1763
1764        -- - Should correctly perform action and remove plugin's lines
1765        local function line_match(lnum, pattern)
1766          matches(pattern, api.nvim_buf_get_lines(0, lnum - 1, lnum, false)[1])
1767        end
1768
1769        -- - Delete not active plugin. Should remove from disk and update lockfile.
1770        assert_action({ 24, 0 }, semver_actions, 1)
1771        eq(false, pack_exists('semver'))
1772        line_match(22, '^# Same')
1773        eq(22, api.nvim_buf_line_count(0))
1774
1775        ref_lockfile.plugins.semver = nil
1776        eq(ref_lockfile, get_lock_tbl())
1777
1778        -- - Skip udating
1779        assert_action({ 11, 0 }, fetch_actions, 2)
1780        pack_assert_content('fetch', 'return "fetch main"')
1781        line_match(9, '^# Update')
1782        line_match(10, '^$')
1783        line_match(11, '^# Same')
1784
1785        -- - Delete active plugin. Should ask for confirmation before force deleting
1786        --   with possibility to not confirm.
1787        mock_confirm(2) -- No
1788        assert_action({ 3, 0 }, defbranch_actions, 1, true)
1789        eq(true, pack_exists('defbranch'))
1790        eq(ref_lockfile, get_lock_tbl())
1791        local confirm_msg = 'Plugin `defbranch` is active.'
1792          .. ' Make sure its `vim.pack.add` call is removed from config.'
1793        local ref_confirm_log = { { confirm_msg, 'Delete? &Yes\n&No', 1, 'Question' } }
1794        eq(ref_confirm_log, exec_lua('return _G.confirm_log'))
1795
1796        mock_confirm(1) -- Yes
1797        assert_action({ 3, 0 }, defbranch_actions, 1)
1798        eq(false, pack_exists('defbranch'))
1799        ref_lockfile.plugins.defbranch = nil
1800        eq(ref_lockfile, get_lock_tbl())
1801        eq(5, api.nvim_buf_line_count(0))
1802        line_match(1, '^# Error')
1803        line_match(3, '^# Update')
1804        line_match(5, '^# Same')
1805
1806        -- - Update plugin. Should not re-fetch new data and update lockfile.
1807        n.exec('quit')
1808        n.exec_lua(function()
1809          vim.pack.update({ 'fetch' })
1810        end)
1811        exec_lua('_G.echo_log = {}')
1812
1813        ref_lockfile.plugins.fetch.rev = git_get_hash('main', 'fetch')
1814        git_cmd({ 'checkout', 'main' }, 'fetch')
1815        repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch new 3"')
1816        git_add_commit('Commit to be added 3', 'fetch')
1817
1818        assert_action({ 3, 0 }, fetch_actions, 1)
1819
1820        pack_assert_content('fetch', 'return "fetch new 2"')
1821
1822        local echo_log = exec_lua('return _G.echo_log')
1823        assert_progress_report(vim.list_slice(echo_log, 1, 3), 'Computing updates', { 'fetch' })
1824        assert_progress_report(vim.list_slice(echo_log, 4, 6), 'Applying updates', { 'fetch' })
1825        eq(6, #echo_log)
1826
1827        line_match(1, '^# Update')
1828        eq(1, api.nvim_buf_line_count(0))
1829
1830        eq(ref_lockfile, get_lock_tbl())
1831
1832        -- - Can still respect `:write` after action
1833        n.exec('write')
1834        eq('vim.pack: Nothing to update', n.exec_capture('1messages'))
1835        eq('', api.nvim_get_option_value('filetype', {}))
1836      end)
1837
1838      it('has buffer-local mappings', function()
1839        t.skip(not is_jit(), "Non LuaJIT reports update errors differently due to 'coxpcall'")
1840        vim_pack_add({
1841          repos_src.fetch,
1842          { src = repos_src.semver, version = 'v0.3.0' },
1843          { src = repos_src.defbranch, version = 'does-not-exist' },
1844        })
1845        -- Enable sourcing filetype script (that creates mappings)
1846        n.exec('filetype plugin on')
1847        exec_lua('vim.pack.update()')
1848
1849        -- Plugin sections navigation
1850        local function assert(keys, ref_cursor)
1851          n.feed(keys)
1852          eq(ref_cursor, api.nvim_win_get_cursor(0))
1853        end
1854
1855        api.nvim_win_set_cursor(0, { 1, 1 })
1856        assert(']]', { 3, 0 })
1857        assert(']]', { 11, 0 })
1858        assert(']]', { 24, 0 })
1859        -- - Should not wrap around the edge
1860        assert(']]', { 24, 0 })
1861
1862        api.nvim_win_set_cursor(0, { 31, 1 })
1863        assert('[[', { 24, 0 })
1864        assert('[[', { 11, 0 })
1865        assert('[[', { 3, 0 })
1866        -- - Should not wrap around the edge
1867        assert('[[', { 3, 0 })
1868      end)
1869
1870      it('suggests newer versions when on non-tagged commit', function()
1871        local commit = git_get_hash('0.3.1~', 'semver')
1872
1873        -- Make fresh install for cleaner test
1874        exec_lua('vim.pack.del({ "semver" })')
1875        vim_pack_add({ { src = repos_src.semver, version = commit } })
1876        exec_lua('vim.pack.update({ "semver" })')
1877
1878        -- Should correctly infer that 0.3.0 is the latest version and suggest
1879        -- versions greater than that
1880        local confirm_text = table.concat(api.nvim_buf_get_lines(0, 0, -1, false), '\n')
1881        matches('Available newer versions:\n• v1%.0%.0\n• 0%.3%.1$', confirm_text)
1882      end)
1883
1884      it('updates lockfile', function()
1885        vim_pack_add({ repos_src.fetch })
1886        local ref_fetch_lock = { rev = hashes.fetch_head, src = repos_src.fetch }
1887        eq(ref_fetch_lock, get_lock_tbl().plugins.fetch)
1888
1889        exec_lua('vim.pack.update()')
1890        n.exec('write')
1891
1892        ref_fetch_lock.rev = git_get_hash('main', 'fetch')
1893        eq(ref_fetch_lock, get_lock_tbl().plugins.fetch)
1894      end)
1895
1896      it('hints about not active plugins', function()
1897        exec_lua(function()
1898          vim.pack.update()
1899        end)
1900
1901        for _, l in ipairs(api.nvim_buf_get_lines(0, 0, -1, false)) do
1902          if l:match('^## ') then
1903            matches(' %(not active%)$', l)
1904          end
1905        end
1906
1907        -- Should also hint in `textDocument/documentSymbol` of in-process LSP,
1908        -- yet still work for navigation
1909        exec_lua('vim.lsp.buf.document_symbol()')
1910        local loclist = fn.getloclist(0)
1911        matches(' %(not active%)$', loclist[2].text)
1912        matches(' %(not active%)$', loclist[4].text)
1913        matches(' %(not active%)$', loclist[5].text)
1914
1915        n.exec('llast')
1916        eq(21, api.nvim_win_get_cursor(0)[1])
1917      end)
1918    end)
1919
1920    it('works with not active plugins', function()
1921      -- No plugins are added, but they are installed in `before_each()`
1922      exec_lua(function()
1923        -- By default should also include not active plugins
1924        vim.pack.update()
1925      end)
1926      pack_assert_content('fetch', 'return "fetch main"')
1927      n.exec('write')
1928      pack_assert_content('fetch', 'return "fetch new 2"')
1929    end)
1930
1931    it('works with submodules', function()
1932      mock_git_file_transport()
1933      vim_pack_add({ { src = repos_src.with_subs, version = 'init-commit' } })
1934
1935      local sub_lua_file = vim.fs.joinpath(pack_get_plug_path('with_subs'), 'sub', 'sub.lua')
1936      eq('return "sub init"', fn.readblob(sub_lua_file))
1937
1938      n.clear()
1939      mock_git_file_transport()
1940      vim_pack_add({ repos_src.with_subs })
1941      exec_lua('vim.pack.update({ "with_subs" })')
1942      n.exec('write')
1943      eq('return "sub main"', fn.readblob(sub_lua_file))
1944    end)
1945
1946    it('can force update', function()
1947      vim_pack_add({ repos_src.fetch })
1948      exec_lua('vim.pack.update({ "fetch" }, { force = true })')
1949
1950      -- Apply changes immediately
1951      local fetch_src = repos_src.fetch
1952      local fetch_path = pack_get_plug_path('fetch')
1953      pack_assert_content('fetch', 'return "fetch new 2"')
1954
1955      -- No special buffer/window/tabpage
1956      eq(1, #api.nvim_list_tabpages())
1957      eq(1, #api.nvim_list_wins())
1958      eq('', api.nvim_get_option_value('filetype', {}))
1959
1960      -- Write to log file
1961      hashes.fetch_new = git_get_hash('main', 'fetch')
1962      short_hashes.fetch_new = git_get_short_hash('main', 'fetch')
1963      short_hashes.fetch_new_prev = git_get_short_hash('main~', 'fetch')
1964
1965      local log_path = vim.fs.joinpath(fn.stdpath('log'), 'nvim-pack.log')
1966      local log_text = fn.readblob(log_path)
1967      local log_1, log_rest = log_text:match('^(.-)\n(.*)$') --- @type string, string
1968      matches('========== Update %d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d ==========', log_1)
1969      local ref_log_lines = ([[
1970        # Update ───────────────────────────────────────────────────────────────────────
1971
1972        ## fetch
1973        Path:            %s
1974        Source:          %s
1975        Revision before: %s
1976        Revision after:  %s (main)
1977
1978        Pending updates:
1979        < %s │ Commit from `main` to be removed
1980        > %s │ Commit to be added 2
1981        > %s │ Commit to be added 1 (tag: dev-tag)]]):format(
1982        fetch_path,
1983        fetch_src,
1984        hashes.fetch_head,
1985        hashes.fetch_new,
1986        short_hashes.fetch_head,
1987        short_hashes.fetch_new,
1988        short_hashes.fetch_new_prev
1989      )
1990      eq(vim.text.indent(0, ref_log_lines), vim.trim(log_rest))
1991
1992      -- Should update lockfile
1993      eq(hashes.fetch_new, get_lock_tbl().plugins.fetch.rev)
1994    end)
1995
1996    it('can use lockfile revision as a target', function()
1997      vim_pack_add({ repos_src.fetch })
1998      pack_assert_content('fetch', 'return "fetch main"')
1999
2000      -- Mock "update -> revert lockfile -> revert plugin"
2001      local lock_path = get_lock_path()
2002      local lockfile_before = fn.readblob(lock_path)
2003      hashes.fetch_new = git_get_hash('main', 'fetch')
2004
2005      -- - Update
2006      exec_lua('vim.pack.update({ "fetch" }, { force = true })')
2007      pack_assert_content('fetch', 'return "fetch new 2"')
2008
2009      -- - Revert lockfile
2010      fn.writefile(vim.split(lockfile_before, '\n'), lock_path)
2011      n.clear()
2012
2013      -- - Revert plugin
2014      pack_assert_content('fetch', 'return "fetch new 2"')
2015      exec_lua('vim.pack.update({ "fetch" }, { target = "lockfile" })')
2016      local confirm_lines = api.nvim_buf_get_lines(0, 0, -1, false)
2017      n.exec('write')
2018      pack_assert_content('fetch', 'return "fetch main"')
2019      eq(hashes.fetch_head, get_lock_tbl().plugins.fetch.rev)
2020
2021      -- - Should mention that new revision comes from *lockfile*
2022      eq(confirm_lines[6], ('Revision before: %s'):format(hashes.fetch_new))
2023      eq(confirm_lines[7], ('Revision after:  %s (*lockfile*)'):format(hashes.fetch_head))
2024    end)
2025
2026    it('can change `src` of installed plugin', function()
2027      local basic_src = repos_src.basic
2028      local defbranch_src = repos_src.defbranch
2029      vim_pack_add({ basic_src })
2030
2031      local function assert_origin(ref)
2032        -- Should be in sync both on disk and in lockfile
2033        local opts = { cwd = pack_get_plug_path('basic') }
2034        local real_origin = n.system_sync({ 'git', 'remote', 'get-url', 'origin' }, opts)
2035        eq(ref, vim.trim(real_origin.stdout))
2036
2037        eq(ref, get_lock_tbl().plugins.basic.src)
2038      end
2039
2040      n.clear()
2041      watch_events({ 'PackChangedPre', 'PackChanged' })
2042
2043      assert_origin(basic_src)
2044      vim_pack_add({ { src = defbranch_src, name = 'basic' } })
2045      -- Should not yet (after `add()`) affect plugin source
2046      assert_origin(basic_src)
2047
2048      -- Should update source immediately (to work if updates are discarded)
2049      exec_lua(function()
2050        vim.pack.update({ 'basic' })
2051      end)
2052      assert_origin(defbranch_src)
2053
2054      -- Should not revert source change even if update is discarded
2055      n.exec('quit')
2056      assert_origin(defbranch_src)
2057      eq({}, exec_lua('return _G.event_log'))
2058
2059      -- Should work with forced update
2060      n.clear()
2061      vim_pack_add({ basic_src })
2062      exec_lua('vim.pack.update({ "basic" }, { force = true })')
2063      assert_origin(basic_src)
2064    end)
2065
2066    it('can do offline update', function()
2067      vim_pack_add({ { src = repos_src.defbranch, version = 'main' } })
2068      track_nvim_echo()
2069
2070      pack_assert_content('defbranch', 'return "defbranch dev"')
2071      n.exec_lua(function()
2072        vim.pack.update({ 'defbranch' }, { offline = true })
2073      end)
2074
2075      -- There should be no progress report about downloading updates
2076      assert_progress_report(nil, 'Computing updates', { 'defbranch' })
2077
2078      n.exec('write')
2079      pack_assert_content('defbranch', 'return "defbranch main"')
2080    end)
2081
2082    it('shows progress report', function()
2083      track_nvim_echo()
2084      vim_pack_add({ repos_src.fetch, repos_src.defbranch })
2085      -- Should also include updates from not active plugins
2086      exec_lua('vim.pack.update()')
2087
2088      -- During initial download
2089      assert_progress_report(nil, 'Downloading updates', { 'fetch', 'defbranch', 'semver' })
2090      exec_lua('_G.echo_log = {}')
2091
2092      -- During application (only for plugins that have updates)
2093      n.exec('write')
2094      assert_progress_report(nil, 'Applying updates', { 'fetch' })
2095
2096      -- During force update
2097      n.clear()
2098      track_nvim_echo()
2099      git_cmd({ 'checkout', 'main' }, 'fetch')
2100      repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch new 3"')
2101      git_add_commit('Commit to be added 3', 'fetch')
2102
2103      vim_pack_add({ repos_src.fetch, repos_src.defbranch })
2104      exec_lua('vim.pack.update(nil, { force = true })')
2105
2106      local echo_log = exec_lua('return _G.echo_log')
2107      local all_plugs = { 'fetch', 'defbranch', 'semver' }
2108      assert_progress_report(vim.list_slice(echo_log, 1, 5), 'Downloading updates', all_plugs)
2109      assert_progress_report(vim.list_slice(echo_log, 6, 8), 'Applying updates', { 'fetch' })
2110      eq(8, #echo_log)
2111    end)
2112
2113    it('triggers relevant events', function()
2114      watch_events({ 'PackChangedPre', 'PackChanged' })
2115      vim_pack_add({ repos_src.fetch, repos_src.defbranch })
2116      exec_lua('_G.event_log = {}')
2117      exec_lua('vim.pack.update()')
2118      eq({}, exec_lua('return _G.event_log'))
2119
2120      -- Should trigger relevant events only for actually updated plugins
2121      n.exec('write')
2122      assert_packchanged({
2123        { 'Pre', 'update', 'fetch', nil, true },
2124        { '', 'update', 'fetch', nil, true },
2125      })
2126    end)
2127
2128    it('sources relevant manifest scripts', function()
2129      vim_pack_add({ repos_src.manifest })
2130      n.clear()
2131
2132      exec_lua(function()
2133        local specs = { { src = repos_src.manifest, version = 'other-branch' } }
2134        vim.pack.add(specs, { load = function() end })
2135      end)
2136
2137      watch_events({ 'PackChangedPre', 'PackChanged' })
2138      track_nvim_echo()
2139      local cwd = fn.getcwd()
2140      exec_lua("vim.pack.update({ 'manifest' }, { force = true })")
2141
2142      -- Should not have side effects after executing script in special context
2143      eq(cwd, fn.getcwd())
2144      local plug_path = pack_get_plug_path('manifest')
2145      eq(false, vim.tbl_contains(api.nvim_list_runtime_paths(), plug_path))
2146
2147      -- Should execute script in special context after triggering events
2148      assert_manifest_scripts(plug_path, {
2149        { event = 'PackChangedPre', kind = 'update' },
2150        { event = 'script', kind = 'preupdate', cwd = plug_path, rtp_has_plug = true },
2151        { event = 'PackChanged', kind = 'update' },
2152        { event = 'script', kind = 'update', cwd = plug_path, rtp_has_plug = true },
2153      })
2154      -- - Should execute update script as it is *after the update*
2155      eq(true, exec_lua('return _G.other_script'))
2156
2157      -- Should warn on errors during script execution
2158      eq(true, is_in_echo_log('Error in preupdate script', 'WarningMsg'))
2159      eq(true, is_in_echo_log('Error in update script', 'WarningMsg'))
2160    end)
2161
2162    it('stashes before applying changes', function()
2163      local fetch_lua_file = vim.fs.joinpath(pack_get_plug_path('fetch'), 'lua', 'fetch.lua')
2164      fn.writefile({ 'A text that will be stashed' }, fetch_lua_file)
2165
2166      vim_pack_add({ repos_src.fetch })
2167      exec_lua('vim.pack.update()')
2168      n.exec('write')
2169
2170      local fetch_path = pack_get_plug_path('fetch')
2171      local stash_list = n.system_sync({ 'git', 'stash', 'list' }, { cwd = fetch_path }).stdout
2172        or ''
2173      matches('vim%.pack: %d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d Stash before checkout', stash_list)
2174
2175      -- Update should still be applied
2176      pack_assert_content('fetch', 'return "fetch new 2"')
2177    end)
2178
2179    it('is not affected by special environment variables', function()
2180      fn.setenv('GIT_WORK_TREE', t.paths.test_source_path)
2181      fn.setenv('GIT_DIR', vim.fs.joinpath(t.paths.test_source_path, '.git'))
2182      local index_path = vim.fs.joinpath(repo_get_path('defbranch'), '.git', 'index')
2183      local index = fn.readblob(index_path)
2184      fn.setenv('GIT_INDEX_FILE', index_path)
2185      local ref_environ = fn.environ()
2186
2187      vim_pack_add({ repos_src.fetch })
2188      exec_lua('vim.pack.update({ "fetch" }, { force = true })')
2189      pack_assert_content('fetch', 'return "fetch new 2"')
2190
2191      eq(ref_environ, fn.environ())
2192      eq(index, fn.readblob(index_path))
2193    end)
2194
2195    it('works with out of sync lockfile', function()
2196      -- Should first autoinstall missing plugin (with confirmation)
2197      n.rmdir(pack_get_plug_path('fetch'))
2198      n.clear()
2199      mock_confirm(1)
2200      exec_lua(function()
2201        vim.pack.update(nil, { force = true })
2202      end)
2203      eq(1, exec_lua('return #_G.confirm_log'))
2204      -- - Should checkout `version='main'` as it says in the lockfile
2205      pack_assert_content('fetch', 'return "fetch new 2"')
2206
2207      -- Should regenerate absent lockfile (from present plugins)
2208      vim.fs.rm(get_lock_path())
2209      n.clear()
2210      exec_lua(function()
2211        vim.pack.update(nil, { force = true })
2212      end)
2213      local lock_plugins = get_lock_tbl().plugins
2214      eq(3, vim.tbl_count(lock_plugins))
2215      -- - Should checkout default branch since `version='main'` info is lost
2216      --   after lockfile is deleted.
2217      eq(nil, lock_plugins.fetch.version)
2218      pack_assert_content('fetch', 'return "fetch dev"')
2219    end)
2220
2221    it("respects 'packlockfile'", function()
2222      n.rmdir(pack_get_dir())
2223      pcall(vim.fs.rm, get_lock_path(), { force = true })
2224
2225      n.clear()
2226      local other_lock_path = get_other_lock_path()
2227      api.nvim_set_option_value('packlockfile', other_lock_path, { scope = 'global' })
2228
2229      exec_lua(function()
2230        vim.pack.add({ repos_src.basic })
2231      end)
2232
2233      eq(true, vim.uv.fs_stat(other_lock_path) ~= nil)
2234      eq(false, vim.uv.fs_stat(get_lock_path()) ~= nil)
2235
2236      n.clear()
2237      api.nvim_set_option_value('packlockfile', other_lock_path, { scope = 'global' })
2238
2239      exec_lua(function()
2240        vim.pack.add({ { src = repos_src.basic, version = 'feat-branch' } })
2241        vim.pack.update({ 'basic' }, { force = true })
2242      end)
2243      pack_assert_content('basic', 'return "basic feat-branch"')
2244      local basic_lock = {
2245        rev = git_get_hash('feat-branch', 'basic'),
2246        src = repos_src.basic,
2247        version = "'feat-branch'",
2248      }
2249      eq({ plugins = { basic = basic_lock } }, vim.json.decode(fn.readblob(other_lock_path)))
2250    end)
2251
2252    it('validates input', function()
2253      local function assert(err_pat, input)
2254        local function update_input()
2255          vim.pack.update(input)
2256        end
2257        matches(err_pat, pcall_err(exec_lua, update_input))
2258      end
2259
2260      assert('list', 1)
2261
2262      -- Should first check if every plugin name represents installed plugin
2263      -- If not - stop early before any update
2264      vim_pack_add({ repos_src.basic })
2265
2266      assert('Plugin `ccc` is not installed', { 'ccc', 'basic', 'aaa' })
2267
2268      -- Empty list is allowed
2269      n.exec('messages clear')
2270      exec_lua(function()
2271        vim.pack.update({})
2272      end)
2273      eq('', n.exec_capture('messages'))
2274    end)
2275  end)
2276
2277  describe('get()', function()
2278    local function make_basic_data(active, info)
2279      local spec = { name = 'basic', src = repos_src.basic, version = 'feat-branch' }
2280      local path = pack_get_plug_path('basic')
2281      local res = { active = active, path = path, spec = spec }
2282      if info then
2283        res.branches = { 'main', 'feat-branch' }
2284        res.rev = git_get_hash('feat-branch', 'basic')
2285        res.rev_to = res.rev
2286        res.tags = { 'some-tag' }
2287      else
2288        res.rev = get_lock_tbl().plugins.basic.rev
2289      end
2290      return res
2291    end
2292
2293    local function make_defbranch_data(active, info)
2294      local spec = { name = 'defbranch', src = repos_src.defbranch }
2295      local path = pack_get_plug_path('defbranch')
2296      local res = { active = active, path = path, spec = spec }
2297      if info then
2298        res.branches = { 'dev', 'main' }
2299        res.rev = git_get_hash('dev', 'defbranch')
2300        res.rev_to = res.rev
2301        res.tags = {}
2302      else
2303        res.rev = get_lock_tbl().plugins.defbranch.rev
2304      end
2305      return res
2306    end
2307
2308    local function make_plugindirs_data(active, info)
2309      local spec =
2310        { name = 'plugindirs', src = repos_src.plugindirs, version = vim.version.range('*') }
2311      local path = pack_get_plug_path('plugindirs')
2312      local res = { active = active, path = path, spec = spec }
2313      if info then
2314        res.branches = { 'main' }
2315        res.rev = git_get_hash('v0.0.1', 'plugindirs')
2316        res.rev_to = res.rev
2317        res.tags = { 'v0.0.1' }
2318      else
2319        res.rev = get_lock_tbl().plugins.plugindirs.rev
2320      end
2321      return res
2322    end
2323
2324    it('returns list with necessary data', function()
2325      local basic_data, defbranch_data, plugindirs_data
2326
2327      -- Should work just after installation
2328      exec_lua(function()
2329        vim.pack.add({
2330          repos_src.defbranch,
2331          { src = repos_src.basic, version = 'feat-branch' },
2332          { src = repos_src.plugindirs, version = vim.version.range('*') },
2333        })
2334      end)
2335      defbranch_data = make_defbranch_data(true, true)
2336      basic_data = make_basic_data(true, true)
2337      plugindirs_data = make_plugindirs_data(true, true)
2338      -- Should preserve order in which plugins were `vim.pack.add()`ed
2339      eq({ defbranch_data, basic_data, plugindirs_data }, exec_lua('return vim.pack.get()'))
2340
2341      -- Should also list non-active plugins and use proper source for `rev`
2342      local lock_tbl = get_lock_tbl()
2343      lock_tbl.plugins.defbranch.rev = 'aaa'
2344      lock_tbl.plugins.basic.rev = 'bbb'
2345      lock_tbl.plugins.plugindirs.rev = 'ccc'
2346      local lockfile_text = vim.json.encode(lock_tbl, { indent = '  ', sort_keys = true })
2347      fn.writefile(vim.split(lockfile_text, '\n'), get_lock_path())
2348      n.clear()
2349
2350      vim_pack_add({ repos_src.defbranch })
2351      defbranch_data = make_defbranch_data(true, true)
2352      basic_data = make_basic_data(false, true)
2353      plugindirs_data = make_plugindirs_data(false, true)
2354
2355      -- Should first list active, then non-active (including their latest
2356      -- set `version` which is inferred from lockfile)
2357      eq({ defbranch_data, basic_data, plugindirs_data }, exec_lua('return vim.pack.get()'))
2358
2359      -- Should respect `names` for both active and not active plugins
2360      eq({ basic_data }, exec_lua('return vim.pack.get({ "basic" })'))
2361      eq({ defbranch_data }, exec_lua('return vim.pack.get({ "defbranch" })'))
2362      eq({ basic_data, defbranch_data }, exec_lua('return vim.pack.get({ "basic", "defbranch" })'))
2363
2364      local bad_get_cmd = 'return vim.pack.get({ "ccc", "basic", "aaa" })'
2365      matches('Plugin `ccc` is not installed', pcall_err(exec_lua, bad_get_cmd))
2366
2367      -- Should respect `opts.info`
2368      defbranch_data = make_defbranch_data(true, false)
2369      basic_data = make_basic_data(false, false)
2370      plugindirs_data = make_plugindirs_data(false, false)
2371      eq(
2372        { defbranch_data, basic_data, plugindirs_data },
2373        exec_lua('return vim.pack.get(nil, { info = false })')
2374      )
2375      eq({ basic_data }, exec_lua('return vim.pack.get({ "basic" }, { info = false })'))
2376      eq({ defbranch_data }, exec_lua('return vim.pack.get({ "defbranch" }, { info = false })'))
2377
2378      -- Reports manifest
2379      vim_pack_add({ repos_src.manifest })
2380      local manifest_tbl = {
2381        name = 'plug',
2382        description = 'Nvim plugin',
2383        engine = { nvim = '>=0.12.0', vim = '>=9.1.0' },
2384        scripts = {
2385          install = 'scripts/install.lua',
2386          preupdate = 'scripts/preupdate.vim',
2387          update = 'scripts/update.lua',
2388          preuninstall = 'scirpts/preuninstall.vim',
2389        },
2390      }
2391      eq(manifest_tbl, exec_lua('return vim.pack.get({ "manifest" })[1].manifest'))
2392    end)
2393
2394    it('reports potential revision after update', function()
2395      -- Install and set up different version without running `vim.pack.update()`
2396      vim_pack_add({ repos_src.defbranch, { src = repos_src.basic, version = 'feat-branch' } })
2397      pack_assert_content('defbranch', 'return "defbranch dev"')
2398      pack_assert_content('basic', 'return "basic feat-branch"')
2399
2400      n.clear()
2401      vim_pack_add({ { src = repos_src.defbranch, version = 'main' }, repos_src.basic })
2402      n.clear()
2403
2404      -- Should report correct `rev_to` with active and not active plugins
2405      vim_pack_add({ { src = repos_src.defbranch, version = 'main' } })
2406      local defbranch_data = make_defbranch_data(true, true)
2407      defbranch_data.spec.version = 'main'
2408      defbranch_data.rev_to = git_get_hash('main', 'defbranch')
2409      local basic_data = make_basic_data(false, true)
2410      basic_data.spec.version = nil
2411      basic_data.rev_to = git_get_hash('main', 'basic')
2412
2413      eq({ defbranch_data, basic_data }, exec_lua('return vim.pack.get()'))
2414    end)
2415
2416    describe('opts.offline', function()
2417      after_each(function()
2418        n.rmdir(repo_get_path('fetch'))
2419      end)
2420
2421      it('can fetch new updates', function()
2422        -- Create a dedicated clean repo for which "push changes" will be mocked
2423        init_test_repo('fetch')
2424
2425        repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch init"')
2426        git_add_commit('Initial commit', 'fetch')
2427
2428        local fetch_head = git_get_hash('HEAD', 'fetch')
2429
2430        -- Install initial versions of tested plugins
2431        vim_pack_add({ repos_src.fetch })
2432
2433        -- Mock remote repo update
2434        -- - Force push
2435        repo_write_file('fetch', 'lua/fetch.lua', 'return "fetch new"')
2436        git_cmd({ 'add', '*' }, 'fetch')
2437        git_cmd({ 'commit', '--amend', '-m', 'Second commit' }, 'fetch')
2438        local fetch_new = git_get_hash('HEAD', 'fetch')
2439        t.neq(fetch_head, fetch_new)
2440
2441        -- Should not fetch new data with `offline=true` (default)
2442        -- or if `info=false`
2443        local spec = { name = 'fetch', src = repos_src.fetch }
2444        local path = pack_get_plug_path('fetch')
2445        local fetch_data = { active = true, path = path, spec = spec }
2446        fetch_data.branches = { 'main' }
2447        fetch_data.tags = {}
2448        fetch_data.rev = fetch_head
2449        fetch_data.rev_to = fetch_head
2450
2451        exec_lua('vim.pack.get(nil, { info = false, offline = false })')
2452        eq({ fetch_data }, exec_lua('return vim.pack.get()'))
2453
2454        -- Should fetch new data with `offline=false`
2455        fetch_data.rev_to = fetch_new
2456        eq({ fetch_data }, exec_lua('return vim.pack.get(nil, { offline = false })'))
2457
2458        -- Should keep using already fetched data with `offline=true`
2459        eq({ fetch_data }, exec_lua('return vim.pack.get(nil, {})'))
2460      end)
2461    end)
2462
2463    it('respects `data` field', function()
2464      vim_pack_add({
2465        { src = repos_src.basic, version = 'feat-branch', data = { test = 'value' } },
2466        { src = repos_src.defbranch, data = 'value' },
2467      })
2468      local out = exec_lua(function()
2469        local plugs = vim.pack.get()
2470        ---@type table<string,string>
2471        return { basic = plugs[1].spec.data.test, defbranch = plugs[2].spec.data }
2472      end)
2473      eq({ basic = 'value', defbranch = 'value' }, out)
2474    end)
2475
2476    it('works with `del()`', function()
2477      vim_pack_add({ repos_src.defbranch, { src = repos_src.basic, version = 'feat-branch' } })
2478
2479      exec_lua(function()
2480        _G.get_log = {}
2481        vim.api.nvim_create_autocmd({ 'PackChangedPre', 'PackChanged' }, {
2482          callback = function()
2483            table.insert(_G.get_log, vim.pack.get())
2484          end,
2485        })
2486      end)
2487
2488      -- Should not include removed plugins immediately after they are removed,
2489      -- while still returning list without holes
2490      local defbranch_data = make_defbranch_data(true, true)
2491      local basic_data = make_basic_data(true, true)
2492      exec_lua('vim.pack.del({ "defbranch" }, { force = true })')
2493      eq({ { defbranch_data, basic_data }, { basic_data } }, exec_lua('return _G.get_log'))
2494    end)
2495
2496    it('works with out of sync lockfile', function()
2497      vim_pack_add({ repos_src.basic, repos_src.defbranch })
2498      eq(2, vim.tbl_count(get_lock_tbl().plugins))
2499
2500      -- Should first autoinstall missing plugin (with confirmation)
2501      n.rmdir(pack_get_plug_path('basic'))
2502      n.clear()
2503      mock_confirm(1)
2504      eq(2, exec_lua('return #vim.pack.get()'))
2505
2506      eq(1, exec_lua('return #_G.confirm_log'))
2507      pack_assert_content('basic', 'return "basic main"')
2508
2509      -- Should regenerate absent lockfile (from present plugins)
2510      vim.fs.rm(get_lock_path())
2511      n.clear()
2512      eq(2, exec_lua('return #vim.pack.get()'))
2513      eq(2, vim.tbl_count(get_lock_tbl().plugins))
2514    end)
2515
2516    it("respects 'packlockfile'", function()
2517      n.rmdir(pack_get_dir())
2518      pcall(vim.fs.rm, get_lock_path(), { force = true })
2519
2520      n.clear()
2521      local other_lock_path = get_other_lock_path()
2522      api.nvim_set_option_value('packlockfile', other_lock_path, { scope = 'global' })
2523
2524      exec_lua(function()
2525        vim.pack.add({ { src = repos_src.basic, version = 'feat-branch' } })
2526      end)
2527
2528      local basic_data = make_basic_data(true, true)
2529      eq({ basic_data }, exec_lua('return vim.pack.get()'))
2530      eq(false, vim.uv.fs_stat(get_lock_path()) ~= nil)
2531    end)
2532  end)
2533
2534  describe('del()', function()
2535    it('works', function()
2536      local basic_spec = { src = repos_src.basic, version = 'feat-branch' }
2537      vim_pack_add({ repos_src.plugindirs, repos_src.defbranch, basic_spec })
2538
2539      local assert_on_disk = function(installed_map)
2540        local installed = {}
2541        for p_name, is_installed in pairs(installed_map) do
2542          eq(is_installed, pack_exists(p_name))
2543          if is_installed then
2544            installed[#installed + 1] = p_name
2545          end
2546        end
2547
2548        table.sort(installed)
2549        local locked = vim.tbl_keys(get_lock_tbl().plugins)
2550        table.sort(locked)
2551        eq(installed, locked)
2552      end
2553
2554      assert_on_disk({ basic = true, defbranch = true, plugindirs = true })
2555
2556      -- By default should delete only non-active plugins, even if
2557      -- there is active one among input plugin names
2558      n.clear()
2559      vim_pack_add({ repos_src.defbranch })
2560      watch_events({ 'PackChangedPre', 'PackChanged' })
2561
2562      local err = pcall_err(exec_lua, function()
2563        vim.pack.del({ 'basic', 'defbranch', 'plugindirs' })
2564      end)
2565      matches('Some plugins are active and were not deleted: defbranch', err)
2566
2567      assert_on_disk({ basic = false, defbranch = true, plugindirs = false })
2568
2569      local msg = 'vim.pack: Removed plugins: basic, plugindirs'
2570      eq(msg, n.exec_capture('messages'))
2571
2572      -- Should trigger relevant events in order as specified in `vim.pack.add()`
2573      assert_packchanged({
2574        { 'Pre', 'delete', 'basic', 'feat-branch', false },
2575        { 'Pre', 'delete', 'defbranch', nil, true },
2576        { 'Pre', 'delete', 'plugindirs', nil, false },
2577        { '', 'delete', 'basic', 'feat-branch', false },
2578        { '', 'delete', 'plugindirs', nil, false },
2579      })
2580      exec_lua('_G.event_log = {}')
2581
2582      -- `:packdel` should output E5810 instead of the normal error
2583      eq(
2584        'Vim(packdel):E5810: Some plugins are active and were not deleted: defbranch',
2585        pcall_err(n.command, 'packdel defbranch')
2586      )
2587      assert_on_disk({ defbranch = true })
2588      assert_packchanged({ { 'Pre', 'delete', 'defbranch', nil, true } })
2589
2590      -- Should be possible to force delete active plugins
2591      n.exec('messages clear')
2592      exec_lua('_G.event_log = {}')
2593      exec_lua(function()
2594        vim.pack.del({ 'defbranch' }, { force = true })
2595      end)
2596
2597      eq('vim.pack: Removed plugin: defbranch', n.exec_capture('messages'))
2598
2599      assert_on_disk({ basic = false, defbranch = false, plugindirs = false })
2600      assert_packchanged({
2601        { 'Pre', 'delete', 'defbranch', nil, true },
2602        { '', 'delete', 'defbranch', nil, false },
2603      })
2604    end)
2605
2606    it('works without prior `add()`', function()
2607      vim_pack_add({ repos_src.basic })
2608      n.clear()
2609
2610      eq(true, pack_exists('basic'))
2611      exec_lua(function()
2612        vim.pack.del({ 'basic' })
2613      end)
2614      eq(false, pack_exists('basic'))
2615      eq({ plugins = {} }, get_lock_tbl())
2616    end)
2617
2618    it('works with out of sync lockfile', function()
2619      vim_pack_add({ repos_src.basic, repos_src.defbranch, repos_src.plugindirs })
2620      eq(3, vim.tbl_count(get_lock_tbl().plugins))
2621
2622      -- Should first autoinstall missing plugin (with confirmation)
2623      n.rmdir(pack_get_plug_path('basic'))
2624      n.clear()
2625      mock_confirm(1)
2626      exec_lua('vim.pack.del({ "defbranch" })')
2627
2628      eq(1, exec_lua('return #_G.confirm_log'))
2629      eq(true, pack_exists('basic'))
2630      eq(false, pack_exists('defbranch'))
2631      eq(true, pack_exists('plugindirs'))
2632
2633      -- Should regenerate absent lockfile (from present plugins)
2634      vim.fs.rm(get_lock_path())
2635      n.clear()
2636      exec_lua('vim.pack.del({ "basic" })')
2637      eq(1, exec_lua('return #vim.pack.get()'))
2638      eq({ 'plugindirs' }, vim.tbl_keys(get_lock_tbl().plugins))
2639    end)
2640
2641    it("respects 'packlockfile'", function()
2642      n.rmdir(pack_get_dir())
2643      pcall(vim.fs.rm, get_lock_path(), { force = true })
2644
2645      n.clear()
2646      local other_lock_path = vim.fs.joinpath(fn.stdpath('data'), 'test-pack-lock')
2647      api.nvim_set_option_value('packlockfile', other_lock_path, { scope = 'global' })
2648
2649      exec_lua(function()
2650        vim.pack.add({ repos_src.basic })
2651      end)
2652
2653      exec_lua('vim.pack.del({ "basic" }, { force = true })')
2654      eq({ plugins = {} }, vim.json.decode(fn.readblob(other_lock_path)))
2655      eq(false, pack_exists('basic'))
2656      eq(false, vim.uv.fs_stat(get_lock_path()) ~= nil)
2657    end)
2658
2659    it('sources relevant manifest scripts', function()
2660      vim_pack_add({ repos_src.manifest })
2661      n.clear()
2662
2663      watch_events({ 'PackChangedPre', 'PackChanged' })
2664      track_nvim_echo()
2665      local cwd = fn.getcwd()
2666      exec_lua("vim.pack.del({ 'manifest' })")
2667
2668      -- Should not have side effects after executing script in special context
2669      eq(cwd, fn.getcwd())
2670      local plug_path = pack_get_plug_path('manifest')
2671      eq(false, vim.tbl_contains(api.nvim_list_runtime_paths(), plug_path))
2672
2673      -- Should execute script in special context after triggering events
2674      assert_manifest_scripts(plug_path, {
2675        { event = 'PackChangedPre', kind = 'delete' },
2676        { event = 'script', kind = 'preuninstall', cwd = plug_path, rtp_has_plug = true },
2677        { event = 'PackChanged', kind = 'delete' },
2678      })
2679
2680      -- Should warn on errors during script execution
2681      eq(true, is_in_echo_log('Error in preuninstall script', 'WarningMsg'))
2682    end)
2683
2684    it('validates input', function()
2685      local function assert(err_pat, input)
2686        local function del_input()
2687          vim.pack.del(input)
2688        end
2689        matches(err_pat, pcall_err(exec_lua, del_input))
2690      end
2691
2692      assert('list', nil)
2693
2694      -- Should first check if every plugin name represents installed plugin
2695      -- If not - stop early before any delete
2696      vim_pack_add({ repos_src.basic })
2697
2698      assert('Plugin `ccc` is not installed', { 'ccc', 'basic', 'aaa' })
2699      eq(true, pack_exists('basic'))
2700
2701      -- Empty list is allowed
2702      n.exec('messages clear')
2703      exec_lua(function()
2704        vim.pack.del({})
2705      end)
2706      eq('', n.exec_capture('messages'))
2707    end)
2708  end)
2709end)