Browse Source

human readable filesizes

master
Lars Hoogestraat 3 years ago
parent
commit
193323cbea
  1. 25
      cfg.go
  2. 8
      cfg_test.go
  3. 3
      go.mod
  4. 2
      sample/main.go
  5. 2
      testcfg/config.conf

25
cfg.go

@ -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)

8
cfg_test.go

@ -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

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

2
sample/main.go

@ -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)

2
testcfg/config.conf

@ -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

Loading…
Cancel
Save