Documentation ¶
Overview ¶
Package godirwalk provides functions to read and traverse directory trees.
In short, why do I use this library?
* It's faster than `filepath.Walk`.
* It's more correct on Windows than `filepath.Walk`.
* It's more easy to use than `filepath.Walk`.
* It's more flexible than `filepath.Walk`.
USAGE ¶
This library will normalize the provided top level directory name based on the os-specific path separator by calling `filepath.Clean` on its first argument. However it always provides the pathname created by using the correct os-specific path separator when invoking the provided callback function.
dirname := "some/directory/root" err := godirwalk.Walk(dirname, &godirwalk.Options{ Callback: func(osPathname string, de *godirwalk.Dirent) error { fmt.Printf("%s %s\n", de.ModeType(), osPathname) return nil }, })
This library not only provides functions for traversing a file system directory tree, but also for obtaining a list of immediate descendants of a particular directory, typically much more quickly than using `os.ReadDir` or `os.ReadDirnames`.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ReadDirnames ¶ added in v0.0.2
ReadDirnames returns a slice of strings, representing the immediate descendants of the specified directory. If the specified directory is a symbolic link, it will be resolved.
If an optional scratch buffer is provided that is at least one page of memory, it will be used when reading directory entries from the file system.
Note that this function, depending on operating system, may or may not invoke the ReadDirents function, in order to prepare the list of immediate descendants. Therefore, if your program needs both the names and the file system mode types of descendants, it will always be faster to invoke ReadDirents directly, rather than calling this function, then looping over the results and calling os.Stat for each child.
children, err := godirwalk.ReadDirnames(osDirname, nil) if err != nil { return nil, errors.Wrap(err, "cannot get list of directory children") } sort.Strings(children) for _, child := range children { fmt.Printf("%s\n", child) }
func Walk ¶ added in v0.1.0
Walk walks the file tree rooted at the specified directory, calling the specified callback function for each file system node in the tree, including root, symbolic links, and other node types. The nodes are walked in lexical order, which makes the output deterministic but means that for very large directories this function can be inefficient.
This function is often much faster than filepath.Walk because it does not invoke os.Stat for every node it encounters, but rather obtains the file system node type when it reads the parent directory.
If an error is returned by an operating system, processing typically stops. However, when an ErrorCallback function is provided in the provided Options structure, that function is invoked with the error along with the OS pathname of the file system node that caused the error. The ErrorCallback function's return value determines the action that Walk will then take.
func main() { dirname := "." if len(os.Args) > 1 { dirname = os.Args[1] } err := godirwalk.Walk(dirname, &godirwalk.Options{ Callback: func(osPathname string, de *godirwalk.Dirent) error { fmt.Printf("%s %s\n", de.ModeType(), osPathname) return nil }, ErrorCallback: func(osPathname string, err error) godirwalk.ErrorAction { // Your program may want to log the error somehow. fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) // For the purposes of this example, a simple SkipNode will suffice, // although in reality perhaps additional logic might be called for. return godirwalk.SkipNode }, }) if err != nil { fmt.Fprintf(os.Stderr, "%s\n", err) os.Exit(1) } }
Types ¶
type Dirent ¶
type Dirent struct {
// contains filtered or unexported fields
}
Dirent stores the name and file system mode type of discovered file system entries.
func (Dirent) IsDir ¶ added in v1.0.0
IsDir returns true if and only if the Dirent represents a file system directory. Note that on some operating systems, more than one file mode bit may be set for a node. For instance, on Windows, a symbolic link that points to a directory will have both the directory and the symbolic link bits set.
func (Dirent) IsSymlink ¶ added in v1.0.0
IsSymlink returns true if and only if the Dirent represents a file system symbolic link. Note that on some operating systems, more than one file mode bit may be set for a node. For instance, on Windows, a symbolic link that points to a directory will have both the directory and the symbolic link bits set.
func (Dirent) ModeType ¶
ModeType returns the mode bits that specify the file system node type. We could make our own enum-like data type for encoding the file type, but Go's runtime already gives us architecture independent file modes, as discussed in `os/types.go`:
Go's runtime FileMode type has same definition on all systems, so that information about files can be moved from one system to another portably.
type Dirents ¶
type Dirents []*Dirent
Dirents represents a slice of Dirent pointers, which are sortable by name. This type satisfies the `sort.Interface` interface.
func ReadDirents ¶ added in v0.0.2
ReadDirents returns a sortable slice of pointers to Dirent structures, each representing the file system name and mode type for one of the immediate descendant of the specified directory. If the specified directory is a symbolic link, it will be resolved.
If an optional scratch buffer is provided that is at least one page of memory, it will be used when reading directory entries from the file system.
children, err := godirwalk.ReadDirents(osDirname, nil) if err != nil { return nil, errors.Wrap(err, "cannot get list of directory children") } sort.Sort(children) for _, child := range children { fmt.Printf("%s %s\n", child.ModeType, child.Name) }
type ErrorAction ¶ added in v1.4.0
type ErrorAction int
ErrorAction defines a set of actions the Walk function could take based on the occurrence of an error returned by the operating system. See the documentation for the ErrorCallback field of the Options structure for more information.
const ( // Halt is the ErrorAction return value when the upstream code wants to halt // the walk process when a runtime error takes place. It matches the default // action the Walk function would take were no ErrorCallback provided. Halt ErrorAction = iota // SkipNode is the ErrorAction return value when the upstream code wants to // ignore the runtime error for the current file system node, skip // processing of the node that caused the error, and continue walking the // file system hierarchy with the remaining nodes. SkipNode )
type Options ¶ added in v1.0.0
type Options struct { // ErrorCallback specifies a function to be invoked in the case of an error // that could potentially be ignored while walking a file system // hierarchy. When set to nil or left as its zero-value, any error condition // causes Walk to immediately return the error describing what took // place. When non-nil, this user supplied function is invoked with the OS // pathname of the file system object that caused the error along with the // error that took place. The return value of the supplied ErrorCallback // function determines whether the error will cause Walk to halt immediately // as it would were no ErrorCallback value provided, or skip this file // system node yet continue on with the remaining nodes in the file system // hierarchy. // // NOTE: ErrorCallback is only invoked for errors that are returned by the // runtime, and not for errors returned by other user supplied callback // functions. ErrorCallback func(string, error) ErrorAction // FollowSymbolicLinks specifies whether Walk will follow symbolic links // that refer to directories. When set to false or left as its zero-value, // Walk will still invoke the callback function with symbolic link nodes, // but if the symbolic link refers to a directory, it will not recurse on // that directory. When set to true, Walk will recurse on symbolic links // that refer to a directory. FollowSymbolicLinks bool // Unsorted controls whether or not Walk will sort the immediate descendants // of a directory by their relative names prior to visiting each of those // entries. // // When set to false or left at its zero-value, Walk will get the list of // immediate descendants of a particular directory, sort that list by // lexical order of their names, and then visit each node in the list in // sorted order. This will cause Walk to always traverse the same directory // tree in the same order, however may be inefficient for directories with // many immediate descendants. // // When set to true, Walk skips sorting the list of immediate descendants // for a directory, and simply visits each node in the order the operating // system enumerated them. This will be more fast, but with the side effect // that the traversal order may be different from one invocation to the // next. Unsorted bool // Callback is a required function that Walk will invoke for every file // system node it encounters. Callback WalkFunc // PostChildrenCallback is an option function that Walk will invoke for // every file system directory it encounters after its children have been // processed. PostChildrenCallback WalkFunc // ScratchBuffer is an optional scratch buffer for Walk to use when reading // directory entries, to reduce amount of garbage generation. Not all // architectures take advantage of the scratch buffer. ScratchBuffer []byte }
Options provide parameters for how the Walk function operates.
type WalkFunc ¶ added in v0.1.0
WalkFunc is the type of the function called for each file system node visited by Walk. The pathname argument will contain the argument to Walk as a prefix; that is, if Walk is called with "dir", which is a directory containing the file "a", the provided WalkFunc will be invoked with the argument "dir/a", using the correct os.PathSeparator for the Go Operating System architecture, GOOS. The directory entry argument is a pointer to a Dirent for the node, providing access to both the basename and the mode type of the file system node.
If an error is returned by the Callback or PostChildrenCallback functions, processing stops. The sole exception is when the function returns the special value filepath.SkipDir. If the function returns filepath.SkipDir when invoked on a directory, Walk skips the directory's contents entirely. If the function returns filepath.SkipDir when invoked on a non-directory file system node, Walk skips the remaining files in the containing directory.