fastwalk

package module
v1.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 9, 2025 License: MIT Imports: 12 Imported by: 47

README

GoDoc Test fastwalk on macOS Test fastwalk on Linux Test fastwalk on Windows

fastwalk

Fast parallel directory traversal for Golang.

Package fastwalk provides a fast parallel version of filepath.WalkDir that is ~2.5x faster on macOS, ~4x faster on Linux, ~6x faster on Windows, allocates 50% less memory, and requires 25% fewer memory allocations. Additionally, it is ~4-5x faster than godirwalk across OSes.

Inspired by and based off of golang.org/x/tools/internal/fastwalk.

Features

Usage

Usage is the same as filepath.WalkDir, but the walkFn argument to fastwalk.Walk must be safe for concurrent use.

Examples can be found in the examples directory.

The below example is a very simple version of the POSIX find utility:

// fwfind is a an example program that is similar to POSIX find,
// but faster and worse (it's an example).
package main

import (
	"flag"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"

	"github.com/charlievieth/fastwalk"
)

const usageMsg = `Usage: %[1]s [-L] [-name] [PATH...]:

%[1]s is a poor replacement for the POSIX find utility

`

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stdout, usageMsg, filepath.Base(os.Args[0]))
		flag.PrintDefaults()
	}
	pattern := flag.String("name", "", "Pattern to match file names against.")
	followLinks := flag.Bool("L", false, "Follow symbolic links")
	flag.Parse()

	// If no paths are provided default to the current directory: "."
	args := flag.Args()
	if len(args) == 0 {
		args = append(args, ".")
	}

	// Follow links if the "-L" flag is provided
	conf := fastwalk.Config{
		Follow: *followLinks,
	}

	walkFn := func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s: %v\n", path, err)
			return nil // returning the error stops iteration
		}
		if *pattern != "" {
			if ok, err := filepath.Match(*pattern, d.Name()); !ok {
				// invalid pattern (err != nil) or name does not match
				return err
			}
		}
		_, err = fmt.Println(path)
		return err
	}
	for _, root := range args {
		if err := fastwalk.Walk(&conf, root, walkFn); err != nil {
			fmt.Fprintf(os.Stderr, "%s: %v\n", root, err)
			os.Exit(1)
		}
	}
}

Benchmarks

Benchmarks were created using go1.17.6 and can be generated with the bench_comp make target:

$ make bench_comp
Darwin

Hardware:

goos: darwin
goarch: arm64
cpu: Apple M1 Max
filepath.WalkDir vs. fastwalk.Walk():
              filepath       fastwalk       delta
time/op       27.9ms ± 1%    13.0ms ± 1%    -53.33%
alloc/op      4.33MB ± 0%    2.14MB ± 0%    -50.55%
allocs/op     50.9k ± 0%     37.7k ± 0%     -26.01%
godirwalk.Walk() vs. fastwalk.Walk():
              godirwalk      fastwalk       delta
time/op       58.5ms ± 3%    18.0ms ± 2%    -69.30%
alloc/op      25.3MB ± 0%    2.1MB ± 0%     -91.55%
allocs/op     57.6k ± 0%     37.7k ± 0%     -34.59%
Linux

Hardware:

goos: linux
goarch: amd64
cpu: Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
drive: Samsung SSD 970 PRO 1TB
filepath.WalkDir vs. fastwalk.Walk():
              filepath       fastwalk       delta
time/op       10.1ms ± 2%    2.8ms ± 2%     -72.83%
alloc/op      2.44MB ± 0%    1.70MB ± 0%    -30.46%
allocs/op     47.2k ± 0%     36.9k ± 0%     -21.80%
godirwalk.Walk() vs. fastwalk.Walk():
              filepath       fastwalk       delta
time/op       13.7ms ±16%    2.8ms ± 2%     -79.88%
alloc/op      7.48MB ± 0%    1.70MB ± 0%    -77.34%
allocs/op     53.8k ± 0%     36.9k ± 0%     -31.38%
Windows

Hardware:

