refactor: fix luals type warnings

This commit is contained in:
dundargoc 2024-05-25 20:35:37 +02:00 committed by dundargoc
parent f70af5c3ca
commit 6e8a728e3d
12 changed files with 62 additions and 60 deletions

View File

@ -65,9 +65,7 @@ local function notify(msg)
if #notifications == 0 then if #notifications == 0 then
vim.schedule(function() vim.schedule(function()
if #notifications > 1 then if #notifications > 1 then
vim.notify( vim.notify(('TOhtml: %s (+ %d more warnings)'):format(notifications[1], #notifications - 1))
('TOhtml: %s (+ %d more warnings)'):format(notifications[1], tostring(#notifications - 1))
)
elseif #notifications == 1 then elseif #notifications == 1 then
vim.notify('TOhtml: ' .. notifications[1]) vim.notify('TOhtml: ' .. notifications[1])
end end

View File

@ -34,3 +34,5 @@ vim.uri_from_fname = uri.uri_from_fname
vim.uri_from_bufnr = uri.uri_from_bufnr vim.uri_from_bufnr = uri.uri_from_bufnr
vim.uri_to_fname = uri.uri_to_fname vim.uri_to_fname = uri.uri_to_fname
vim.uri_to_bufnr = uri.uri_to_bufnr vim.uri_to_bufnr = uri.uri_to_bufnr
vim.provider = require('vim.provider')

View File

@ -1642,7 +1642,7 @@ function vim.fn.execute(command, silent) end
--- If {expr} starts with "./" the |current-directory| is used. --- If {expr} starts with "./" the |current-directory| is used.
--- ---
--- @param expr any --- @param expr any
--- @return any --- @return string
function vim.fn.exepath(expr) end function vim.fn.exepath(expr) end
--- The result is a Number, which is |TRUE| if {expr} is --- The result is a Number, which is |TRUE| if {expr} is

View File

@ -1,7 +1,7 @@
local M = {} local M = {}
local health = vim.health local health = vim.health
local deprecated = {} local deprecated = {} ---@type {[1]: string, [2]: table, [3]: string}[]
function M.check() function M.check()
if next(deprecated) == nil then if next(deprecated) == nil then

View File

@ -104,10 +104,10 @@ local function filepath_to_healthcheck(path)
local subpath = path:gsub('.*lua/', '') local subpath = path:gsub('.*lua/', '')
if vim.fs.basename(subpath) == 'health.lua' then if vim.fs.basename(subpath) == 'health.lua' then
-- */health.lua -- */health.lua
name = assert(vim.fs.dirname(subpath)) name = vim.fs.dirname(subpath)
else else
-- */health/init.lua -- */health/init.lua
name = assert(vim.fs.dirname(assert(vim.fs.dirname(subpath)))) name = vim.fs.dirname(vim.fs.dirname(subpath))
end end
name = name:gsub('/', '.') name = name:gsub('/', '.')
@ -301,11 +301,13 @@ end
local PATTERNS = { '/autoload/health/*.vim', '/lua/**/**/health.lua', '/lua/**/**/health/init.lua' } local PATTERNS = { '/autoload/health/*.vim', '/lua/**/**/health.lua', '/lua/**/**/health/init.lua' }
--- :checkhealth completion function used by cmdexpand.c get_healthcheck_names() --- :checkhealth completion function used by cmdexpand.c get_healthcheck_names()
M._complete = function() M._complete = function()
local unique = vim local unique = vim ---@type table<string,boolean>
---@param pattern string
.iter(vim.tbl_map(function(pattern) .iter(vim.tbl_map(function(pattern)
return vim.tbl_map(path2name, vim.api.nvim_get_runtime_file(pattern, true)) return vim.tbl_map(path2name, vim.api.nvim_get_runtime_file(pattern, true))
end, PATTERNS)) end, PATTERNS))
:flatten() :flatten()
---@param t table<string,boolean>
:fold({}, function(t, name) :fold({}, function(t, name)
t[name] = true -- Remove duplicates t[name] = true -- Remove duplicates
return t return t
@ -364,7 +366,7 @@ function M._check(mods, plugin_names)
vim.fn.call(func, {}) vim.fn.call(func, {})
else else
local f = assert(loadstring(func)) local f = assert(loadstring(func))
local ok, output = pcall(f) local ok, output = pcall(f) ---@type boolean, string
if not ok then if not ok then
M.error( M.error(
string.format('Failed to run healthcheck for "%s" plugin. Exception:\n%s\n', name, output) string.format('Failed to run healthcheck for "%s" plugin. Exception:\n%s\n', name, output)
@ -391,7 +393,7 @@ function M._check(mods, plugin_names)
end end
s_output[#s_output + 1] = '' s_output[#s_output + 1] = ''
s_output = vim.list_extend(header, s_output) s_output = vim.list_extend(header, s_output)
vim.fn.append('$', s_output) vim.fn.append(vim.fn.line('$'), s_output)
vim.cmd.redraw() vim.cmd.redraw()
end end

View File

@ -239,6 +239,7 @@ local function check_tmux()
return return
end end
---@param option string
local get_tmux_option = function(option) local get_tmux_option = function(option)
local cmd = 'tmux show-option -qvg ' .. option -- try global scope local cmd = 'tmux show-option -qvg ' .. option -- try global scope
local out = vim.fn.system(vim.fn.split(cmd)) local out = vim.fn.system(vim.fn.split(cmd))
@ -378,7 +379,7 @@ local function check_terminal()
'SSH_TTY', 'SSH_TTY',
}) do }) do
if vim.env[env_var] then if vim.env[env_var] then
health.info(vim.fn.printf('$%s="%s"', env_var, vim.env[env_var])) health.info(string.format('$%s="%s"', env_var, vim.env[env_var]))
end end
end end
end end

View File

@ -616,7 +616,7 @@ function M.rename(old_fname, new_fname, opts)
buf_rename[b] = { from = old_bname, to = new_bname } buf_rename[b] = { from = old_bname, to = new_bname }
end end
local newdir = assert(vim.fs.dirname(new_fname)) local newdir = vim.fs.dirname(new_fname)
vim.fn.mkdir(newdir, 'p') vim.fn.mkdir(newdir, 'p')
local ok, err = os.rename(old_fname_full, new_fname) local ok, err = os.rename(old_fname_full, new_fname)
@ -625,7 +625,7 @@ function M.rename(old_fname, new_fname, opts)
local old_undofile = vim.fn.undofile(old_fname_full) local old_undofile = vim.fn.undofile(old_fname_full)
if uv.fs_stat(old_undofile) ~= nil then if uv.fs_stat(old_undofile) ~= nil then
local new_undofile = vim.fn.undofile(new_fname) local new_undofile = vim.fn.undofile(new_fname)
vim.fn.mkdir(assert(vim.fs.dirname(new_undofile)), 'p') vim.fn.mkdir(vim.fs.dirname(new_undofile), 'p')
os.rename(old_undofile, new_undofile) os.rename(old_undofile, new_undofile)
end end

View File

@ -95,10 +95,10 @@ local function system(cmd, args)
error(emsg) error(emsg)
end end
-- return opts.output
return vim.trim(vim.fn.system(cmd)), shell_error_code return vim.trim(vim.fn.system(cmd)), shell_error_code
end end
---@param provider string
local function provider_disabled(provider) local function provider_disabled(provider)
local loaded_var = 'loaded_' .. provider .. '_provider' local loaded_var = 'loaded_' .. provider .. '_provider'
local v = vim.g[loaded_var] local v = vim.g[loaded_var]
@ -126,9 +126,9 @@ local function clipboard()
health.error('pbcopy does not work with tmux version: ' .. tmux_version, advice) health.error('pbcopy does not work with tmux version: ' .. tmux_version, advice)
end end
local clipboard_tool = vim.fn['provider#clipboard#Executable']() local clipboard_tool = vim.fn['provider#clipboard#Executable']() ---@type string
if vim.g.clipboard ~= nil and clipboard_tool == '' then if vim.g.clipboard ~= nil and clipboard_tool == '' then
local error_message = vim.fn['provider#clipboard#Error']() local error_message = vim.fn['provider#clipboard#Error']() ---@type string
health.error( health.error(
error_message, error_message,
"Use the example in :help g:clipboard as a template, or don't set g:clipboard at all." "Use the example in :help g:clipboard as a template, or don't set g:clipboard at all."
@ -179,7 +179,7 @@ local function node()
) )
end end
local node_detect_table = vim.fn['provider#node#Detect']() local node_detect_table = vim.fn['provider#node#Detect']() ---@type string[]
local host = node_detect_table[1] local host = node_detect_table[1]
if host:find('^%s*$') then if host:find('^%s*$') then
health.warn('Missing "neovim" npm (or yarn, pnpm) package.', { health.warn('Missing "neovim" npm (or yarn, pnpm) package.', {
@ -290,7 +290,7 @@ local function perl()
elseif latest_cpan[1] == '!' then elseif latest_cpan[1] == '!' then
local cpanm_errs = vim.split(latest_cpan, '!') local cpanm_errs = vim.split(latest_cpan, '!')
if cpanm_errs[1]:find("Can't write to ") then if cpanm_errs[1]:find("Can't write to ") then
local advice = {} local advice = {} ---@type string[]
for i = 2, #cpanm_errs do for i = 2, #cpanm_errs do
advice[#advice + 1] = cpanm_errs[i] advice[#advice + 1] = cpanm_errs[i]
end end
@ -303,7 +303,7 @@ local function perl()
return return
end end
end end
latest_cpan = vim.fn.matchstr(latest_cpan, [[\(\.\?\d\)\+]]) latest_cpan = tostring(vim.fn.matchstr(latest_cpan, [[\(\.\?\d\)\+]]))
if latest_cpan:find('^%s*$') then if latest_cpan:find('^%s*$') then
health.error('Cannot parse version number from cpanm output: ' .. latest_cpan) health.error('Cannot parse version number from cpanm output: ' .. latest_cpan)
return return
@ -349,9 +349,11 @@ local function python_exepath(invocation)
return vim.fs.normalize(vim.trim(p.stdout)) return vim.fs.normalize(vim.trim(p.stdout))
end end
-- Check if pyenv is available and a valid pyenv root can be found, then return --- Check if pyenv is available and a valid pyenv root can be found, then return
-- their respective paths. If either of those is invalid, return two empty --- their respective paths. If either of those is invalid, return two empty
-- strings, effectively ignoring pyenv. --- strings, effectively ignoring pyenv.
---
--- @return {[1]: string, [2]: string}
local function check_for_pyenv() local function check_for_pyenv()
local pyenv_path = vim.fn.resolve(vim.fn.exepath('pyenv')) local pyenv_path = vim.fn.resolve(vim.fn.exepath('pyenv'))
@ -394,7 +396,9 @@ local function check_bin(bin)
return true return true
end end
-- Fetch the contents of a URL. --- Fetch the contents of a URL.
---
--- @param url string
local function download(url) local function download(url)
local has_curl = vim.fn.executable('curl') == 1 local has_curl = vim.fn.executable('curl') == 1
if has_curl and vim.fn.system({ 'curl', '-V' }):find('Protocols:.*https') then if has_curl and vim.fn.system({ 'curl', '-V' }):find('Protocols:.*https') then
@ -429,25 +433,24 @@ local function download(url)
return message return message
end end
-- Get the latest Nvim Python client (pynvim) version from PyPI. --- Get the latest Nvim Python client (pynvim) version from PyPI.
local function latest_pypi_version() local function latest_pypi_version()
local pypi_version = 'unable to get pypi response' local pypi_version = 'unable to get pypi response'
local pypi_response = download('https://pypi.python.org/pypi/pynvim/json') local pypi_response = download('https://pypi.python.org/pypi/pynvim/json')
if pypi_response ~= '' then if pypi_response ~= '' then
local pcall_ok, output = pcall(vim.fn.json_decode, pypi_response) local pcall_ok, output = pcall(vim.fn.json_decode, pypi_response)
local pypi_data if not pcall_ok then
if pcall_ok then
pypi_data = output
else
return 'error: ' .. pypi_response return 'error: ' .. pypi_response
end end
local pypi_data = output
local pypi_element = pypi_data['info'] or {} local pypi_element = pypi_data['info'] or {}
pypi_version = pypi_element['version'] or 'unable to parse' pypi_version = pypi_element['version'] or 'unable to parse'
end end
return pypi_version return pypi_version
end end
--- @param s string
local function is_bad_response(s) local function is_bad_response(s)
local lower = s:lower() local lower = s:lower()
return vim.startswith(lower, 'unable') return vim.startswith(lower, 'unable')
@ -455,16 +458,18 @@ local function is_bad_response(s)
or vim.startswith(lower, 'outdated') or vim.startswith(lower, 'outdated')
end end
-- Get version information using the specified interpreter. The interpreter is --- Get version information using the specified interpreter. The interpreter is
-- used directly in case breaking changes were introduced since the last time --- used directly in case breaking changes were introduced since the last time
-- Nvim's Python client was updated. --- Nvim's Python client was updated.
-- ---
-- Returns: { --- @param python string
-- {python executable version}, ---
-- {current nvim version}, --- Returns: {
-- {current pypi nvim status}, --- {python executable version},
-- {installed version status} --- {current nvim version},
-- } --- {current pypi nvim status},
--- {installed version status}
--- }
local function version_info(python) local function version_info(python)
local pypi_version = latest_pypi_version() local pypi_version = latest_pypi_version()
@ -512,9 +517,9 @@ local function version_info(python)
if rc ~= 0 or nvim_version == '' then if rc ~= 0 or nvim_version == '' then
nvim_version = 'unable to find pynvim module version' nvim_version = 'unable to find pynvim module version'
local base = vim.fs.basename(nvim_path) local base = vim.fs.basename(nvim_path)
local metas = vim.fn.glob(base .. '-*/METADATA', 1, 1) local metas = vim.fn.glob(base .. '-*/METADATA', true, 1)
vim.list_extend(metas, vim.fn.glob(base .. '-*/PKG-INFO', 1, 1)) vim.list_extend(metas, vim.fn.glob(base .. '-*/PKG-INFO', true, 1))
vim.list_extend(metas, vim.fn.glob(base .. '.egg-info/PKG-INFO', 1, 1)) vim.list_extend(metas, vim.fn.glob(base .. '.egg-info/PKG-INFO', true, 1))
metas = table.sort(metas, compare) metas = table.sort(metas, compare)
if metas and next(metas) ~= nil then if metas and next(metas) ~= nil then
@ -544,14 +549,13 @@ end
local function python() local function python()
health.start('Python 3 provider (optional)') health.start('Python 3 provider (optional)')
local pyname = 'python3' ---@type string?
local python_exe = '' local python_exe = ''
local virtual_env = os.getenv('VIRTUAL_ENV') local virtual_env = os.getenv('VIRTUAL_ENV')
local venv = virtual_env and vim.fn.resolve(virtual_env) or '' local venv = virtual_env and vim.fn.resolve(virtual_env) or ''
local host_prog_var = pyname .. '_host_prog' local host_prog_var = 'python3_host_prog'
local python_multiple = {} local python_multiple = {} ---@type string[]
if provider_disabled(pyname) then if provider_disabled('python3') then
return return
end end
@ -564,8 +568,7 @@ local function python()
health.info(message) health.info(message)
end end
local pythonx_warnings local pyname, pythonx_warnings = vim.provider.python.detect_by_module('neovim')
pyname, pythonx_warnings = vim.provider.python.detect_by_module('neovim')
if not pyname then if not pyname then
health.warn( health.warn(
@ -653,12 +656,7 @@ local function python()
) )
health.warn('pyenv is not set up optimally.', advice) health.warn('pyenv is not set up optimally.', advice)
elseif venv ~= '' then elseif venv ~= '' then
local venv_root local venv_root = pyenv_root ~= '' and pyenv_root or vim.fs.dirname(venv)
if pyenv_root ~= '' then
venv_root = pyenv_root
else
venv_root = vim.fs.dirname(venv)
end
if vim.startswith(vim.fn.resolve(python_exe), venv_root .. '/') then if vim.startswith(vim.fn.resolve(python_exe), venv_root .. '/') then
local advice = string.format( local advice = string.format(
@ -743,9 +741,9 @@ local function python()
health.ok('no $VIRTUAL_ENV') health.ok('no $VIRTUAL_ENV')
return return
end end
local errors = {} local errors = {} ---@type string[]
-- Keep hints as dict keys in order to discard duplicates. -- Keep hints as dict keys in order to discard duplicates.
local hints = {} local hints = {} ---@type table<string, boolean>
-- The virtualenv should contain some Python executables, and those -- The virtualenv should contain some Python executables, and those
-- executables should be first both on Nvim's $PATH and the $PATH of -- executables should be first both on Nvim's $PATH and the $PATH of
-- subshells launched from Nvim. -- subshells launched from Nvim.

View File

@ -1372,7 +1372,7 @@ function M.validate(help_dir, include, parser_path)
parser_path = parser_path and vim.fn.expand(parser_path) or nil parser_path = parser_path and vim.fn.expand(parser_path) or nil
for _, f in ipairs(helpfiles) do for _, f in ipairs(helpfiles) do
local helpfile = assert(vim.fs.basename(f)) local helpfile = vim.fs.basename(f)
local rv = validate_one(f, parser_path) local rv = validate_one(f, parser_path)
print(('validated (%-4s errors): %s'):format(#rv.parse_errors, helpfile)) print(('validated (%-4s errors): %s'):format(#rv.parse_errors, helpfile))
if #rv.parse_errors > 0 then if #rv.parse_errors > 0 then
@ -1430,7 +1430,7 @@ end
--- :help files, we can be precise about the tolerances here. --- :help files, we can be precise about the tolerances here.
--- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc' --- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
function M.test_gen(help_dir) function M.test_gen(help_dir)
local tmpdir = assert(vim.fs.dirname(vim.fn.tempname())) local tmpdir = vim.fs.dirname(vim.fn.tempname())
help_dir = vim.fn.expand(help_dir or '$VIMRUNTIME/doc') help_dir = vim.fn.expand(help_dir or '$VIMRUNTIME/doc')
print('doc path = ' .. vim.uv.fs_realpath(help_dir)) print('doc path = ' .. vim.uv.fs_realpath(help_dir))

View File

@ -813,7 +813,7 @@ local function get_script_path()
end end
local script_path = get_script_path() local script_path = get_script_path()
local base_dir = vim.fs.dirname(assert(vim.fs.dirname(script_path))) local base_dir = vim.fs.dirname(vim.fs.dirname(script_path))
local function delete_lines_below(doc_file, tokenstr) local function delete_lines_below(doc_file, tokenstr)
local lines = {} --- @type string[] local lines = {} --- @type string[]
@ -965,7 +965,7 @@ local function gen_target(cfg)
end end
end end
-- FIXME: Using f_base will confuse `_meta/protocol.lua` with `protocol.lua` -- FIXME: Using f_base will confuse `_meta/protocol.lua` with `protocol.lua`
local f_base = assert(vim.fs.basename(f)) local f_base = vim.fs.basename(f)
sections[f_base] = make_section(f_base, cfg, briefs_txt, funs_txt) sections[f_base] = make_section(f_base, cfg, briefs_txt, funs_txt)
end end

View File

@ -458,7 +458,7 @@ local function dump_uncommitted(filename, uncommitted)
local out_path = 'luacats-uncommited/' .. filename:gsub('/', '%%') .. '.txt' local out_path = 'luacats-uncommited/' .. filename:gsub('/', '%%') .. '.txt'
if #uncommitted > 0 then if #uncommitted > 0 then
print(string.format('Could not commit %d objects in %s', #uncommitted, filename)) print(string.format('Could not commit %d objects in %s', #uncommitted, filename))
vim.fn.mkdir(assert(vim.fs.dirname(out_path)), 'p') vim.fn.mkdir(vim.fs.dirname(out_path), 'p')
local f = assert(io.open(out_path, 'w')) local f = assert(io.open(out_path, 'w'))
for i, x in ipairs(uncommitted) do for i, x in ipairs(uncommitted) do
f:write(i) f:write(i)

View File

@ -2133,6 +2133,7 @@ M.funcs = {
name = 'exepath', name = 'exepath',
params = { { 'expr', 'any' } }, params = { { 'expr', 'any' } },
signature = 'exepath({expr})', signature = 'exepath({expr})',
returns = 'string',
}, },
exists = { exists = {
args = 1, args = 1,