Skip to content

Commit

Permalink
Merge pull request #112 from ndeloof/mapping
Browse files Browse the repository at this point in the history
introduce func to build Mapping from a set of KEY=VALUE strings
  • Loading branch information
ndeloof committed Mar 2, 2021
2 parents e11aa1d + cc747e3 commit a66de60
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
30 changes: 30 additions & 0 deletions types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,20 @@ type StringOrNumberList []string
// For the key without value (`key`), the mapped value is set to nil.
type MappingWithEquals map[string]*string

// NewMappingWithEquals build a new Mapping from a set of KEY=VALUE strings
func NewMappingWithEquals(values []string) MappingWithEquals {
mapping := MappingWithEquals{}
for _, env := range values {
tokens := strings.SplitN(env, "=", 2)
if len(tokens) > 1 {
mapping[tokens[0]] = &tokens[1]
} else {
mapping[env] = nil
}
}
return mapping
}

// OverrideBy update MappingWithEquals with values from another MappingWithEquals
func (e MappingWithEquals) OverrideBy(other MappingWithEquals) MappingWithEquals {
for k, v := range other {
Expand Down Expand Up @@ -298,6 +312,22 @@ func (e MappingWithEquals) RemoveEmpty() MappingWithEquals {
// mapped value is set to an empty string `""`.
type Mapping map[string]string

// NewMapping build a new Mapping from a set of KEY=VALUE strings
func NewMapping(values []string) Mapping {
mapping := Mapping{}
for _, value := range values {
parts := strings.SplitN(value, "=", 2)
key := parts[0]
switch {
case len(parts) == 1:
mapping[key] = ""
default:
mapping[key] = parts[1]
}
}
return mapping
}

// Labels is a mapping type for labels
type Labels map[string]string

Expand Down
19 changes: 19 additions & 0 deletions types/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,22 @@ func TestExtension(t *testing.T) {
assert.NilError(t, err)
assert.Check(t, ok == false)
}

func TestNewMapping(t *testing.T) {
m := NewMapping([]string{
"FOO=BAR",
"ZOT=",
"QIX",
})
mw := NewMappingWithEquals([]string{
"FOO=BAR",
"ZOT=",
"QIX",
})
assert.Check(t, m["FOO"] == "BAR")
assert.Check(t, m["ZOT"] == "")
assert.Check(t, m["QIX"] == "")
assert.Check(t, *mw["FOO"] == "BAR")
assert.Check(t, *mw["ZOT"] == "")
assert.Check(t, mw["QIX"] == nil)
}

0 comments on commit a66de60

Please sign in to comment.