human readable filesizes

This commit is contained in:
Lars Hoogestraat 2019-03-07 17:23:03 +01:00
parent cf2681a7fc
commit 193323cbea
5 changed files with 38 additions and 2 deletions

25
cfg.go
View File

@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
"math"
"os"
"path/filepath"
"reflect"
@ -48,6 +49,30 @@ type CustomType interface {
// e.g. 10MB
type FileSize uint64
const (
B = 1 << (iota * 10)
KB
MB
GB
TB
)
var sizes = []string{"B", "KB", "MB", "GB", "TB"}
func (fs FileSize) HumanReadable() string {
exp := math.Round(math.Log(float64(fs)) / math.Log(1024))
s := sizes[int(exp)]
if exp == 0 {
return fmt.Sprintf("%d %s", fs, s)
}
val := float64(fs) / float64(math.Pow(1024, exp))
return fmt.Sprintf("%.2f %s", val, s)
}
func (fs *FileSize) Unmarshal(value string) error {
size := FileSize(0)

View File

@ -1,6 +1,7 @@
package cfg
import (
"fmt"
"testing"
"time"
)
@ -66,6 +67,7 @@ func TestStandardConfig(t *testing.T) {
if len(def) != 3 {
t.Error("expected three entries in applied default values")
}
}
func TestInnerStruct(t *testing.T) {
@ -176,6 +178,12 @@ func TestFileSizes(t *testing.T) {
if s.Empty != 0 {
t.Errorf("s.Empty expected to be 0 but was %d", s.Empty)
}
fmt.Println(s.Byte.HumanReadable())
fmt.Println(s.Kilobyte.HumanReadable())
fmt.Println(s.Megabyte.HumanReadable())
fmt.Println(s.Gigabyte.HumanReadable())
fmt.Println(s.Terabyte.HumanReadable())
}
func addConfig(path, filename string) ConfigFiles {

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.hoogi.eu/cfg
go 1.12

View File

@ -39,7 +39,7 @@ func (lm *LogLevel) Unmarshal(value string) error {
func main() {
c := cfg.ConfigFiles{}
c.AddConfig(".", "myconfig.conf")
c.AddConfig(".", "myconfig.conf", true)
settings := new(Settings)
def, err := c.MergeConfigsInto(settings)

View File

@ -15,7 +15,7 @@ login_method = username
#FileSizes
file_size_byte = 1024B
file_size_byte = 5B
file_size_kilobyte = 1 KB
file_size_megabyte = 1 MB
file_size_gigabyte = 1 GB