vcom/internal/vfs/walk.go
vrubelroman 5132daa292 feat(vfs): Walk, RemoveTree, DirSize, SameFile and Within helpers (2A.2)
One implementation for every FS. Walk and RemoveTree never follow symlinks,
so deleting a link to a directory removes only the link (N-P0-3). DirSize
returns the root error and counts unreadable subdirectories instead of
reporting a silent 0 B (N-P1-14). SameFile compares inodes locally and
RealPath on other volumes, so an alias directory is recognised (N-P0-6);
Within resolves symlinks on both sides and accepts a not-yet-existing child.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:24:12 +03:00

61 lines
1.8 KiB
Go

package vfs
import (
"context"
"errors"
"sort"
)
// WalkFunc is called for every node Walk visits. err != nil means p could not
// be read: for the root it is the Lstat error (fi is zero); for a directory it
// is the ReadDir error, reported in a second call after the first one for that
// directory succeeded. Returning SkipDir skips a directory's contents (or, for
// a non-directory, the rest of its parent); SkipAll stops the walk with nil.
// Any other error stops the walk and is returned.
type WalkFunc func(p string, fi FileInfo, err error) error
// Walk visits root and everything under it through Lstat/ReadDir; symlinks are
// reported but never followed. A parent is visited before its children and
// children in name order. ctx is checked before every directory read.
func Walk(ctx context.Context, fsys FS, root string, fn WalkFunc) error {
fi, err := fsys.Lstat(ctx, root)
if err != nil {
err = fn(root, FileInfo{}, err)
} else {
err = walk(ctx, fsys, root, fi, fn)
}
if errors.Is(err, SkipDir) || errors.Is(err, SkipAll) {
return nil
}
return err
}
func walk(ctx context.Context, fsys FS, p string, fi FileInfo, fn WalkFunc) error {
if err := fn(p, fi, nil); err != nil || !fi.IsDir() {
return err
}
if err := ctx.Err(); err != nil {
return err
}
ents, err := fsys.ReadDir(ctx, p)
if err != nil {
if errors.Is(err, ErrCancelled) {
return err
}
return fn(p, fi, err)
}
sort.Slice(ents, func(i, j int) bool { return ents[i].Name < ents[j].Name })
ops := fsys.Paths()
for _, e := range ents {
if err := walk(ctx, fsys, ops.Join(p, e.Name), e, fn); err != nil {
if errors.Is(err, SkipDir) {
if e.IsDir() {
continue
}
return nil // SkipDir on a file: skip the rest of this directory
}
return err
}
}
return nil
}