1
0
dwelling-upload/pkg/utils/filesize.go

48 lines
1.1 KiB
Go
Raw Normal View History

package utils
import (
"os"
"path"
"strconv"
"strings"
"github.com/pkg/errors"
)
var sizeSuffixes = [...]string{"B", "KiB", "MiB", "GiB", "TiB"}
// ConvertFileSize converts size in bytes down to biggest units it represents.
// Returns converted size, unit and, a concatenation of size and unit
func ConvertFileSize(size int64) (float64, string, string) {
idx := 0
fSize := float64(size)
for ; fSize >= 1024; fSize /= 1024 {
idx++
}
fSizeStr := strconv.FormatFloat(fSize, 'f', 3, 64)
fSizeStr = strings.TrimRight(fSizeStr, "0")
fSizeStr = strings.TrimSuffix(fSizeStr, ".")
return fSize, sizeSuffixes[idx],
strings.Join([]string{fSizeStr, sizeSuffixes[idx]}, " ")
}
func DirectorySize(dirPath string) (dirSz int64, err error) {
dir, err := os.ReadDir(dirPath)
if err != nil {
return 0, errors.Wrapf(err, "failed to compute %s directory size", dirPath)
}
for _, entry := range dir {
file, err := os.Stat(path.Join(dirPath, entry.Name()))
if err != nil {
return 0, errors.Wrapf(err, "failed to stat a file %s", entry.Name())
}
dirSz += file.Size()
}
return dirSz, nil
}