Skip to content

Commit f0faa1d

Browse files
Add .String method for dyn.Pattern (#3234)
## Changes This PR adds a String() method for dyn.Patterns that are the symmetric counterpart to `dyn.MustPatternToString`. ## Why It is used in https://github.com/databricks/cli/pull/3044/files ## Tests Unit tests.
1 parent 109db31 commit f0faa1d

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

libs/dyn/pattern.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"errors"
55
"fmt"
66
"slices"
7+
"strings"
78
)
89

910
// Pattern represents a matcher for paths in a [Value] configuration tree.
@@ -12,6 +13,37 @@ import (
1213
// The reverse is not true; not every [Pattern] is a valid [Path], as patterns may contain wildcards.
1314
type Pattern []patternComponent
1415

16+
func (p Pattern) String() string {
17+
buf := strings.Builder{}
18+
first := true
19+
20+
for _, c := range p {
21+
switch c := c.(type) {
22+
case anyKeyComponent:
23+
if !first {
24+
buf.WriteString(".")
25+
}
26+
buf.WriteString("*")
27+
case anyIndexComponent:
28+
buf.WriteString("[*]")
29+
case pathComponent:
30+
if c.isKey() {
31+
if !first {
32+
buf.WriteString(".")
33+
}
34+
buf.WriteString(c.Key())
35+
} else {
36+
buf.WriteString(fmt.Sprintf("[%d]", c.Index()))
37+
}
38+
default:
39+
buf.WriteString("???")
40+
}
41+
42+
first = false
43+
}
44+
return buf.String()
45+
}
46+
1547
// A pattern component can visit a [Value] and recursively call into [visit] for matching elements.
1648
// Fixed components can match a single key or index, while wildcards can match any key or index.
1749
type patternComponent interface {

libs/dyn/pattern_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,28 @@ import (
88
assert "github.com/databricks/cli/libs/dyn/dynassert"
99
)
1010

11+
func TestPatternString(t *testing.T) {
12+
patterns := []string{
13+
"foo.bar",
14+
"foo.bar.baz",
15+
"foo[1]",
16+
"foo[*]",
17+
"*[1].bar",
18+
"foo.*.bar",
19+
"foo[*].bar",
20+
"",
21+
"foo",
22+
"[1]",
23+
"[*]",
24+
"*",
25+
}
26+
27+
for _, p := range patterns {
28+
pp := dyn.MustPatternFromString(p)
29+
assert.Equal(t, p, pp.String())
30+
}
31+
}
32+
1133
func TestNewPattern(t *testing.T) {
1234
pat := dyn.NewPattern(
1335
dyn.Key("foo"),

0 commit comments

Comments
 (0)