0

I am learning to write Neovim extensions.

Let's name it my-extension.

From my extension, I want to detect the presence of a .my-extension.json at the root of the project.

This is because I want to store different information in that file, that I will grab from the extension.

The extension is written in Lua.

If I write it full Lua, it would look like:

local function get_nearest_git_dir()
  -- Use `package.loaded` to avoid redundant calculations
  if not package.loaded["nearest_git_dir"] then
    local current_dir = package.cwd
    local found = false
    while not found and current_dir ~= "" do
      if fs.access(current_dir .. "/.git", "r") then
        found = true
      else
        current_dir = string.sub(current_dir, 0, string.len(current_dir) - string.len(string.match(current_dir, "^[^/]+")))
      end
    end
    if found then
      package.loaded["nearest_git_dir"] = string.sub(current_dir, 1, string.len(current_dir) - string.len(package.cwd))
    else
      package.loaded["nearest_git_dir"] = nil
    end
  end
  return package.loaded["nearest_git_dir"]
end

local relative_git_dir = get_nearest_git_dir()

if relative_git_dir then
  print("Relative path to nearest git directory:", relative_git_dir)
else
  print("No .git directory found in the current directory or its ancestors.")
end

Is there a Vim function that would be shorter?

2

1 Answer 1

2

Is there a Vim function that would be shorter?

In vim, you can use findfile or finddir.

Find .git directory upwards:

let gitDir = finddir('.git', expand("%:p") . ";")
if !empty(gitDir)
    " .git directory is found
    echo fnamemodify(gitDir, ":h")
endif

Find .my-extension.json file up directory structure:

let fileAtRoot = findfile('.my-extension.json', expand("%:p") . ";")
if !empty(fileAtRoot)
    echo fnamemodify(fileAtRoot, ":p")
endif

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.