From 16d07d3f1853486d5093a8e4584e025e11623c8b Mon Sep 17 00:00:00 2001 From: Anton Evangelatov Date: Tue, 19 Jan 2021 14:43:19 +0100 Subject: [PATCH] fix FileSize to return correct disk usage recursively --- extern/sector-storage/fsutil/filesize_unix.go | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/extern/sector-storage/fsutil/filesize_unix.go b/extern/sector-storage/fsutil/filesize_unix.go index 500e54386..e5d220764 100644 --- a/extern/sector-storage/fsutil/filesize_unix.go +++ b/extern/sector-storage/fsutil/filesize_unix.go @@ -2,7 +2,7 @@ package fsutil import ( "os" - "syscall" + "path/filepath" "golang.org/x/xerrors" ) @@ -11,19 +11,24 @@ type SizeInfo struct { OnDisk int64 } -// FileSize returns bytes used by a file on disk +// FileSize returns bytes used by a file or directory on disk func FileSize(path string) (SizeInfo, error) { - var stat syscall.Stat_t - if err := syscall.Stat(path, &stat); err != nil { - if err == syscall.ENOENT { + var size int64 + err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if !info.IsDir() { + size += info.Size() + } + return err + }) + if err != nil { + if os.IsNotExist(err) { return SizeInfo{}, os.ErrNotExist } - return SizeInfo{}, xerrors.Errorf("stat: %w", err) + return SizeInfo{}, xerrors.Errorf("filepath.Walk err: %w", err) } - // NOTE: stat.Blocks is in 512B blocks, NOT in stat.Blksize - // See https://www.gnu.org/software/libc/manual/html_node/Attribute-Meanings.html - return SizeInfo{ - int64(stat.Blocks) * 512, // nolint NOTE: int64 cast is needed on osx - }, nil + return SizeInfo{size}, nil }