diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-16 19:19:13 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-16 19:19:13 +0000 |
commit | ccd992355df7192993c666236047820244914598 (patch) | |
tree | f00fea65147227b7743083c6148396f74cd66935 /src/path/filepath/example_unix_walk_test.go | |
parent | Initial commit. (diff) | |
download | golang-1.21-ccd992355df7192993c666236047820244914598.tar.xz golang-1.21-ccd992355df7192993c666236047820244914598.zip |
Adding upstream version 1.21.8.upstream/1.21.8
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/path/filepath/example_unix_walk_test.go')
-rw-r--r-- | src/path/filepath/example_unix_walk_test.go | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/src/path/filepath/example_unix_walk_test.go b/src/path/filepath/example_unix_walk_test.go new file mode 100644 index 0000000..86146db --- /dev/null +++ b/src/path/filepath/example_unix_walk_test.go @@ -0,0 +1,66 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !windows && !plan9 + +package filepath_test + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" +) + +func prepareTestDirTree(tree string) (string, error) { + tmpDir, err := os.MkdirTemp("", "") + if err != nil { + return "", fmt.Errorf("error creating temp directory: %v\n", err) + } + + err = os.MkdirAll(filepath.Join(tmpDir, tree), 0755) + if err != nil { + os.RemoveAll(tmpDir) + return "", err + } + + return tmpDir, nil +} + +func ExampleWalk() { + tmpDir, err := prepareTestDirTree("dir/to/walk/skip") + if err != nil { + fmt.Printf("unable to create test dir tree: %v\n", err) + return + } + defer os.RemoveAll(tmpDir) + os.Chdir(tmpDir) + + subDirToSkip := "skip" + + fmt.Println("On Unix:") + err = filepath.Walk(".", func(path string, info fs.FileInfo, err error) error { + if err != nil { + fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err) + return err + } + if info.IsDir() && info.Name() == subDirToSkip { + fmt.Printf("skipping a dir without errors: %+v \n", info.Name()) + return filepath.SkipDir + } + fmt.Printf("visited file or dir: %q\n", path) + return nil + }) + if err != nil { + fmt.Printf("error walking the path %q: %v\n", tmpDir, err) + return + } + // Output: + // On Unix: + // visited file or dir: "." + // visited file or dir: "dir" + // visited file or dir: "dir/to" + // visited file or dir: "dir/to/walk" + // skipping a dir without errors: skip +} |