Source file
src/path/filepath/example_unix_walk_test.go
1
2
3
4
5
6
7 package filepath_test
8
9 import (
10 "fmt"
11 "io/fs"
12 "os"
13 "path/filepath"
14 )
15
16 func prepareTestDirTree(tree string) (string, error) {
17 tmpDir, err := os.MkdirTemp("", "")
18 if err != nil {
19 return "", fmt.Errorf("error creating temp directory: %v\n", err)
20 }
21
22 err = os.MkdirAll(filepath.Join(tmpDir, tree), 0755)
23 if err != nil {
24 os.RemoveAll(tmpDir)
25 return "", err
26 }
27
28 return tmpDir, nil
29 }
30
31 func ExampleWalk() {
32 tmpDir, err := prepareTestDirTree("dir/to/walk/skip")
33 if err != nil {
34 fmt.Printf("unable to create test dir tree: %v\n", err)
35 return
36 }
37 defer os.RemoveAll(tmpDir)
38 os.Chdir(tmpDir)
39
40 subDirToSkip := "skip"
41
42 fmt.Println("On Unix:")
43 err = filepath.Walk(".", func(path string, info fs.FileInfo, err error) error {
44 if err != nil {
45 fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err)
46 return err
47 }
48 if info.IsDir() && info.Name() == subDirToSkip {
49 fmt.Printf("skipping a dir without errors: %+v \n", info.Name())
50 return filepath.SkipDir
51 }
52 fmt.Printf("visited file or dir: %q\n", path)
53 return nil
54 })
55 if err != nil {
56 fmt.Printf("error walking the path %q: %v\n", tmpDir, err)
57 return
58 }
59
60
61
62
63
64
65
66 }
67
View as plain text