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>
54 lines
1.3 KiB
Go
54 lines
1.3 KiB
Go
package vfs
|
|
|
|
import "context"
|
|
|
|
// SizeResult is the outcome of DirSize. Bytes sums the (lstat) sizes of all
|
|
// non-directory entries; Files counts them; Dirs counts directories below the
|
|
// root. Unreadable counts subdirectories whose listing failed — when it is
|
|
// non-zero the totals are a lower bound ("≥ X, N unreadable").
|
|
type SizeResult struct {
|
|
Bytes int64
|
|
Files int
|
|
Dirs int
|
|
Unreadable int
|
|
}
|
|
|
|
// DirSize sums the tree under p without following symlinks. An error on the
|
|
// root (missing, unreadable, cancelled) is returned; errors on nested
|
|
// directories are counted in Unreadable instead (N-P1-14). progress, if
|
|
// non-nil, receives the running totals after each directory.
|
|
func DirSize(ctx context.Context, fsys FS, p string, progress func(SizeResult)) (SizeResult, error) {
|
|
var r SizeResult
|
|
err := Walk(ctx, fsys, p, func(q string, fi FileInfo, err error) error {
|
|
if err != nil {
|
|
if q == p {
|
|
return err
|
|
}
|
|
r.Unreadable++
|
|
return SkipDir
|
|
}
|
|
switch {
|
|
case fi.IsDir():
|
|
if q != p {
|
|
r.Dirs++
|
|
}
|
|
if progress != nil {
|
|
progress(r)
|
|
}
|
|
default:
|
|
r.Files++
|
|
r.Bytes += fi.Size
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return r, err
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return r, err
|
|
}
|
|
if progress != nil {
|
|
progress(r)
|
|
}
|
|
return r, nil
|
|
}
|