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