Skip to content

Commit

Permalink
add Tags.FindTag and Tags.HasTag methods
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmach committed Nov 29, 2022
1 parent 99378f9 commit cfefe3c
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 0 deletions.
24 changes: 24 additions & 0 deletions tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,30 @@ func (ts Tags) Find(k string) string {
return ""
}

// FindTag will return the Tag for the given key.
// Can be used to determine if a key exists, even with an empty value.
// Returns nil if not found.
func (ts Tags) FindTag(k string) *Tag {
for _, t := range ts {
if t.Key == k {
return &t
}
}

return nil
}

// HasTag will return the true if a tag exists for the given key.
func (ts Tags) HasTag(k string) bool {
for _, t := range ts {
if t.Key == k {
return true
}
}

return false
}

// Map returns the tags as a key/value map.
func (ts Tags) Map() map[string]string {
result := make(map[string]string, len(ts))
Expand Down
88 changes: 88 additions & 0 deletions tag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,94 @@ import (
"testing"
)

func TestTags_FindTag(t *testing.T) {
cases := []struct {
name string
tags Tags
key string
tag *Tag
}{
{
name: "find tag",
tags: Tags{
{Key: "area", Value: "true"},
{Key: "building", Value: "yes"},
},
key: "building",
tag: &Tag{Key: "building", Value: "yes"},
},
{
name: "not found",
tags: Tags{
{Key: "building", Value: "yes"},
},
key: "not found",
tag: nil,
},
{
name: "empty value",
tags: Tags{
{Key: "present", Value: ""},
},
key: "present",
tag: &Tag{Key: "present", Value: ""},
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
v := tc.tags.FindTag(tc.key)
if !reflect.DeepEqual(v, tc.tag) {
t.Errorf("incorrect find tag: %v != %v", v, tc.tag)
}
})
}
}

func TestTags_HasTag(t *testing.T) {
cases := []struct {
name string
tags Tags
key string
has bool
}{
{
name: "has tag",
tags: Tags{
{Key: "area", Value: "true"},
{Key: "building", Value: "yes"},
},
key: "building",
has: true,
},
{
name: "not found",
tags: Tags{
{Key: "building", Value: "yes"},
},
key: "not found",
has: false,
},
{
name: "empty value",
tags: Tags{
{Key: "present", Value: ""},
},
key: "present",
has: true,
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
v := tc.tags.HasTag(tc.key)
if v != tc.has {
t.Errorf("incorrect has tag: %v != %v", v, tc.has)
}
})
}
}

func TestTags_AnyInteresting(t *testing.T) {
cases := []struct {
name string
Expand Down

0 comments on commit cfefe3c

Please sign in to comment.