aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/vim/fs.lua
diff options
context:
space:
mode:
authorGregory Anders <greg@gpanders.com>2022-05-15 14:38:19 -0600
committerGregory Anders <greg@gpanders.com>2022-05-31 13:04:40 -0600
commit67cbaf58c41a3db19c5014587e72d06be9e3d58e (patch)
tree49fa85e672d6637ef38a9e910a1323224ca653ab /runtime/lua/vim/fs.lua
parente6652821bd32e4ff8d62a0b67fc2041a5f41e252 (diff)
downloadrneovim-67cbaf58c41a3db19c5014587e72d06be9e3d58e.tar.gz
rneovim-67cbaf58c41a3db19c5014587e72d06be9e3d58e.tar.bz2
rneovim-67cbaf58c41a3db19c5014587e72d06be9e3d58e.zip
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.
Diffstat (limited to 'runtime/lua/vim/fs.lua')
-rw-r--r--runtime/lua/vim/fs.lua35
1 files changed, 35 insertions, 0 deletions
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:
+--- <pre>
+--- 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
+--- </pre>
+---
+---@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