From 67cbaf58c41a3db19c5014587e72d06be9e3d58e Mon Sep 17 00:00:00 2001 From: Gregory Anders Date: Sun, 15 May 2022 14:38:19 -0600 Subject: feat(fs): add vim.fs.parents() vim.fs.parents() is a Lua iterator that returns the next parent directory of the given file or directory on each iteration. --- runtime/doc/lua.txt | 28 ++++++++++++++++++++++++++++ runtime/lua/vim/_editor.lua | 1 + runtime/lua/vim/fs.lua | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 runtime/lua/vim/fs.lua (limited to 'runtime') diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index dd1843ade3..8f74dca418 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -2147,4 +2147,32 @@ set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* See also: ~ |nvim_set_keymap()| + +============================================================================== +Lua module: fs *lua-fs* + +parents({start}) *vim.fs.parents()* + Iterate over all the parents of the given file or directory. + + Example: > + + local root_dir + for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do + if vim.fn.isdirectory(dir .. "/.git") == 1 then + root_dir = dir + break + end + end + + if root_dir then + print("Found git repository at", root_dir) + end +< + + Parameters: ~ + {start} (string) Initial file or directory. + + Return: ~ + (function) Iterator + vim:tw=78:ts=8:ft=help:norl: diff --git a/runtime/lua/vim/_editor.lua b/runtime/lua/vim/_editor.lua index c8a0aa8260..453aa6ac81 100644 --- a/runtime/lua/vim/_editor.lua +++ b/runtime/lua/vim/_editor.lua @@ -50,6 +50,7 @@ for k, v in pairs({ keymap = true, ui = true, health = true, + fs = true, }) do vim._submodules[k] = v end diff --git a/runtime/lua/vim/fs.lua b/runtime/lua/vim/fs.lua new file mode 100644 index 0000000000..08d2e495d2 --- /dev/null +++ b/runtime/lua/vim/fs.lua @@ -0,0 +1,35 @@ +local M = {} + +--- Iterate over all the parents of the given file or directory. +--- +--- Example: +---
+--- local root_dir
+--- for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
+---   if vim.fn.isdirectory(dir .. "/.git") == 1 then
+---     root_dir = dir
+---     break
+---   end
+--- end
+---
+--- if root_dir then
+---   print("Found git repository at", root_dir)
+--- end
+--- 
+--- +---@param start (string) Initial file or directory. +---@return (function) Iterator +function M.parents(start) + return function(_, dir) + local parent = vim.fn.fnamemodify(dir, ":h") + if parent == dir then + return nil + end + + return parent + end, + nil, + start +end + +return M -- cgit