Skip to content

Commit

Permalink
adds go flags type for byte size
Browse files Browse the repository at this point in the history
  • Loading branch information
casualjim committed Nov 24, 2016
1 parent 12c07ac commit 14b161b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
23 changes: 23 additions & 0 deletions flagext/byte_size.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package flagext

import (
"github.com/docker/go-units"
)

// ByteSize used to pass byte sizes to a go-flags CLI
type ByteSize int

// MarshalFlag implements go-flags Marshaller interface
func (b ByteSize) MarshalFlag() (string, error) {
return units.HumanSize(float64(b)), nil
}

// UnmarshalFlag implements go-flags Unmarshaller interface
func (b *ByteSize) UnmarshalFlag(value string) error {
sz, err := units.FromHumanSize(value)
if err != nil {
return err
}
*b = ByteSize(int(sz))
return nil
}
22 changes: 22 additions & 0 deletions flagext/byte_size_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package flagext

import "testing"
import "github.com/stretchr/testify/assert"

func TestMarshalBytesize(t *testing.T) {
v, err := ByteSize(1024).MarshalFlag()
if assert.NoError(t, err) {
assert.Equal(t, "1.024 kB", v)
}
}

func TestUnmarshalBytesize(t *testing.T) {
var b ByteSize
err := b.UnmarshalFlag("notASize")
assert.Error(t, err)

err = b.UnmarshalFlag("1MB")
if assert.NoError(t, err) {
assert.Equal(t, ByteSize(1000000), b)
}
}

0 comments on commit 14b161b

Please sign in to comment.