perf(util): split lazyvim.util in smaller separate modules

This commit is contained in:
Folke Lemaitre
2023-10-10 19:29:24 +02:00
parent 5f5acb5b88
commit c8c929c9fd
20 changed files with 442 additions and 283 deletions

49
lua/lazyvim/util/root.lua Normal file
View File

@ -0,0 +1,49 @@
local Util = require("lazyvim.util")
---@class lazyvim.util.root
local M = {}
M.patterns = { ".git", "lua" }
-- returns the root directory based on:
-- * lsp workspace folders
-- * lsp root_dir
-- * root pattern of filename of the current buffer
-- * root pattern of cwd
---@return string
function M.get()
---@type string?
local path = vim.api.nvim_buf_get_name(0)
path = path ~= "" and vim.loop.fs_realpath(path) or nil
---@type string[]
local roots = {}
if path then
for _, client in pairs(Util.lsp.get_clients({ bufnr = 0 })) do
local workspace = client.config.workspace_folders
local paths = workspace and vim.tbl_map(function(ws)
return vim.uri_to_fname(ws.uri)
end, workspace) or client.config.root_dir and { client.config.root_dir } or {}
for _, p in ipairs(paths) do
local r = vim.loop.fs_realpath(p)
if path:find(r, 1, true) then
roots[#roots + 1] = r
end
end
end
end
table.sort(roots, function(a, b)
return #a > #b
end)
---@type string?
local root = roots[1]
if not root then
path = path and vim.fs.dirname(path) or vim.loop.cwd()
---@type string?
root = vim.fs.find(M.patterns, { path = path, upward = true })[1]
root = root and vim.fs.dirname(root) or vim.loop.cwd()
end
---@cast root string
return root
end
return M