Skip to content

Commit

Permalink
Merge pull request #33 from appuio/print-allowed-labels
Browse files Browse the repository at this point in the history
Print allowed labels on error
  • Loading branch information
bastjan authored Oct 6, 2022
2 parents d0641f3 + fc5110b commit c6f8ed7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
24 changes: 23 additions & 1 deletion validate/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package validate
import (
"fmt"
"regexp"
"strings"

"go.uber.org/multierr"
)
Expand All @@ -12,6 +13,10 @@ type regexKV struct {
V *regexp.Regexp
}

func (r regexKV) String() string {
return fmt.Sprintf("%s=%s", r.K, r.V)
}

// AllowedLabels allows labels to be validated against a set of allowed labels.
// The zero value is ready to use and denies all labels.
type AllowedLabels struct {
Expand Down Expand Up @@ -46,7 +51,11 @@ func (l *AllowedLabels) Validate(lbls map[string]string) error {
violations = append(violations, l.ValidateLabel(k, v))
}

return multierr.Combine(violations...)
if err := multierr.Combine(violations...); err != nil {
return fmt.Errorf("label validation failed: %w, allowed labels: %s", err, l.formatLabels())
}

return nil
}

func anchor(s string) string {
Expand All @@ -63,3 +72,16 @@ func (l *AllowedLabels) ValidateLabel(key, value string) error {

return fmt.Errorf("label %s=%s is not allowed", key, value)
}

func (l *AllowedLabels) String() string {
return fmt.Sprintf("allowed %s", l.formatLabels())
}

func (l *AllowedLabels) formatLabels() string {
s := make([]string, 0, len(l.allowed))
for _, allowed := range l.allowed {
s = append(s, allowed.String())
}

return fmt.Sprintf("{ %s }", strings.Join(s, ", "))
}
9 changes: 9 additions & 0 deletions validate/labels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,12 @@ func Test_AllowedLabels_Validate(t *testing.T) {
assert.ErrorContains(t, err, "some.other.io=a")
assert.ErrorContains(t, err, "some.other.io/2=a")
}

func Test_AllowedLabels_String(t *testing.T) {
v := validate.AllowedLabels{}

v.Add("my.ns.io/node-class", "flex|plus")
v.Add("app", ".+")

assert.Equal(t, "allowed { ^(?:my.ns.io/node-class)$=^(?:flex|plus)$, ^(?:app)$=^(?:.+)$ }", v.String())
}

0 comments on commit c6f8ed7

Please sign in to comment.