简体   繁体   English

在 Go (Golang) 中查找文件系统对象

[英]Find filesystem objects in Go (Golang)

I am trying to find matching filesystem objects using Go and determine the type of path I received as input.我正在尝试使用 Go 查找匹配的文件系统对象并确定我作为输入收到的路径类型。 Specifically, I need to perform actions on the object(s) if they match the path provided.具体来说,如果对象与提供的路径匹配,我需要对它们执行操作。 Example input for the path could look like this:路径的示例输入可能如下所示:

/path/to/filename.ext
/path/to/dirname
/path/to/*.txt

I need to know if the path exists, is a file or a directory or a regex so I can process the input accordingly.我需要知道路径是否存在,是文件、目录还是正则表达式,以便我可以相应地处理输入。 Here's the solution I've devised so far:这是我迄今为止设计的解决方案:

func getPathType(path string) (bool, string, error) {
    cpath := filepath.Clean(path)

    l, err := filepath.Glob(cpath)
    if err != nil {
        return false, "", err
    }

    switch len(l) {
    case 0:
        return false, "", nil
    case 1:
        fsstat, fserr := os.Stat(cpath)
        if fserr != nil {
            return false, "", fserr
        }
        if fsstat.IsDir() {
            return true, "dir", nil
        }
        return true, "file", nil
    default:
        return false, "regex", nil
    }
}

I realize that the above code would allow a regex that returned a single value to be interpreted as a dir or file and not as a regex.我意识到上面的代码将允许将返回单个值的正则表达式解释为目录或文件而不是正则表达式。 For my purposes, I can let that slide but just curious if anyone has developed a better way of taking a path potentially containing regex as input and determining whether or not the last element is a regex or not.出于我的目的,我可以放这张幻灯片,但只是好奇是否有人开发了一种更好的方法来采用可能包含正则表达式的路径作为输入并确定最后一个元素是否是正则表达式。

Test for glob special characters to determine if the path is a glob pattern.测试 glob 特殊字符以确定路径是否为 glob 模式。 Use filepath.Match to check for valid glob pattern syntax.使用 filepath.Match 检查有效的 glob 模式语法。

func getPathType(path string) (bool, string, error) {
    cpath := filepath.Clean(path)

    // Use Match to check glob syntax.
    if _, err := filepath.Match(cpath, ""); err != nil {
        return false, "", err
    }

    // If syntax is good and the path includes special
    // glob characters, then it's a glob pattern.
    special := `*?[`
    if runtime.GOOS != "windows" {
        special = `*?[\`
    }
    if strings.ContainsAny(cpath, special) {
        return false, "regex", nil
    }

    fsstat, err := os.Stat(cpath)
    if os.IsNotExist(err) {
        return false, "", nil
    } else if err != nil {
        return false, "", err
    }
    if fsstat.IsDir() {
        return true, "dir", nil
    }
    return true, "file", nil
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM