filepath.Walk() – can i provides rules on which directories not to walk on?

Issue

I’m writing a GoLang app using Go 1.7rc1.

now I want to find all go files in a specific path. besides that I want not to walk on some directories.. for example.. hidden directories like .git.

is there a way to provide Walk() with some rules ? or.. is there a diferent libraries that provide these capabilities ?

for now this is my code:

func visit(path string, f os.FileInfo, err error) error {
    fmt.Printf("Visited: %s\n", path)
    return nil
}

func main() {
    filepath.Walk(path,visit)
}

any information regarding the issue would be greatly appreciated. thanks!

Solution

You can skip directories by returning the error filepath.SkipDir from your visit function.

Here’s how to skip .git directories:

func visit(path string, f os.FileInfo, err error) error {
    if f.IsDir() && f.Name() == ".git" {
        return filepath.SkipDir
    }
    fmt.Printf("Visited: %s\n", path)
    return nil
}

The test f.IsDir() is required to avoid skipping the remainder of a directory that contains a normal file named “.git”.

Answered By – Bayta Darell

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.