generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walkdir.go
46 lines (43 loc) · 1011 Bytes
/
walkdir.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package scaffolder
import (
"errors"
"io/fs"
"os"
"path/filepath"
)
// ErrSkip can be returned by WalkDir callbacks to skip a file or directory.
var ErrSkip = errors.New("skip directory")
// WalkDir performs a depth-first walk of dir, executing fn before each file or
// directory.
//
// If fn returns ErrSkip, the directory will be skipped.
func WalkDir(dir string, fn func(path string, d fs.DirEntry) error) error {
dirInfo, err := os.Stat(dir)
if err != nil {
return err
}
if err = fn(dir, fs.FileInfoToDirEntry(dirInfo)); err != nil {
if errors.Is(err, ErrSkip) {
return nil
}
return err
}
entries, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, entry := range entries {
if entry.IsDir() {
err = WalkDir(filepath.Join(dir, entry.Name()), fn)
if err != nil && !errors.Is(err, ErrSkip) {
return err
}
} else {
err = fn(filepath.Join(dir, entry.Name()), entry)
if err != nil && !errors.Is(err, ErrSkip) {
return err
}
}
}
return nil
}