Rosettea / Hilbish

🌓 The Moon-powered shell! A comfy and extensible shell for Lua fans! 🌺 ✨
https://rosettea.github.io/Hilbish/
MIT License
499 stars 23 forks source link

An easy way to check if a path exists in the fs library. #245

Closed Pikabyte closed 1 year ago

Pikabyte commented 1 year ago

Edit: Nevermind I'm sorry for wasting your time. I hadn't realized that fs.abs() existed. You can simply use that before checking the path with io.open. I suppose I'll leave the issue up in case there's any interest in making a better solution than io.open, but this should work well enough for most usecases. Feel free to immediately close.

Hey, I'm new to Hilbish and things are going pretty smoothly so far, except I'm having a bit of a problem where there isn't exactly a good way to check the existence of a file.

For some background on my usecase: currently, I'm trying to implement an autocd functionality akin to other modern shells. I've decided to try to do this via a custom runner.

local fs = require("fs")
hilbish.runner.add("autocd", function(input)
    --absolute path
    if fs.stat(input).isDir then
        fs.cd(input)
        return {input, 0, nil}
    end

    local path = fs.join(require("hilbish").cwd(), input)

    --nilcheck
    if not path then
        return {input, 2, "Obtaining the relative path failed."}
    end

    --relative path
    if fs.stat(path).isDir then
        fs.cd(path)
        return {input, 0, nil}
    end

    return {input, 1, "The input is not a directory."}
end)

This almost works perfectly, except that fs.stat errors if the given path doesn't exist. This means I cannot have it then try a different runner, such as sh afterward. You can obviously check io.open, but this isn't ideal as it by default isn't going to work on aliases, such as ~ for the home directory.

Personally, I think the nicest solution would be to simply have fs.stat() return nil if the path doesn't exist.