Skip to content

Instantly share code, notes, and snippets.

@ianfoo
Last active June 9, 2021 04:43
Show Gist options
  • Save ianfoo/a580f9c9c57c100e5f2262ebfaf5b143 to your computer and use it in GitHub Desktop.
Save ianfoo/a580f9c9c57c100e5f2262ebfaf5b143 to your computer and use it in GitHub Desktop.
Cheap-ass filepath.WalkDir example
.
./all-files.txt
./sub1
./sub1/foo.toml
./sub1/foo.json
./sub1/bar.json
./sub1/foo.yaml
./sub1/sub2
./sub1/sub2/foo.blarg
./sub1/sub2/blarg.yamllllll
./globwalk.go
./foo.txt
./bar.txt
./glob.go
./output.txt
package main
import (
"fmt"
"io/fs"
"log"
"path/filepath"
)
func main() {
const excludePat = "foo*"
var (
include []string
filter = genExcludeFilter(excludePat, &include)
)
if err := filepath.WalkDir(".", filter); err != nil {
log.Fatalf("error walking directory: %v", err)
}
for _, f := range include {
fmt.Println(f)
}
}
func genExcludeFilter(
excludePat string,
include *[]string,
) func(string, fs.DirEntry, error) error {
return func(path string, dirEntry fs.DirEntry, err error) error {
if err != nil {
if dirEntry != nil {
return fs.SkipDir
}
return err
}
if dirEntry.IsDir() {
// Skip directories.
return nil
}
exclude, err := filepath.Match(excludePat, dirEntry.Name())
if err != nil {
return err
}
if !exclude {
*include = append(*include, path)
}
return nil
}
}
all-files.txt
bar.txt
glob.go
globwalk.go
output.txt
sub1/bar.json
sub1/sub2/blarg.yamllllll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment