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>
47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package vfs
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
)
|
|
|
|
// RemoveTree deletes p and, if p is a real directory, everything under it
|
|
// (post-order). The root is Lstat'ed: a symlink — even to a directory — is
|
|
// removed as a link, and links met inside are never followed (N-P0-3).
|
|
// progress, if non-nil, is called after every removed node with the running
|
|
// count. The first error stops the removal and is returned; ctx is checked
|
|
// before every node.
|
|
func RemoveTree(ctx context.Context, fsys FS, p string, progress func(removed int)) error {
|
|
fi, err := fsys.Lstat(ctx, p)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
n := 0
|
|
return removeTree(ctx, fsys, p, fi, &n, progress)
|
|
}
|
|
|
|
func removeTree(ctx context.Context, fsys FS, p string, fi FileInfo, n *int, progress func(int)) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
if fi.IsDir() {
|
|
ents, err := fsys.ReadDir(ctx, p)
|
|
if err != nil {
|
|
return fmt.Errorf("remove %s: %w", p, err)
|
|
}
|
|
ops := fsys.Paths()
|
|
for _, e := range ents {
|
|
if err := removeTree(ctx, fsys, ops.Join(p, e.Name), e, n, progress); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
if err := fsys.Remove(ctx, p); err != nil {
|
|
return err
|
|
}
|
|
*n++
|
|
if progress != nil {
|
|
progress(*n)
|
|
}
|
|
return nil
|
|
}
|