lotus/extern/sector-storage/fsutil/filesize_unix.go

44 lines
1.0 KiB
Go
Raw Normal View History

2020-07-08 15:09:35 +00:00
package fsutil
import (
2020-08-04 14:20:59 +00:00
"os"
"path/filepath"
2021-01-19 16:52:24 +00:00
"syscall"
2020-07-08 15:09:35 +00:00
"golang.org/x/xerrors"
)
type SizeInfo struct {
OnDisk int64
}
// FileSize returns bytes used by a file or directory on disk
2021-01-19 16:52:24 +00:00
// NOTE: We care about the allocated bytes, not file or directory size
2020-07-08 15:09:35 +00:00
func FileSize(path string) (SizeInfo, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
2021-01-19 17:53:37 +00:00
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return xerrors.New("FileInfo.Sys of wrong type")
}
2021-01-19 16:52:24 +00:00
// 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
})
if err != nil {
if os.IsNotExist(err) {
2020-08-04 14:20:59 +00:00
return SizeInfo{}, os.ErrNotExist
}
return SizeInfo{}, xerrors.Errorf("filepath.Walk err: %w", err)
2020-07-08 15:09:35 +00:00
}
return SizeInfo{size}, nil
2020-07-08 17:51:26 +00:00
}