goos: windows
goarch: amd64
pkg: github.com/charlievieth/fastwalk
cpu: Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
filepath.WalkDir vs. fastwalk.Walk():
              filepath       fastwalk       delta
time/op       88.0ms ± 1%    14.6ms ± 1%    -83.47%
alloc/op      5.68MB ± 0%    6.76MB ± 0%    +19.01%
allocs/op     69.6k ± 0%     90.4k ± 0%     +29.87%
godirwalk.Walk() vs. fastwalk.Walk():
              filepath       fastwalk       delta
time/op       87.4ms ± 1%    14.6ms ± 1%    -83.34%
alloc/op      6.14MB ± 0%    6.76MB ± 0%    +10.24%
allocs/op     100k ± 0%      90k ± 0%       -9.59%

Documentation

Overview

Package fastwalk provides a faster version of filepath.WalkDir for file system scanning tools.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultConfig = Config{
	Follow:     false,
	ToSlash:    DefaultToSlash(),
	NumWorkers: DefaultNumWorkers(),
	Sort:       SortNone,
	MaxDepth:   0,
}

DefaultConfig is the default Config used when none is supplied.

View Source
var ErrSkipFiles = errors.New("fastwalk: skip remaining files in directory")

ErrSkipFiles is a used as a return value from WalkFuncs to indicate that the callback should not be called for any other files in the current directory. Child directories will still be traversed.

View Source
var ErrTraverseLink = errors.New("fastwalk: traverse symlink, assuming target is a directory")

ErrTraverseLink is used as a return value from WalkDirFuncs to indicate that the symlink named in the call may be traversed. This error is ignored if the Follow Config option is true.

View Source
var SkipDir = fs.SkipDir

SkipDir is used as a return value from WalkDirFuncs to indicate that the directory named in the call is to be skipped. It is not returned as an error by any function.

Functions

func DefaultNumWorkers

func DefaultNumWorkers() int

DefaultNumWorkers returns the default number of worker goroutines to use in Walk and is the value of runtime.GOMAXPROCS(-1) clamped to a range of 4 to 32 except on Darwin where it is either 4 (8 cores or less), 6 (10 cores or less), or 10 (more than 10 cores). This is because Walk / IO performance on Darwin degrades with more concurrency.

The optimal number for your workload may be lower or higher. The results of BenchmarkFastWalkNumWorkers benchmark may be informative.

func DefaultToSlash added in v1.0.5

func DefaultToSlash() bool

DefaultToSlash returns true if this is a Go program compiled for Windows running in an environment (MSYS/MSYS2 or Git for Windows) that uses forward slashes as the path separator instead of the native backslash.

On non-Windows OSes this is a no-op and always returns false.

To detect if we're running in MSYS/MSYS2 we check if the "MSYSTEM" environment variable exists.

DefaultToSlash does not detect if this is a Windows executable running in WSL. Instead, users should (ideally) use programs compiled for Linux in WSL.

See: github.com/junegunn/fzf/issues/3859

NOTE: The reason that we do not check if we're running in WSL is that the test was inconsistent since it depended on the working directory (it seems that "/proc" cannot be accessed when programs are ran from a mounted Windows directory) and what environment variables are shared between WSL and Win32 (this requires explicit configuration).

func DirEntryDepth added in v1.0.11

func DirEntryDepth(de fs.DirEntry) int

DirEntryDepth returns the depth at which entry de was generated relative to the root being walked or -1 if de does not have type fastwalk.DirEntry.

This is a helper function that saves the user from having to cast the fs.DirEntry argument to their walk function to a fastwalk.DirEntry and is equivalent to the below code:

if d, _ := de.(DirEntry); d != nil {
	return d.Depth()
}
return -1

func IgnoreDuplicateDirs

func IgnoreDuplicateDirs(walkFn fs.WalkDirFunc) fs.WalkDirFunc

IgnoreDuplicateDirs wraps fs.WalkDirFunc walkFn to make it follow symbolic links and ignore duplicate directories (if a symlink points to a directory that has already been traversed it is skipped). The walkFn is called for for skipped directories, but the directory is not traversed (this is required for error handling).

The Follow Config setting has no effect on the behavior of Walk when this wrapper is used.

