use stat.Blocks and not info.Size

This commit is contained in:
Anton Evangelatov 2021-01-19 17:52:24 +01:00
parent 16d07d3f18
commit 834a6148b0

View File

@ -3,6 +3,7 @@ package fsutil
import (
"os"
"path/filepath"
"syscall"
"golang.org/x/xerrors"
)
@ -12,6 +13,7 @@ type SizeInfo struct {
}
// FileSize returns bytes used by a file or directory on disk
// NOTE: We care about the allocated bytes, not file or directory size
func FileSize(path string) (SizeInfo, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
@ -19,7 +21,11 @@ func FileSize(path string) (SizeInfo, error) {
return err
}
if !info.IsDir() {
size += info.Size()
stat := info.Sys().(*syscall.Stat_t)
// NOTE: stat.Blocks is in 512B blocks, NOT in stat.Blksize return SizeInfo{size}, nil
// See https://www.gnu.org/software/libc/manual/html_node/Attribute-Meanings.html
size += int64(stat.Blocks) * 512 // nolint NOTE: int64 cast is needed on osx
}
return err
})