2022-02-06 03:00:32 +04:00
|
|
|
package utils
|
|
|
|
|
2022-02-07 04:48:33 +04:00
|
|
|
import (
|
2022-02-07 22:17:40 +04:00
|
|
|
"io/fs"
|
|
|
|
"path/filepath"
|
2022-02-07 04:48:33 +04:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2022-02-08 00:24:57 +04:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2022-02-07 04:48:33 +04:00
|
|
|
)
|
2022-02-06 03:00:32 +04:00
|
|
|
|
2022-02-07 04:48:33 +04:00
|
|
|
var sizeSuffixes = [...]string{"B", "KiB", "MiB", "GiB", "TiB"}
|
2022-02-06 03:00:32 +04:00
|
|
|
|
|
|
|
// ConvertFileSize converts size in bytes down to biggest units it represents.
|
|
|
|
// Returns converted size, unit and, a concatenation of size and unit
|
2022-02-07 04:48:33 +04:00
|
|
|
func ConvertFileSize(size int64) (float64, string, string) {
|
2022-02-06 03:00:32 +04:00
|
|
|
var idx int
|
2022-02-07 04:48:33 +04:00
|
|
|
var fSize float64 = float64(size)
|
2022-02-06 03:00:32 +04:00
|
|
|
|
2022-02-07 04:48:33 +04:00
|
|
|
for idx = 0; fSize >= 1024; fSize /= 1024 {
|
|
|
|
idx++
|
2022-02-06 03:00:32 +04:00
|
|
|
}
|
|
|
|
|
2022-02-07 04:48:33 +04:00
|
|
|
fSizeStr := strconv.FormatFloat(fSize, 'f', 3, 64)
|
|
|
|
fSizeStr = strings.TrimRight(fSizeStr, "0")
|
|
|
|
fSizeStr = strings.TrimSuffix(fSizeStr, ".")
|
|
|
|
|
2022-02-08 01:52:27 +04:00
|
|
|
return fSize, sizeSuffixes[idx], strings.Join([]string{fSizeStr, sizeSuffixes[idx]}, " ")
|
2022-02-06 03:00:32 +04:00
|
|
|
}
|
2022-02-07 22:17:40 +04:00
|
|
|
|
|
|
|
func DirectorySize(path string) (dirSz int64, err error) {
|
|
|
|
err = filepath.Walk(path, func(_ string, info fs.FileInfo, err error) error {
|
|
|
|
if err != nil {
|
2022-02-08 00:24:57 +04:00
|
|
|
return errors.Wrapf(err, "failed to compute %s directory size", path)
|
2022-02-07 22:17:40 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
dirSz += info.Size()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
2022-02-08 00:24:57 +04:00
|
|
|
return 0, err
|
2022-02-07 22:17:40 +04:00
|
|
|
}
|
|
|
|
|
2023-03-11 23:45:19 +04:00
|
|
|
return dirSz - 4096, nil
|
2022-02-07 22:17:40 +04:00
|
|
|
}
|