Skip to content

Commit 47607bb

Browse files
committed
feat(yaml): support array notation within yaml
1 parent 78b27e2 commit 47607bb

File tree

2 files changed

+55
-4
lines changed

2 files changed

+55
-4
lines changed

internal/pkg/gitops/version.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"fmt"
77
"gopkg.in/yaml.v3"
88
"io/ioutil"
9+
"regexp"
10+
"strconv"
911
"strings"
1012
)
1113

@@ -41,8 +43,31 @@ func WriteVersion(f []byte, version string, newVersion string, filename string)
4143

4244
func unwrapYaml(yaml map[string]interface{}, notion string) (string, error) {
4345
d := yaml
46+
r := regexp.MustCompile(`\d+]$`)
4447

4548
for _, k := range strings.Split(notion, ".") {
49+
if r.MatchString(k) {
50+
idx := r.FindString(k)[:1]
51+
52+
if len(idx) > 0 {
53+
i, err := strconv.ParseInt(idx, 10, 8)
54+
55+
if err != nil {
56+
return "", err
57+
}
58+
59+
k = k[:len(k)-int(i)]
60+
61+
if a, ok := d[k].([]interface{}); ok {
62+
if b, ok := a[i].(map[string]interface{}); ok {
63+
d = b
64+
65+
continue
66+
}
67+
}
68+
}
69+
}
70+
4671
if _, ok := d[k]; !ok {
4772
return "", fmt.Errorf("unable to find %s in yaml", notion)
4873
}

internal/pkg/gitops/version_test.go

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ func TestReadCurrentVersion(t *testing.T) {
3030
{
3131
name: "invalid yaml",
3232
args: args{
33-
f: []byte("wibble&&3..\nfff"),
33+
f: []byte("wibble&&3..\nfff"),
3434
notation: "image.tag",
3535
},
3636
want: "",
@@ -39,7 +39,7 @@ func TestReadCurrentVersion(t *testing.T) {
3939
{
4040
name: "simple yaml",
4141
args: args{
42-
f: createSimpleYaml("v1.2.99"),
42+
f: createSimpleYaml("v1.2.99"),
4343
notation: "image.tag",
4444
},
4545
want: "v1.2.99",
@@ -48,15 +48,24 @@ func TestReadCurrentVersion(t *testing.T) {
4848
{
4949
name: "invalid notation to yaml",
5050
args: args{
51-
f: createSimpleYaml("v1.2.99"),
51+
f: createSimpleYaml("v1.2.99"),
5252
notation: "image.nope",
5353
},
5454
want: "",
5555
wantErr: true,
5656
},
57+
{
58+
name: "array notation",
59+
args: args{
60+
f: createSimpleArrayYaml("v1.9"),
61+
notation: "images[3].tag",
62+
},
63+
want: "v1.9",
64+
wantErr: false,
65+
},
5766
}
5867

59-
fmt.Println(string(createSimpleYaml("v1.2.99")))
68+
fmt.Println(string(createSimpleArrayYaml("v1.2.99")))
6069

6170
for _, tt := range tests {
6271
t.Run(tt.name, func(t *testing.T) {
@@ -88,3 +97,20 @@ func createSimpleYaml(t string) []byte {
8897

8998
return marshal
9099
}
100+
101+
func createSimpleArrayYaml(t string) []byte {
102+
type tag struct {
103+
Tag string `yaml:"tag"`
104+
}
105+
106+
marshal, err := yaml.Marshal(&struct {
107+
Images []tag `yaml:"images"`
108+
}{
109+
Images: []tag{{Tag: "v1"},{Tag: "v2"},{Tag: "v3"},{Tag: t}},
110+
})
111+
if err != nil {
112+
return nil
113+
}
114+
115+
return marshal
116+
}

0 commit comments

Comments
 (0)