In most use cases, the returned fs.WalkDirFunc should not be reused. If it is reused, any previously visited file will be skipped.

NOTE: The order of traversal is undefined. Given an "example" directory like the one below where "dir" is a directory and "smydir1" and "smydir2" are links to it, only one of "dir", "smydir1", or "smydir2" will be traversed, but which one is undefined.

example
├── dir
├── smydir1 -> dir
└── smydir2 -> dir

func IgnoreDuplicateFiles

func IgnoreDuplicateFiles(walkFn fs.WalkDirFunc) fs.WalkDirFunc

IgnoreDuplicateFiles wraps walkFn so that symlinks are followed and duplicate files are ignored. If a symlink resolves to a file that has already been visited it will be skipped.

In most use cases, the returned fs.WalkDirFunc should not be reused. If it is reused, any previously visited file will be skipped.

This can significantly slow Walk as os.Stat() is called for each path (on Windows, os.Stat() is only needed for symlinks).

func IgnorePermissionErrors

func IgnorePermissionErrors(walkFn fs.WalkDirFunc) fs.WalkDirFunc

IgnorePermissionErrors wraps walkFn so that fs.ErrPermission permission errors are ignored. The returned fs.WalkDirFunc may be reused.

func StatDirEntry

func StatDirEntry(path string, de fs.DirEntry) (fs.FileInfo, error)

StatDirEntry returns a fs.FileInfo describing the named file (os.Stat). If de is a fastwalk.DirEntry its Stat method is used and the returned FileInfo may be cached from a prior call to Stat. If a cached result is not desired, users should just call os.Stat directly.

This is a helper function for calling Stat on the DirEntry passed to the walkFn argument to Walk.

The path argument is only used if de is not of type fastwalk.DirEntry. Therefore, de should be the DirEntry describing path.

func Walk

func Walk(conf *Config, root string, walkFn fs.WalkDirFunc) error

Walk is a faster implementation of filepath.WalkDir that walks the file tree rooted at root in parallel, calling walkFn for each file or directory in the tree, including root.

All errors that arise visiting files and directories are filtered by walkFn see the fs.WalkDirFunc documentation for details. The IgnorePermissionErrors adapter is provided to handle to common case of ignoring fs.ErrPermission errors.

By default files are walked in directory order, which makes the output non-deterministic. The Sort Config option can be used to control the order in which directory entries are visited, but since we walk the file tree in parallel the output is still non-deterministic (it's just slightly more sorted).

When a symbolic link is encountered, by default Walk will not follow it unless walkFn returns ErrTraverseLink or the Follow Config setting is true. See below for a more detailed explanation.

Walk calls walkFn with paths that use the separator character appropriate for the operating system unless the ToSlash Config setting is true which will cause all paths to be joined with a forward slash.

If walkFn returns the SkipDir sentinel error, the directory is skipped. If walkFn returns the ErrSkipFiles sentinel error, the callback will not be called for any other files in the current directory. Unlike, filepath.Walk and filepath.WalkDir the fs.SkipAll sentinel error is not respected.

Unlike filepath.WalkDir:

  • Multiple goroutines stat the filesystem concurrently. The provided walkFn must be safe for concurrent use.

  • The order that directories are visited is non-deterministic.

  • File stat calls must be done by the user and should be done via the DirEntry argument to walkFn. The DirEntry caches the result of both Info() and Stat(). The Stat() method is a fastwalk specific extension and can be called by casting the fs.DirEntry to a fastwalk.DirEntry or via the StatDirEntry helper. The fs.DirEntry argument to walkFn will always be convertible to a fastwalk.DirEntry.

  • The fs.DirEntry argument is always a fastwalk.DirEntry, which has a Stat() method that returns the result of calling os.Stat on the file. The result of Stat() and Info() are cached. The StatDirEntry helper can be used to call Stat() on the returned fastwalk.DirEntry.

  • Additionally, the fs.DirEntry argument (which has type fastwalk.DirEntry), has a Depth() method that returns the depth at which the entry was generated relative to the root being walked. The DirEntryDepth helper function can be used to call Depth() on the fs.DirEntry argument.

  • Walk can follow symlinks in two ways: the fist, and simplest, is to set Follow Config option to true - this will cause Walk to follow symlinks and detect/ignore any symlink loops; the second, is for walkFn to return the sentinel ErrTraverseLink error. When using ErrTraverseLink to follow symlinks it is walkFn's responsibility to prevent Walk from going into symlink cycles. By default Walk does not follow symbolic links.

  • When walking a directory, walkFn will be called for each non-directory entry and directories will be enqueued and visited at a later time or by another goroutine.

  • The fs.SkipAll sentinel error is not respected and not ignored. If the WalkDirFunc returns SkipAll then Walk will exit with the error SkipAll.

Example
package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"

	"github.com/charlievieth/fastwalk"
)

