diff --git a/lua/packer.lua b/lua/packer.lua index a67e2b43..0d699fcb 100644 --- a/lua/packer.lua +++ b/lua/packer.lua @@ -1,6 +1,6 @@ -- TODO: Performance analysis/tuning -- TODO: Merge start plugins? -local util = require('packer.util') +local util = require 'packer.util' local join_paths = util.join_paths local stdpath = vim.fn.stdpath @@ -9,8 +9,8 @@ local stdpath = vim.fn.stdpath local packer = {} local config_defaults = { ensure_dependencies = true, - package_root = join_paths(stdpath('data'), 'site', 'pack'), - compile_path = join_paths(stdpath('config'), 'plugin', 'packer_compiled.lua'), + package_root = join_paths(stdpath 'data', 'site', 'pack'), + compile_path = join_paths(stdpath 'config', 'plugin', 'packer_compiled.lua'), plugin_package = 'packer', max_jobs = nil, auto_clean = true, @@ -31,15 +31,15 @@ local config_defaults = { current_branch = 'rev-parse --abbrev-ref HEAD', diff = 'log --color=never --pretty=format:FMT --no-show-signature HEAD@{1}...HEAD', diff_fmt = '%%h %%s (%%cr)', - git_diff_fmt = "show --no-color --pretty=medium %s", + git_diff_fmt = 'show --no-color --pretty=medium %s', get_rev = 'rev-parse --short HEAD', get_msg = 'log --color=never --pretty=format:FMT --no-show-signature HEAD -n 1', submodules = 'submodule update --init --recursive --progress', - revert = 'reset --hard HEAD@{1}' + revert = 'reset --hard HEAD@{1}', }, depth = 1, clone_timeout = 60, - default_url_format = 'https://github.com/%s.git' + default_url_format = 'https://github.com/%s.git', }, display = { non_interactive = false, @@ -55,11 +55,11 @@ local config_defaults = { title = 'packer.nvim', show_all_info = true, prompt_border = 'double', - keybindings = {quit = 'q', toggle_info = '', diff = 'd', prompt_revert = 'r'} + keybindings = { quit = 'q', toggle_info = '', diff = 'd', prompt_revert = 'r' }, }, - luarocks = {python_cmd = 'python'}, - log = {level = 'warn'}, - profile = {enable = false} + luarocks = { python_cmd = 'python' }, + log = { level = 'warn' }, + profile = { enable = false }, } --- Initialize global namespace for use for callbacks and other data generated whilst packer is @@ -81,7 +81,7 @@ local configurable_modules = { plugin_utils = false, update = false, luarocks = false, - log = false + log = false, } local function require_and_configure(module_name) @@ -109,9 +109,11 @@ packer.init = function(user_config) config.pack_dir = join_paths(config.package_root, config.plugin_package) config.opt_dir = join_paths(config.pack_dir, 'opt') config.start_dir = join_paths(config.pack_dir, 'start') - local plugin_utils = require_and_configure('plugin_utils') + local plugin_utils = require_and_configure 'plugin_utils' plugin_utils.ensure_dirs() - if not config.disable_commands then packer.make_commands() end + if not config.disable_commands then + packer.make_commands() + end end packer.make_commands = function() @@ -133,7 +135,9 @@ end --- Add a Luarocks package to be managed packer.use_rocks = function(rock) - if type(rock) == 'string' then rock = {rock} end + if type(rock) == 'string' then + rock = { rock } + end if not vim.tbl_islist(rock) and type(rock[1]) == 'string' then rocks[rock[1]] = rock else @@ -155,13 +159,15 @@ manage = function(plugin_data) local spec_line = plugin_data.line local spec_type = type(plugin_spec) if spec_type == 'string' then - plugin_spec = {plugin_spec} + plugin_spec = { plugin_spec } elseif spec_type == 'table' and #plugin_spec > 1 then - for _, spec in ipairs(plugin_spec) do manage({spec = spec, line = spec_line}) end + for _, spec in ipairs(plugin_spec) do + manage { spec = spec, line = spec_line } + end return end - local log = require_and_configure('log') + local log = require_and_configure 'log' if plugin_spec[1] == vim.NIL or plugin_spec[1] == nil then log.warn('No plugin name provided at line ' .. spec_line .. '!') return @@ -187,8 +193,15 @@ manage = function(plugin_data) end if plugin_spec.as and plugins[plugin_spec.as] then - log.error('The alias ' .. plugin_spec.as .. ', specified for ' .. path .. ' at ' .. spec_line - .. ' is already used as another plugin name!') + log.error( + 'The alias ' + .. plugin_spec.as + .. ', specified for ' + .. path + .. ' at ' + .. spec_line + .. ' is already used as another plugin name!' + ) return end @@ -205,7 +218,7 @@ manage = function(plugin_data) plugin_spec.opt = true end - local compile = require_and_configure('compile') + local compile = require_and_configure 'compile' for _, key in ipairs(compile.opt_keys) do if plugin_spec[key] then plugin_spec.opt = true @@ -213,123 +226,154 @@ manage = function(plugin_data) end end - plugin_spec.install_path = join_paths(plugin_spec.opt and config.opt_dir or config.start_dir, - plugin_spec.short_name) + plugin_spec.install_path = join_paths(plugin_spec.opt and config.opt_dir or config.start_dir, plugin_spec.short_name) - local plugin_utils = require_and_configure('plugin_utils') - local plugin_types = require_and_configure('plugin_types') - local handlers = require_and_configure('handlers') - if not plugin_spec.type then plugin_utils.guess_type(plugin_spec) end + local plugin_utils = require_and_configure 'plugin_utils' + local plugin_types = require_and_configure 'plugin_types' + local handlers = require_and_configure 'handlers' + if not plugin_spec.type then + plugin_utils.guess_type(plugin_spec) + end if plugin_spec.type ~= plugin_utils.custom_plugin_type then plugin_types[plugin_spec.type].setup(plugin_spec) end - for k, v in pairs(plugin_spec) do if handlers[k] then handlers[k](plugins, plugin_spec, v) end end + for k, v in pairs(plugin_spec) do + if handlers[k] then + handlers[k](plugins, plugin_spec, v) + end + end plugins[plugin_spec.short_name] = plugin_spec - if plugin_spec.rocks then packer.use_rocks(plugin_spec.rocks) end + if plugin_spec.rocks then + packer.use_rocks(plugin_spec.rocks) + end if plugin_spec.requires and config.ensure_dependencies then - if type(plugin_spec.requires) == 'string' then plugin_spec.requires = {plugin_spec.requires} end + if type(plugin_spec.requires) == 'string' then + plugin_spec.requires = { plugin_spec.requires } + end for _, req in ipairs(plugin_spec.requires) do - if type(req) == 'string' then req = {req} end + if type(req) == 'string' then + req = { req } + end local req_name_segments = vim.split(req[1], '/') local req_name = req_name_segments[#req_name_segments] if not plugins[req_name] then if config.transitive_opt and plugin_spec.manual_opt then req.opt = true if type(req.after) == 'string' then - req.after = {req.after, plugin_spec.short_name} + req.after = { req.after, plugin_spec.short_name } elseif type(req.after) == 'table' then local already_after = false for _, name in ipairs(req.after) do already_after = already_after or (name == plugin_spec.short_name) end - if not already_after then table.insert(req.after, plugin_spec.short_name) end + if not already_after then + table.insert(req.after, plugin_spec.short_name) + end elseif req.after == nil then req.after = plugin_spec.short_name end end - if config.transitive_disable and plugin_spec.disable then req.disable = true end - manage({spec = req, line = spec_line}) + if config.transitive_disable and plugin_spec.disable then + req.disable = true + end + manage { spec = req, line = spec_line } end end end end --- Add a new keyword handler -packer.set_handler = function(name, func) require_and_configure('handlers')[name] = func end +packer.set_handler = function(name, func) + require_and_configure('handlers')[name] = func +end --- Add a plugin to the managed set packer.use = function(plugin_spec) plugin_specifications[#plugin_specifications + 1] = { spec = plugin_spec, - line = debug.getinfo(2, 'l').currentline + line = debug.getinfo(2, 'l').currentline, } end local function manage_all_plugins() - local log = require_and_configure('log') - log.debug('Processing plugin specs') + local log = require_and_configure 'log' + log.debug 'Processing plugin specs' if plugins == nil or next(plugins) == nil then - for _, spec in ipairs(plugin_specifications) do manage(spec) end + for _, spec in ipairs(plugin_specifications) do + manage(spec) + end end end packer.__manage_all = manage_all_plugins --- Hook to fire events after packer operations -packer.on_complete = vim.schedule_wrap(function() vim.cmd [[doautocmd User PackerComplete]] end) +packer.on_complete = vim.schedule_wrap(function() + vim.cmd [[doautocmd User PackerComplete]] +end) --- Hook to fire events after packer compilation -packer.on_compile_done = function() vim.cmd [[doautocmd User PackerCompileDone]] end +packer.on_compile_done = function() + vim.cmd [[doautocmd User PackerCompileDone]] +end --- Clean operation: -- Finds plugins present in the `packer` package but not in the managed set packer.clean = function(results) - local plugin_utils = require_and_configure('plugin_utils') - local a = require('packer.async') + local plugin_utils = require_and_configure 'plugin_utils' + local a = require 'packer.async' local async = a.sync local await = a.wait - local luarocks = require_and_configure('luarocks') - local clean = require_and_configure('clean') - require_and_configure('display') + local luarocks = require_and_configure 'luarocks' + local clean = require_and_configure 'clean' + require_and_configure 'display' manage_all_plugins() async(function() local luarocks_clean_task = luarocks.clean(rocks, results, nil) - if luarocks_clean_task ~= nil then await(luarocks_clean_task) end + if luarocks_clean_task ~= nil then + await(luarocks_clean_task) + end local fs_state = await(plugin_utils.get_fs_state(plugins)) await(clean(plugins, fs_state, results)) packer.on_complete() end)() end -local function args_or_all(...) return util.nonempty_or({...}, vim.tbl_keys(plugins)) end +local function args_or_all(...) + return util.nonempty_or({ ... }, vim.tbl_keys(plugins)) +end --- Install operation: -- Takes an optional list of plugin names as an argument. If no list is given, operates on all -- managed plugins. -- Installs missing plugins, then updates helptags and rplugins packer.install = function(...) - local log = require_and_configure('log') - log.debug('packer.install: requiring modules') - local plugin_utils = require_and_configure('plugin_utils') - local a = require('packer.async') + local log = require_and_configure 'log' + log.debug 'packer.install: requiring modules' + local plugin_utils = require_and_configure 'plugin_utils' + local a = require 'packer.async' local async = a.sync local await = a.wait - local luarocks = require_and_configure('luarocks') - local clean = require_and_configure('clean') - local install = require_and_configure('install') - local display = require_and_configure('display') + local luarocks = require_and_configure 'luarocks' + local clean = require_and_configure 'clean' + local install = require_and_configure 'install' + local display = require_and_configure 'display' manage_all_plugins() local install_plugins - if ... then install_plugins = {...} end + if ... then + install_plugins = { ... } + end async(function() local fs_state = await(plugin_utils.get_fs_state(plugins)) - if not install_plugins then install_plugins = vim.tbl_keys(fs_state.missing) end + if not install_plugins then + install_plugins = vim.tbl_keys(fs_state.missing) + end if #install_plugins == 0 then - log.info('All configured plugins are installed') + log.info 'All configured plugins are installed' packer.on_complete() return end @@ -339,21 +383,26 @@ packer.install = function(...) local results = {} await(clean(plugins, fs_state, results)) await(a.main) - log.debug('Gathering install tasks') + log.debug 'Gathering install tasks' local tasks, display_win = install(plugins, install_plugins, results) if next(tasks) then - log.debug('Gathering Luarocks tasks') + log.debug 'Gathering Luarocks tasks' local luarocks_ensure_task = luarocks.ensure(rocks, results, display_win) - if luarocks_ensure_task ~= nil then table.insert(tasks, luarocks_ensure_task) end - table.insert(tasks, 1, function() return not display.status.running end) + if luarocks_ensure_task ~= nil then + table.insert(tasks, luarocks_ensure_task) + end + table.insert(tasks, 1, function() + return not display.status.running + end) table.insert(tasks, 1, config.max_jobs and config.max_jobs or (#tasks - 1)) - log.debug('Running tasks') - display_win:update_headline_message('installing ' .. #tasks - 2 .. ' / ' .. #tasks - 2 - .. ' plugins') + log.debug 'Running tasks' + display_win:update_headline_message('installing ' .. #tasks - 2 .. ' / ' .. #tasks - 2 .. ' plugins') a.interruptible_wait_pool(unpack(tasks)) local install_paths = {} for plugin_name, r in pairs(results.installs) do - if r.ok then table.insert(install_paths, results.plugins[plugin_name].install_path) end + if r.ok then + table.insert(install_paths, results.plugins[plugin_name].install_path) + end end await(a.main) @@ -363,7 +412,7 @@ packer.install = function(...) display_win:final_results(results, delta) packer.on_complete() else - log.info('Nothing to install!') + log.info 'Nothing to install!' packer.on_complete() end end)() @@ -375,17 +424,17 @@ end -- Fixes plugin types, installs missing plugins, then updates installed plugins and updates helptags -- and rplugins packer.update = function(...) - local log = require_and_configure('log') - log.debug('packer.update: requiring modules') - local plugin_utils = require_and_configure('plugin_utils') - local a = require('packer.async') + local log = require_and_configure 'log' + log.debug 'packer.update: requiring modules' + local plugin_utils = require_and_configure 'plugin_utils' + local a = require 'packer.async' local async = a.sync local await = a.wait - local luarocks = require_and_configure('luarocks') - local clean = require_and_configure('clean') - local install = require_and_configure('install') - local display = require_and_configure('display') - local update = require_and_configure('update') + local luarocks = require_and_configure 'luarocks' + local clean = require_and_configure 'clean' + local install = require_and_configure 'install' + local display = require_and_configure 'display' + local update = require_and_configure 'update' manage_all_plugins() @@ -394,36 +443,42 @@ packer.update = function(...) local start_time = vim.fn.reltime() local results = {} local fs_state = await(plugin_utils.get_fs_state(plugins)) - local missing_plugins, installed_plugins = util.partition(vim.tbl_keys(fs_state.missing), - update_plugins) + local missing_plugins, installed_plugins = util.partition(vim.tbl_keys(fs_state.missing), update_plugins) update.fix_plugin_types(plugins, missing_plugins, results, fs_state) await(clean(plugins, fs_state, results)) local _ _, missing_plugins = util.partition(vim.tbl_keys(results.moves), missing_plugins) - log.debug('Gathering install tasks') + log.debug 'Gathering install tasks' await(a.main) local tasks, display_win = install(plugins, missing_plugins, results) local update_tasks - log.debug('Gathering update tasks') + log.debug 'Gathering update tasks' await(a.main) update_tasks, display_win = update(plugins, installed_plugins, display_win, results) vim.list_extend(tasks, update_tasks) - log.debug('Gathering luarocks tasks') + log.debug 'Gathering luarocks tasks' local luarocks_ensure_task = luarocks.ensure(rocks, results, display_win) - if luarocks_ensure_task ~= nil then table.insert(tasks, luarocks_ensure_task) end - table.insert(tasks, 1, function() return not display.status.running end) + if luarocks_ensure_task ~= nil then + table.insert(tasks, luarocks_ensure_task) + end + table.insert(tasks, 1, function() + return not display.status.running + end) table.insert(tasks, 1, config.max_jobs and config.max_jobs or (#tasks - 1)) - display_win:update_headline_message('updating ' .. #tasks - 2 .. ' / ' .. #tasks - 2 - .. ' plugins') - log.debug('Running tasks') + display_win:update_headline_message('updating ' .. #tasks - 2 .. ' / ' .. #tasks - 2 .. ' plugins') + log.debug 'Running tasks' a.interruptible_wait_pool(unpack(tasks)) local install_paths = {} for plugin_name, r in pairs(results.installs) do - if r.ok then table.insert(install_paths, results.plugins[plugin_name].install_path) end + if r.ok then + table.insert(install_paths, results.plugins[plugin_name].install_path) + end end for plugin_name, r in pairs(results.updates) do - if r.ok then table.insert(install_paths, results.plugins[plugin_name].install_path) end + if r.ok then + table.insert(install_paths, results.plugins[plugin_name].install_path) + end end await(a.main) @@ -444,17 +499,17 @@ end -- - Install missing plugins and update installed plugins -- - Update helptags and rplugins packer.sync = function(...) - local log = require_and_configure('log') - log.debug('packer.sync: requiring modules') - local plugin_utils = require_and_configure('plugin_utils') - local a = require('packer.async') + local log = require_and_configure 'log' + log.debug 'packer.sync: requiring modules' + local plugin_utils = require_and_configure 'plugin_utils' + local a = require 'packer.async' local async = a.sync local await = a.wait - local luarocks = require_and_configure('luarocks') - local clean = require_and_configure('clean') - local install = require_and_configure('install') - local display = require_and_configure('display') - local update = require_and_configure('update') + local luarocks = require_and_configure 'luarocks' + local clean = require_and_configure 'clean' + local install = require_and_configure 'install' + local display = require_and_configure 'display' + local update = require_and_configure 'update' manage_all_plugins() @@ -463,8 +518,7 @@ packer.sync = function(...) local start_time = vim.fn.reltime() local results = {} local fs_state = await(plugin_utils.get_fs_state(plugins)) - local missing_plugins, installed_plugins = util.partition(vim.tbl_keys(fs_state.missing), - sync_plugins) + local missing_plugins, installed_plugins = util.partition(vim.tbl_keys(fs_state.missing), sync_plugins) await(a.main) update.fix_plugin_types(plugins, missing_plugins, results, fs_state) @@ -476,35 +530,46 @@ packer.sync = function(...) end await(a.main) - log.debug('Gathering install tasks') + log.debug 'Gathering install tasks' local tasks, display_win = install(plugins, missing_plugins, results) local update_tasks - log.debug('Gathering update tasks') + log.debug 'Gathering update tasks' await(a.main) update_tasks, display_win = update(plugins, installed_plugins, display_win, results) vim.list_extend(tasks, update_tasks) - log.debug('Gathering luarocks tasks') + log.debug 'Gathering luarocks tasks' local luarocks_clean_task = luarocks.clean(rocks, results, display_win) - if luarocks_clean_task ~= nil then table.insert(tasks, luarocks_clean_task) end + if luarocks_clean_task ~= nil then + table.insert(tasks, luarocks_clean_task) + end local luarocks_ensure_task = luarocks.ensure(rocks, results, display_win) - if luarocks_ensure_task ~= nil then table.insert(tasks, luarocks_ensure_task) end - table.insert(tasks, 1, function() return not display.status.running end) + if luarocks_ensure_task ~= nil then + table.insert(tasks, luarocks_ensure_task) + end + table.insert(tasks, 1, function() + return not display.status.running + end) table.insert(tasks, 1, config.max_jobs and config.max_jobs or (#tasks - 1)) - log.debug('Running tasks') - display_win:update_headline_message( - 'syncing ' .. #tasks - 2 .. ' / ' .. #tasks - 2 .. ' plugins') + log.debug 'Running tasks' + display_win:update_headline_message('syncing ' .. #tasks - 2 .. ' / ' .. #tasks - 2 .. ' plugins') a.interruptible_wait_pool(unpack(tasks)) local install_paths = {} for plugin_name, r in pairs(results.installs) do - if r.ok then table.insert(install_paths, results.plugins[plugin_name].install_path) end + if r.ok then + table.insert(install_paths, results.plugins[plugin_name].install_path) + end end for plugin_name, r in pairs(results.updates) do - if r.ok then table.insert(install_paths, results.plugins[plugin_name].install_path) end + if r.ok then + table.insert(install_paths, results.plugins[plugin_name].install_path) + end end await(a.main) - if config.compile_on_sync then packer.compile() end + if config.compile_on_sync then + packer.compile() + end plugin_utils.update_helptags(install_paths) plugin_utils.update_rplugins() local delta = string.gsub(vim.fn.reltimestr(vim.fn.reltime(start_time)), ' ', '') @@ -515,8 +580,8 @@ end packer.status = function() local async = require('packer.async').sync - local display = require_and_configure('display') - require_and_configure('log') + local display = require_and_configure 'display' + require_and_configure 'log' manage_all_plugins() async(function() @@ -538,18 +603,30 @@ end --- reload the user module. local function refresh_configs(plugs) local reverse_index = {} - for k, v in pairs(package.loaded) do if type(v) == "function" then reverse_index[v] = k end end + for k, v in pairs(package.loaded) do + if type(v) == 'function' then + reverse_index[v] = k + end + end for _, plugin in pairs(plugs) do local cfg = reload_module(reverse_index[plugin.config]) local setup = reload_module(reverse_index[plugin.setup]) - if cfg then plugin.config = cfg end - if setup then plugin.setup = setup end + if cfg then + plugin.config = cfg + end + if setup then + plugin.setup = setup + end end end local function parse_value(value) - if value == "true" then return true end - if value == "false" then return false end + if value == 'true' then + return true + end + if value == 'false' then + return false + end return value end @@ -559,7 +636,7 @@ local function parse_args(args) local parts = vim.split(args, ' ') for _, part in ipairs(parts) do if part then - if part:find('=') then + if part:find '=' then local key, value = unpack(vim.split(part, '=')) result[key] = parse_value(value) end @@ -572,8 +649,8 @@ end --- Update the compiled lazy-loader code --- Takes an optional argument of a path to which to output the resulting compiled code packer.compile = function(raw_args) - local compile = require_and_configure('compile') - local log = require_and_configure('log') + local compile = require_and_configure 'compile' + local log = require_and_configure 'log' manage_all_plugins() local args = parse_args(raw_args) @@ -582,17 +659,21 @@ packer.compile = function(raw_args) local should_profile = args.profile -- the user might explicitly choose for this value to be false in which case -- an or operator will not work - if should_profile == nil then should_profile = config.profile.enable end + if should_profile == nil then + should_profile = config.profile.enable + end refresh_configs(plugins) -- NOTE: we copy the plugins table so the in memory value is not mutated during compilation local compiled_loader = compile(vim.deepcopy(plugins), output_lua, should_profile) output_path = vim.fn.expand(output_path) - vim.fn.mkdir(vim.fn.fnamemodify(output_path, ":h"), 'p') + vim.fn.mkdir(vim.fn.fnamemodify(output_path, ':h'), 'p') local output_file = io.open(output_path, 'w') output_file:write(compiled_loader) output_file:close() - if config.auto_reload_compiled then vim.cmd('source ' .. output_path) end - log.info('Finished compiling lazy-loaders!') + if config.auto_reload_compiled then + vim.cmd('source ' .. output_path) + end + log.info 'Finished compiling lazy-loaders!' packer.on_compile_done() -- TODO: remove this after migration period (written 2021/06/28) @@ -605,17 +686,22 @@ packer.compile = function(raw_args) if vim.loop.fs_stat(old_output_path) then os.remove(old_output_path) - log.warn('"' .. vim.fn.fnamemodify(old_output_path, ':~:.') .. '" was replaced by "' - .. vim.fn.fnamemodify(output_path, ':~:.') .. '"') - log.warn('If you have not updated Neovim since 2021/06/11 you must do so now') + log.warn( + '"' + .. vim.fn.fnamemodify(old_output_path, ':~:.') + .. '" was replaced by "' + .. vim.fn.fnamemodify(output_path, ':~:.') + .. '"' + ) + log.warn 'If you have not updated Neovim since 2021/06/11 you must do so now' end -- TODO: end migration chunk (2021/07/02) end packer.profile_output = function() local async = require('packer.async').sync - local display = require_and_configure('display') - local log = require_and_configure('log') + local display = require_and_configure 'display' + local log = require_and_configure 'log' manage_all_plugins() if _G._packer.profile_output then @@ -624,8 +710,7 @@ packer.profile_output = function() display_win:profile_output(_G._packer.profile_output) end)() else - log.warn( - 'You must run PackerCompile with profiling enabled first e.g. PackerCompile profile=true') + log.warn 'You must run PackerCompile with profiling enabled first e.g. PackerCompile profile=true' end end @@ -633,9 +718,10 @@ end -- @param plugins string String of space separated plugins names -- intended for PackerLoad command packer.loader = function(plugins_names) - local plugin_list = vim.tbl_filter(function(name) return #name > 0 end, - vim.split(plugins_names, ' ')) - require('packer.load')(plugin_list, {}, _G.packer_plugins) + local plugin_list = vim.tbl_filter(function(name) + return #name > 0 + end, vim.split(plugins_names, ' ')) + require 'packer.load'(plugin_list, {}, _G.packer_plugins) end -- Completion for not yet loaded plugins @@ -643,7 +729,9 @@ end packer.loader_complete = function(lead, _, _) local completion_list = {} for name, plugin in pairs(_G.packer_plugins) do - if vim.startswith(name, lead) and not plugin.loaded then table.insert(completion_list, name) end + if vim.startswith(name, lead) and not plugin.loaded then + table.insert(completion_list, name) + end end table.sort(completion_list) return completion_list @@ -664,7 +752,7 @@ packer.config = config -- overrides as another element: -- packer.startup({{'tjdevries/colorbuddy.vim'}, config = { ... }}) packer.startup = function(spec) - local log = require_and_configure('log') + local log = require_and_configure 'log' local user_func = nil local user_config = nil local user_plugins = nil @@ -676,8 +764,7 @@ packer.startup = function(spec) elseif type(spec[1]) == 'table' then user_plugins = spec[1] else - log.error( - 'You must provide a function or table of specifications as the first element of the argument to startup!') + log.error 'You must provide a function or table of specifications as the first element of the argument to startup!' return end @@ -691,8 +778,7 @@ packer.startup = function(spec) packer.reset() if user_func then - setfenv(user_func, - vim.tbl_extend('force', getfenv(), {use = packer.use, use_rocks = packer.use_rocks})) + setfenv(user_func, vim.tbl_extend('force', getfenv(), { use = packer.use, use_rocks = packer.use_rocks })) local status, err = pcall(user_func, packer.use, packer.use_rocks) if not status then log.error('Failure running setup function: ' .. vim.inspect(err)) diff --git a/lua/packer/async.lua b/lua/packer/async.lua index d103ed7e..f837824f 100644 --- a/lua/packer/async.lua +++ b/lua/packer/async.lua @@ -1,5 +1,5 @@ -- Adapted from https://ms-jpq.github.io/neovim-async-tutorial/ -local log = require('packer.log') +local log = require 'packer.log' local yield = coroutine.yield local resume = coroutine.resume local thread_create = coroutine.create @@ -27,7 +27,7 @@ end local function wrap(func) return function(...) - local params = {...} + local params = { ... } return function(tick) params[#params + 1] = tick return func(unpack(params)) @@ -36,14 +36,16 @@ local function wrap(func) end local function join(...) - local thunks = {...} + local thunks = { ... } local thunk_all = function(s) - if #thunks == 0 then return s() end + if #thunks == 0 then + return s() + end local to_go = #thunks local results = {} for i, thunk in ipairs(thunks) do local callback = function(...) - results[i] = {...} + results[i] = { ... } if to_go == 1 then s(unpack(results)) else @@ -58,20 +60,24 @@ local function join(...) return thunk_all end -local function wait_all(...) return yield(join(...)) end +local function wait_all(...) + return yield(join(...)) +end local function pool(n, interrupt_check, ...) - local thunks = {...} + local thunks = { ... } return function(s) - if #thunks == 0 then return s() end - local remaining = {select(n + 1, unpack(thunks))} + if #thunks == 0 then + return s() + end + local remaining = { select(n + 1, unpack(thunks)) } local results = {} local to_go = #thunks local make_callback = nil make_callback = function(idx, left) local i = (left == nil) and idx or (idx + left) return function(...) - results[i] = {...} + results[i] = { ... } to_go = to_go - 1 if to_go == 0 then s(unpack(results)) @@ -91,13 +97,17 @@ local function pool(n, interrupt_check, ...) end end -local function wait_pool(limit, ...) return yield(pool(limit, false, ...)) end +local function wait_pool(limit, ...) + return yield(pool(limit, false, ...)) +end local function interruptible_wait_pool(limit, interrupt_check, ...) return yield(pool(limit, interrupt_check, ...)) end -local function main(f) vim.schedule(f) end +local function main(f) + vim.schedule(f) +end local M = { --- Wrapper for functions that do not take a callback to make async functions @@ -116,7 +126,7 @@ local M = { wrap = wrap, --- Convenience function to ensure a function runs on the main "thread" (i.e. for functions which -- use Neovim functions, etc.) - main = main + main = main, } return M diff --git a/lua/packer/clean.lua b/lua/packer/clean.lua index 0d2f8bc5..2e8e7965 100644 --- a/lua/packer/clean.lua +++ b/lua/packer/clean.lua @@ -1,8 +1,8 @@ -local plugin_utils = require('packer.plugin_utils') -local a = require('packer.async') -local display = require('packer.display') -local log = require('packer.log') -local util = require('packer.util') +local plugin_utils = require 'packer.plugin_utils' +local a = require 'packer.async' +local display = require 'packer.display' +local log = require 'packer.log' +local util = require 'packer.util' local await = a.wait local async = a.sync @@ -13,14 +13,13 @@ local PLUGIN_OPTIONAL_LIST = 1 local PLUGIN_START_LIST = 2 local function is_dirty(plugin, typ) - return (plugin.opt and typ == PLUGIN_START_LIST) - or (not plugin.opt and typ == PLUGIN_OPTIONAL_LIST) + return (plugin.opt and typ == PLUGIN_START_LIST) or (not plugin.opt and typ == PLUGIN_OPTIONAL_LIST) end -- Find and remove any plugins not currently configured for use local clean_plugins = function(_, plugins, fs_state, results) return async(function() - log.debug('Starting clean') + log.debug 'Starting clean' local dirty_plugins = {} results = results or {} results.removals = results.removals or {} @@ -54,32 +53,40 @@ local clean_plugins = function(_, plugins, fs_state, results) -- Any path which was not set to `nil` above will be set to dirty here local function mark_remaining_as_dirty(plugin_list) - for path, _ in pairs(plugin_list) do dirty_plugins[#dirty_plugins + 1] = path end + for path, _ in pairs(plugin_list) do + dirty_plugins[#dirty_plugins + 1] = path + end end mark_remaining_as_dirty(opt_plugins) mark_remaining_as_dirty(start_plugins) if next(dirty_plugins) then local lines = {} - for _, path in ipairs(dirty_plugins) do table.insert(lines, ' - ' .. path) end + for _, path in ipairs(dirty_plugins) do + table.insert(lines, ' - ' .. path) + end await(a.main) if await(display.ask_user('Removing the following directories. OK? (y/N)', lines)) then results.removals = dirty_plugins log.debug('Removed ' .. vim.inspect(dirty_plugins)) for _, path in ipairs(dirty_plugins) do local result = vim.fn.delete(path, 'rf') - if result == -1 then log.warn('Could not remove ' .. path) end + if result == -1 then + log.warn('Could not remove ' .. path) + end end else - log.warn('Cleaning cancelled!') + log.warn 'Cleaning cancelled!' end else - log.info('Already clean!') + log.info 'Already clean!' end end) end -local function cfg(_config) config = _config end +local function cfg(_config) + config = _config +end -local clean = setmetatable({cfg = cfg}, {__call = clean_plugins}) +local clean = setmetatable({ cfg = cfg }, { __call = clean_plugins }) return clean diff --git a/lua/packer/compile.lua b/lua/packer/compile.lua index e5286e51..904718d0 100644 --- a/lua/packer/compile.lua +++ b/lua/packer/compile.lua @@ -1,11 +1,13 @@ -- Compiling plugin specifications to Lua for lazy-loading -local util = require('packer.util') -local log = require('packer.log') +local util = require 'packer.util' +local log = require 'packer.log' local fmt = string.format -local luarocks = require('packer.luarocks') +local luarocks = require 'packer.luarocks' local config -local function cfg(_config) config = _config.profile end +local function cfg(_config) + config = _config.profile +end local feature_guard = [[ if !has('nvim-0.5') @@ -31,7 +33,6 @@ vim.api.nvim_command('packadd packer.nvim') local no_errors = pcall(function() ]] - local catch_errors = [[ catch echohl ErrorMsg @@ -52,7 +53,8 @@ end ---@param should_profile boolean ---@return string local profile_time = function(should_profile) - return fmt([[ + return fmt( + [[ local time local profile_info local should_profile = %s @@ -69,7 +71,9 @@ local profile_time = function(should_profile) else time = function(chunk, start) end end - ]], vim.inspect(should_profile)) + ]], + vim.inspect(should_profile) + ) end local profile_output = [[ @@ -95,9 +99,12 @@ end ---@return string local conditionally_output_profile = function(threshold) if threshold then - return fmt([[ + return fmt( + [[ if should_profile then save_profiles(%d) end -]], threshold) +]], + threshold + ) else return [[ if should_profile then save_profiles() end @@ -170,7 +177,9 @@ end local function dump_loaders(loaders) local result = vim.deepcopy(loaders) for k, _ in pairs(result) do - if result[k].only_setup or result[k].only_sequence then result[k].loaded = true end + if result[k].only_setup or result[k].only_sequence then + result[k].loaded = true + end result[k].only_setup = nil result[k].only_sequence = nil end @@ -180,18 +189,17 @@ end local function make_try_loadstring(item, chunk, name) local bytecode = string.dump(item, true) - local executable_string = 'try_loadstring(' .. vim.inspect(bytecode) .. ', "' .. chunk .. '", "' - .. name .. '")' + local executable_string = 'try_loadstring(' .. vim.inspect(bytecode) .. ', "' .. chunk .. '", "' .. name .. '")' return executable_string, bytecode end -local after_plugin_pattern = table.concat({'after', 'plugin', '**/*.vim'}, util.get_separator()) +local after_plugin_pattern = table.concat({ 'after', 'plugin', '**/*.vim' }, util.get_separator()) local function detect_after_plugin(name, plugin_path) local path = plugin_path .. util.get_separator() .. after_plugin_pattern local glob_ok, files = pcall(vim.fn.glob, path, false, true) if not glob_ok then if string.find(files, 'E77') then - return {path} + return { path } else log.error('Error compiling ' .. name .. ': ' .. vim.inspect(files)) error(files) @@ -204,13 +212,13 @@ local function detect_after_plugin(name, plugin_path) end local ftdetect_patterns = { - table.concat({'ftdetect', '**/*.vim'}, util.get_separator()), - table.concat({'after', 'ftdetect', '**/*.vim'}, util.get_separator()) + table.concat({ 'ftdetect', '**/*.vim' }, util.get_separator()), + table.concat({ 'after', 'ftdetect', '**/*.vim' }, util.get_separator()), } local function detect_ftdetect(name, plugin_path) local paths = { plugin_path .. util.get_separator() .. ftdetect_patterns[1], - plugin_path .. util.get_separator() .. ftdetect_patterns[2] + plugin_path .. util.get_separator() .. ftdetect_patterns[2], } local source_paths = {} for i = 1, 2 do @@ -231,10 +239,14 @@ local function detect_ftdetect(name, plugin_path) return source_paths end -local source_dirs = {'ftdetect', 'ftplugin', 'after/ftdetect', 'after/ftplugin'} +local source_dirs = { 'ftdetect', 'ftplugin', 'after/ftdetect', 'after/ftplugin' } local function detect_bufread(plugin_path) local path = plugin_path - for i = 1, 4 do if #vim.fn.finddir(source_dirs[i], path) > 0 then return true end end + for i = 1, 4 do + if #vim.fn.finddir(source_dirs[i], path) > 0 then + return true + end + end return false end @@ -258,7 +270,9 @@ local function make_loaders(_, plugins, output_lua, should_profile) local quote_name = "'" .. name .. "'" if plugin.config and not plugin.executable_config then plugin.executable_config = {} - if type(plugin.config) ~= 'table' then plugin.config = {plugin.config} end + if type(plugin.config) ~= 'table' then + plugin.config = { plugin.config } + end for i, config_item in ipairs(plugin.config) do local executable_string = config_item if type(config_item) == 'function' then @@ -282,7 +296,7 @@ local function make_loaders(_, plugins, output_lua, should_profile) config = plugin.config, path = path, only_sequence = plugin.manual_opt == nil, - only_setup = false + only_setup = false, } if plugin.opt then @@ -291,7 +305,9 @@ local function make_loaders(_, plugins, output_lua, should_profile) end if plugin.setup then - if type(plugin.setup) ~= 'table' then plugin.setup = {plugin.setup} end + if type(plugin.setup) ~= 'table' then + plugin.setup = { plugin.setup } + end for i, setup_item in ipairs(plugin.setup) do if type(setup_item) == 'function' then plugin.setup[i], _ = make_try_loadstring(setup_item, 'setup', name) @@ -306,7 +322,9 @@ local function make_loaders(_, plugins, output_lua, should_profile) loaders[name].only_sequence = false loaders[name].only_setup = false vim.list_extend(ftdetect_paths, detect_ftdetect(name, loaders[name].path)) - if type(plugin.ft) == 'string' then plugin.ft = {plugin.ft} end + if type(plugin.ft) == 'string' then + plugin.ft = { plugin.ft } + end for _, ft in ipairs(plugin.ft) do fts[ft] = fts[ft] or {} table.insert(fts[ft], quote_name) @@ -317,15 +335,15 @@ local function make_loaders(_, plugins, output_lua, should_profile) loaders[name].only_sequence = false loaders[name].only_setup = false if type(plugin.event) == 'string' then - if not plugin.event:find('%s') then - plugin.event = {plugin.event .. ' *'} + if not plugin.event:find '%s' then + plugin.event = { plugin.event .. ' *' } else - plugin.event = {plugin.event} + plugin.event = { plugin.event } end end for _, event in ipairs(plugin.event) do - if event:sub(#event, -1) ~= '*' and not event:find('%s') then + if event:sub(#event, -1) ~= '*' and not event:find '%s' then event = event .. ' *' end events[event] = events[event] or {} @@ -337,7 +355,7 @@ local function make_loaders(_, plugins, output_lua, should_profile) loaders[name].only_sequence = false loaders[name].only_setup = false if type(plugin.cond) == 'string' or type(plugin.cond) == 'function' then - plugin.cond = {plugin.cond} + plugin.cond = { plugin.cond } end for _, condition in ipairs(plugin.cond) do @@ -354,7 +372,9 @@ local function make_loaders(_, plugins, output_lua, should_profile) if plugin.cmd then loaders[name].only_sequence = false loaders[name].only_setup = false - if type(plugin.cmd) == 'string' then plugin.cmd = {plugin.cmd} end + if type(plugin.cmd) == 'string' then + plugin.cmd = { plugin.cmd } + end loaders[name].commands = {} for _, command in ipairs(plugin.cmd) do @@ -367,10 +387,14 @@ local function make_loaders(_, plugins, output_lua, should_profile) if plugin.keys then loaders[name].only_sequence = false loaders[name].only_setup = false - if type(plugin.keys) == 'string' then plugin.keys = {plugin.keys} end + if type(plugin.keys) == 'string' then + plugin.keys = { plugin.keys } + end loaders[name].keys = {} for _, keymap in ipairs(plugin.keys) do - if type(keymap) == 'string' then keymap = {'', keymap} end + if type(keymap) == 'string' then + keymap = { '', keymap } + end keymaps[keymap] = keymaps[keymap] or {} table.insert(loaders[name].keys, keymap) table.insert(keymaps[keymap], quote_name) @@ -380,7 +404,9 @@ local function make_loaders(_, plugins, output_lua, should_profile) if plugin.after then loaders[name].only_setup = false - if type(plugin.after) == 'string' then plugin.after = {plugin.after} end + if type(plugin.after) == 'string' then + plugin.after = { plugin.after } + end for _, other_plugin in ipairs(plugin.after) do after[other_plugin] = after[other_plugin] or {} @@ -389,14 +415,18 @@ local function make_loaders(_, plugins, output_lua, should_profile) end if plugin.wants then - if type(plugin.wants) == 'string' then plugin.wants = {plugin.wants} end + if type(plugin.wants) == 'string' then + plugin.wants = { plugin.wants } + end loaders[name].wants = plugin.wants end if plugin.fn then loaders[name].only_sequence = false loaders[name].only_setup = false - if type(plugin.fn) == 'string' then plugin.fn = {plugin.fn} end + if type(plugin.fn) == 'string' then + plugin.fn = { plugin.fn } + end for _, fn in ipairs(plugin.fn) do fns[fn] = fns[fn] or {} table.insert(fns[fn], quote_name) @@ -406,7 +436,9 @@ local function make_loaders(_, plugins, output_lua, should_profile) if plugin.module then loaders[name].only_sequence = false loaders[name].only_setup = false - if type(plugin.module) == 'string' then plugin.module = {plugin.module} end + if type(plugin.module) == 'string' then + plugin.module = { plugin.module } + end for _, module_name in ipairs(plugin.module) do module_lazy_loads['^' .. vim.pesc(module_name)] = name end @@ -421,33 +453,49 @@ local function make_loaders(_, plugins, output_lua, should_profile) local ft_aucmds = {} for ft, names in pairs(fts) do - table.insert(ft_aucmds, fmt( - 'vim.cmd [[au FileType %s ++once lua require("packer.load")({%s}, { ft = "%s" }, _G.packer_plugins)]]', - ft, table.concat(names, ', '), ft)) + table.insert( + ft_aucmds, + fmt( + 'vim.cmd [[au FileType %s ++once lua require("packer.load")({%s}, { ft = "%s" }, _G.packer_plugins)]]', + ft, + table.concat(names, ', '), + ft + ) + ) end local event_aucmds = {} for event, names in pairs(events) do - table.insert(event_aucmds, fmt( - 'vim.cmd [[au %s ++once lua require("packer.load")({%s}, { event = "%s" }, _G.packer_plugins)]]', - event, table.concat(names, ', '), event:gsub([[\]], [[\\]]))) + table.insert( + event_aucmds, + fmt( + 'vim.cmd [[au %s ++once lua require("packer.load")({%s}, { event = "%s" }, _G.packer_plugins)]]', + event, + table.concat(names, ', '), + event:gsub([[\]], [[\\]]) + ) + ) end local config_lines = {} for name, plugin_config in pairs(configs) do - local lines = {'-- Config for: ' .. name} + local lines = { '-- Config for: ' .. name } timed_chunk(plugin_config, 'Config for ' .. name, lines) vim.list_extend(config_lines, lines) end local rtp_line = '' - for _, rtp in ipairs(rtps) do rtp_line = rtp_line .. ' .. ",' .. vim.fn.escape(rtp, '\\,') .. '"' end + for _, rtp in ipairs(rtps) do + rtp_line = rtp_line .. ' .. ",' .. vim.fn.escape(rtp, '\\,') .. '"' + end - if rtp_line ~= '' then rtp_line = 'vim.o.runtimepath = vim.o.runtimepath' .. rtp_line end + if rtp_line ~= '' then + rtp_line = 'vim.o.runtimepath = vim.o.runtimepath' .. rtp_line + end local setup_lines = {} for name, plugin_setup in pairs(setup) do - local lines = {'-- Setup for: ' .. name} + local lines = { '-- Setup for: ' .. name } timed_chunk(plugin_setup, 'Setup for ' .. name, lines) if loaders[name].only_setup then timed_chunk('vim.cmd [[packadd ' .. name .. ']]', 'packadd for ' .. name, lines) @@ -462,40 +510,53 @@ local function make_loaders(_, plugins, output_lua, should_profile) for _, name in ipairs(names) do timed_chunk('\tvim.cmd [[packadd ' .. name .. ']]', 'packadd for ' .. name, conditional_loads) if plugins[name].config then - local lines = {'-- Config for: ' .. name} + local lines = { '-- Config for: ' .. name } timed_chunk(plugins[name].executable_config, 'Config for ' .. name, lines) vim.list_extend(conditional_loads, lines) end end local executable_conditional = condition if condition_bytecode[condition] then - executable_conditional = 'try_loadstring(' .. condition .. ', "condition", \'' - .. vim.inspect(names) .. '\')' + executable_conditional = 'try_loadstring(' .. condition .. ', "condition", \'' .. vim.inspect(names) .. "')" end - vim.list_extend(conditionals, - timed_condition(executable_conditional, table.concat(conditional_loads, '\n\t'), - 'Condition for ' .. vim.inspect(names):gsub('"', "'"))) + vim.list_extend( + conditionals, + timed_condition( + executable_conditional, + table.concat(conditional_loads, '\n\t'), + 'Condition for ' .. vim.inspect(names):gsub('"', "'") + ) + ) end local command_defs = {} for command, names in pairs(commands) do local command_line = fmt( - 'vim.cmd [[command! -nargs=* -range -bang -complete=file %s lua require("packer.load")({%s}, { cmd = "%s", l1 = , l2 = , bang = , args = }, _G.packer_plugins)]]', - command, table.concat(names, ', '), command) + 'vim.cmd [[command! -nargs=* -range -bang -complete=file %s lua require("packer.load")({%s}, { cmd = "%s", l1 = , l2 = , bang = , args = }, _G.packer_plugins)]]', + command, + table.concat(names, ', '), + command + ) table.insert(command_defs, command_line) end local keymap_defs = {} for keymap, names in pairs(keymaps) do local prefix = nil - if keymap[1] ~= 'i' then prefix = '' end + if keymap[1] ~= 'i' then + prefix = '' + end local escaped_map_lt = string.gsub(keymap[2], '<', '') local escaped_map = string.gsub(escaped_map_lt, '([\\"])', '\\%1') local keymap_line = fmt( - 'vim.cmd [[%snoremap %s lua require("packer.load")({%s}, { keys = "%s"%s }, _G.packer_plugins)]]', - keymap[1], keymap[2], table.concat(names, ', '), escaped_map, - prefix == nil and '' or (', prefix = "' .. prefix .. '"')) + 'vim.cmd [[%snoremap %s lua require("packer.load")({%s}, { keys = "%s"%s }, _G.packer_plugins)]]', + keymap[1], + keymap[2], + table.concat(names, ', '), + escaped_map, + prefix == nil and '' or (', prefix = "' .. prefix .. '"') + ) table.insert(keymap_defs, keymap_line) end @@ -509,7 +570,7 @@ local function make_loaders(_, plugins, output_lua, should_profile) if plugins[pre].opt then loaders[pre].after = posts elseif plugins[pre].only_config then - loaders[pre] = {after = posts, only_sequence = true, only_config = true} + loaders[pre] = { after = posts, only_sequence = true, only_config = true } end if plugins[pre].opt or plugins[pre].only_config then @@ -523,17 +584,22 @@ local function make_loaders(_, plugins, output_lua, should_profile) local fn_aucmds = {} for fn, names in pairs(fns) do - table.insert(fn_aucmds, fmt( - 'vim.cmd[[au FuncUndefined %s ++once lua require("packer.load")({%s}, {}, _G.packer_plugins)]]', - fn, table.concat(names, ', '))) + table.insert( + fn_aucmds, + fmt( + 'vim.cmd[[au FuncUndefined %s ++once lua require("packer.load")({%s}, {}, _G.packer_plugins)]]', + fn, + table.concat(names, ', ') + ) + ) end local sequence_lines = {} local graph = {} for name, precedents in pairs(sequence_loads) do - graph[name] = graph[name] or {in_links = {}, out_links = {}} + graph[name] = graph[name] or { in_links = {}, out_links = {} } for _, pre in ipairs(precedents) do - graph[pre] = graph[pre] or {in_links = {}, out_links = {}} + graph[pre] = graph[pre] or { in_links = {}, out_links = {} } graph[name].in_links[pre] = true table.insert(graph[pre].out_links, name) end @@ -541,16 +607,17 @@ local function make_loaders(_, plugins, output_lua, should_profile) local frontier = {} for name, links in pairs(graph) do - if next(links.in_links) == nil then table.insert(frontier, name) end + if next(links.in_links) == nil then + table.insert(frontier, name) + end end while next(frontier) ~= nil do local plugin = table.remove(frontier) - if loaders[plugin].only_sequence - and not (loaders[plugin].only_setup or loaders[plugin].only_config) then + if loaders[plugin].only_sequence and not (loaders[plugin].only_setup or loaders[plugin].only_config) then table.insert(sequence_lines, 'vim.cmd [[ packadd ' .. plugin .. ' ]]') if plugins[plugin].config then - local lines = {'', '-- Config for: ' .. plugin} + local lines = { '', '-- Config for: ' .. plugin } vim.list_extend(lines, plugins[plugin].executable_config) table.insert(lines, '') vim.list_extend(sequence_lines, lines) @@ -564,20 +631,22 @@ local function make_loaders(_, plugins, output_lua, should_profile) end graph[name].in_links[plugin] = nil - if next(graph[name].in_links) == nil then table.insert(frontier, name) end + if next(graph[name].in_links) == nil then + table.insert(frontier, name) + end end graph[plugin] = nil end if next(graph) then - log.warn('Cycle detected in sequenced loads! Load order may be incorrect') + log.warn 'Cycle detected in sequenced loads! Load order may be incorrect' -- TODO: This should actually just output the cycle, then continue with toposort. But I'm too -- lazy to do that right now, so. for plugin, _ in pairs(graph) do table.insert(sequence_lines, 'vim.cmd [[ packadd ' .. plugin .. ' ]]') if plugins[plugin].config then - local lines = {'-- Config for: ' .. plugin} + local lines = { '-- Config for: ' .. plugin } vim.list_extend(lines, plugins[plugin].config) vim.list_extend(sequence_lines, lines) end @@ -587,19 +656,18 @@ local function make_loaders(_, plugins, output_lua, should_profile) -- Output everything: -- First, the Lua code - local result = {(output_lua and '--' or '"')..' Automatically generated packer.nvim plugin loader code\n'} + local result = { (output_lua and '--' or '"') .. ' Automatically generated packer.nvim plugin loader code\n' } if output_lua then - table.insert(result, feature_guard_lua) + table.insert(result, feature_guard_lua) else - table.insert(result, feature_guard) - table.insert(result, 'lua << END') + table.insert(result, feature_guard) + table.insert(result, 'lua << END') end table.insert(result, profile_time(should_profile)) table.insert(result, profile_output) timed_chunk(luarocks.generate_path_setup(), 'Luarocks path setup', result) timed_chunk(try_loadstring, 'try_loadstring definition', result) - timed_chunk(fmt('_G.packer_plugins = %s\n', dump_loaders(loaders)), 'Defining packer_plugins', - result) + timed_chunk(fmt('_G.packer_plugins = %s\n', dump_loaders(loaders)), 'Defining packer_plugins', result) -- Then the runtimepath line if rtp_line ~= '' then table.insert(result, '-- Runtimepath customization') @@ -613,8 +681,12 @@ local function make_loaders(_, plugins, output_lua, should_profile) end -- Then setups, configs, and conditionals - if next(setup_lines) then vim.list_extend(result, setup_lines) end - if next(config_lines) then vim.list_extend(result, config_lines) end + if next(setup_lines) then + vim.list_extend(result, setup_lines) + end + if next(config_lines) then + vim.list_extend(result, config_lines) + end if next(conditionals) then table.insert(result, '-- Conditional loads') vim.list_extend(result, conditionals) @@ -662,13 +734,14 @@ local function make_loaders(_, plugins, output_lua, should_profile) timed_chunk(fn_aucmds, 'Defining lazy-load function autocommands', result) end - if some_ft or some_event or some_fn then table.insert(result, 'vim.cmd("augroup END")') end + if some_ft or some_event or some_fn then + table.insert(result, 'vim.cmd("augroup END")') + end if next(ftdetect_paths) then table.insert(result, 'vim.cmd [[augroup filetypedetect]]') for _, path in ipairs(ftdetect_paths) do local escaped_path = vim.fn.escape(path, ' ') - timed_chunk('vim.cmd [[source ' .. escaped_path .. ']]', - 'Sourcing ftdetect script at: ' .. escaped_path, result) + timed_chunk('vim.cmd [[source ' .. escaped_path .. ']]', 'Sourcing ftdetect script at: ' .. escaped_path, result) end table.insert(result, 'vim.cmd("augroup END")') @@ -676,16 +749,16 @@ local function make_loaders(_, plugins, output_lua, should_profile) table.insert(result, conditionally_output_profile(config.threshold)) if output_lua then - table.insert(result, catch_errors_lua) + table.insert(result, catch_errors_lua) else - table.insert(result, 'END\n') - table.insert(result, catch_errors) + table.insert(result, 'END\n') + table.insert(result, catch_errors) end return table.concat(result, '\n') end -local compile = setmetatable({cfg = cfg}, {__call = make_loaders}) +local compile = setmetatable({ cfg = cfg }, { __call = make_loaders }) -compile.opt_keys = {'after', 'cmd', 'ft', 'keys', 'event', 'cond', 'setup', 'fn', 'module'} +compile.opt_keys = { 'after', 'cmd', 'ft', 'keys', 'event', 'cond', 'setup', 'fn', 'module' } return compile diff --git a/lua/packer/display.lua b/lua/packer/display.lua index 22ee14d5..418680e4 100644 --- a/lua/packer/display.lua +++ b/lua/packer/display.lua @@ -1,7 +1,7 @@ local api = vim.api -local log = require('packer.log') -local a = require('packer.async') -local plugin_utils = require('packer.plugin_utils') +local log = require 'packer.log' +local a = require 'packer.async' +local plugin_utils = require 'packer.plugin_utils' local fmt = string.format local in_headless = #api.nvim_list_uis() == 0 @@ -9,12 +9,18 @@ local in_headless = #api.nvim_list_uis() == 0 -- Temporary wrappers to compensate for the updated extmark API, until most people have updated to -- the latest HEAD (2020-09-04) local function set_extmark(buf, ns, id, line, col) - if not api.nvim_buf_is_valid(buf) then return end - local opts = {id = id} + if not api.nvim_buf_is_valid(buf) then + return + end + local opts = { id = id } local result, mark_id = pcall(api.nvim_buf_set_extmark, buf, ns, line, col, opts) - if result then return mark_id end + if result then + return mark_id + end -- We must be in an older version of Neovim - if not id then id = 0 end + if not id then + id = 0 + end return api.nvim_buf_set_extmark(buf, ns, id, line, col, {}) end @@ -32,16 +38,18 @@ end local function strip_newlines(raw_lines) local lines = {} for _, line in ipairs(raw_lines) do - for _, chunk in ipairs(vim.split(line, '\n')) do table.insert(lines, chunk) end + for _, chunk in ipairs(vim.split(line, '\n')) do + table.insert(lines, chunk) + end end return lines end local function unpack_config_value(value, value_type, formatter) - if value_type == "string" then - return {value} - elseif value_type == "table" then + if value_type == 'string' then + return { value } + elseif value_type == 'table' then local result = {} for _, k in ipairs(value) do local item = formatter and formatter(k) or k @@ -49,21 +57,25 @@ local function unpack_config_value(value, value_type, formatter) end return result end - return "" + return '' end local function format_keys(value) local value_type = type(value) - local mapping = value_type == "string" and value or value[2] - local mode = value[1] ~= "" and "mode: " .. value[1] or "" + local mapping = value_type == 'string' and value or value[2] + local mode = value[1] ~= '' and 'mode: ' .. value[1] or '' local line = fmt('"%s", %s', mapping, mode) return line end -local function format_cmd(value) return fmt('"%s"', value) end +local function format_cmd(value) + return fmt('"%s"', value) +end local function get_key_name(key) - if key == "path" then return "opt" end + if key == 'path' then + return 'opt' + end return key end @@ -73,12 +85,12 @@ end ---@return string|string[] local function format_values(key, value) local value_type = type(value) - if key == "path" then - local is_opt = value:match("opt") ~= nil + if key == 'path' then + local is_opt = value:match 'opt' ~= nil return vim.inspect(is_opt) - elseif key == "keys" then + elseif key == 'keys' then return unpack_config_value(value, value_type, format_keys) - elseif key == "commands" then + elseif key == 'commands' then return unpack_config_value(value, value_type, format_cmd) else return vim.inspect(value) @@ -86,22 +98,32 @@ local function format_values(key, value) end local status_keys = { - "path", "commands", "keys", "module", "as", "ft", "event", "rocks", "branch", "commit", "tag", - "lock" + 'path', + 'commands', + 'keys', + 'module', + 'as', + 'ft', + 'event', + 'rocks', + 'branch', + 'commit', + 'tag', + 'lock', } local config = nil local keymaps = { - quit = {rhs = 'lua require"packer.display".quit()', action = 'quit'}, - diff = {rhs = 'lua require"packer.display".diff()', action = 'show the diff'}, + quit = { rhs = 'lua require"packer.display".quit()', action = 'quit' }, + diff = { rhs = 'lua require"packer.display".diff()', action = 'show the diff' }, toggle_info = { rhs = 'lua require"packer.display".toggle_info()', - action = 'show more info' + action = 'show more info', }, prompt_revert = { rhs = 'lua require"packer.display".prompt_revert()', - action = 'revert an update' - } + action = 'revert an update', + }, } --- The order of the keys in a dict-like table isn't guaranteed, meaning the display window can @@ -110,7 +132,7 @@ local keymap_display_order = { [1] = 'quit', [2] = 'toggle_info', [3] = 'diff', - [4] = 'prompt_revert' + [4] = 'prompt_revert', } --- Utility function to prompt a user with a question in a floating window @@ -124,7 +146,9 @@ local function prompt_user(headline, body, callback) local longest_line = 0 for _, line in ipairs(body) do local line_length = string.len(line) - if line_length > longest_line then longest_line = line_length end + if line_length > longest_line then + longest_line = line_length + end end local width = math.min(longest_line + 2, math.floor(0.9 * vim.o.columns)) @@ -132,10 +156,16 @@ local function prompt_user(headline, body, callback) local x = (vim.o.columns - width) / 2.0 local y = (vim.o.lines - height) / 2.0 local pad_width = math.max(math.floor((width - string.len(headline)) / 2.0), 0) - api.nvim_buf_set_lines(buf, 0, -1, true, vim.list_extend( - { - string.rep(' ', pad_width) .. headline .. string.rep(' ', pad_width), '' - }, body)) + api.nvim_buf_set_lines( + buf, + 0, + -1, + true, + vim.list_extend({ + string.rep(' ', pad_width) .. headline .. string.rep(' ', pad_width), + '', + }, body) + ) api.nvim_buf_set_option(buf, 'modifiable', false) local opts = { relative = 'editor', @@ -152,65 +182,78 @@ local function prompt_user(headline, body, callback) local win = api.nvim_open_win(buf, false, opts) local check = vim.loop.new_prepare() local prompted = false - vim.loop.prepare_start(check, vim.schedule_wrap(function() - if not api.nvim_win_is_valid(win) then return end - vim.loop.prepare_stop(check) - if not prompted then - prompted = true - local ans = string.lower(vim.fn.input('OK to remove? [y/N] ')) == 'y' - api.nvim_win_close(win, true) - callback(ans) - end - end)) + vim.loop.prepare_start( + check, + vim.schedule_wrap(function() + if not api.nvim_win_is_valid(win) then + return + end + vim.loop.prepare_stop(check) + if not prompted then + prompted = true + local ans = string.lower(vim.fn.input 'OK to remove? [y/N] ') == 'y' + api.nvim_win_close(win, true) + callback(ans) + end + end) + ) end local display = {} local display_mt = { --- Check if we have a valid display window valid_display = function(self) - return self and self.interactive and api.nvim_buf_is_valid(self.buf) - and api.nvim_win_is_valid(self.win) + return self and self.interactive and api.nvim_buf_is_valid(self.buf) and api.nvim_win_is_valid(self.win) end, --- Update the text of the display buffer set_lines = function(self, start_idx, end_idx, lines) - if not self:valid_display() then return end + if not self:valid_display() then + return + end api.nvim_buf_set_option(self.buf, 'modifiable', true) api.nvim_buf_set_lines(self.buf, start_idx, end_idx, true, lines) api.nvim_buf_set_option(self.buf, 'modifiable', false) end, get_current_line = function(self) - if not self:valid_display() then return end + if not self:valid_display() then + return + end return api.nvim_get_current_line() end, --- Start displaying a new task task_start = vim.schedule_wrap(function(self, plugin, message) - if not self:valid_display() then return end + if not self:valid_display() then + return + end if self.marks[plugin] then self:task_update(plugin, message) return end display.status.running = true - self:set_lines(config.header_lines, config.header_lines, - {fmt(' %s %s: %s', config.working_sym, plugin, message)}) + self:set_lines(config.header_lines, config.header_lines, { fmt(' %s %s: %s', config.working_sym, plugin, message) }) self.marks[plugin] = set_extmark(self.buf, self.ns, nil, config.header_lines, 0) end), --- Decrement the count of active operations in the headline decrement_headline_count = vim.schedule_wrap(function(self) - if not self:valid_display() then return end + if not self:valid_display() then + return + end local cursor_pos = api.nvim_win_get_cursor(self.win) - api.nvim_win_set_cursor(self.win, {1, 0}) + api.nvim_win_set_cursor(self.win, { 1, 0 }) api.nvim_buf_set_option(self.buf, 'modifiable', true) - vim.fn.execute('normal! ') + vim.fn.execute 'normal! ' api.nvim_buf_set_option(self.buf, 'modifiable', false) api.nvim_win_set_cursor(self.win, cursor_pos) end), --- Update a task as having successfully completed task_succeeded = vim.schedule_wrap(function(self, plugin, message) - if not self:valid_display() then return end + if not self:valid_display() then + return + end local line, _ = get_extmark_by_id(self.buf, self.ns, self.marks[plugin]) - self:set_lines(line[1], line[1] + 1, {fmt(' %s %s: %s', config.done_sym, plugin, message)}) + self:set_lines(line[1], line[1] + 1, { fmt(' %s %s: %s', config.done_sym, plugin, message) }) api.nvim_buf_del_extmark(self.buf, self.ns, self.marks[plugin]) self.marks[plugin] = nil self:decrement_headline_count() @@ -218,9 +261,11 @@ local display_mt = { --- Update a task as having unsuccessfully failed task_failed = vim.schedule_wrap(function(self, plugin, message) - if not self:valid_display() then return end + if not self:valid_display() then + return + end local line, _ = get_extmark_by_id(self.buf, self.ns, self.marks[plugin]) - self:set_lines(line[1], line[1] + 1, {fmt(' %s %s: %s', config.error_sym, plugin, message)}) + self:set_lines(line[1], line[1] + 1, { fmt(' %s %s: %s', config.error_sym, plugin, message) }) api.nvim_buf_del_extmark(self.buf, self.ns, self.marks[plugin]) self.marks[plugin] = nil self:decrement_headline_count() @@ -228,81 +273,101 @@ local display_mt = { --- Update the status message of a task in progress task_update = vim.schedule_wrap(function(self, plugin, message) - if not self:valid_display() then return end - if not self.marks[plugin] then return end + if not self:valid_display() then + return + end + if not self.marks[plugin] then + return + end local line, _ = get_extmark_by_id(self.buf, self.ns, self.marks[plugin]) - self:set_lines(line[1], line[1] + 1, {fmt(' %s %s: %s', config.working_sym, plugin, message)}) + self:set_lines(line[1], line[1] + 1, { fmt(' %s %s: %s', config.working_sym, plugin, message) }) set_extmark(self.buf, self.ns, self.marks[plugin], line[1], 0) end), open_preview = function(_, commit, lines) - if not lines or #lines < 1 then return log.warn('No diff available') end - vim.cmd("pedit " .. commit) + if not lines or #lines < 1 then + return log.warn 'No diff available' + end + vim.cmd('pedit ' .. commit) vim.cmd [[wincmd P]] vim.wo.previewwindow = true - vim.bo.buftype = "nofile" + vim.bo.buftype = 'nofile' vim.bo.buflisted = false vim.api.nvim_buf_set_lines(0, 0, -1, false, lines) - vim.api.nvim_buf_set_keymap(0, "n", "q", "close!", - {silent = true, noremap = true, nowait = true}) - vim.bo.filetype = "git" + vim.api.nvim_buf_set_keymap(0, 'n', 'q', 'close!', { silent = true, noremap = true, nowait = true }) + vim.bo.filetype = 'git' end, --- Update the text of the headline message update_headline_message = vim.schedule_wrap(function(self, message) - if not self:valid_display() then return end + if not self:valid_display() then + return + end local headline = config.title .. ' - ' .. message local width = api.nvim_win_get_width(self.win) - 2 local pad_width = math.max(math.floor((width - string.len(headline)) / 2.0), 0) - self:set_lines(0, config.header_lines - 1, - {string.rep(' ', pad_width) .. headline}) + self:set_lines(0, config.header_lines - 1, { string.rep(' ', pad_width) .. headline }) end), --- Setup new syntax group links for the status window setup_status_syntax = function(self) local highlights = { - 'hi def link packerStatus Type', 'hi def link packerStatusCommit Constant', - 'hi def link packerStatusSuccess Constant', 'hi def link packerStatusFail WarningMsg', - 'hi def link packerPackageName Label', 'hi def link packerPackageNotLoaded Comment', - 'hi def link packerString String', 'hi def link packerBool Boolean' + 'hi def link packerStatus Type', + 'hi def link packerStatusCommit Constant', + 'hi def link packerStatusSuccess Constant', + 'hi def link packerStatusFail WarningMsg', + 'hi def link packerPackageName Label', + 'hi def link packerPackageNotLoaded Comment', + 'hi def link packerString String', + 'hi def link packerBool Boolean', } - for _, c in ipairs(highlights) do vim.cmd(c) end + for _, c in ipairs(highlights) do + vim.cmd(c) + end end, setup_profile_syntax = function(_) local highlights = { - 'hi def link packerTimeHigh WarningMsg', 'hi def link packerTimeMedium Float', - 'hi def link packerTimeLow String', 'hi def link packerTimeTrivial Comment' + 'hi def link packerTimeHigh WarningMsg', + 'hi def link packerTimeMedium Float', + 'hi def link packerTimeLow String', + 'hi def link packerTimeTrivial Comment', } - for _, c in ipairs(highlights) do vim.cmd(c) end + for _, c in ipairs(highlights) do + vim.cmd(c) + end end, status = vim.schedule_wrap(function(self, plugins) - if not self:valid_display() then return end + if not self:valid_display() then + return + end self:setup_status_syntax() - self:update_headline_message(fmt("Total plugins: %d", vim.tbl_count(plugins))) + self:update_headline_message(fmt('Total plugins: %d', vim.tbl_count(plugins))) local plugs = {} local lines = {} - local padding = string.rep(" ", 3) + local padding = string.rep(' ', 3) for plug_name, plug_conf in pairs(plugins) do local header_lines = { - fmt(" • %s", plug_name) .. (not plug_conf.loaded and ' (not loaded)' or '') + fmt(' • %s', plug_name) .. (not plug_conf.loaded and ' (not loaded)' or ''), } local config_lines = {} for key, value in pairs(plug_conf) do if vim.tbl_contains(status_keys, key) then local details = format_values(key, value) local name = get_key_name(key) - if type(details) == "string" then + if type(details) == 'string' then -- insert a position one so that one line details appear above multiline ones - table.insert(config_lines, 1, fmt("%s%s: %s", padding, name, details)) + table.insert(config_lines, 1, fmt('%s%s: %s', padding, name, details)) else - details = vim.tbl_map(function(line) return padding .. line end, details) - vim.list_extend(config_lines, {fmt("%s%s: ", padding, name), unpack(details)}) + details = vim.tbl_map(function(line) + return padding .. line + end, details) + vim.list_extend(config_lines, { fmt('%s%s: ', padding, name), unpack(details) }) end - plugs[plug_name] = {lines = config_lines, displayed = false} + plugs[plug_name] = { lines = config_lines, displayed = false } end end vim.list_extend(lines, header_lines) @@ -313,7 +378,9 @@ local display_mt = { --- Display the final results of an operation final_results = vim.schedule_wrap(function(self, results, time) - if not self:valid_display() then return end + if not self:valid_display() then + return + end self:setup_status_syntax() display.status.running = false time = tonumber(time) @@ -331,19 +398,33 @@ local display_mt = { if results.moves then for plugin, result in pairs(results.moves) do table.insert(item_order, plugin) - table.insert(raw_lines, - fmt(' %s %s %s: %s %s %s', - result.result.ok and config.done_sym or config.error_sym, - result.result.ok and 'Moved' or 'Failed to move', plugin, result.from, - config.moved_sym, result.to)) + table.insert( + raw_lines, + fmt( + ' %s %s %s: %s %s %s', + result.result.ok and config.done_sym or config.error_sym, + result.result.ok and 'Moved' or 'Failed to move', + plugin, + result.from, + config.moved_sym, + result.to + ) + ) end end if results.installs then for plugin, result in pairs(results.installs) do table.insert(item_order, plugin) - table.insert(raw_lines, fmt(' %s %s %s', result.ok and config.done_sym or config.error_sym, - result.ok and 'Installed' or 'Failed to install', plugin)) + table.insert( + raw_lines, + fmt( + ' %s %s %s', + result.ok and config.done_sym or config.error_sym, + result.ok and 'Installed' or 'Failed to install', + plugin + ) + ) end end @@ -359,8 +440,10 @@ local display_mt = { table.insert(message, fmt(' %s %s is already up to date', config.done_sym, plugin_name)) else table.insert(item_order, plugin_name) - table.insert(message, fmt(' %s Updated %s: %s..%s', config.done_sym, plugin_name, - plugin.revs[1], plugin.revs[2])) + table.insert( + message, + fmt(' %s Updated %s: %s..%s', config.done_sym, plugin_name, plugin.revs[1], plugin.revs[2]) + ) end else failed_update = true @@ -370,7 +453,9 @@ local display_mt = { end plugin.actual_update = actual_update - if actual_update or failed_update then vim.list_extend(raw_lines, message) end + if actual_update or failed_update then + vim.list_extend(raw_lines, message) + end end end @@ -378,35 +463,48 @@ local display_mt = { if results.luarocks.installs then for package, result in pairs(results.luarocks.installs) do if result.err then - rocks_items[package] = {lines = strip_newlines(result.err.output.data.stderr)} + rocks_items[package] = { lines = strip_newlines(result.err.output.data.stderr) } end - table.insert(raw_lines, - fmt(' %s %s %s', result.ok and config.done_sym or config.error_sym, - result.ok and 'Installed' or 'Failed to install', package)) + table.insert( + raw_lines, + fmt( + ' %s %s %s', + result.ok and config.done_sym or config.error_sym, + result.ok and 'Installed' or 'Failed to install', + package + ) + ) end end if results.luarocks.removals then for package, result in pairs(results.luarocks.removals) do if result.err then - rocks_items[package] = {lines = strip_newlines(result.err.output.data.stderr)} + rocks_items[package] = { lines = strip_newlines(result.err.output.data.stderr) } end - table.insert(raw_lines, - fmt(' %s %s %s', result.ok and config.done_sym or config.error_sym, - result.ok and 'Removed' or 'Failed to remove', package)) + table.insert( + raw_lines, + fmt( + ' %s %s %s', + result.ok and config.done_sym or config.error_sym, + result.ok and 'Removed' or 'Failed to remove', + package + ) + ) end end end - if #raw_lines == 0 then table.insert(raw_lines, ' Everything already up to date!') end + if #raw_lines == 0 then + table.insert(raw_lines, ' Everything already up to date!') + end table.insert(raw_lines, '') for _, keymap in ipairs(keymap_display_order) do if keymaps[keymap].lhs then - table.insert(raw_lines, - fmt(" Press '%s' to %s", keymaps[keymap].lhs, keymaps[keymap].action)) + table.insert(raw_lines, fmt(" Press '%s' to %s", keymaps[keymap].lhs, keymaps[keymap].action)) end end @@ -415,14 +513,14 @@ local display_mt = { self:set_lines(config.header_lines, -1, lines) local plugins = {} for plugin_name, plugin in pairs(results.plugins) do - local plugin_data = {displayed = false, lines = {}, spec = plugin} + local plugin_data = { displayed = false, lines = {}, spec = plugin } if plugin.output then if plugin.output.err and #plugin.output.err > 0 then table.insert(plugin_data.lines, ' Errors:') for _, line in ipairs(plugin.output.err) do line = vim.trim(line) - if line:find('\n') then - for sub_line in line:gmatch("[^\r\n]+") do + if line:find '\n' then + for sub_line in line:gmatch '[^\r\n]+' do table.insert(plugin_data.lines, ' ' .. sub_line) end else @@ -448,14 +546,18 @@ local display_mt = { self.items = vim.tbl_extend('keep', plugins, rocks_items) self.item_order = item_order - if config.show_all_info then self:show_all_info() end + if config.show_all_info then + self:show_all_info() + end end), --- Toggle the display of detailed information for all plugins in the final results display show_all_info = function(self) - if not self:valid_display() then return end + if not self:valid_display() then + return + end if next(self.items) == nil then - log.info('Operations are still running; plugin info is not ready yet') + log.info 'Operations are still running; plugin info is not ready yet' return end @@ -475,21 +577,25 @@ local display_mt = { profile_output = function(self, output) self:setup_profile_syntax() local result = {} - for i, line in ipairs(output) do result[i] = string.rep(" ", 2) .. line end + for i, line in ipairs(output) do + result[i] = string.rep(' ', 2) .. line + end self:set_lines(config.header_lines, -1, result) end, --- Toggle the display of detailed information for a plugin in the final results display toggle_info = function(self) - if not self:valid_display() then return end + if not self:valid_display() then + return + end if self.items == nil or next(self.items) == nil then - log.info('Operations are still running; plugin info is not ready yet') + log.info 'Operations are still running; plugin info is not ready yet' return end local plugin_name, cursor_pos = self:find_nearest_plugin() if plugin_name == nil then - log.warn('No plugin selected!') + log.warn 'No plugin selected!' return end @@ -506,20 +612,22 @@ local display_mt = { end, diff = function(self) - if not self:valid_display() then return end + if not self:valid_display() then + return + end if next(self.items) == nil then - log.info('Operations are still running; plugin info is not ready yet') + log.info 'Operations are still running; plugin info is not ready yet' return end local plugin_name, _ = self:find_nearest_plugin() if plugin_name == nil then - log.warn('No plugin selected!') + log.warn 'No plugin selected!' return end if not self.items[plugin_name] or not self.items[plugin_name].spec then - log.warn('Plugin not available!') + log.warn 'Plugin not available!' return end @@ -527,35 +635,46 @@ local display_mt = { local current_line = self:get_current_line() local commit_hash = vim.fn.matchstr(current_line, [[\X*\zs[0-9a-f]\{7,9}]]) if not commit_hash then - log.warn('Unable to find the diff for this line') + log.warn 'Unable to find the diff for this line' return end plugin_data.diff(commit_hash, function(diff, err) - if err then return log.warn('Unable to get diff!') end + if err then + return log.warn 'Unable to get diff!' + end local lines = vim.split(diff[1], '\n') - vim.schedule(function() self:open_preview(commit_hash, lines) end) + vim.schedule(function() + self:open_preview(commit_hash, lines) + end) end) end, --- Prompt a user to revert the latest update for a plugin prompt_revert = function(self) - if not self:valid_display() then return end + if not self:valid_display() then + return + end if next(self.items) == nil then - log.info('Operations are still running; plugin info is not ready yet') + log.info 'Operations are still running; plugin info is not ready yet' return end local plugin_name, _ = self:find_nearest_plugin() if plugin_name == nil then - log.warn('No plugin selected!') + log.warn 'No plugin selected!' return end local plugin_data = self.items[plugin_name].spec if plugin_data.actual_update then prompt_user('Revert update for ' .. plugin_name .. '?', { - 'Do you want to revert ' .. plugin_name .. ' from ' .. plugin_data.revs[2] .. ' to ' - .. plugin_data.revs[1] .. '?' + 'Do you want to revert ' + .. plugin_name + .. ' from ' + .. plugin_data.revs[2] + .. ' to ' + .. plugin_data.revs[1] + .. '?', }, function(ans) if ans then local r = plugin_data.revert_last() @@ -573,46 +692,60 @@ local display_mt = { --- Heuristically find the plugin nearest to the cursor for displaying detailed information find_nearest_plugin = function(self) - if not self:valid_display() then return end + if not self:valid_display() then + return + end local cursor_pos = api.nvim_win_get_cursor(0) -- TODO: this is a dumb hack for i = cursor_pos[1], 1, -1 do local curr_line = api.nvim_buf_get_lines(0, i - 1, i, true)[1] for name, _ in pairs(self.items) do - if string.find(curr_line, name, 1, true) then return name, {i, 0} end + if string.find(curr_line, name, 1, true) then + return name, { i, 0 } + end end end - end + end, } display_mt.__index = display_mt -local function look_back(str) return string.format([[\(%s\)\@%d<=]], str, #str) end +local function look_back(str) + return string.format([[\(%s\)\@%d<=]], str, #str) +end -- TODO: Option for no colors local function make_filetype_cmds(working_sym, done_sym, error_sym) return { -- Adapted from https://github.com/kristijanhusak/vim-packager 'setlocal buftype=nofile bufhidden=wipe nobuflisted nolist noswapfile nowrap nospell nonumber norelativenumber nofoldenable signcolumn=no', - 'syntax clear', 'syn match packerWorking /^ ' .. working_sym .. '/', + 'syntax clear', + 'syn match packerWorking /^ ' .. working_sym .. '/', 'syn match packerSuccess /^ ' .. done_sym .. '/', - 'syn match packerFail /^ ' .. error_sym .. '/', 'syn match packerStatus /^+.*—\\zs\\s.*$/', + 'syn match packerFail /^ ' .. error_sym .. '/', + 'syn match packerStatus /^+.*—\\zs\\s.*$/', 'syn match packerStatusSuccess /' .. look_back('^ ' .. done_sym) .. '\\s.*$/', 'syn match packerStatusFail /' .. look_back('^ ' .. error_sym) .. '\\s.*$/', 'syn match packerStatusCommit /^\\*.*—\\zs\\s.*$/', 'syn match packerHash /\\(\\s\\)[0-9a-f]\\{7,8}\\(\\s\\)/', - 'syn match packerRelDate /([^)]*)$/', 'syn match packerProgress /\\[\\zs[\\=]*/', + 'syn match packerRelDate /([^)]*)$/', + 'syn match packerProgress /\\[\\zs[\\=]*/', 'syn match packerOutput /\\(Output:\\)\\|\\(Commits:\\)\\|\\(Errors:\\)/', [[syn match packerTimeHigh /\d\{3\}\.\d\+ms/]], - [[syn match packerTimeMedium /\d\{2\}\.\d\+ms/]], [[syn match packerTimeLow /\d\.\d\+ms/]], + [[syn match packerTimeMedium /\d\{2\}\.\d\+ms/]], + [[syn match packerTimeLow /\d\.\d\+ms/]], [[syn match packerTimeTrivial /0\.\d\+ms/]], [[syn match packerPackageNotLoaded /(not loaded)$/]], [[syn match packerPackageName /^\ • \zs[^ ]*/]], [[syn match packerString /\v(''|""|(['"]).{-}[^\\]\2)/]], - [[syn match packerBool /\<\(false\|true\)\>/]], 'hi def link packerWorking SpecialKey', - 'hi def link packerSuccess Question', 'hi def link packerFail ErrorMsg', - 'hi def link packerHash Identifier', 'hi def link packerRelDate Comment', - 'hi def link packerProgress Boolean', 'hi def link packerOutput Type' + [[syn match packerBool /\<\(false\|true\)\>/]], + 'hi def link packerWorking SpecialKey', + 'hi def link packerSuccess Question', + 'hi def link packerFail ErrorMsg', + 'hi def link packerHash Identifier', + 'hi def link packerRelDate Comment', + 'hi def link packerProgress Boolean', + 'hi def link packerOutput Type', } end @@ -620,7 +753,9 @@ display.cfg = function(_config) config = _config.display if config.keybindings then for name, lhs in pairs(config.keybindings) do - if keymaps[name] then keymaps[name].lhs = lhs end + if keymaps[name] then + keymaps[name].lhs = lhs + end end end config.filetype_cmds = make_filetype_cmds(config.working_sym, config.done_sym, config.error_sym) @@ -632,7 +767,7 @@ local function make_header(disp) local pad_width = math.floor((width - string.len(config.title)) / 2.0) api.nvim_buf_set_lines(disp.buf, 0, 1, true, { string.rep(' ', pad_width) .. config.title, - ' ' .. string.rep(config.header_sym, width - 2) + ' ' .. string.rep(config.header_sym, width - 2), }) end @@ -642,10 +777,12 @@ local function setup_window(disp) api.nvim_buf_set_name(disp.buf, '[packer]') for _, m in pairs(keymaps) do if m.lhs then - api.nvim_buf_set_keymap(disp.buf, 'n', m.lhs, m.rhs, {nowait = true, silent = true}) + api.nvim_buf_set_keymap(disp.buf, 'n', m.lhs, m.rhs, { nowait = true, silent = true }) end end - for _, c in ipairs(config.filetype_cmds) do vim.cmd(c) end + for _, c in ipairs(config.filetype_cmds) do + vim.cmd(c) + end end --- Open a new display window @@ -670,7 +807,7 @@ display.open = function(opener) disp.win = api.nvim_get_current_win() disp.buf = api.nvim_get_current_buf() else - local status, win, buf = opener('[packer]') + local status, win, buf = opener '[packer]' if not status then log.error('Failure running opener function: ' .. vim.inspect(win)) error(win) @@ -680,7 +817,7 @@ display.open = function(opener) disp.buf = buf end - disp.ns = api.nvim_create_namespace('') + disp.ns = api.nvim_create_namespace '' make_header(disp) setup_window(disp) display.status.disp = disp @@ -689,7 +826,7 @@ display.open = function(opener) return disp end -display.status = {running = false, disp = nil} +display.status = { running = false, disp = nil } --- Close a display window and signal that any running operations should terminate display.quit = function() @@ -697,13 +834,22 @@ display.quit = function() vim.fn.execute('q!', 'silent') end -display.toggle_info = - function() if display.status.disp then display.status.disp:toggle_info() end end +display.toggle_info = function() + if display.status.disp then + display.status.disp:toggle_info() + end +end -display.diff = function() if display.status.disp then display.status.disp:diff() end end +display.diff = function() + if display.status.disp then + display.status.disp:diff() + end +end display.prompt_revert = function() - if display.status.disp then display.status.disp:prompt_revert() end + if display.status.disp then + display.status.disp:prompt_revert() + end end --- Async prompt_user diff --git a/lua/packer/handlers.lua b/lua/packer/handlers.lua index 6f917439..63a09064 100644 --- a/lua/packer/handlers.lua +++ b/lua/packer/handlers.lua @@ -5,7 +5,7 @@ local function cfg(_config) end local handlers = { - cfg = cfg + cfg = cfg, } return handlers diff --git a/lua/packer/install.lua b/lua/packer/install.lua index b8317aa2..a80f26fe 100644 --- a/lua/packer/install.lua +++ b/lua/packer/install.lua @@ -1,8 +1,8 @@ -local a = require('packer.async') -local log = require('packer.log') -local util = require('packer.util') -local display = require('packer.display') -local plugin_utils = require('packer.plugin_utils') +local a = require 'packer.async' +local log = require 'packer.log' +local util = require 'packer.util' +local display = require 'packer.display' +local plugin_utils = require 'packer.plugin_utils' local fmt = string.format local async = a.sync @@ -49,8 +49,10 @@ local function do_install(_, plugins, missing_plugins, results) return tasks, display_win end -local function cfg(_config) config = _config end +local function cfg(_config) + config = _config +end -local install = setmetatable({cfg = cfg}, {__call = do_install}) +local install = setmetatable({ cfg = cfg }, { __call = do_install }) return install diff --git a/lua/packer/jobs.lua b/lua/packer/jobs.lua index f49fcd34..cd791d89 100644 --- a/lua/packer/jobs.lua +++ b/lua/packer/jobs.lua @@ -1,9 +1,9 @@ -- Interface with Neovim job control and provide a simple job sequencing structure local split = vim.split local loop = vim.loop -local a = require('packer.async') -local log = require('packer.log') -local result = require('packer.result') +local a = require 'packer.async' +local log = require 'packer.log' +local result = require 'packer.result' --- Utility function to make a "standard" logging callback for a given set of tables -- Arguments: @@ -15,11 +15,15 @@ local result = require('packer.result') -- - name: optional string name for a current task. Used to update task status local function make_logging_callback(err_tbl, data_tbl, pipe, disp, name) return function(err, data) - if err then table.insert(err_tbl, vim.trim(err)) end + if err then + table.insert(err_tbl, vim.trim(err)) + end if data ~= nil then local trimmed = vim.trim(data) table.insert(data_tbl, trimmed) - if disp then disp:task_update(name, split(trimmed, '\n')[1]) end + if disp then + disp:task_update(name, split(trimmed, '\n')[1]) + end else loop.read_stop(pipe) loop.close(pipe) @@ -29,7 +33,7 @@ end --- Utility function to make a table for capturing output with "standard" structure local function make_output_table() - return {err = {stdout = {}, stderr = {}}, data = {stdout = {}, stderr = {}}} + return { err = { stdout = {}, stderr = {} }, data = { stdout = {}, stderr = {} } } end --- Utility function to merge stdout and stderr from two tables with "standard" structure (either @@ -56,7 +60,11 @@ local spawn = a.wrap(function(cmd, options, callback) loop.close(options.stdio[1]) local check = loop.new_check() loop.check_start(check, function() - for _, pipe in pairs(options.stdio) do if not loop.is_closing(pipe) then return end end + for _, pipe in pairs(options.stdio) do + if not loop.is_closing(pipe) then + return + end + end loop.check_stop(check) callback(exit_code, signal) end) @@ -64,13 +72,15 @@ local spawn = a.wrap(function(cmd, options, callback) if options.stdio then for i, pipe in pairs(options.stdio) do - if options.stdio_callbacks[i] then loop.read_start(pipe, options.stdio_callbacks[i]) end + if options.stdio_callbacks[i] then + loop.read_start(pipe, options.stdio_callbacks[i]) + end end end if options.timeout then timer = loop.new_timer() - timer:start(options.timeout, 0, function () + timer:start(options.timeout, 0, function() timer:stop() timer:close() if loop.is_active(handle) then @@ -108,10 +118,10 @@ end -- to the given tables) local run_job = function(task, opts) return a.sync(function() - local options = opts.options or {hide = true} + local options = opts.options or { hide = true } local stdout = nil local stderr = nil - local job_result = {exit_code = -1, signal = -1} + local job_result = { exit_code = -1, signal = -1 } local success_test = opts.success_test or was_successful local uv_err local output = make_output_table() @@ -183,13 +193,15 @@ local run_job = function(task, opts) options.cwd = opts.cwd local stdin = loop.new_pipe(false) - options.args = {unpack(task, 2)} - options.stdio = {stdin, stdout, stderr} - options.stdio_callbacks = {nil, callbacks.stdout, callbacks.stderr} + options.args = { unpack(task, 2) } + options.stdio = { stdin, stdout, stderr } + options.stdio_callbacks = { nil, callbacks.stdout, callbacks.stderr } local exit_code, signal = a.wait(spawn(cmd, options)) - job_result = {exit_code = exit_code, signal = signal} - if output_valid then job_result.output = output end + job_result = { exit_code = exit_code, signal = signal } + if output_valid then + job_result.output = output + end return success_test(job_result) end) end @@ -198,7 +210,7 @@ local jobs = { run = run_job, logging_callback = make_logging_callback, output_table = make_output_table, - extend_output = extend_output + extend_output = extend_output, } return jobs diff --git a/lua/packer/load.lua b/lua/packer/load.lua index 39ab7413..2bc36d70 100644 --- a/lua/packer/load.lua +++ b/lua/packer/load.lua @@ -8,8 +8,7 @@ packer_load = function(names, cause, plugins) for i = 1, num_names do local plugin = plugins[names[i]] if not plugin then - local err_message = 'Error: attempted to load ' .. names[i] - .. ' which is not present in plugins table!' + local err_message = 'Error: attempted to load ' .. names[i] .. ' which is not present in plugins table!' print(err_message) error(err_message) end @@ -21,15 +20,21 @@ packer_load = function(names, cause, plugins) some_unloaded = true needs_bufread = needs_bufread or plugin.needs_bufread if plugin.wants then - for _, wanted_name in ipairs(plugin.wants) do packer_load({wanted_name}, {}, plugins) end + for _, wanted_name in ipairs(plugin.wants) do + packer_load({ wanted_name }, {}, plugins) + end end if plugin.commands then - for _, del_cmd in ipairs(plugin.commands) do cmd('silent! delcommand ' .. del_cmd) end + for _, del_cmd in ipairs(plugin.commands) do + cmd('silent! delcommand ' .. del_cmd) + end end if plugin.keys then - for _, key in ipairs(plugin.keys) do cmd(fmt('silent! %sunmap %s', key[1], key[2])) end + for _, key in ipairs(plugin.keys) do + cmd(fmt('silent! %sunmap %s', key[1], key[2])) + end end cmd('packadd ' .. names[i]) @@ -54,15 +59,19 @@ packer_load = function(names, cause, plugins) local after_plugin = plugins[after_name] after_plugin.load_after[names[i]] = nil if next(after_plugin.load_after) == nil then - packer_load({after_name}, {}, plugins) + packer_load({ after_name }, {}, plugins) end end end end end - if not some_unloaded then return end - if needs_bufread then cmd('doautocmd BufRead') end + if not some_unloaded then + return + end + if needs_bufread then + cmd 'doautocmd BufRead' + end if cause.cmd then local lines = cause.l1 == cause.l2 and '' or (cause.l1 .. ',' .. cause.l2) vim.cmd(fmt('%s%s%s %s', lines, cause.cmd, cause.bang, cause.args)) @@ -70,15 +79,19 @@ packer_load = function(names, cause, plugins) local extra = '' while true do local c = vim.fn.getchar(0) - if c == 0 then break end + if c == 0 then + break + end extra = extra .. vim.fn.nr2char(c) end if cause.prefix then local prefix = vim.v.count ~= 0 and vim.v.count or '' prefix = prefix .. '"' .. vim.v.register .. cause.prefix - if vim.fn.mode('full') == 'no' then - if vim.v.operator == 'c' then prefix = '' .. prefix end + if vim.fn.mode 'full' == 'no' then + if vim.v.operator == 'c' then + prefix = '' .. prefix + end prefix = prefix .. vim.v.operator end @@ -98,10 +111,10 @@ end local function load_wrapper(names, cause, plugins) local success, err_msg = pcall(packer_load, names, cause, plugins) if not success then - vim.cmd('echohl ErrorMsg') + vim.cmd 'echohl ErrorMsg' vim.cmd('echomsg "Error in packer_compiled: ' .. vim.fn.escape(err_msg, '"') .. '"') - vim.cmd('echomsg "Please check your config for correctness"') - vim.cmd('echohl None') + vim.cmd 'echomsg "Please check your config for correctness"' + vim.cmd 'echohl None' end end diff --git a/lua/packer/log.lua b/lua/packer/log.lua index 405b2ac7..7d0e851d 100644 --- a/lua/packer/log.lua +++ b/lua/packer/log.lua @@ -20,20 +20,23 @@ local default_config = { use_file = true, -- Any messages above this level will be logged. - level = "debug", + level = 'debug', -- Level configuration modes = { - {name = "trace", hl = "Comment"}, {name = "debug", hl = "Comment"}, - {name = "info", hl = "None"}, {name = "warn", hl = "WarningMsg"}, - {name = "error", hl = "ErrorMsg"}, {name = "fatal", hl = "ErrorMsg"} + { name = 'trace', hl = 'Comment' }, + { name = 'debug', hl = 'Comment' }, + { name = 'info', hl = 'None' }, + { name = 'warn', hl = 'WarningMsg' }, + { name = 'error', hl = 'ErrorMsg' }, + { name = 'fatal', hl = 'ErrorMsg' }, }, -- Which levels should be printed? - console_levels = {[3] = true, [4] = true, [5] = true, [6] = true}, + console_levels = { [3] = true, [4] = true, [5] = true, [6] = true }, -- Can limit the number of decimals displayed for floats - float_precision = 0.01 + float_precision = 0.01, } -- {{{ NO NEED TO CHANGE @@ -41,18 +44,22 @@ local log = {} local unpack = unpack or table.unpack -local level_ids = {trace = 1, debug = 2, info = 3, warn = 4, error = 5, fatal = 6} +local level_ids = { trace = 1, debug = 2, info = 3, warn = 4, error = 5, fatal = 6 } log.cfg = function(_config) local print_level = level_ids[_config.log.level] - local config = {console_levels = {}} - if print_level then for i = print_level, 6 do config.console_levels[i] = true end end + local config = { console_levels = {} } + if print_level then + for i = print_level, 6 do + config.console_levels[i] = true + end + end log.new(config, true) end log.new = function(config, standalone) - config = vim.tbl_deep_extend("force", default_config, config) - local outfile = string.format('%s/%s.log', vim.fn.stdpath('cache'), config.plugin) - vim.fn.mkdir(vim.fn.stdpath('cache'), 'p') + config = vim.tbl_deep_extend('force', default_config, config) + local outfile = string.format('%s/%s.log', vim.fn.stdpath 'cache', config.plugin) + vim.fn.mkdir(vim.fn.stdpath 'cache', 'p') local obj if standalone then obj = log @@ -61,12 +68,14 @@ log.new = function(config, standalone) end local levels = {} - for i, v in ipairs(config.modes) do levels[v.name] = i end + for i, v in ipairs(config.modes) do + levels[v.name] = i + end local round = function(x, increment) increment = increment or 1 x = x / increment - return (x > 0 and math.floor(x + .5) or math.ceil(x - .5)) * increment + return (x > 0 and math.floor(x + 0.5) or math.ceil(x - 0.5)) * increment end local make_string = function(...) @@ -74,9 +83,9 @@ log.new = function(config, standalone) for i = 1, select('#', ...) do local x = select(i, ...) - if type(x) == "number" and config.float_precision then + if type(x) == 'number' and config.float_precision then x = tostring(round(x, config.float_precision)) - elseif type(x) == "table" then + elseif type(x) == 'table' then x = vim.inspect(x) else x = tostring(x) @@ -84,34 +93,37 @@ log.new = function(config, standalone) t[#t + 1] = x end - return table.concat(t, " ") + return table.concat(t, ' ') end local console_output = vim.schedule_wrap(function(level_config, info, nameupper, msg) local console_lineinfo = vim.fn.fnamemodify(info.short_src, ':t') .. ':' .. info.currentline - local console_string = string.format("[%-6s%s] %s: %s", nameupper, os.date("%H:%M:%S"), - console_lineinfo, msg) + local console_string = string.format('[%-6s%s] %s: %s', nameupper, os.date '%H:%M:%S', console_lineinfo, msg) if config.highlights and level_config.hl then - vim.cmd(string.format("echohl %s", level_config.hl)) + vim.cmd(string.format('echohl %s', level_config.hl)) end - local split_console = vim.split(console_string, "\n") + local split_console = vim.split(console_string, '\n') for _, v in ipairs(split_console) do vim.cmd(string.format([[echom "[%s] %s"]], config.plugin, vim.fn.escape(v, '"'))) end - if config.highlights and level_config.hl then vim.cmd("echohl NONE") end + if config.highlights and level_config.hl then + vim.cmd 'echohl NONE' + end end) local log_at_level = function(level, level_config, message_maker, ...) -- Return early if we're below the config.level - if level < levels[config.level] then return end + if level < levels[config.level] then + return + end local nameupper = level_config.name:upper() local msg = message_maker(...) - local info = debug.getinfo(2, "Sl") - local lineinfo = info.short_src .. ":" .. info.currentline + local info = debug.getinfo(2, 'Sl') + local lineinfo = info.short_src .. ':' .. info.currentline -- Output to console if config.use_console and config.console_levels[level] then @@ -120,28 +132,31 @@ log.new = function(config, standalone) -- Output to log file if config.use_file then - local fp, err = io.open(outfile, "a") + local fp, err = io.open(outfile, 'a') if not fp then print(err) return end - local str = string.format("[%-6s%s %s] %s: %s\n", nameupper, os.date(), vim.loop.hrtime(), - lineinfo, msg) + local str = string.format('[%-6s%s %s] %s: %s\n', nameupper, os.date(), vim.loop.hrtime(), lineinfo, msg) fp:write(str) fp:close() end end for i, x in ipairs(config.modes) do - obj[x.name] = function(...) return log_at_level(i, x, make_string, ...) end + obj[x.name] = function(...) + return log_at_level(i, x, make_string, ...) + end - obj[("fmt_%s"):format(x.name)] = function() + obj[('fmt_%s'):format(x.name)] = function() return log_at_level(i, x, function(...) - local passed = {...} + local passed = { ... } local fmt = table.remove(passed, 1) local inspected = {} - for _, v in ipairs(passed) do table.insert(inspected, vim.inspect(v)) end + for _, v in ipairs(passed) do + table.insert(inspected, vim.inspect(v)) + end return string.format(fmt, unpack(inspected)) end) end diff --git a/lua/packer/luarocks.lua b/lua/packer/luarocks.lua index 4195e91b..e668e786 100644 --- a/lua/packer/luarocks.lua +++ b/lua/packer/luarocks.lua @@ -1,23 +1,27 @@ -- Add support for installing and cleaning Luarocks dependencies -- Based off of plenary/neorocks/init.lua in https://github.com/nvim-lua/plenary.nvim -local a = require('packer.async') -local jobs = require('packer.jobs') -local log = require('packer.log') -local result = require('packer.result') -local util = require('packer.util') +local a = require 'packer.async' +local jobs = require 'packer.jobs' +local log = require 'packer.log' +local result = require 'packer.result' +local util = require 'packer.util' local fmt = string.format local async = a.sync local await = a.wait local config = nil -local function cfg(_config) config = _config.luarocks end -local function warn_need_luajit() log.error('LuaJIT is required for Luarocks functionality!') end +local function cfg(_config) + config = _config.luarocks +end +local function warn_need_luajit() + log.error 'LuaJIT is required for Luarocks functionality!' +end local lua_version = nil if jit then local jit_version = string.gsub(jit.version, 'LuaJIT ', '') - lua_version = {lua = string.gsub(_VERSION, 'Lua ', ''), jit = jit_version, dir = jit_version} + lua_version = { lua = string.gsub(_VERSION, 'Lua ', ''), jit = jit_version, dir = jit_version } else return { handle_command = warn_need_luajit, @@ -29,19 +33,23 @@ else clean = warn_need_luajit, install = warn_need_luajit, ensure = warn_need_luajit, - generate_path_setup = function() return '' end, - cfg = cfg + generate_path_setup = function() + return '' + end, + cfg = cfg, } end -local cache_path = vim.fn.stdpath('cache') +local cache_path = vim.fn.stdpath 'cache' local rocks_path = util.join_paths(cache_path, 'packer_hererocks') local hererocks_file = util.join_paths(rocks_path, 'hererocks.py') local hererocks_install_dir = util.join_paths(rocks_path, lua_version.dir) local shell_hererocks_dir = vim.fn.shellescape(hererocks_install_dir) local _hererocks_setup_done = false local function hererocks_is_setup() - if _hererocks_setup_done then return true end + if _hererocks_setup_done then + return true + end local path_info = vim.loop.fs_stat(util.join_paths(hererocks_install_dir, 'lib')) _hererocks_setup_done = (path_info ~= nil) and (path_info['type'] == 'directory') return _hererocks_setup_done @@ -53,36 +61,49 @@ local function hererocks_installer(disp) local hererocks_cmd await(a.main) vim.fn.mkdir(rocks_path, 'p') - if vim.fn.executable('curl') > 0 then + if vim.fn.executable 'curl' > 0 then hererocks_cmd = 'curl ' .. hererocks_url .. ' -o ' .. hererocks_file - elseif vim.fn.executable('wget') > 0 then + elseif vim.fn.executable 'wget' > 0 then hererocks_cmd = 'wget ' .. hererocks_url .. ' -O ' .. hererocks_file .. ' --verbose' else - return result.err('"curl" or "wget" is required to install hererocks') + return result.err '"curl" or "wget" is required to install hererocks' end - if disp ~= nil then disp:task_start('luarocks-hererocks', 'installing hererocks...') end + if disp ~= nil then + disp:task_start('luarocks-hererocks', 'installing hererocks...') + end local output = jobs.output_table() local callbacks = { - stdout = jobs.logging_callback(output.err.stdout, output.data.stdout, nil, disp, - 'luarocks-hererocks'), - stderr = jobs.logging_callback(output.err.stderr, output.data.stderr) + stdout = jobs.logging_callback(output.err.stdout, output.data.stdout, nil, disp, 'luarocks-hererocks'), + stderr = jobs.logging_callback(output.err.stderr, output.data.stderr), } - local opts = {capture_output = callbacks} + local opts = { capture_output = callbacks } local r = await(jobs.run(hererocks_cmd, opts)):map_err(function(err) - return {msg = 'Error installing hererocks', data = err, output = output} + return { msg = 'Error installing hererocks', data = err, output = output } end) - local luarocks_cmd = config.python_cmd .. ' ' .. hererocks_file .. ' --verbose -j ' - .. lua_version.jit .. ' -r latest ' .. hererocks_install_dir - r:and_then(await, jobs.run(luarocks_cmd, opts)):map_ok(function() - if disp then disp:task_succeeded('luarocks-hererocks', 'installed hererocks!') end - end):map_err(function(err) - if disp then disp:task_failed('luarocks-hererocks', 'failed to install hererocks!') end - log.error('Failed to install hererocks: ' .. vim.inspect(err)) - return {msg = 'Error installing luarocks', data = err, output = output} - end) + local luarocks_cmd = config.python_cmd + .. ' ' + .. hererocks_file + .. ' --verbose -j ' + .. lua_version.jit + .. ' -r latest ' + .. hererocks_install_dir + r + :and_then(await, jobs.run(luarocks_cmd, opts)) + :map_ok(function() + if disp then + disp:task_succeeded('luarocks-hererocks', 'installed hererocks!') + end + end) + :map_err(function(err) + if disp then + disp:task_failed('luarocks-hererocks', 'failed to install hererocks!') + end + log.error('Failed to install hererocks: ' .. vim.inspect(err)) + return { msg = 'Error installing luarocks', data = err, output = output } + end) return r end) end @@ -93,8 +114,7 @@ local function package_patterns(dir) end local package_paths = (function() - local install_path = util.join_paths(hererocks_install_dir, 'lib', 'luarocks', - fmt('rocks-%s', lua_version.lua)) + local install_path = util.join_paths(hererocks_install_dir, 'lib', 'luarocks', fmt('rocks-%s', lua_version.lua)) local share_path = util.join_paths(hererocks_install_dir, 'share', 'lua', lua_version.lua) return package_patterns(share_path) .. ';' .. package_patterns(install_path) end)() @@ -102,12 +122,12 @@ end)() local nvim_paths_are_setup = false local function setup_nvim_paths() if not hererocks_is_setup() then - log.warn('Tried to setup Neovim Lua paths before hererocks was setup!') + log.warn 'Tried to setup Neovim Lua paths before hererocks was setup!' return end if nvim_paths_are_setup then - log.warn('Tried to setup Neovim Lua paths redundantly!') + log.warn 'Tried to setup Neovim Lua paths redundantly!' return end @@ -146,8 +166,8 @@ end local function activate_hererocks_cmd(install_path) local activate_file = 'activate' - local user_shell = os.getenv('SHELL') - local shell = user_shell:gmatch('([^/]*)$')() + local user_shell = os.getenv 'SHELL' + local shell = user_shell:gmatch '([^/]*)$'() if shell == 'fish' then activate_file = 'activate.fish' elseif shell == 'csh' then @@ -159,38 +179,45 @@ end local function run_luarocks(args, disp, operation_name) local cmd = { - os.getenv('SHELL'), '-c', - fmt('%s && luarocks --tree=%s %s', activate_hererocks_cmd(hererocks_install_dir), - shell_hererocks_dir, args) + os.getenv 'SHELL', + '-c', + fmt('%s && luarocks --tree=%s %s', activate_hererocks_cmd(hererocks_install_dir), shell_hererocks_dir, args), } return async(function() local output = jobs.output_table() local callbacks = { - stdout = jobs.logging_callback(output.err.stdout, output.data.stdout, nil, disp, - operation_name), - stderr = jobs.logging_callback(output.err.stderr, output.data.stderr) + stdout = jobs.logging_callback(output.err.stdout, output.data.stdout, nil, disp, operation_name), + stderr = jobs.logging_callback(output.err.stderr, output.data.stderr), } - local opts = {capture_output = callbacks} - return await(jobs.run(cmd, opts)):map_err(function(err) - return {msg = fmt('Error running luarocks %s', args), data = err, output = output} - end):map_ok(function(data) return {data = data, output = output} end) + local opts = { capture_output = callbacks } + return await(jobs.run(cmd, opts)) + :map_err(function(err) + return { msg = fmt('Error running luarocks %s', args), data = err, output = output } + end) + :map_ok(function(data) + return { data = data, output = output } + end) end) end -local luarocks_keys = {only_server = 'only-server', only_source = 'only-sources'} +local luarocks_keys = { only_server = 'only-server', only_source = 'only-sources' } -local function is_valid_luarock_key(key) return not (key == 'tree' or key == 'local') end +local function is_valid_luarock_key(key) + return not (key == 'tree' or key == 'local') +end local function format_luarocks_args(package) - if type(package) ~= 'table' then return '' end + if type(package) ~= 'table' then + return '' + end local args = {} for key, value in pairs(package) do - if type(key) == "string" and is_valid_luarock_key(key) then + if type(key) == 'string' and is_valid_luarock_key(key) then local luarock_key = luarocks_keys[key] and luarocks_keys[key] or key if luarock_key and type(value) == 'string' then table.insert(args, string.format('--%s=%s', key, value)) - elseif key == "env" and type(value) == "table" then + elseif key == 'env' and type(value) == 'table' then for name, env_value in pairs(value) do table.insert(args, string.format('%s=%s', name, env_value)) end @@ -203,12 +230,15 @@ end local function luarocks_install(package, results, disp) return async(function() local package_name = type(package) == 'table' and package[1] or package - if disp then disp:task_update('luarocks-install', 'installing ' .. package_name) end + if disp then + disp:task_update('luarocks-install', 'installing ' .. package_name) + end local args = format_luarocks_args(package) local version = package.version and ' ' .. package.version .. ' ' or '' - local install_result = await(run_luarocks('install ' .. package_name .. version .. args, disp, - 'luarocks-install')) - if results then results.luarocks.installs[package_name] = install_result end + local install_result = await(run_luarocks('install ' .. package_name .. version .. args, disp, 'luarocks-install')) + if results then + results.luarocks.installs[package_name] = install_result + end return install_result end) end @@ -216,24 +246,38 @@ end local function install_packages(packages, results, disp) return async(function() local r = result.ok() - if not hererocks_is_setup() then r:and_then(await, hererocks_installer(disp)) end - if disp then disp:task_start('luarocks-install', 'installing rocks...') end - if results then results.luarocks.installs = {} end + if not hererocks_is_setup() then + r:and_then(await, hererocks_installer(disp)) + end + if disp then + disp:task_start('luarocks-install', 'installing rocks...') + end + if results then + results.luarocks.installs = {} + end for _, package in ipairs(packages) do r:and_then(await, luarocks_install(package, results, disp)) end - r:map_ok(function() - if disp then disp:task_succeeded('luarocks-install', 'rocks installed!') end - end):map_err(function() - if disp then disp:task_failed('luarocks-install', 'installing rocks failed!') end - end) + r + :map_ok(function() + if disp then + disp:task_succeeded('luarocks-install', 'rocks installed!') + end + end) + :map_err(function() + if disp then + disp:task_failed('luarocks-install', 'installing rocks failed!') + end + end) return r end) end --- Install the packages specified with `packages` synchronously local function install_sync(packages) - return async(function() return await(install_packages(packages)) end)() + return async(function() + return await(install_packages(packages)) + end)() end local function chunk_output(output) @@ -246,19 +290,20 @@ end local function luarocks_list(disp) return async(function() local r = result.ok() - if not hererocks_is_setup() then r:and_then(await, hererocks_installer(disp)) end - r:and_then(await, run_luarocks('list --porcelain')) + if not hererocks_is_setup() then + r:and_then(await, hererocks_installer(disp)) + end + r:and_then(await, run_luarocks 'list --porcelain') return r:map_ok(function(data) local results = {} local output = chunk_output(data.output.data.stdout) for _, line in ipairs(output) do - for l_package, version, status, install_path in string.gmatch(line, - "([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)") do + for l_package, version, status, install_path in string.gmatch(line, '([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)') do table.insert(results, { name = l_package, version = version, status = status, - install_path = install_path + install_path = install_path, }) end end @@ -271,7 +316,9 @@ end local function luarocks_show(package, disp) return async(function() local r = result.ok() - if not hererocks_is_setup() then r:and_then(await, hererocks_installer(disp)) end + if not hererocks_is_setup() then + r:and_then(await, hererocks_installer(disp)) + end r:and_then(await, run_luarocks('show --porcelain ' .. package)) return r:map_ok(function(data) local output = chunk_output(data.output.data.stdout) @@ -282,8 +329,9 @@ local function luarocks_show(package, disp) components[#components + 1] = component end - if (components[1] == 'dependency' or components[1] == 'indirect_dependency') - and (components[2] ~= 'lua') then dependencies[components[2]] = components[2] end + if (components[1] == 'dependency' or components[1] == 'indirect_dependency') and (components[2] ~= 'lua') then + dependencies[components[2]] = components[2] + end end return dependencies @@ -293,9 +341,13 @@ end local function luarocks_remove(package, results, disp) return async(function() - if disp then disp:task_update('luarocks-remove', 'removing ' .. package) end + if disp then + disp:task_update('luarocks-remove', 'removing ' .. package) + end local remove_result = await(run_luarocks('remove ' .. package, disp, 'luarocks-remove')) - if results then results.luarocks.removals[package] = remove_result end + if results then + results.luarocks.removals[package] = remove_result + end return remove_result end) end @@ -303,17 +355,29 @@ end local function uninstall_packages(packages, results, disp) return async(function() local r = result.ok() - if not hererocks_is_setup() then r:and_then(await, hererocks_installer(disp)) end - if disp then disp:task_start('luarocks-remove', 'uninstalling rocks...') end - if results then results.luarocks.removals = {} end + if not hererocks_is_setup() then + r:and_then(await, hererocks_installer(disp)) + end + if disp then + disp:task_start('luarocks-remove', 'uninstalling rocks...') + end + if results then + results.luarocks.removals = {} + end for _, package in ipairs(packages) do - local name = type(package) == "table" and package[1] or package + local name = type(package) == 'table' and package[1] or package r:and_then(await, luarocks_remove(name, results, disp)) end - r:map_ok( - function() if disp then disp:task_succeeded('luarocks-remove', 'rocks cleaned!') end end) + r + :map_ok(function() + if disp then + disp:task_succeeded('luarocks-remove', 'rocks cleaned!') + end + end) :map_err(function() - if disp then disp:task_failed('luarocks-remove', 'cleaning rocks failed!') end + if disp then + disp:task_failed('luarocks-remove', 'cleaning rocks failed!') + end end) return r end) @@ -321,13 +385,17 @@ end --- Uninstall the packages specified with `packages` synchronously local function uninstall_sync(packages) - return async(function() return await(uninstall_packages(packages)) end)() + return async(function() + return await(uninstall_packages(packages)) + end)() end local function clean_rocks(rocks, results, disp) return async(function() local r = result.ok() - if not hererocks_is_setup() then return r end + if not hererocks_is_setup() then + return r + end r:and_then(await, luarocks_list(disp)) local installed_packages if r.ok then @@ -339,12 +407,16 @@ local function clean_rocks(rocks, results, disp) local dependency_info = {} for _, package in ipairs(installed_packages) do r:and_then(await, luarocks_show(package.name, disp)) - if r.ok then dependency_info[package.name] = r.ok end + if r.ok then + dependency_info[package.name] = r.ok + end end r = r:map_ok(function() local to_remove = {} - for _, package in ipairs(installed_packages) do to_remove[package.name] = package end + for _, package in ipairs(installed_packages) do + to_remove[package.name] = package + end for _, rock in pairs(rocks) do if type(rock) == 'table' then if to_remove[rock[1]] and (not rock.version or to_remove[rock[1]].version == rock.version) then @@ -357,7 +429,9 @@ local function clean_rocks(rocks, results, disp) for rock, dependencies in pairs(dependency_info) do if rocks[rock] ~= nil then - for _, dependency in pairs(dependencies) do to_remove[dependency] = nil end + for _, dependency in pairs(dependencies) do + to_remove[dependency] = nil + end end end @@ -386,17 +460,23 @@ local function clean_rocks(rocks, results, disp) if inv_depends ~= nil then for depends, _ in pairs(inverse_dependencies[rock]) do table.remove(dependency_info[depends]) - if #dependency_info[depends] == 0 then frontier[#frontier + 1] = depends end + if #dependency_info[depends] == 0 then + frontier[#frontier + 1] = depends + end end end end local reverse_order = {} - for i = #removal_order, 1, -1 do reverse_order[#reverse_order + 1] = removal_order[i] end + for i = #removal_order, 1, -1 do + reverse_order[#reverse_order + 1] = removal_order[i] + end return reverse_order end) - if results ~= nil then results.luarocks = results.luarocks or {} end + if results ~= nil then + results.luarocks = results.luarocks or {} + end return r:and_then(await, uninstall_packages(r.ok, results, disp)) end) end @@ -413,8 +493,12 @@ local function ensure_rocks(rocks, results, disp) end local r = result.ok() - if next(to_install) == nil then return r end - if not hererocks_is_setup() then r = r:and_then(await, hererocks_installer(disp)) end + if next(to_install) == nil then + return r + end + if not hererocks_is_setup() then + r = r:and_then(await, hererocks_installer(disp)) + end r:and_then(await, luarocks_list(disp)) r:map_ok(function(installed_packages) for _, package in ipairs(installed_packages) do @@ -437,7 +521,7 @@ local function ensure_rocks(rocks, results, disp) if type(spec) == 'table' then table.insert(package_specs, spec) else - table.insert(package_specs, {name}) + table.insert(package_specs, { name }) end end @@ -451,29 +535,30 @@ end local function handle_command(cmd, ...) local task - local packages = {...} + local packages = { ... } if cmd == 'install' then task = install_packages(packages) elseif cmd == 'remove' then task = uninstall_packages(packages) else - log.warn('Unrecognized command!') - return result.err('Unrecognized command') + log.warn 'Unrecognized command!' + return result.err 'Unrecognized command' end return async(function() local r = await(task) await(a.main) local package_names = vim.fn.escape(vim.inspect(packages), '"') - return r:map_ok(function(data) - local operation_name = cmd:sub(1, 1):upper() .. cmd:sub(2) - log.info(fmt('%sed packages %s', operation_name, package_names)) - return data - end):map_err(function(err) - log.error(fmt('Failed to %s packages %s: %s', cmd, package_names, - vim.fn.escape(vim.inspect(err), '"\n'))) - return err - end) + return r + :map_ok(function(data) + local operation_name = cmd:sub(1, 1):upper() .. cmd:sub(2) + log.info(fmt('%sed packages %s', operation_name, package_names)) + return data + end) + :map_err(function(err) + log.error(fmt('Failed to %s packages %s: %s', cmd, package_names, vim.fn.escape(vim.inspect(err), '"\n'))) + return err + end) end)() end @@ -492,5 +577,5 @@ return { install = install_sync, ensure = ensure_rocks, generate_path_setup = generate_path_setup_code, - cfg = cfg + cfg = cfg, } diff --git a/lua/packer/plugin_types.lua b/lua/packer/plugin_types.lua index 4841e438..37f81a88 100644 --- a/lua/packer/plugin_types.lua +++ b/lua/packer/plugin_types.lua @@ -9,7 +9,8 @@ local plugin_types = setmetatable({ cfg = cfg }, { local v = require('packer.plugin_types.' .. k) v.cfg(config) self[k] = v - return v end, + return v + end, }) return plugin_types diff --git a/lua/packer/plugin_types/git.lua b/lua/packer/plugin_types/git.lua index 0559eab0..97841241 100644 --- a/lua/packer/plugin_types/git.lua +++ b/lua/packer/plugin_types/git.lua @@ -1,7 +1,7 @@ -local util = require('packer.util') -local jobs = require('packer.jobs') -local a = require('packer.async') -local result = require('packer.result') +local util = require 'packer.util' +local jobs = require 'packer.jobs' +local a = require 'packer.async' +local result = require 'packer.result' local await = a.wait local async = a.sync local fmt = string.format @@ -21,31 +21,36 @@ end local handle_checkouts = function(plugin, dest, disp) local plugin_name = util.get_plugin_full_name(plugin) return async(function() - if disp ~= nil then disp:task_update(plugin_name, 'fetching reference...') end + if disp ~= nil then + disp:task_update(plugin_name, 'fetching reference...') + end local output = jobs.output_table() local callbacks = { stdout = jobs.logging_callback(output.err.stdout, output.data.stdout, nil, disp, plugin_name), - stderr = jobs.logging_callback(output.err.stderr, output.data.stderr) + stderr = jobs.logging_callback(output.err.stderr, output.data.stderr), } - local opts = {capture_output = callbacks, cwd = dest} + local opts = { capture_output = callbacks, cwd = dest } local r = result.ok() if plugin.branch or plugin.tag then local branch_or_tag = plugin.branch and plugin.branch or plugin.tag if disp ~= nil then - disp:task_update(plugin_name, fmt('checking out %s %s...', - plugin.branch and 'branch' or 'tag', branch_or_tag)) + disp:task_update(plugin_name, fmt('checking out %s %s...', plugin.branch and 'branch' or 'tag', branch_or_tag)) end - r:and_then(await, jobs.run( - config.exec_cmd .. fmt(config.subcommands.checkout, branch_or_tag), opts)) + r + :and_then(await, jobs.run(config.exec_cmd .. fmt(config.subcommands.checkout, branch_or_tag), opts)) :map_err(function(err) return { - msg = fmt('Error checking out %s %s for %s', plugin.branch and 'branch' or 'tag', - branch_or_tag, plugin_name), + msg = fmt( + 'Error checking out %s %s for %s', + plugin.branch and 'branch' or 'tag', + branch_or_tag, + plugin_name + ), data = err, - output = output + output = output, } end) end @@ -54,38 +59,43 @@ local handle_checkouts = function(plugin, dest, disp) if disp ~= nil then disp:task_update(plugin_name, fmt('checking out %s...', plugin.commit)) end - r:and_then(await, jobs.run( - config.exec_cmd .. fmt(config.subcommands.checkout, plugin.commit), opts)) + r + :and_then(await, jobs.run(config.exec_cmd .. fmt(config.subcommands.checkout, plugin.commit), opts)) :map_err(function(err) return { msg = fmt('Error checking out commit %s for %s', plugin.commit, plugin_name), data = err, - output = output + output = output, } end) end - return r:map_ok(function(ok) return {status = ok, output = output} end):map_err(function(err) - if not err.msg then - return { - msg = fmt('Error updating %s: %s', plugin_name, table.concat(err, '\n')), - data = err, - output = output - } - end + return r + :map_ok(function(ok) + return { status = ok, output = output } + end) + :map_err(function(err) + if not err.msg then + return { + msg = fmt('Error updating %s: %s', plugin_name, table.concat(err, '\n')), + data = err, + output = output, + } + end - err.output = output - return err - end) + err.output = output + return err + end) end) end git.setup = function(plugin) local plugin_name = util.get_plugin_full_name(plugin) local install_to = plugin.install_path - local install_cmd = vim.split(config.exec_cmd - .. fmt(config.subcommands.install, - plugin.commit and 999999 or config.depth), '%s+') + local install_cmd = vim.split( + config.exec_cmd .. fmt(config.subcommands.install, plugin.commit and 999999 or config.depth), + '%s+' + ) local submodule_cmd = config.exec_cmd .. config.subcommands.submodules local rev_cmd = config.exec_cmd .. config.subcommands.get_rev @@ -97,8 +107,7 @@ git.setup = function(plugin) end local branch_cmd = config.exec_cmd .. config.subcommands.current_branch - local commit_cmd = - vim.split(config.exec_cmd .. config.subcommands.get_msg, '%s+') + local commit_cmd = vim.split(config.exec_cmd .. config.subcommands.get_msg, '%s+') for i, arg in ipairs(commit_cmd) do commit_cmd[i] = string.gsub(arg, 'FMT', config.subcommands.diff_fmt) end @@ -122,13 +131,15 @@ git.setup = function(plugin) local output = jobs.output_table() local callbacks = { stdout = jobs.logging_callback(output.err.stdout, output.data.stdout), - stderr = jobs.logging_callback(output.err.stderr, output.data.stderr, nil, disp, plugin_name) + stderr = jobs.logging_callback(output.err.stderr, output.data.stderr, nil, disp, plugin_name), } if git.job_env == nil then local job_env = {} for k, v in pairs(vim.fn.environ()) do - if k ~= 'GIT_TERMINAL_PROMPT' then table.insert(job_env, k .. '=' .. v) end + if k ~= 'GIT_TERMINAL_PROMPT' then + table.insert(job_env, k .. '=' .. v) + end end table.insert(job_env, 'GIT_TERMINAL_PROMPT=0') @@ -138,7 +149,7 @@ git.setup = function(plugin) local installer_opts = { capture_output = callbacks, timeout = config.clone_timeout, - options = {env = git.job_env} + options = { env = git.job_env }, } return async(function() @@ -150,28 +161,30 @@ git.setup = function(plugin) if plugin.commit then disp:task_update(plugin_name, fmt('checking out %s...', plugin.commit)) - r:and_then(await, - jobs.run( - config.exec_cmd .. fmt(config.subcommands.checkout, plugin.commit), - installer_opts)):map_err(function(err) - return { - msg = fmt('Error checking out commit %s for %s', plugin.commit, plugin_name), - data = {err, output} - } - end) + r + :and_then(await, jobs.run(config.exec_cmd .. fmt(config.subcommands.checkout, plugin.commit), installer_opts)) + :map_err(function(err) + return { + msg = fmt('Error checking out commit %s for %s', plugin.commit, plugin_name), + data = { err, output }, + } + end) end - r:and_then(await, jobs.run(commit_cmd, installer_opts)):map_ok(function(_) - plugin.messages = output.data.stdout - end):map_err(function(err) - plugin.output = {err = output.data.stderr} - if not err.msg then - return { - msg = fmt('Error installing %s: %s', plugin_name, table.concat(output.data.stderr, '\n')), - data = {err, output} - } - end - end) + r + :and_then(await, jobs.run(commit_cmd, installer_opts)) + :map_ok(function(_) + plugin.messages = output.data.stdout + end) + :map_err(function(err) + plugin.output = { err = output.data.stderr } + if not err.msg then + return { + msg = fmt('Error installing %s: %s', plugin_name, table.concat(output.data.stderr, '\n')), + data = { err, output }, + } + end + end) return r end) @@ -179,59 +192,64 @@ git.setup = function(plugin) plugin.remote_url = function() return async(function() - return await(jobs.run(fmt("%s remote get-url origin", config.exec_cmd), - {capture_output = true, cwd = plugin.install_path})):map_ok(function( - data) return {remote = data.output.data.stdout[1]} end) + return await( + jobs.run(fmt('%s remote get-url origin', config.exec_cmd), { capture_output = true, cwd = plugin.install_path }) + ):map_ok(function(data) + return { remote = data.output.data.stdout[1] } + end) end) end plugin.updater = function(disp) return async(function() - local update_info = {err = {}, revs = {}, output = {}, messages = {}} + local update_info = { err = {}, revs = {}, output = {}, messages = {} } local function exit_ok(r) - if #update_info.err > 0 or r.exit_code ~= 0 then return result.err(r) end + if #update_info.err > 0 or r.exit_code ~= 0 then + return result.err(r) + end return result.ok(r) end local rev_onread = jobs.logging_callback(update_info.err, update_info.revs) - local rev_callbacks = {stdout = rev_onread, stderr = rev_onread} + local rev_callbacks = { stdout = rev_onread, stderr = rev_onread } disp:task_update(plugin_name, 'checking current commit...') local r = - await(jobs.run(rev_cmd, {success_test = exit_ok, capture_output = rev_callbacks, cwd = install_to})):map_err( + await(jobs.run(rev_cmd, { success_test = exit_ok, capture_output = rev_callbacks, cwd = install_to })):map_err( function(err) - plugin.output = {err = vim.list_extend(update_info.err, update_info.revs), data = {}} + plugin.output = { err = vim.list_extend(update_info.err, update_info.revs), data = {} } return { - msg = fmt('Error getting current commit for %s: %s', plugin_name, - table.concat(update_info.revs, '\n')), - data = err + msg = fmt('Error getting current commit for %s: %s', plugin_name, table.concat(update_info.revs, '\n')), + data = err, } - end) + end + ) local current_branch disp:task_update(plugin_name, 'checking current branch...') - r:and_then(await, jobs.run(branch_cmd, {success_test = exit_ok, capture_output = true, cwd = install_to})) - :map_ok(function(ok) current_branch = ok.output.data.stdout[1] end):map_err(function(err) - plugin.output = {err = vim.list_extend(update_info.err, update_info.revs), data = {}} + r + :and_then(await, jobs.run(branch_cmd, { success_test = exit_ok, capture_output = true, cwd = install_to })) + :map_ok(function(ok) + current_branch = ok.output.data.stdout[1] + end) + :map_err(function(err) + plugin.output = { err = vim.list_extend(update_info.err, update_info.revs), data = {} } return { - msg = fmt('Error checking current branch for %s: %s', plugin_name, - table.concat(update_info.revs, '\n')), - data = err + msg = fmt('Error checking current branch for %s: %s', plugin_name, table.concat(update_info.revs, '\n')), + data = err, } end) if not needs_checkout then local origin_branch = '' disp:task_update(plugin_name, 'checking origin branch...') - local origin_refs_path = util.join_paths(install_to, '.git', 'refs', 'remotes', 'origin', - 'HEAD') + local origin_refs_path = util.join_paths(install_to, '.git', 'refs', 'remotes', 'origin', 'HEAD') local origin_refs_file = vim.loop.fs_open(origin_refs_path, 'r', 438) if origin_refs_file ~= nil then local origin_refs_stat = vim.loop.fs_fstat(origin_refs_file) -- NOTE: This should check for errors - local origin_refs = vim.split( - vim.loop.fs_read(origin_refs_file, origin_refs_stat.size, 0), '\n') + local origin_refs = vim.split(vim.loop.fs_read(origin_refs_file, origin_refs_stat.size, 0), '\n') vim.loop.fs_close(origin_refs_file) if #origin_refs > 0 then origin_branch = string.match(origin_refs[1], [[^ref: refs/remotes/origin/(.*)]]) @@ -258,51 +276,60 @@ git.setup = function(plugin) r:map_ok(merge_output) r:map_err(function(err) merge_output(err) - plugin.output = {err = vim.list_extend(update_info.err, update_info.output), data = {}} - return {msg = err.msg .. ' ' .. table.concat(update_info.output, '\n'), data = err.data} + plugin.output = { err = vim.list_extend(update_info.err, update_info.output), data = {} } + return { msg = err.msg .. ' ' .. table.concat(update_info.output, '\n'), data = err.data } end) end local update_callbacks = { stdout = jobs.logging_callback(update_info.err, update_info.output), - stderr = jobs.logging_callback(update_info.err, update_info.output, nil, disp, plugin_name) + stderr = jobs.logging_callback(update_info.err, update_info.output, nil, disp, plugin_name), } disp:task_update(plugin_name, 'pulling updates...') - r:and_then(await, - jobs.run(update_cmd, {success_test = exit_ok, capture_output = update_callbacks, cwd = install_to})) - :and_then(await, jobs.run(submodule_cmd, - {success_test = exit_ok, capture_output = update_callbacks, cwd = install_to})) + r + :and_then( + await, + jobs.run(update_cmd, { success_test = exit_ok, capture_output = update_callbacks, cwd = install_to }) + ) + :and_then( + await, + jobs.run(submodule_cmd, { success_test = exit_ok, capture_output = update_callbacks, cwd = install_to }) + ) :map_err(function(err) - plugin.output = {err = vim.list_extend(update_info.err, update_info.output), data = {}} + plugin.output = { err = vim.list_extend(update_info.err, update_info.output), data = {} } return { - msg = fmt('Error pulling updates for %s: %s', plugin_name, - table.concat(update_info.output, '\n')), - data = err + msg = fmt('Error pulling updates for %s: %s', plugin_name, table.concat(update_info.output, '\n')), + data = err, } end) disp:task_update(plugin_name, 'checking updated commit...') - r:and_then(await, jobs.run(rev_cmd, {success_test = exit_ok, capture_output = rev_callbacks, cwd = install_to})) + r + :and_then( + await, + jobs.run(rev_cmd, { success_test = exit_ok, capture_output = rev_callbacks, cwd = install_to }) + ) :map_err(function(err) - plugin.output = {err = vim.list_extend(update_info.err, update_info.revs), data = {}} + plugin.output = { err = vim.list_extend(update_info.err, update_info.revs), data = {} } return { - msg = fmt('Error checking updated commit for %s: %s', plugin_name, - table.concat(update_info.revs, '\n')), - data = err + msg = fmt('Error checking updated commit for %s: %s', plugin_name, table.concat(update_info.revs, '\n')), + data = err, } end) if r.ok then if update_info.revs[1] ~= update_info.revs[2] then local messages_onread = jobs.logging_callback(update_info.err, update_info.messages) - local messages_callbacks = {stdout = messages_onread, stderr = messages_onread} + local messages_callbacks = { stdout = messages_onread, stderr = messages_onread } disp:task_update(plugin_name, 'getting commit messages...') - r:and_then(await, jobs.run(messages_cmd, - {success_test = exit_ok, capture_output = messages_callbacks, cwd = install_to})) + r:and_then( + await, + jobs.run(messages_cmd, { success_test = exit_ok, capture_output = messages_callbacks, cwd = install_to }) + ) - plugin.output = {err = update_info.err, data = update_info.output} + plugin.output = { err = update_info.err, data = update_info.output } if r.ok then plugin.messages = update_info.messages plugin.revs = update_info.revs @@ -323,12 +350,16 @@ git.setup = function(plugin) plugin.diff = function(commit, callback) async(function() local diff_cmd = config.exec_cmd .. fmt(config.subcommands.git_diff_fmt, commit) - local diff_info = {err = {}, output = {}, messages = {}} + local diff_info = { err = {}, output = {}, messages = {} } local diff_onread = jobs.logging_callback(diff_info.err, diff_info.messages) - local diff_callbacks = {stdout = diff_onread, stderr = diff_onread} - return await(jobs.run(diff_cmd, {capture_output = diff_callbacks, cwd = install_to})):map_ok(function(_) - return callback(diff_info.messages) - end):map_err(function(err) return callback(nil, err) end) + local diff_callbacks = { stdout = diff_onread, stderr = diff_onread } + return await(jobs.run(diff_cmd, { capture_output = diff_callbacks, cwd = install_to })) + :map_ok(function(_) + return callback(diff_info.messages) + end) + :map_err(function(err) + return callback(nil, err) + end) end)() end @@ -336,8 +367,10 @@ git.setup = function(plugin) local r = result.ok() async(function() local revert_cmd = config.exec_cmd .. config.subcommands.revert - r:and_then(await, jobs.run(revert_cmd, {capture_output = true, cwd = install_to})) - if needs_checkout then r:and_then(await, handle_checkouts(plugin, install_to, nil)) end + r:and_then(await, jobs.run(revert_cmd, { capture_output = true, cwd = install_to })) + if needs_checkout then + r:and_then(await, handle_checkouts(plugin, install_to, nil)) + end return r end)() return r diff --git a/lua/packer/plugin_types/local.lua b/lua/packer/plugin_types/local.lua index ee9c4076..50bf4544 100644 --- a/lua/packer/plugin_types/local.lua +++ b/lua/packer/plugin_types/local.lua @@ -1,13 +1,15 @@ -local a = require('packer.async') -local log = require('packer.log') -local util = require('packer.util') -local result = require('packer.result') +local a = require 'packer.async' +local log = require 'packer.log' +local util = require 'packer.util' +local result = require 'packer.result' local async = a.sync local await = a.wait local config = nil -local function cfg(_config) config = _config end +local function cfg(_config) + config = _config +end local symlink = a.wrap(vim.loop.fs_symlink) @@ -19,20 +21,24 @@ local function setup_local(plugin) plugin.installer = function(disp) return async(function() disp:task_update(plugin_name, 'making symlink...') - local err, success = await(symlink(from, to, {dir = true})) + local err, success = await(symlink(from, to, { dir = true })) if not success then - plugin.output = {err = {err}} + plugin.output = { err = { err } } return result.err(err) end return result.ok() end) end - plugin.updater = function(_) return async(function() return result.ok() end) end + plugin.updater = function(_) + return async(function() + return result.ok() + end) + end plugin.revert_last = function(_) - log.warn("Can't revert a local plugin!") + log.warn "Can't revert a local plugin!" return result.ok() end end -return {setup = setup_local, cfg = cfg} +return { setup = setup_local, cfg = cfg } diff --git a/lua/packer/plugin_utils.lua b/lua/packer/plugin_utils.lua index b22f0978..e262ad3e 100644 --- a/lua/packer/plugin_utils.lua +++ b/lua/packer/plugin_utils.lua @@ -1,14 +1,16 @@ -local a = require('packer.async') -local jobs = require('packer.jobs') -local util = require('packer.util') -local result = require('packer.result') -local log = require('packer.log') +local a = require 'packer.async' +local jobs = require 'packer.jobs' +local util = require 'packer.util' +local result = require 'packer.result' +local log = require 'packer.log' local await = a.wait local config = nil local plugin_utils = {} -plugin_utils.cfg = function(_config) config = _config end +plugin_utils.cfg = function(_config) + config = _config +end plugin_utils.custom_plugin_type = 'custom' plugin_utils.local_plugin_type = 'local' @@ -20,12 +22,15 @@ plugin_utils.guess_type = function(plugin) elseif vim.fn.isdirectory(plugin.path) ~= 0 then plugin.url = plugin.path plugin.type = plugin_utils.local_plugin_type - elseif string.sub(plugin.path, 1, 6) == 'git://' or string.sub(plugin.path, 1, 4) == 'http' - or string.match(plugin.path, '@') then + elseif + string.sub(plugin.path, 1, 6) == 'git://' + or string.sub(plugin.path, 1, 4) == 'http' + or string.match(plugin.path, '@') + then plugin.url = plugin.path plugin.type = plugin_utils.git_plugin_type else - local path = table.concat(vim.split(plugin.path, "\\", true), "/") + local path = table.concat(vim.split(plugin.path, '\\', true), '/') plugin.url = string.format(config.git.default_url_format, path) plugin.type = plugin_utils.git_plugin_type end @@ -33,7 +38,7 @@ end plugin_utils.guess_dir_type = function(dir) local globdir = vim.fn.glob(dir) - local dir_type = (vim.loop.fs_lstat(globdir) or {type = 'noexist'}).type + local dir_type = (vim.loop.fs_lstat(globdir) or { type = 'noexist' }).type --[[ NOTE: We're assuming here that: 1. users only create custom plugins for non-git repos; @@ -56,8 +61,12 @@ plugin_utils.helptags_stale = function(dir) vim.list_extend(tags, vim.fn.glob(util.join_paths(dir, 'tags-[a-z][a-z]'), true, true)) local txt_ftimes = util.map(vim.fn.getftime, txts) local tag_ftimes = util.map(vim.fn.getftime, tags) - if #txt_ftimes == 0 then return false end - if #tag_ftimes == 0 then return true end + if #txt_ftimes == 0 then + return false + end + if #tag_ftimes == 0 then + return true + end local txt_newest = math.max(unpack(txt_ftimes)) local tag_oldest = math.min(unpack(tag_ftimes)) return txt_newest > tag_oldest @@ -74,13 +83,19 @@ plugin_utils.update_helptags = vim.schedule_wrap(function(...) end) plugin_utils.update_rplugins = vim.schedule_wrap(function() - if vim.fn.exists(':UpdateRemotePlugins') == 2 then vim.cmd [[silent UpdateRemotePlugins]] end + if vim.fn.exists ':UpdateRemotePlugins' == 2 then + vim.cmd [[silent UpdateRemotePlugins]] + end end) plugin_utils.ensure_dirs = function() - if vim.fn.isdirectory(config.opt_dir) == 0 then vim.fn.mkdir(config.opt_dir, 'p') end + if vim.fn.isdirectory(config.opt_dir) == 0 then + vim.fn.mkdir(config.opt_dir, 'p') + end - if vim.fn.isdirectory(config.start_dir) == 0 then vim.fn.mkdir(config.start_dir, 'p') end + if vim.fn.isdirectory(config.start_dir) == 0 then + vim.fn.mkdir(config.start_dir, 'p') + end end plugin_utils.list_installed_plugins = function() @@ -125,8 +140,7 @@ plugin_utils.find_missing_plugins = function(plugins, opt_plugins, start_plugins for _, plugin_name in ipairs(vim.tbl_keys(plugins)) do local plugin = plugins[plugin_name] if not plugin.disable then - local plugin_path = util.join_paths(config[plugin.opt and 'opt_dir' or 'start_dir'], - plugin.short_name) + local plugin_path = util.join_paths(config[plugin.opt and 'opt_dir' or 'start_dir'], plugin.short_name) local plugin_installed = (plugin.opt and opt_plugins or start_plugins)[plugin_path] await(a.main) @@ -140,15 +154,13 @@ plugin_utils.find_missing_plugins = function(plugins, opt_plugins, start_plugins -- Form a Github-style user/repo string local parts = vim.split(remote, '[:/]') local repo_name = parts[#parts - 1] .. '/' .. parts[#parts] - repo_name = repo_name:gsub("%.git", "") + repo_name = repo_name:gsub('%.git', '') -- Also need to test for "full URL" plugin names, but normalized to get rid of the -- protocol - local normalized_remote = remote:gsub("https://", ""):gsub("ssh://git@", "") - local normalized_plugin_name = plugin.name:gsub("https://", ""):gsub("ssh://git@", "") - :gsub("\\", "/") - if (normalized_remote ~= normalized_plugin_name) - and (repo_name ~= normalized_plugin_name) then + local normalized_remote = remote:gsub('https://', ''):gsub('ssh://git@', '') + local normalized_plugin_name = plugin.name:gsub('https://', ''):gsub('ssh://git@', ''):gsub('\\', '/') + if (normalized_remote ~= normalized_plugin_name) and (repo_name ~= normalized_plugin_name) then missing_plugins[plugin_name] = true end end @@ -161,12 +173,11 @@ plugin_utils.find_missing_plugins = function(plugins, opt_plugins, start_plugins end plugin_utils.get_fs_state = function(plugins) - log.debug('Updating FS state') + log.debug 'Updating FS state' local opt_plugins, start_plugins = plugin_utils.list_installed_plugins() return a.sync(function() - local missing_plugins = await(plugin_utils.find_missing_plugins(plugins, opt_plugins, - start_plugins)) - return {opt = opt_plugins, start = start_plugins, missing = missing_plugins} + local missing_plugins = await(plugin_utils.find_missing_plugins(plugins, opt_plugins, start_plugins)) + return { opt = opt_plugins, start = start_plugins, missing = missing_plugins } end) end @@ -175,10 +186,10 @@ plugin_utils.load_plugin = function(plugin) vim.cmd('packadd ' .. plugin.short_name) else vim.o.runtimepath = vim.o.runtimepath .. ',' .. plugin.install_path - for _, pat in ipairs({ - table.concat({'plugin', '**/*.vim'}, util.get_separator()), - table.concat({'after', 'plugin', '**/*.vim'}, util.get_separator()) - }) do + for _, pat in ipairs { + table.concat({ 'plugin', '**/*.vim' }, util.get_separator()), + table.concat({ 'after', 'plugin', '**/*.vim' }, util.get_separator()), + } do local path = util.join_paths(plugin.install_path, pat) local glob_ok, files = pcall(vim.fn.glob, path, false, true) if not glob_ok then @@ -206,7 +217,9 @@ plugin_utils.post_update_hook = function(plugin, disp) end if plugin.run then - if type(plugin.run) ~= 'table' then plugin.run = {plugin.run} end + if type(plugin.run) ~= 'table' then + plugin.run = { plugin.run } + end disp:task_update(plugin_name, 'running post update hooks...') for _, task in ipairs(plugin.run) do if type(task) == 'function' then @@ -214,7 +227,7 @@ plugin_utils.post_update_hook = function(plugin, disp) if success then return result.ok() else - return result.err({msg = 'Error running post update hook: ' .. vim.inspect(err)}) + return result.err { msg = 'Error running post update hook: ' .. vim.inspect(err) } end elseif type(task) == 'string' then if string.sub(task, 1, 1) == ':' then @@ -222,23 +235,20 @@ plugin_utils.post_update_hook = function(plugin, disp) vim.cmd(string.sub(task, 2)) return result.ok() else - local hook_output = {err = {}, output = {}} + local hook_output = { err = {}, output = {} } local hook_callbacks = { - stderr = jobs.logging_callback(hook_output.err, hook_output.output, nil, disp, - plugin_name), - stdout = jobs.logging_callback(hook_output.err, hook_output.output, nil, disp, - plugin_name) + stderr = jobs.logging_callback(hook_output.err, hook_output.output, nil, disp, plugin_name), + stdout = jobs.logging_callback(hook_output.err, hook_output.output, nil, disp, plugin_name), } - local cmd = {os.getenv('SHELL') or vim.o.shell, '-c', task} - return - await(jobs.run(cmd, {capture_output = hook_callbacks, cwd = plugin.install_path})):map_err( - function(err) - return { - msg = string.format('Error running post update hook: %s', - table.concat(hook_output.output, '\n')), - data = err - } - end) + local cmd = { os.getenv 'SHELL' or vim.o.shell, '-c', task } + return await(jobs.run(cmd, { capture_output = hook_callbacks, cwd = plugin.install_path })):map_err( + function(err) + return { + msg = string.format('Error running post update hook: %s', table.concat(hook_output.output, '\n')), + data = err, + } + end + ) end else -- TODO/NOTE: This case should also capture output in case of error. The minor difficulty is @@ -247,7 +257,7 @@ plugin_utils.post_update_hook = function(plugin, disp) return await(jobs.run(task)):map_err(function(err) return { msg = string.format('Error running post update hook: %s', vim.inspect(err)), - data = err + data = err, } end) end diff --git a/lua/packer/result.lua b/lua/packer/result.lua index ce469199..1e3a3d47 100644 --- a/lua/packer/result.lua +++ b/lua/packer/result.lua @@ -13,18 +13,24 @@ local ok_result_mt = { setmetatable(self, getmetatable(r)) return self end, - or_else = function(self) return self end, + or_else = function(self) + return self + end, map_ok = function(self, f) self.ok = f(self.ok) or self.ok return self end, - map_err = function(self) return self end + map_err = function(self) + return self + end, } ok_result_mt.__index = ok_result_mt local err_result_mt = { - and_then = function(self) return self end, + and_then = function(self) + return self + end, or_else = function(self, f, ...) local r = f(...) if r == nil then @@ -36,24 +42,30 @@ local err_result_mt = { setmetatable(self, getmetatable(r)) return self end, - map_ok = function(self) return self end, + map_ok = function(self) + return self + end, map_err = function(self, f) self.err = f(self.err) or self.err return self - end + end, } err_result_mt.__index = err_result_mt result.ok = function(val) - if val == nil then val = true end + if val == nil then + val = true + end local r = setmetatable({}, ok_result_mt) r.ok = val return r end result.err = function(err) - if err == nil then err = true end + if err == nil then + err = true + end local r = setmetatable({}, err_result_mt) r.err = err return r diff --git a/lua/packer/update.lua b/lua/packer/update.lua index eb98ca45..a1b78002 100644 --- a/lua/packer/update.lua +++ b/lua/packer/update.lua @@ -1,9 +1,9 @@ -local util = require('packer.util') -local result = require('packer.result') -local display = require('packer.display') -local a = require('packer.async') -local log = require('packer.log') -local plugin_utils = require('packer.plugin_utils') +local util = require 'packer.util' +local result = require 'packer.result' +local display = require 'packer.display' +local a = require 'packer.async' +local log = require 'packer.log' +local plugin_utils = require 'packer.plugin_utils' local fmt = string.format local async = a.sync @@ -14,15 +14,14 @@ local config = nil local function get_plugin_status(plugins, plugin_name, start_plugins, opt_plugins) local status = {} local plugin = plugins[plugin_name] - status.wrong_type = (plugin.opt - and vim.tbl_contains(start_plugins, - util.join_paths(config.start_dir, plugin_name))) - or vim.tbl_contains(opt_plugins, - util.join_paths(config.opt_dir, plugin_name)) + status.wrong_type = (plugin.opt and vim.tbl_contains(start_plugins, util.join_paths(config.start_dir, plugin_name))) + or vim.tbl_contains(opt_plugins, util.join_paths(config.opt_dir, plugin_name)) return status end -local function cfg(_config) config = _config end +local function cfg(_config) + config = _config +end local function fix_plugin_type(plugin, results, fs_state) local from @@ -46,34 +45,36 @@ local function fix_plugin_type(plugin, results, fs_state) local success, msg = os.rename(from, to) if not success then log.error('Failed to move ' .. from .. ' to ' .. to .. ': ' .. msg) - results.moves[plugin.short_name] = {from = from, to = to, result = result.err(success)} + results.moves[plugin.short_name] = { from = from, to = to, result = result.err(success) } else - results.moves[plugin.short_name] = {from = from, to = to, result = result.ok(success)} + results.moves[plugin.short_name] = { from = from, to = to, result = result.ok(success) } end end local function fix_plugin_types(plugins, plugin_names, results, fs_state) - log.debug('Fixing plugin types') + log.debug 'Fixing plugin types' results = results or {} results.moves = results.moves or {} -- NOTE: This function can only be run on plugins already installed for _, v in ipairs(plugin_names) do local plugin = plugins[v] - local install_dir = util.join_paths(plugin.opt and config.start_dir or config.opt_dir, - plugin.short_name) - if vim.loop.fs_stat(install_dir) ~= nil then fix_plugin_type(plugin, results, fs_state) end + local install_dir = util.join_paths(plugin.opt and config.start_dir or config.opt_dir, plugin.short_name) + if vim.loop.fs_stat(install_dir) ~= nil then + fix_plugin_type(plugin, results, fs_state) + end end - log.debug('Done fixing plugin types') + log.debug 'Done fixing plugin types' end local function update_plugin(plugin, display_win, results) local plugin_name = util.get_plugin_full_name(plugin) -- TODO: This will have to change when separate packages are implemented - local install_path = util.join_paths(config.pack_dir, plugin.opt and 'opt' or 'start', - plugin.short_name) + local install_path = util.join_paths(config.pack_dir, plugin.opt and 'opt' or 'start', plugin.short_name) plugin.install_path = install_path return async(function() - if plugin.lock or plugin.disable then return end + if plugin.lock or plugin.disable then + return + end display_win:task_start(plugin_name, 'updating...') local r = await(plugin.updater(display_win)) if r ~= nil and r.ok then @@ -81,15 +82,16 @@ local function update_plugin(plugin, display_win, results) if plugin.type == plugin_utils.git_plugin_type then local info = r.info local actual_update = info.revs[1] ~= info.revs[2] - msg = actual_update and ('updated: ' .. info.revs[1] .. '...' .. info.revs[2]) - or 'already up to date' + msg = actual_update and ('updated: ' .. info.revs[1] .. '...' .. info.revs[2]) or 'already up to date' if actual_update then log.debug(fmt('Updated %s: %s', plugin_name, vim.inspect(info))) r = r:and_then(await, plugin_utils.post_update_hook(plugin, display_win)) end end - if r.ok then display_win:task_succeeded(plugin_name, msg) end + if r.ok then + display_win:task_succeeded(plugin_name, msg) + end else display_win:task_failed(plugin_name, 'failed to update') log.debug(fmt('Failed to update %s: %s', plugin_name, vim.inspect(r.err))) @@ -116,12 +118,14 @@ local function do_update(_, plugins, update_plugins, display_win, results) end end - if #tasks == 0 then log.info('Nothing to update!') end + if #tasks == 0 then + log.info 'Nothing to update!' + end return tasks, display_win end -local update = setmetatable({cfg = cfg}, {__call = do_update}) +local update = setmetatable({ cfg = cfg }, { __call = do_update }) update.get_plugin_status = get_plugin_status update.fix_plugin_types = fix_plugin_types diff --git a/lua/packer/util.lua b/lua/packer/util.lua index 5d39440a..449ad13f 100644 --- a/lua/packer/util.lua +++ b/lua/packer/util.lua @@ -2,16 +2,20 @@ local util = {} util.map = function(func, seq) local result = {} - for _, v in ipairs(seq) do table.insert(result, func(v)) end + for _, v in ipairs(seq) do + table.insert(result, func(v)) + end return result end util.partition = function(sub, seq) local sub_vals = {} - for _, val in ipairs(sub) do sub_vals[val] = true end + for _, val in ipairs(sub) do + sub_vals[val] = true + end - local result = {{}, {}} + local result = { {}, {} } for _, val in ipairs(seq) do if sub_vals[val] then table.insert(result[1], val) @@ -38,13 +42,15 @@ else end util.get_separator = function() - if util.is_windows then return '\\' end + if util.is_windows then + return '\\' + end return '/' end util.join_paths = function(...) local separator = util.get_separator() - return table.concat({...}, separator) + return table.concat({ ... }, separator) end util.get_plugin_full_name = function(plugin) @@ -54,7 +60,9 @@ util.get_plugin_full_name = function(plugin) plugin_name = plugin_name .. '/' .. plugin.branch end - if plugin.rev then plugin_name = plugin_name .. '@' .. plugin.rev end + if plugin.rev then + plugin_name = plugin_name .. '@' .. plugin.rev + end return plugin_name end @@ -75,7 +83,7 @@ util.deep_extend = function(policy, ...) end end - for _, t in ipairs({...}) do + for _, t in ipairs { ... } do for k, v in pairs(t) do if result[k] ~= nil then result[k] = helper(policy, k, result[k], v) @@ -103,7 +111,9 @@ util.float = function(opts) --- https://github.com/wbthomason/packer.nvim/pull/325#issuecomment-832874005 --- ideally we should decide if the string argument passed to display openers is --- required or not - if type(opts) ~= "table" then opts = {} end + if type(opts) ~= 'table' then + opts = {} + end opts = vim.tbl_deep_extend('force', { relative = 'editor', @@ -112,7 +122,7 @@ util.float = function(opts) width = width, height = height, col = left, - row = top + row = top, }, opts or {}) local buf = vim.api.nvim_create_buf(false, true) @@ -123,7 +133,7 @@ util.float = function(opts) vim.api.nvim_win_set_cursor(last_win, last_pos) end - vim.cmd('autocmd! BufWipeout lua __packer_restore_cursor()') + vim.cmd 'autocmd! BufWipeout lua __packer_restore_cursor()' return true, win, buf end