...

Source file src/path/filepath/example_unix_walk_test.go

Documentation: path/filepath

		 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  // +build !windows,!plan9
		 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  	// Output:
		61  	// On Unix:
		62  	// visited file or dir: "."
		63  	// visited file or dir: "dir"
		64  	// visited file or dir: "dir/to"
		65  	// visited file or dir: "dir/to/walk"
		66  	// skipping a dir without errors: skip
		67  }
		68  

View as plain text