8000 mini.nvim/lua/mini/deps.lua at main · td0m/mini.nvim · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
1626 lines (1436 loc) · 62.6 KB

deps.lua

File metadata and controls

1626 lines (1436 loc) · 62.6 KB
table.insert(H.session, p)
-- Add to 'runtimepath'
vim.cmd(cmd .. p.name)
end
-- Execute 'after/' scripts if not during startup (when they will be sourced
-- automatically), as `:packadd` only sources plain 'plugin/' files.
-- See https://github.com/vim/vim/issues/1994.
-- Deliberately do so after executing all currently known 'plugin/' files.
local should_load_after_dir = vim.v.vim_did_enter == 1 and not opts.bang and vim.o.loadplugins
if not should_load_after_dir then return end
for _, p in ipairs(plugs) do
-- NOTE: This sources first lua and then vim, not how it is done during
-- startup (`:h loadplugins`) for speed (one `glob()` instead of two).
local after_paths = vim.fn.glob(p.path .. '/after/plugin/**/*.{vim,lua}', false, true)
vim.tbl_map(H.source, after_paths)
end
end
--- Update plugins
---
--- - Synchronize specs with state of plugins on disk (set `source`, etc.).
--- - Infer data before downloading updates.
--- - If not offline, download updates (in parallel).
--- - Infer data after downloading updates.
--- - If update is forced, apply all changes immediately while updating log
--- file (at `config.path.log`; use |:DepsShowLog| to review).
--- Otherwise show confirmation buffer with instructions on how to proceed.
---
---@param names table|nil Array of plugin names to update.
--- Default: all plugins from current session (see |MiniDeps.get_session()|).
---@param opts table|nil Options. Possible fields:
--- - <force> `(boolean)` - whether to force update without confirmation.
--- Default: `false`.
--- - <offline> `(boolean)` - whether to skip downloading updates from sources.
--- Default: `false`.
MiniDeps.update = function(names, opts)
opts = vim.tbl_deep_extend('force', { force = false, offline = false }, opts or {})
-- Compute array of plugin data to be reused in update. Each contains a CLI
-- job "assigned" to plugin's path which stops execution after first error.
local plugs = H.plugs_from_names(names)
if #plugs == 0 then return H.notify('Nothing to update') end
-- Prepare repositories and specifications
H.ensure_git_exec()
H.plugs_ensure_origin_source(plugs)
-- Preprocess before downloading
H.plugs_infer_head(plugs)
H.plugs_ensure_target_refs(plugs)
H.plugs_infer_commit(plugs, 'monitor', 'monitor_from')
-- Download data if asked
if not opts.offline then H.plugs_download_updates(plugs) end
-- Process data for update
H.plugs_infer_commit(plugs, 'checkout', 'checkout_to')
H.plugs_infer_commit(plugs, 'monitor', 'monitor_to')
H.plugs_infer_log(plugs, 'head', 'checkout_to', 'checkout_log')
H.plugs_infer_log(plugs, 'monitor_from', 'monitor_to', 'monitor_log')
-- Checkout if asked (before feedback to include possible checkout errors)
if opts.force then H.plugs_checkout(plugs) end
-- Make feedback
local lines = H.update_compute_feedback_lines(plugs)
local feedback = opts.force and H.update_feedback_log or H.update_feedback_confirm
feedback(lines)
-- Show job warnings and errors
H.plugs_show_job_notifications(plugs, 'update')
end
--- Clean plugins
---
--- - Compute absent plugins: not registered in current session
--- (see |MiniDeps.get_session()|) but present on disk in dedicated "pack/deps"
--- package (inside `config.path.package`).
--- - If cleaning is forced, delete all absent plugins from disk.
--- Otherwise show confirmation buffer with instructions on how to proceed.
---
---@param opts table|nil Options. Possible fields:
--- - <force> `(boolean)` - whether to force delete without confirmation.
--- Default: `false`.
MiniDeps.clean = function(opts)
opts = vim.tbl_deep_extend('force', { force = false }, opts or {})
-- Compute path candidates to delete
local is_in_session = {}
for _, s in ipairs(MiniDeps.get_session()) do
is_in_session[s.path] = true
end
local is_absent_plugin = function(x) return vim.fn.isdirectory(x) == 1 and not is_in_session[x] end
local absent_paths = vim.tbl_filter(is_absent_plugin, H.get_all_plugin_paths())
-- Clean
if #absent_paths == 0 then return H.notify('Nothing to clean') end
local clean_fun = opts.force and H.clean_delete or H.clean_confirm
clean_fun(absent_paths)
end
--- Compute snapshot
---
---@return table A snapshot table: plugin names as keys and state as values.
--- All plugins in current session are processed.
MiniDeps.snap_get = function()
local plugs = H.plugs_from_names()
H.ensure_git_exec()
H.plugs_infer_head(plugs)
H.plugs_show_job_notifications(plugs, 'computing snapshot')
local snap = {}
for _, p in ipairs(plugs) do
if p.head ~= '' then snap[p.name] = p.head end
end
return snap
end
--- Apply snapshot
---
--- Notes:
--- - Checking out states from snapshot does not update session plugin spec
--- (`checkout` field in particular). Among others, it means that next call
--- to |MiniDeps.update()| might override the result of this function.
--- To make changes permanent, set `checkout` spec field to state from snapshot.
---
---@param snap table A snapshot table: plugin names as keys and state as values.
--- Only plugins in current session are processed.
MiniDeps.snap_set = function(snap)
if type(snap) ~= 'table' then H.error('Snapshot should be a table.') end
-- Construct current session plugin data with `checkout` from snapshot
for k, v in pairs(snap) do
if not (type(k) == 'string' and type(v) == 'string') then snap[k] = nil end
end
local plugs = H.plugs_from_names(vim.tbl_keys(snap))
for _, p in ipairs(plugs) do
p.checkout = snap[p.name]
end
-- Checkout
H.ensure_git_exec()
H.plugs_checkout(plugs)
H.plugs_show_job_notifications(plugs, 'applying snapshot')
end
--- Save snapshot
---
---@param path string|nil A valid path on disk where to write snapshot computed
--- with |MiniDeps.snap_get()|.
--- Default: `config.path.snapshot`.
MiniDeps.snap_save = function(path)
path = path or H.full_path(H.get_config().path.snapshot)
if type(path) ~= 'string' then H.error('`path` should be string.') end
-- Compute snapshot
local snap = MiniDeps.snap_get()
-- Write snapshot
local lines = vim.split(vim.inspect(snap), '\n')
lines[1] = 'return ' .. lines[1]
vim.fn.mkdir(vim.fn.fnamemodify(path, ':h'), 'p')
vim.fn.writefile(lines, path)
H.notify('Created snapshot at ' .. vim.inspect(path))
end
--- Load snapshot file
---
--- Notes from |MiniDeps.snap_set()| also apply here.
---
---@param path string|nil A valid path on disk from where to read snapshot.
--- Default: `config.path.snapshot`.
MiniDeps.snap_load = function(path)
path = path or H.full_path(H.get_config().path.snapshot)
if vim.fn.filereadable(path) ~= 1 then H.error('`path` should be path to a readable file.') end
local ok, snap = pcall(dofile, H.full_path(path))
if not (ok and type(snap) == 'table') then H.error('`path` is not a path to proper snapshot.') end
MiniDeps.snap_set(snap)
end
--- Get session
---
--- Plugin is registered in current session if it either:
--- - Was added with |MiniDeps.add()| (preserving order of calls).
--- - Is a "start" plugin and present in 'runtimpath'.
---
---@return session table Array with specifications of all plugins registered in
--- current session.
MiniDeps.get_session = function()
-- Normalize `H.session` allowing specs for same plugin
local res, plugin_ids = {}, {}
local add_spec = function(spec)
local id = plugin_ids[spec.path] or (#res + 1)
-- Treat `depends` differently as it is an array and direct merge is bad
-- Also: https://github.com/neovim/neovim/pull/15094#discussion_r671663938
local depends = vim.deepcopy((res[id] or {}).depends or {})
vim.list_extend(depends, spec.depends or {})
res[id] = vim.tbl_deep_extend('force', res[id] or {}, spec)
res[id].depends = depends
plugin_ids[spec.path] = id
end
vim.tbl_map(add_spec, H.session)
H.session = res
-- Add 'start/' plugins that are in 'rtp'. NOTE: not whole session concept is
-- built around presence in 'rtp' to 100% ensure to preserve the order in
-- which user called `add()`.
local start_path = H.full_path(H.get_package_path() .. '/pack/deps/start')
local pattern = string.format('^%s/([^/]+)$', vim.pesc(start_path))
for _, runtime_path in ipairs(vim.api.nvim_list_runtime_paths()) do
-- Make sure plugin path is normalized (matters on Windows)
local path = H.full_path(runtime_path)
local name = string.match(path, pattern)
if name ~= nil then add_spec({ path = path, name = name, hooks = {}, depends = {} }) end
end
-- Return copy to not allow modification in place
return vim.deepcopy(res)
end
--- Execute function now
---
--- Safely execute function immediately. Errors are shown with |vim.notify()|
--- later, after all queued functions (including with |MiniDeps.later()|)
--- are executed, thus not blocking execution of next code in file.
---
--- Assumed to be used as a first step during two-stage config execution to
--- load plugins immediately during startup. See |MiniDeps-overview|.
---
---@param f function Callable to execute.
MiniDeps.now = function(f)
local ok, err = pcall(f)
if not ok then table.insert(H.cache.exec_errors, err) end
H.schedule_finish()
end
--- Execute function later
---
--- Queue function to be safely executed later without blocking execution of
--- next code in file. All queued functions are guaranteed to be executed in
--- order they were added.
--- Errors are shown with |vim.notify()| after all queued functions are executed.
---
--- Assumed to be used as a second step during two-stage config execution to
--- load plugins "lazily" after startup. See |MiniDeps-overview|.
---
---@param f function Callable to execute.
MiniDeps.later = function(f)
table.insert(H.cache.later_callback_queue, f)
H.schedule_finish()
end
-- Helper data ================================================================
-- Module default config
H.default_config = MiniDeps.config
-- Array of plugin specs
H.session = {}
-- Various cache
H.cache = {
-- Whether finish of `now()` or `later()` is already scheduled
finish_is_scheduled = false,
-- Callback queue for `later()`
later_callback_queue = {},
-- Errors during execution of `now()` or `later()`
exec_errors = {},
-- Git version
git_version = nil,
}
-- Buffer name counts
H.buf_name_counts = {}
-- Helper functionality =======================================================
-- Settings -------------------------------------------------------------------
H.setup_config = function(config)
-- General idea: if some table elements are not present in user-supplied
-- `config`, take them from default config
vim.validate({ config = { config, 'table', true } })
config = vim.tbl_deep_extend('force', vim.deepcopy(H.default_config), config or {})
vim.validate({
job = { config.job, 'table' },
path = { config.path, 'table' },
silent = { config.silent, 'boolean' },
})
vim.validate({
['job.n_threads'] = { config.job.n_threads, 'number', true },
['job.timeout'] = { config.job.timeout, 'number' },
['path.package'] = { config.path.package, 'string' },
['path.snapshot'] = { config.path.snapshot, 'string' },
['path.log'] = { config.path.log, 'string' },
})
return config
end
H.apply_config = function(config)
MiniDeps.config = config
-- Reset current session to allow resourcing script with `setup()` call
H.session = {}
-- Add target package path to 'packpath'
local pack_path = H.full_path(config.path.package)
vim.cmd('set packpath^=' .. vim.fn.fnameescape(pack_path))
end
H.get_config = function(config)
return vim.tbl_deep_extend('force', MiniDeps.config, vim.b.minideps_config or {}, config or {})
end
H.create_autocommands = function()
local gr = vim.api.nvim_create_augroup('MiniDeps', {})
vim.api.nvim_create_autocmd('ColorScheme', { group = gr, callback = H.create_default_hl, desc = 'Ensure colors' })
end
--stylua: ignore
H.create_default_hl = function()
local hi = function(name, opts)
opts.default = true
vim.api.nvim_set_hl(0, name, opts)
end
local has_core_diff_hl = vim.fn.has('nvim-0.10') == 1
hi('MiniDepsChangeAdded', { link = has_core_diff_hl and 'Added' or 'diffAdded' })
hi('MiniDepsChangeRemoved', { link = has_core_diff_hl and 'Removed' or 'diffRemoved' })
hi('MiniDepsHint', { link = 'DiagnosticHint' })
hi('MiniDepsInfo', { link = 'DiagnosticInfo' })
hi('MiniDepsMsgBreaking', { link = 'DiagnosticWarn' })
hi('MiniDepsPlaceholder', { link = 'Comment' })
hi('MiniDepsTitle', { link = 'Title' })
hi('MiniDepsTitleError', { link = 'DiffDelete' })
hi('MiniDepsTitleSame', { link = 'DiffText' })
hi('MiniDepsTitleUpdate', { link = 'DiffAdd' })
end
H.create_user_commands = function()
-- Do not create commands immediately to increase startup time
local new_cmd = vim.schedule_wrap(vim.api.nvim_create_user_command)
local complete_session_names = function(arg, _, _)
local session_names = vim.tbl_map(function(s) return s.name end, MiniDeps.get_session())
return vim.tbl_filter(function(n) return vim.startswith(n, arg) end, session_names)
end
local complete_disk_names = function(arg, _, _)
local disk_names = vim.tbl_map(function(p) return vim.fn.fnamemodify(p, ':t') end, H.get_all_plugin_paths())
return vim.tbl_filter(function(n) return vim.startswith(n, arg) end, disk_names)
end
local add = function(input) MiniDeps.add(input.fargs[1]) end
new_cmd('DepsAdd', add, { nargs = '+', complete = complete_disk_names, desc = 'Add plugin to session' })
local make_update_cmd = function(name, offline, desc)
local callback = function(input)
local names
if #input.fargs > 0 then names = input.fargs end
MiniDeps.update(names, { force = input.bang, offline = offline })
end
local opts = { bang = true, complete = complete_session_names, nargs = '*', desc = desc }
new_cmd(name, callback, opts)
end
make_update_cmd('DepsUpdate', false, 'Update plugins')
make_update_cmd('DepsUpdateOffline', true, 'Update plugins without downloading from source')
local show_log = function()
vim.cmd('edit ' .. vim.fn.fnameescape(H.get_config().path.log))
H.update_add_syntax()
vim.cmd([[syntax match MiniDepsTitle "^\(==========\).*\1$"]])
end
new_cmd('DepsShowLog', show_log, { desc = 'Show log' })
local clean = function(input) MiniDeps.clean({ force = input.bang }) end
new_cmd('DepsClean', clean, { bang = true, desc = 'Delete unused plugins' })
local snap_save = function(input) MiniDeps.snap_save(input.fargs[1]) end
new_cmd('DepsSnapSave', snap_save, { nargs = '*', complete = 'file', desc = 'Save plugin snapshot' })
local snap_load = function(input) MiniDeps.snap_load(input.fargs[1]) end
new_cmd('DepsSnapLoad', snap_load, { nargs = '*', complete = 'file', desc = 'Load plugin snapshot' })
end
-- Git commands ---------------------------------------------------------------
H.git_cmd = function(cmd_name, ...)
local args = H.git_args[cmd_name](...)
if args == nil then return {} end
-- Use '-c gc.auto=0' to disable `stderr` "Auto packing..." messages
return { 'git', '-c', 'gc.auto=0', unpack(args) }
end
--stylua: ignore
H.git_args = {
version = function()
return { 'version' }
end,
clone = function(source, path)
local res = {
'clone', '--quiet', '--filter=blob:none',
'--recurse-submodules', '--also-filter-submodules', '--origin', 'origin',
source, path,
}
-- Use `--also-filter-submodules` only with appropriate version
if not (H.cache.git_version.major >= 2 and H.cache.git_version.minor >= 36) then
table.remove(res, 5)
end
return res
end,
stash = function(timestamp)
return { 'stash', '--quiet', '--message', '(mini.deps) ' .. timestamp .. ' Stash before checkout' }
end,
checkout = function(target)
return { 'checkout', '--quiet', target }
end,
-- Using '--tags --force' means conflicting tags will be synced with remote
fetch = function()
return { 'fetch', '--quiet', '--tags', '--force', '--recurse-submodules=yes', 'origin' }
end,
set_origin = function(source)
return { 'remote', 'set-url', 'origin', source }
end,
get_origin = function()
return { 'remote', 'get-url', 'origin' }
end,
get_default_origin_branch = function()
return { 'rev-parse', '--abbrev-ref', 'origin/HEAD' }
end,
is_origin_branch = function(name)
-- Returns branch's name if it is present
return { 'branch', '--list', '--all', '--format=%(refname:short)', 'origin/' .. name }
end,
-- Using `rev-list -1` shows a commit of revision, while `rev-parse` shows
-- hash of revision. Those are different for annotated tags.
get_hash = function(rev)
return { 'rev-list', '-1', rev }
end,
log = function(from, to)
if from == nil or to == nil or from == to then return nil end
-- `--topo-order` makes showing divergent branches nicer
-- `--decorate-refs` shows only tags near commits (not `origin/main`, etc.)
--stylua: ignore
return {
'log', '--pretty=format:%m %h | %ai | %an%d%n %s%n', '--topo-order', '--decorate-refs=refs/tags',
from .. '...' .. to,
}
end,
}
H.ensure_git_exec = function()
if H.cache.git_version ~= nil then return end
local jobs = { H.cli_new_job(H.git_cmd('version'), vim.fn.getcwd()) }
H.cli_run(jobs)
if #jobs[1].err > 0 then H.error('Could not find executable `git` CLI tool') end
local major, minor = string.match(H.cli_stream_tostring(jobs[1].out), '(%d+)%.(%d+)')
H.cache.git_version = { major = tonumber(major), minor = tonumber(minor) }
end
-- Plugin specification -------------------------------------------------------
H.expand_spec = function(target, spec)
-- Prepare
if type(spec) == 'string' then
local field = string.find(spec, '/') ~= nil and 'source' or 'name'
spec = { [field] = spec }
end
if type(spec) ~= 'table' then H.error('Plugin spec should be table.') end
local has_min_fields = type(spec.source) == 'string' or type(spec.name) == 'string'
if not has_min_fields then H.error('Plugin spec should have proper `source` or `name`.') end
-- Normalize
spec = vim.deepcopy(spec)
if spec.source and type(spec.source) ~= 'string' then H.error('`source` in plugin spec should be string.') end
local is_user_repo = type(spec.source) == 'string' and spec.source:find('^[%w-]+/[%w-_.]+$') ~= nil
if is_user_repo then spec.source = 'https://github.com/' .. spec.source end
spec.name = spec.name or vim.fn.fnamemodify(spec.source, ':t')
if type(spec.name) ~= 'string' then H.error('`name` in plugin spec should be string.') end
if string.find(spec.name, '/') ~= nil then H.error('`name` in plugin spec should not contain "/".') end
if spec.name == '' then H.error('`name` in plugin spec should not be empty.') end
if spec.checkout and type(spec.checkout) ~= 'string' then H.error('`checkout` in plugin spec should be string.') end
if spec.monitor and type(spec.monitor) ~= 'string' then H.error('`monitor` in plugin spec should be string.') end
spec.hooks = vim.deepcopy(spec.hooks) or {}
if type(spec.hooks) ~= 'table' then H.error('`hooks` in plugin spec should be table.') end
local hook_names = { 'pre_install', 'post_install', 'pre_checkout', 'post_checkout' }
0