2022-02-06 03:00:32 +04:00
|
|
|
package utils
|
|
|
|
|
2022-02-07 04:48:33 +04:00
|
|
|
import (
|
2023-08-05 05:03:34 +04:00
|
|
|
"os"
|
2023-08-05 05:07:59 +04:00
|
|
|
"path"
|
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
|
|
|
|
2023-08-05 05:07:59 +04:00
|
|
|
func DirectorySize(dirPath string) (dirSz int64, err error) {
|
|
|
|
dir, err := os.ReadDir(dirPath)
|
2022-02-07 22:17:40 +04:00
|
|
|
if err != nil {
|
2023-08-05 05:07:59 +04:00
|
|
|
return 0, errors.Wrapf(err, "failed to compute %s directory size", dirPath)
|
2023-05-26 17:22:21 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, entry := range dir {
|
2023-08-05 05:07:59 +04:00
|
|
|
file, err := os.Stat(path.Join(dirPath, entry.Name()))
|
2023-08-05 05:03:34 +04:00
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrapf(err, "failed to stat a file %s", entry.Name())
|
|
|
|
}
|
|
|
|
dirSz += file.Size()
|
2022-02-07 22:17:40 +04:00
|
|
|
}
|
|
|
|
|
2023-05-26 22:41:48 +04:00
|
|
|
return dirSz, nil
|
2022-02-07 22:17:40 +04:00
|
|
|
}
|