func CreateFiles(files map[string]string) (root string, cleanup func()) {
	tempdir, err := os.MkdirTemp("", "fastwalk-example-*")
	if err != nil {
		panic(err)
	}

	symlinks := map[string]string{}
	for path, contents := range files {
		file := filepath.Join(tempdir, "/src", path)
		if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil {
			panic(err)
		}
		if strings.HasPrefix(contents, "LINK:") {
			symlinks[file] = filepath.FromSlash(strings.TrimPrefix(contents, "LINK:"))
			continue
		}
		if err := os.WriteFile(file, []byte(contents), 0644); err != nil {
			panic(err)
		}
	}

	for file, dst := range symlinks {
		if err := os.Symlink(dst, file); err != nil {
			panic(err)
		}
	}

	return filepath.Join(tempdir, "src") + "/", func() { os.RemoveAll(tempdir) }
}

func PrettyPrintEntry(root, path string, de fs.DirEntry) {
	rel, err := filepath.Rel(root, path)
	if err != nil {
		panic(err)
	}
	rel = filepath.ToSlash(rel)
	if de.Type()&fs.ModeSymlink != 0 {
		dst, err := os.Readlink(path)
		if err != nil {
			panic(err)
		}
		fmt.Printf("%s: %s -> %s\n", de.Type(), rel, filepath.ToSlash(dst))
	} else {
		fmt.Printf("%s: %s\n", de.Type(), rel)
	}
}

func main() {
	root, cleanup := CreateFiles(map[string]string{
		"bar/b.txt": "",
		"foo/f.txt": "",
		// Since Config.Follow is set to false, the symbolic link "link" will
		// be visited, but we will not traverse into it (since our walk func
		// does not return [fastwalk.ErrTraverseLink]).
		"link": "LINK:bar",
	})
	defer cleanup()

	err := fastwalk.Walk(nil, root, func(path string, de fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		PrettyPrintEntry(root, path, de)
		return nil
	})
	if err != nil {
		panic(err)
	}
}
Output:
d---------: .
d---------: bar
d---------: foo
L---------: link -> bar
----------: bar/b.txt
----------: foo/f.txt
Example (Follow)

This example shows how the fastwalk.Config Follow field can be used to efficiently and safely follow symlinks. The below example contains a symlink loop ("bar/symloop"), which fastwalk detects and does not follow.

NOTE: We still call the fs.WalkDirFunc on the symlink that creates a loop, but we do not follow/traverse it.

package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"

	"github.com/charlievieth/fastwalk"
)

func CreateFiles(files map[string]string) (root string, cleanup func()) {
	tempdir, err := os.MkdirTemp("", "fastwalk-example-*")
	if err != nil {
		panic(err)
	}

	symlinks := map[string]string{}
	for path, contents := range files {
		file := filepath.Join(tempdir, "/src", path)
		if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil {
			panic(err)
		}
		if strings.HasPrefix(contents, "LINK:") {
			symlinks[file] = filepath.FromSlash(strings.TrimPrefix(contents, "LINK:"))
			continue
		}
		if err := os.WriteFile(file, []byte(contents), 0644); err != nil {
			panic(err)
		}
	}

	for file, dst := range symlinks {
		if err := os.Symlink(dst, file); err != nil {
			panic(err)
		}
	}

	return filepath.Join(tempdir, "src") + "/", func() { os.RemoveAll(tempdir) }
}

