2022-02-06 03:00:32 +04:00
|
|
|
package utils
|
|
|
|
|
2022-02-07 04:48:33 +04:00
|
|
|
import (
|
2023-05-26 17:23:09 +04:00
|
|
|
"io/ioutil"
|
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) {
|
2023-05-26 17:23:09 +04:00
|
|
|
idx := 0
|
|
|
|
fSize := float64(size)
|
2022-02-06 03:00:32 +04:00
|
|
|
|
2023-05-26 17:23:09 +04:00
|
|
|
for ; fSize >= 1024; fSize /= 1024 {
|
2022-02-07 04:48:33 +04:00
|
|
|
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, ".")
|
|
|
|
|
2023-05-26 17:23:09 +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) {
|
2023-05-26 17:22:21 +04:00
|
|
|
dir, err := ioutil.ReadDir(path)
|
2022-02-07 22:17:40 +04:00
|
|
|
if err != nil {
|
2023-05-26 17:22:21 +04:00
|
|
|
return 0, errors.Wrapf(err, "failed to compute %s directory size", path)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, entry := range dir {
|
|
|
|
dirSz += entry.Size()
|
2022-02-07 22:17:40 +04:00
|
|
|
}
|
|
|
|
|
2023-05-26 17:22:21 +04:00
|
|
|
// Here we subtract a size of a directory's inode to get size of files only.
|
2023-03-11 23:45:19 +04:00
|
|
|
return dirSz - 4096, nil
|
2022-02-07 22:17:40 +04:00
|
|
|
}
|