aboutsummaryrefslogtreecommitdiffstats
path: root/lua
diff options
context:
space:
mode:
authorWilliam Boman <william@redwill.se>2023-10-13 15:40:24 +0200
committerWilliam Boman <william@redwill.se>2025-02-19 09:23:19 +0100
commit3bc4b74f12303319e088c963a7c13486c4e4e776 (patch)
tree8ed4f5deef05605337a371795cb9f2fd994a53eb /lua
parentrefactor(path): use InstallLocation to produce paths, remove static path methods (diff)
downloadmason-3bc4b74f12303319e088c963a7c13486c4e4e776.tar
mason-3bc4b74f12303319e088c963a7c13486c4e4e776.tar.gz
mason-3bc4b74f12303319e088c963a7c13486c4e4e776.tar.bz2
mason-3bc4b74f12303319e088c963a7c13486c4e4e776.tar.lz
mason-3bc4b74f12303319e088c963a7c13486c4e4e776.tar.xz
mason-3bc4b74f12303319e088c963a7c13486c4e4e776.tar.zst
mason-3bc4b74f12303319e088c963a7c13486c4e4e776.zip
feat(path): add relative(from, to)
Diffstat (limited to 'lua')
-rw-r--r--lua/mason-core/path.lua33
1 files changed, 32 insertions, 1 deletions
diff --git a/lua/mason-core/path.lua b/lua/mason-core/path.lua
index 9eeed3ba..66f0f964 100644
--- a/lua/mason-core/path.lua
+++ b/lua/mason-core/path.lua
@@ -24,7 +24,38 @@ end
---@path root_path string
---@path path string
function M.is_subdirectory(root_path, path)
- return root_path == path or path:sub(1, #root_path + 1) == root_path .. sep
+ local root_path_normalized = vim.fs.normalize(root_path)
+ local path_normalized = vim.fs.normalize(path)
+ if path_normalized == root_path_normalized then
+ return true
+ end
+ for dir in vim.fs.parents(path_normalized) do
+ if root_path_normalized == dir then
+ return true
+ end
+ end
+ return false
+end
+
+local function find_closest_common_parent(from, to)
+ local distance = 0
+ for parent in vim.fs.parents(from) do
+ if to:find(parent, 1, true) then
+ return parent, distance
+ else
+ distance = distance + 1
+ end
+ end
+ return "/", distance
+end
+
+function M.relative(from, to)
+ local from_normalized = vim.fs.normalize(from)
+ local to_normalized = vim.fs.normalize(to)
+
+ local common_parent, distance = find_closest_common_parent(from_normalized, to_normalized)
+ local relative_path_component = distance == 0 and "." or (".."):rep(distance, "/")
+ return vim.fs.joinpath(relative_path_component, to_normalized:sub(#common_parent + 1))
end
return M