fix(#2004): relative path detection handles regex magic (#2005)

* fix(#2004): Change path_relative to use string find and substring to avoid using regex.

- This removed the original gsub with unintentional captures in path_to_matching_str
- The original regex based code captures create a limit where input path cannot
  have more than 32 special charactors ( `.`  , `_` or `-`)

* style nit

---------

Co-authored-by: Alexander Courtis <alex@courtis.org>
This commit is contained in:
Kai Ting
2023-02-19 15:15:42 -08:00
committed by GitHub
parent 04f99f14b5
commit 66c15afd13

View File

@@ -11,10 +11,6 @@ M.is_wsl = vim.fn.has "wsl" == 1
-- false for WSL
M.is_windows = vim.fn.has "win32" == 1 or vim.fn.has "win32unix" == 1
function M.path_to_matching_str(path)
return path:gsub("(%-)", "(%%-)"):gsub("(%.)", "(%%.)"):gsub("(%_)", "(%%_)")
end
function M.str_find(haystack, needle)
return vim.fn.stridx(haystack, needle) ~= -1
end
@@ -59,7 +55,14 @@ end
---@param relative_to string
---@return string
function M.path_relative(path, relative_to)
local p, _ = path:gsub("^" .. M.path_to_matching_str(M.path_add_trailing(relative_to)), "")
local _, r = path:find(M.path_add_trailing(relative_to), 1, true)
local p = path
if r then
-- take the relative path starting after '/'
-- if somehow given a completely matching path,
-- returns ""
p = path:sub(r + 1)
end
return p
end