lualua-5.4

Search upward for a file in lua?


How can I search upward from my cwd to find a file?

Essentially, I want the lua version of this question.

I want to use my .luacheckrc as a root project marker.

I'm using Lua 5.4 without luafilesystem.


Solution

  • I figured out a dumb version that can only find files (not folders) and doesn't canonicalize paths:

    local function file_exists(path)
        local f = io.open(path, "r")
        if f then
            f:close()
            return true
        end
        return false
    end
    
    function find_file_upwards(filename, start_directory)
        assert(filename:sub(-1, -1) ~= '/', "Cannot find folders: Only files are supported.")
        assert(start_directory:sub(-1, -1) == '/', "Folder paths must end with slash: /")
        local dir = start_directory
        for i=1,1000 do
            local fpath = dir .. filename
            if file_exists(fpath) then
                return fpath
            end
            dir = dir .. "../"
        end
    end
    

    Probably should strip paths off instead of using a loop so it can stop when it hits the root of the filesystem instead of many pointless retries.