Skip to content

Commit

Permalink
feat: Add flags helpers for lists flags
Browse files Browse the repository at this point in the history
  Simplify the usage of lists flags with typed return values.

  Lists flags are defined like this:

  ```json
  "<name>": { "list": ["<value>", ...] }
  ```
  • Loading branch information
taratatach committed Feb 19, 2024
1 parent f177f49 commit 5b51b33
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
32 changes: 32 additions & 0 deletions model/feature/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,38 @@ func (f *Flags) UnmarshalJSON(bytes []byte) error {
return nil
}

func (f *Flags) GetList(name string) ([]interface{}, error) {
if f.M[name] == nil {
return []interface{}{}, nil
}

value, ok := f.M[name].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Flag %s is not a list flag", name)
}

list, ok := value["list"].([]interface{})
if !ok {
return nil, fmt.Errorf("Flag %s is not a list flag", name)
}

return list, nil
}

func (f *Flags) HasListItem(name, item string) (bool, error) {
list, err := f.GetList(name)
if err != nil {
return false, err
}

for _, i := range list {
if i == item {
return true, nil
}
}
return false, nil
}

// GetFlags returns the list of feature flags for the given instance.
func GetFlags(inst *instance.Instance) (*Flags, error) {
sources := make([]*Flags, 0)
Expand Down
38 changes: 38 additions & 0 deletions model/feature/flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/cozy/cozy-stack/model/instance"
"github.com/gofrs/uuid/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func uuidv7() string {
Expand Down Expand Up @@ -38,3 +39,40 @@ func TestFeatureFlagRatio(t *testing.T) {
assert.InDelta(t, 4000, results[float64(4)], 100)
assert.InDelta(t, 3000, results[nil], 100)
}

func TestFeatureFlagList(t *testing.T) {
var flags Flags
err := json.Unmarshal(
[]byte(`{
"flag1": { "list": ["other", "val"] },
"flag2": { "list": ["other"] },
"flag3": { "list": [] },
"flag4": ["val"],
"flag5": "val"
}`),
&flags,
)
require.NoError(t, err)

// GetList
list, err := flags.GetList("flag1")
require.NoError(t, err)
assert.EqualValues(t, []interface{}{"other", "val"}, list)
_, err = flags.GetList("flag4")
assert.Error(t, err)
_, err = flags.GetList("flag5")
assert.Error(t, err)

// HasListItem
hasVal, err := flags.HasListItem("flag1", "val")
require.NoError(t, err)
assert.True(t, hasVal)
hasVal, _ = flags.HasListItem("flag2", "val")
assert.False(t, hasVal)
hasVal, _ = flags.HasListItem("flag3", "val")
assert.False(t, hasVal)
_, err = flags.HasListItem("flag4", "val")
assert.Error(t, err)
_, err = flags.HasListItem("flag5", "val")
assert.Error(t, err)
}

0 comments on commit 5b51b33

Please sign in to comment.