func PrettyPrintEntry(root, path string, de fs.DirEntry) {
	rel, err := filepath.Rel(root, path)
	if err != nil {
		panic(err)
	}
	rel = filepath.ToSlash(rel)
	if de.Type()&fs.ModeSymlink != 0 {
		dst, err := os.Readlink(path)
		if err != nil {
			panic(err)
		}
		fmt.Printf("%s: %s -> %s\n", de.Type(), rel, filepath.ToSlash(dst))
	} else {
		fmt.Printf("%s: %s\n", de.Type(), rel)
	}
}

func main() {
	// Setup
	root, cleanup := CreateFiles(map[string]string{
		"bar/bar.go":  "one",
		"bar/symlink": "LINK:bar.go",
		"foo/foo.go":  "two",
		"foo/symdir":  "LINK:../bar/",
		"foo/broken":  "LINK:nope.txt", // Broken symlink
		"foo/foo":     "LINK:../foo/",  // Symlink loop
	})
	defer cleanup()

	conf := fastwalk.Config{
		Follow: true,
	}
	err := fastwalk.Walk(&conf, root, func(path string, de fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		PrettyPrintEntry(root, path, de)
		return nil
	})
	if err != nil {
		panic(err)
	}
}
Output:
d---------: .
d---------: bar
----------: bar/bar.go
L---------: bar/symlink -> bar.go
d---------: foo
L---------: foo/broken -> nope.txt
----------: foo/foo.go
L---------: foo/foo -> ../foo/
L---------: foo/symdir -> ../bar/
L---------: foo/symdir/symlink -> bar.go
----------: foo/symdir/bar.go

Types

type Config

type Config struct {

	// Follow symbolic links ignoring directories that would lead
	// to infinite loops; that is, entering a previously visited
	// directory that is an ancestor of the last file encountered.
	//
	// The sentinel error ErrTraverseLink is ignored when Follow
	// is true (this to prevent users from defeating the loop
	// detection logic), but SkipDir and ErrSkipFiles are still
	// respected.
	Follow bool

	// Join all paths using a forward slash "/" instead of the system
	// default (the root path will be converted with filepath.ToSlash).
	// This option exists for users on Windows Subsystem for Linux (WSL)
	// that are running a Windows executable (like FZF) in WSL and need
	// forward slashes for compatibility (since binary was compiled for
	// Windows the path separator will be "\" which can cause issues in
	// in a Unix shell).
	//
	// This option has no effect when the OS path separator is a
	// forward slash "/".
	//
	// See FZF issue: https://github.com/junegunn/fzf/issues/3859
	ToSlash bool

	// Sort a directory's entries by SortMode before visiting them.
	// The order that files are visited is deterministic only at the directory
	// level, but not generally deterministic because we process directories
	// in parallel. The performance impact of sorting entries is generally
	// negligible compared to the syscalls required to read directories.
	//
	// This option mostly exists for programs that print the output of Walk
	// (like FZF) since it provides some order and thus makes the output much
	// nicer compared to the default directory order, which is basically random.
	Sort SortMode

	// Number of parallel workers to use. If NumWorkers if ≤ 0 then
	// DefaultNumWorkers is used.
	NumWorkers int

	// MaxDepth limits the depth of directory traversal to MaxDepth levels
	// beyond the root directory being walked. By default, there is no limit
	// on the search depth and a value of zero or less disables this feature.
	MaxDepth int
}

A Config controls the behavior of Walk.

func (*Config) Copy added in v1.0.7

func (c *Config) Copy() *Config

Copy returns a copy of c. If c is nil an empty Config is returned.

type DirEntry

type DirEntry interface {
	fs.DirEntry

	// Stat returns the fs.FileInfo for the file or subdirectory described
	// by the entry. The returned FileInfo may be from the time of the
	// original directory read or from the time of the call to os.Stat.
	// If the entry denotes a symbolic link, Stat reports the information
	// about the target itself, not the link.
	Stat() (fs.FileInfo, error)

	// Depth returns the depth at which this entry was generated relative to the
	// root being walked.
	Depth() int
}

