2023-01-17 06:03:10 +00:00
|
|
|
//go:build !windows
|
|
|
|
// +build !windows
|
|
|
|
|
2020-07-08 15:09:35 +00:00
|
|
|
package fsutil
|
|
|
|
|
|
|
|
import (
|
2020-08-04 14:20:59 +00:00
|
|
|
"os"
|
2021-01-19 13:43:19 +00:00
|
|
|
"path/filepath"
|
2021-01-19 16:52:24 +00:00
|
|
|
"syscall"
|
2022-05-05 17:12:09 +00:00
|
|
|
"time"
|
2020-07-08 15:09:35 +00:00
|
|
|
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
)
|
|
|
|
|
|
|
|
type SizeInfo struct {
|
|
|
|
OnDisk int64
|
|
|
|
}
|
|
|
|
|
2021-01-19 13:43:19 +00:00
|
|
|
// 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) {
|
2022-05-05 17:12:09 +00:00
|
|
|
start := time.Now()
|
|
|
|
|
2021-01-19 13:43:19 +00:00
|
|
|
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
|
2021-01-19 13:43:19 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
})
|
2022-05-05 17:12:09 +00:00
|
|
|
|
|
|
|
if time.Now().Sub(start) >= 3*time.Second {
|
|
|
|
log.Warnw("very slow file size check", "took", time.Now().Sub(start), "path", path)
|
|
|
|
}
|
|
|
|
|
2021-01-19 13:43:19 +00:00
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
2020-08-04 14:20:59 +00:00
|
|
|
return SizeInfo{}, os.ErrNotExist
|
|
|
|
}
|
2021-01-19 13:43:19 +00:00
|
|
|
return SizeInfo{}, xerrors.Errorf("filepath.Walk err: %w", err)
|
2020-07-08 15:09:35 +00:00
|
|
|
}
|
|
|
|
|
2021-01-19 13:43:19 +00:00
|
|
|
return SizeInfo{size}, nil
|
2020-07-08 17:51:26 +00:00
|
|
|
}
|