@cryptotaxi247 / kubo / commits / 7ce67b895

go-ipfs-config: feat: add WithDefault for flag/priority

This makes it easier to resolve these fields.

Steven Allen committed Jun 15, 2020 at 19:19 UTC 7ce67b895457339b33b0560bd3f5cc346da432e1
2 files changed +66
config/types.go
+30
@@ -55,6 +55,19 @@ const (
55 True Flag = 1
56 )
57
58 +func (f Flag) WithDefault(defaultValue bool) bool {
59 + switch f {
60 + case False:
61 + return false
62 + case Default:
63 + return defaultValue
64 + case True:
65 + return true
66 + default:
67 + panic(fmt.Sprintf("invalid flag value %d", f))
68 + }
69 +}
70 +
71 func (f Flag) MarshalJSON() ([]byte, error) {
72 switch f {
73 case Default:
@@ -110,6 +123,23 @@ const (
123 Disabled Priority = -1
124 )
125
126 +// WithDefault resolves the priority with the given default.
127 +//
128 +// If `defaultPriority` is Default/0, this function will return 0.
129 +func (p Priority) WithDefault(defaultPriority Priority) (priority int64, enabled bool) {
130 + switch p {
131 + case Disabled:
132 + return 0, false
133 + case DefaultPriority:
134 + if defaultPriority < 0 {
135 + return 0, false
136 + }
137 + return int64(defaultPriority), true
138 + default:
139 + return int64(p), true
140 + }
141 +}
142 +
143 func (p Priority) MarshalJSON() ([]byte, error) {
144 // > 0 == Priority
145 if p > 0 {
config/types_test.go
+36
@@ -91,6 +91,30 @@ func TestFlag(t *testing.T) {
91 t.Errorf("expected default flag to be %q, got %q", Default, defaultFlag)
92 }
93
94 + if defaultFlag.WithDefault(true) != true {
95 + t.Error("expected default & true to be true")
96 + }
97 +
98 + if defaultFlag.WithDefault(false) != false {
99 + t.Error("expected default & false to be false")
100 + }
101 +
102 + if True.WithDefault(false) != true {
103 + t.Error("default should only apply to default")
104 + }
105 +
106 + if False.WithDefault(true) != false {
107 + t.Error("default should only apply to default")
108 + }
109 +
110 + if True.WithDefault(true) != true {
111 + t.Error("true & true is true")
112 + }
113 +
114 + if False.WithDefault(true) != false {
115 + t.Error("false & false is false")
116 + }
117 +
118 for jsonStr, goValue := range map[string]Flag{
119 "null": Default,
120 "true": True,
@@ -135,6 +159,18 @@ func TestPriority(t *testing.T) {
159 t.Errorf("expected default priority to be %q, got %q", DefaultPriority, defaultPriority)
160 }
161
162 + if _, ok := defaultPriority.WithDefault(Disabled); ok {
163 + t.Error("should have been disabled")
164 + }
165 +
166 + if p, ok := defaultPriority.WithDefault(1); !ok || p != 1 {
167 + t.Errorf("priority should have been 1, got %d", p)
168 + }
169 +
170 + if p, ok := defaultPriority.WithDefault(DefaultPriority); !ok || p != 0 {
171 + t.Errorf("priority should have been 0, got %d", p)
172 + }
173 +
174 for jsonStr, goValue := range map[string]Priority{
175 "null": DefaultPriority,
176 "false": Disabled,