Source File
walk.go
Belonging Package
github.com/kr/fs
// Package fs provides filesystem-related functions.
package fs
import (
)
// Walker provides a convenient interface for iterating over the
// descendants of a filesystem path.
// Successive calls to the Step method will step through each
// file or directory in the tree, including the root. The files
// are walked in lexical order, which makes the output deterministic
// but means that for very large directories Walker can be inefficient.
// Walker does not follow symbolic links.
type Walker struct {
fs FileSystem
cur item
stack []item
descend bool
}
type item struct {
path string
info os.FileInfo
err error
}
// Walk returns a new Walker rooted at root.
func ( string) *Walker {
return WalkFS(, new(fs))
}
// WalkFS returns a new Walker rooted at root on the FileSystem fs.
func ( string, FileSystem) *Walker {
, := .Lstat()
return &Walker{
fs: ,
stack: []item{{, , }},
}
}
// Step advances the Walker to the next file or directory,
// which will then be available through the Path, Stat,
// and Err methods.
// It returns false when the walk stops at the end of the tree.
func ( *Walker) () bool {
if .descend && .cur.err == nil && .cur.info.IsDir() {
, := .fs.ReadDir(.cur.path)
if != nil {
.cur.err =
.stack = append(.stack, .cur)
} else {
for := len() - 1; >= 0; -- {
:= .fs.Join(.cur.path, [].Name())
.stack = append(.stack, item{, [], nil})
}
}
}
if len(.stack) == 0 {
return false
}
:= len(.stack) - 1
.cur = .stack[]
.stack = .stack[:]
.descend = true
return true
}
// Path returns the path to the most recent file or directory
// visited by a call to Step. It contains the argument to Walk
// as a prefix; that is, if Walk is called with "dir", which is
// a directory containing the file "a", Path will return "dir/a".
func ( *Walker) () string {
return .cur.path
}
// Stat returns info for the most recent file or directory
// visited by a call to Step.
func ( *Walker) () os.FileInfo {
return .cur.info
}
// Err returns the error, if any, for the most recent attempt
// by Step to visit a file or directory. If a directory has
// an error, w will not descend into that directory.
func ( *Walker) () error {
return .cur.err
}
// SkipDir causes the currently visited directory to be skipped.
// If w is not on a directory, SkipDir has no effect.
func ( *Walker) () {
.descend = false
}
![]() |
The pages are generated with Golds v0.6.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |