Skip to content
This repository has been archived by the owner on Mar 9, 2022. It is now read-only.

Commit

Permalink
feat: add WithDefault for flag/priority
Browse files Browse the repository at this point in the history
This makes it easier to resolve these fields.
  • Loading branch information
Stebalien committed Jun 16, 2020
1 parent a303859 commit 297b85c
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
30 changes: 30 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,19 @@ const (
True Flag = 1
)

func (f Flag) WithDefault(defaultValue bool) bool {
switch f {
case False:
return false
case Default:
return defaultValue
case True:
return true
default:
panic(fmt.Sprintf("invalid flag value %d", f))
}
}

func (f Flag) MarshalJSON() ([]byte, error) {
switch f {
case Default:
Expand Down Expand Up @@ -110,6 +123,23 @@ const (
Disabled Priority = -1
)

// WithDefault resolves the priority with the given default.
//
// If `defaultPriority` is Default/0, this function will return 0.
func (p Priority) WithDefault(defaultPriority Priority) (priority int64, enabled bool) {
switch p {
case Disabled:
return 0, false
case DefaultPriority:
if defaultPriority < 0 {
return 0, false
}
return int64(defaultPriority), true
default:
return int64(p), true
}
}

func (p Priority) MarshalJSON() ([]byte, error) {
// > 0 == Priority
if p > 0 {
Expand Down
36 changes: 36 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,30 @@ func TestFlag(t *testing.T) {
t.Errorf("expected default flag to be %q, got %q", Default, defaultFlag)
}

if defaultFlag.WithDefault(true) != true {
t.Error("expected default & true to be true")
}

if defaultFlag.WithDefault(false) != false {
t.Error("expected default & false to be false")
}

if True.WithDefault(false) != true {
t.Error("default should only apply to default")
}

if False.WithDefault(true) != false {
t.Error("default should only apply to default")
}

if True.WithDefault(true) != true {
t.Error("true & true is true")
}

if False.WithDefault(true) != false {
t.Error("false & false is false")
}

for jsonStr, goValue := range map[string]Flag{
"null": Default,
"true": True,
Expand Down Expand Up @@ -135,6 +159,18 @@ func TestPriority(t *testing.T) {
t.Errorf("expected default priority to be %q, got %q", DefaultPriority, defaultPriority)
}

if _, ok := defaultPriority.WithDefault(Disabled); ok {
t.Error("should have been disabled")
}

if p, ok := defaultPriority.WithDefault(1); !ok || p != 1 {
t.Errorf("priority should have been 1, got %d", p)
}

if p, ok := defaultPriority.WithDefault(DefaultPriority); !ok || p != 0 {
t.Errorf("priority should have been 0, got %d", p)
}

for jsonStr, goValue := range map[string]Priority{
"null": DefaultPriority,
"false": Disabled,
Expand Down

0 comments on commit 297b85c

Please sign in to comment.