Skip to content

Commit c6f8ed7

Browse files
authored
Merge pull request #33 from appuio/print-allowed-labels
Print allowed labels on error
2 parents d0641f3 + fc5110b commit c6f8ed7

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

validate/labels.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package validate
33
import (
44
"fmt"
55
"regexp"
6+
"strings"
67

78
"go.uber.org/multierr"
89
)
@@ -12,6 +13,10 @@ type regexKV struct {
1213
V *regexp.Regexp
1314
}
1415

16+
func (r regexKV) String() string {
17+
return fmt.Sprintf("%s=%s", r.K, r.V)
18+
}
19+
1520
// AllowedLabels allows labels to be validated against a set of allowed labels.
1621
// The zero value is ready to use and denies all labels.
1722
type AllowedLabels struct {
@@ -46,7 +51,11 @@ func (l *AllowedLabels) Validate(lbls map[string]string) error {
4651
violations = append(violations, l.ValidateLabel(k, v))
4752
}
4853

49-
return multierr.Combine(violations...)
54+
if err := multierr.Combine(violations...); err != nil {
55+
return fmt.Errorf("label validation failed: %w, allowed labels: %s", err, l.formatLabels())
56+
}
57+
58+
return nil
5059
}
5160

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

6473
return fmt.Errorf("label %s=%s is not allowed", key, value)
6574
}
75+
76+
func (l *AllowedLabels) String() string {
77+
return fmt.Sprintf("allowed %s", l.formatLabels())
78+
}
79+
80+
func (l *AllowedLabels) formatLabels() string {
81+
s := make([]string, 0, len(l.allowed))
82+
for _, allowed := range l.allowed {
83+
s = append(s, allowed.String())
84+
}
85+
86+
return fmt.Sprintf("{ %s }", strings.Join(s, ", "))
87+
}

validate/labels_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,12 @@ func Test_AllowedLabels_Validate(t *testing.T) {
4646
assert.ErrorContains(t, err, "some.other.io=a")
4747
assert.ErrorContains(t, err, "some.other.io/2=a")
4848
}
49+
50+
func Test_AllowedLabels_String(t *testing.T) {
51+
v := validate.AllowedLabels{}
52+
53+
v.Add("my.ns.io/node-class", "flex|plus")
54+
v.Add("app", ".+")
55+
56+
assert.Equal(t, "allowed { ^(?:my.ns.io/node-class)$=^(?:flex|plus)$, ^(?:app)$=^(?:.+)$ }", v.String())
57+
}

0 commit comments

Comments
 (0)