clean up of the codebase

This commit is contained in:
ari committed 2026-11-01 13:01:54 -05:00
1 parent 7822529a38
commit 0ac61b4ece
52 files changed
+2545 -2274

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
package units
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
var StorageToken = regexp.MustCompile(`^([+-]?)(\d+(?:\.\d+)?)(tib|tb|t|gib|gb|g|mib|mb|m)$`)
func ParseSizeMB(s string) (int64, error) {
t := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(s), " ", ""))
p := StorageToken.FindStringSubmatch(t)
if p == nil || p[1] != "" {
return 0, fmt.Errorf("%q isn't a size like 5G or 500M", s)
}
return ToMB(p[2], p[3]), nil
}
func ToMB(num, unit string) int64 {
n, _ := strconv.ParseFloat(num, 64)
switch unit[0] {
case 't':
n *= 1024 * 1024
case 'g':
n *= 1024
}
return int64(math.Round(n))
}
func FormatMB(mb int64) string {
trim := func(f float64) string { return strconv.FormatFloat(math.Round(f*10)/10, 'f', -1, 64) }
switch {
case mb >= 1024*1024:
return trim(float64(mb)/(1024*1024)) + " TB"
case mb >= 1024:
return trim(float64(mb)/1024) + " GB"
}
return fmt.Sprintf("%d MB", mb)
}
+19
View File
@@ -0,0 +1,19 @@
package units
import "testing"
func TestSizes(t *testing.T) {
for in, want := range map[string]int64{"5G": 5120, "500M": 500, "1.5gb": 1536, "1T": 1048576, "20 GB": 20480} {
if got, err := ParseSizeMB(in); err != nil || got != want {
t.Fatalf("ParseSizeMB(%q) = %d, %v; want %d", in, got, err, want)
}
}
if _, err := ParseSizeMB("+5G"); err == nil {
t.Fatal("a signed size isn't a config size")
}
for mb, want := range map[int64]string{512: "512 MB", 5120: "5 GB", 2560: "2.5 GB", 1258291: "1.2 TB"} {
if got := FormatMB(mb); got != want {
t.Fatalf("FormatMB(%d) = %q, want %q", mb, got, want)
}
}
}