fix(git): make git.get_root work for work-trees and cache git root checks. Closes #136. Fixes #115

This commit is contained in:
Folke Lemaitre 2024-11-22 13:26:34 +01:00
parent c8d76a765e
commit 9462273bf7
No known key found for this signature in database
GPG key ID: 41F8B1FBACAE2040

View file

@ -10,6 +10,14 @@ Snacks.config.style("blame_line", {
ft = "git",
})
local git_cache = {} ---@type table<string, boolean>
local function is_git_root(dir)
if git_cache[dir] == nil then
git_cache[dir] = (vim.uv or vim.loop).fs_stat(dir .. "/.git") ~= nil
end
return git_cache[dir]
end
--- Gets the git root for a buffer or path.
--- Defaults to the current buffer.
---@param path? number|string buffer or path
@ -17,15 +25,18 @@ function M.get_root(path)
path = path or 0
path = type(path) == "number" and vim.api.nvim_buf_get_name(path) or path --[[@as string]]
path = vim.fs.normalize(path)
path = path == "" and (vim.uv or vim.loop).cwd() or path
local git_root ---@type string?
path = path == "" and (vim.uv or vim.loop).cwd() .. "/foo" or path
-- check cache first
for dir in vim.fs.parents(path) do
if vim.fn.isdirectory(dir .. "/.git") == 1 then
git_root = dir
break
if git_cache[dir] then
return vim.fs.normalize(dir) or nil
end
end
for dir in vim.fs.parents(path) do
if is_git_root(dir) then
return vim.fs.normalize(dir) or nil
end
end
return git_root and vim.fs.normalize(git_root) or nil
end
--- Show git log for the current line.