A DirEntry extends the fs.DirEntry interface to add a Stat() method that returns the result of calling os.Stat on the underlying file. The results of Info() and Stat() are cached.

The fs.DirEntry argument passed to the fs.WalkDirFunc by Walk is always a DirEntry.

type EntryFilter

type EntryFilter struct {
	// contains filtered or unexported fields
}

An EntryFilter keeps track of visited directory entries and can be used to detect and avoid symlink loops or processing the same file twice.

func NewEntryFilter

func NewEntryFilter() *EntryFilter

NewEntryFilter returns a new EntryFilter

func (*EntryFilter) Entry

func (e *EntryFilter) Entry(path string, de fs.DirEntry) (seen bool)

Entry returns if path and fs.DirEntry have been seen before.

type SortMode added in v1.0.7

type SortMode uint32

SortMode determines the order that a directory's entries are visited by Walk. Sorting applies only at the directory level and since we process directories in parallel the order in which all files are visited is still non-deterministic.

Sorting is mostly useful for programs that print the output of Walk since it makes it slightly more ordered compared to the default directory order. Sorting may also help some programs that wish to change the order in which a directory is processed by either processing all files first or enqueuing all directories before processing files.

All lexical sorting is case-sensitive.

The overhead of sorting is minimal compared to the syscalls needed to walk directories. The impact on performance due to changing the order in which directory entries are processed will be dependent on the workload and the structure of the file tree being visited (it might also have no impact).

const (
	// Perform no sorting. Files will be visited in directory order.
	// This is the default.
	SortNone SortMode = iota

	// Directory entries are sorted by name before being visited.
	SortLexical

	// Sort the directory entries so that regular files and non-directories
	// (e.g. symbolic links) are visited before directories. Within each
	// group (regular files, other files, directories) the entries are sorted
	// by name.
	//
	// This is likely the mode that programs that print the output of Walk
	// want to use. Since by processing all files before enqueuing
	// sub-directories the output is slightly more grouped.
	//
	// Example order:
	//   - file: "a.txt"
	//   - file: "b.txt"
	//   - link: "a.link"
	//   - link: "b.link"
	//   - dir:  "d1/"
	//   - dir:  "d2/"
	//
	SortFilesFirst

	// Sort the directory entries so that directories are visited first, then
	// regular files are visited, and finally everything else is visited
	// (e.g. symbolic links). Within each group (directories, regular files,
	// other files) the entries are sorted by name.
	//
	// This mode is might be useful at preventing other walk goroutines from
	// stalling due to lack of work since it immediately enqueues all of a
	// directory's sub-directories for processing. The impact on performance
	// will be dependent on the workload and the structure of the file tree
	// being visited - it might also have no (or even a negative) impact on
	// performance so testing/benchmarking is recommend.
	//
	// An example workload that might cause this is: processing one directory
	// takes a long time, that directory has sub-directories we want to walk,
	// while processing that directory all other Walk goroutines have finished
	// processing their directories, those goroutines are now stalled waiting
	// for more work (waiting on the one running goroutine to enqueue its
	// sub-directories for processing).
	//
	// This might also be beneficial if processing files is expensive.
	//
	// Example order:
	//   - dir:  "d1/"
	//   - dir:  "d2/"
	//   - file: "a.txt"
	//   - file: "b.txt"
	//   - link: "a.link"
	//   - link: "b.link"
	//
	SortDirsFirst
)

func (SortMode) String added in v1.0.7

func (s SortMode) String() string

Directories

Path Synopsis
examples
fwfind command
fwfind is a an example program that is similar to POSIX find, but faster and worse (it's an example).
fwfind is a an example program that is similar to POSIX find, but faster and worse (it's an example).
fwwc command
fwwc is a an example program that recursively walks directories and prints the number of lines in each file it encounters.
fwwc is a an example program that recursively walks directories and prints the number of lines in each file it encounters.
internal
dirent
Package dirent parses raw syscall dirents
Package dirent parses raw syscall dirents

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL