Home > OS >  Find filesystem objects in Go (Golang)
Find filesystem objects in Go (Golang)

Time:10-22

I am trying to find matching filesystem objects using Go and determine the type of path I received as input. 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.

CodePudding user response:

Test for glob special characters to determine if the path is a glob pattern. Use filepath.Match to check for valid glob pattern syntax.

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
}
  • Related