Skip to content

Commit

Permalink
feat(exp): add labelutils with Selector
Browse files Browse the repository at this point in the history
This method is very helpful if you want to create resources and later
clean them up with the same label set. Creating resources requires a
`map[string]string`, but filtering resource lists takes a selector
string.
  • Loading branch information
apricote committed Jun 19, 2024
1 parent 0eb5e0d commit 86cdd59
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
24 changes: 24 additions & 0 deletions hcloud/exp/labelutils/selector.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package labelutils

import (
"fmt"
"sort"
"strings"
)

// Selector combines the label set into a [label selector](https://docs.hetzner.cloud/#label-selector) that only selects
// resources have all specified labels set.
//
// The selector string can be used to filter resources when listing, for example with [hcloud.ServerClient.AllWithOpts()].
func Selector(labels map[string]string) string {
selectors := make([]string, 0, len(labels))

for k, v := range labels {
selectors = append(selectors, fmt.Sprintf("%s=%s", k, v))
}

// Reproducible result for tests
sort.Strings(selectors)

return strings.Join(selectors, ",")
}
39 changes: 39 additions & 0 deletions hcloud/exp/labelutils/selector_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package labelutils

import "testing"

func TestSelector(t *testing.T) {
tests := []struct {
name string
labels map[string]string
expectedSelector string
}{
{
name: "empty selector",
labels: map[string]string{},
expectedSelector: "",
},
{
name: "single label",
labels: map[string]string{"foo": "bar"},
expectedSelector: "foo=bar",
},
{
name: "multiple labels",
labels: map[string]string{"foo": "bar", "foz": "baz"},
expectedSelector: "foo=bar,foz=baz",
},
{
name: "nil map",
labels: nil,
expectedSelector: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Selector(tt.labels); got != tt.expectedSelector {
t.Errorf("Selector() = %v, want %v", got, tt.expectedSelector)
}
})
}
}

0 comments on commit 86cdd59

Please sign in to comment.