• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
7package filepath_test
8
9import (
10	"fmt"
11	"io/fs"
12	"os"
13	"path/filepath"
14)
15
16func 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
31func 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	// Output:
60	// On Unix:
61	// visited file or dir: "."
62	// visited file or dir: "dir"
63	// visited file or dir: "dir/to"
64	// visited file or dir: "dir/to/walk"
65	// skipping a dir without errors: skip
66}
67