How can I loop over all paths/filenames in dir and require them?


I want to create my first plugin which is suppose to be a snippets library for LuaSnip,
and my idea is to put snippets for each file type in its own file in a directory like so:

init.lua -- require all snippets into luasnip table here
snippets_dir/ -- loop over all snippet modules in this dir

And then import each snippets file module in the main init.lua file

Is there a way to get a list of these file paths / file names in nvim lua so
that I can require these in a loop and then insert eache filetype module into a table

From what I understand there is a function called scandir in plenary.vim that
would be nice to use but I am unsure if it works in a plugin when I don’t know
where the plugin will be located on a system since it takes a valid path as
first param? So therefore I am was thinking that I should maybe use a relative
path for this in my plugin but that seems a complicated in lua at first glance?

Am I thinking correctly or is there a smarter way to do this? Can achieve my
goal with requiring all files in the snippets dir with scandir somehow?
I guess everybody doesn’t know or have used plenary (me not so much either) but
so the questino is then what type of path do I pass to scandir so that the plugin
will work with not just a single plugin manager with a fixed path?

I have found that debug.getinfo(1,"S").source:sub(2) can be used to get the absolute path and
then I can take it from there.

Is this okay in a plugin? Are there any security issues or something that I don’t know about here?

After this I am thinking about using this function to get all the files in a table:

function scandir(directory)
    local i, t, popen = 0, {}, io.popen
    local pfile = popen('ls -a "''"')
    for filename in pfile:lines() do
        i = i + 1
        t[i] = filename
    return t

I would make the user put the files in a directory on the runtime and use vim.api.nvim_get_runtime_file with the pattern mysnippet_plugin/*.lua that would find all the files, then I would do a little regex to generete the names needed to load them using the built in require() which will do the cache for you and will only see improvements since it’s being worked on (in the future what impatient.nvim does will be implemented in core).

This way you avoid reinventing the weel :slight_smile:

1 Like

Great!! Thanks for pointing this out to me man!