fix(uri): using vim.normalize to simplify code

This commit is contained in:
FrancescoLuzzi 2024-04-26 22:27:27 +02:00
parent 1edadd8501
commit 63e8575217
1 changed files with 12 additions and 22 deletions

View File

@ -11,8 +11,8 @@ local URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):.*'
local WINDOWS_URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):[a-zA-Z]:.*'
-- https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/naming-conventions-for-computer-domain-site-ou
-- added also "." to the regex to handle \\wsl.localhost
local WINDOWS_UNC_PATTERN = '^\\\\([a-zA-Z.-]+)(\\.*)'
local WINDOWS_VOLUME_PATTERN = '^([a-zA-Z]:)(.*)'
-- vim.fs.normalize returns paths formatted with "/" so we don't handle "\" (PR #28203)
local WINDOWS_UNC_PATTERN = '^//([a-zA-Z.-]+)(/.*)'
local IS_WINDOWS = vim.uv.os_uname().version:match('Windows')
local PATTERNS = {
@ -66,19 +66,16 @@ end
---@param path string Path to file
---@return string URI
function M.uri_from_fname(path)
local volume_path, vfname = path:match(WINDOWS_VOLUME_PATTERN) ---@type string?,string?
local unc_path, ufname = path:match(WINDOWS_UNC_PATTERN) ---@type string?,string?
local win_pre_fname = volume_path or unc_path
local is_windows = win_pre_fname ~= nil
if is_windows then
local fname = unc_path and ufname or vfname
path = win_pre_fname .. M.uri_encode(fname:gsub('\\', '/'))
else
path = M.uri_encode(path)
end
path = vim.fs.normalize(path)
path = M.uri_encode(path)
local uri_parts = { 'file://' }
if is_windows and not unc_path then
table.insert(uri_parts, '/')
if IS_WINDOWS then
local unc_path, _ = path:match(WINDOWS_UNC_PATTERN) ---@type string?,string?
if unc_path then
path = path:gsub('^//', '')
else
table.insert(uri_parts, '/')
end
end
table.insert(uri_parts, path)
return table.concat(uri_parts)
@ -89,15 +86,8 @@ end
---@return string URI
function M.uri_from_bufnr(bufnr)
local fname = vim.api.nvim_buf_get_name(bufnr)
local volume_path, vfname = fname:match(WINDOWS_VOLUME_PATTERN) ---@type string?,string?
local unc_path, ufname = fname:match(WINDOWS_UNC_PATTERN) ---@type string?,string?
local win_pre_fname = volume_path or unc_path
local is_windows = win_pre_fname ~= nil
local scheme ---@type string?
if is_windows then
fname = unc_path and ufname or vfname
fname = win_pre_fname .. fname
fname = fname:gsub('\\', '/')
if IS_WINDOWS then
scheme = fname:match(WINDOWS_URI_SCHEME_PATTERN)
else
scheme = fname:match(URI_SCHEME_PATTERN)