github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/path/filepath/example_unix_walk_test.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build !windows && !plan9 6 7 package filepath_test 8 9 import ( 10 "github.com/shogo82148/std/fmt" 11 "github.com/shogo82148/std/io/fs" 12 "github.com/shogo82148/std/os" 13 "github.com/shogo82148/std/path/filepath" 14 ) 15 16 func ExampleWalk() { 17 tmpDir, err := prepareTestDirTree("dir/to/walk/skip") 18 if err != nil { 19 fmt.Printf("unable to create test dir tree: %v\n", err) 20 return 21 } 22 defer os.RemoveAll(tmpDir) 23 os.Chdir(tmpDir) 24 25 subDirToSkip := "skip" 26 27 fmt.Println("On Unix:") 28 err = filepath.Walk(".", func(path string, info fs.FileInfo, err error) error { 29 if err != nil { 30 fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err) 31 return err 32 } 33 if info.IsDir() && info.Name() == subDirToSkip { 34 fmt.Printf("skipping a dir without errors: %+v \n", info.Name()) 35 return filepath.SkipDir 36 } 37 fmt.Printf("visited file or dir: %q\n", path) 38 return nil 39 }) 40 if err != nil { 41 fmt.Printf("error walking the path %q: %v\n", tmpDir, err) 42 return 43 } 44 // Output: 45 // On Unix: 46 // visited file or dir: "." 47 // visited file or dir: "dir" 48 // visited file or dir: "dir/to" 49 // visited file or dir: "dir/to/walk" 50 // skipping a dir without errors: skip 51 }