Skip to content

Commit c4b2491

Browse files
Add "last" element handling in nested arrays (#80)
* Add "last" element handlign in nested arrays * Increase version * Possible fix --------- Co-authored-by: Cezar Antohe <[email protected]>
1 parent c5b133b commit c4b2491

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.5.0-unstable
1+
1.5.1-unstable

pkg/client/controllers/servicemetadatawatcher_controller.go

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ package controllers
1515
import (
1616
"context"
1717
"fmt"
18+
"reflect"
19+
"regexp"
20+
"strconv"
21+
"strings"
22+
"time"
23+
1824
registryv1 "github.com/adobe/cluster-registry/pkg/api/registry/v1"
1925
registryv1alpha1 "github.com/adobe/cluster-registry/pkg/api/registry/v1alpha1"
2026
jsonpatch "github.com/evanphx/json-patch/v5"
@@ -25,17 +31,12 @@ import (
2531
"k8s.io/apimachinery/pkg/runtime/schema"
2632
"k8s.io/apimachinery/pkg/types"
2733
"k8s.io/apimachinery/pkg/util/json"
28-
"reflect"
29-
"regexp"
3034
"sigs.k8s.io/controller-runtime/pkg/builder"
3135
"sigs.k8s.io/controller-runtime/pkg/controller"
3236
crevent "sigs.k8s.io/controller-runtime/pkg/event"
3337
"sigs.k8s.io/controller-runtime/pkg/handler"
3438
"sigs.k8s.io/controller-runtime/pkg/predicate"
3539
"sigs.k8s.io/controller-runtime/pkg/reconcile"
36-
"strconv"
37-
"strings"
38-
"time"
3940

4041
ctrl "sigs.k8s.io/controller-runtime"
4142
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -320,17 +321,23 @@ func createServiceMetadataPatch(serviceId string, namespace string, field string
320321
// path is a list of keys separated by dots, e.g. "spec.template.spec.containers[0].image"
321322
// if the field is a slice, the last key must be in the form of "key[index]"
322323
func getNestedString(object interface{}, path []string) (string, bool, error) {
323-
re := regexp.MustCompile(`^(.*)\[(\d+)]$`)
324+
re := regexp.MustCompile(`^(.*)\[(\d+|[a-z]+)]$`)
324325
var cpath []string
325326
for i, key := range path {
326327
m := re.FindStringSubmatch(key)
327328
if len(m) > 0 {
328329
cpath = append(cpath, m[1])
329-
index, _ := strconv.Atoi(m[2])
330330
slice, found, err := unstructured.NestedSlice(object.(map[string]interface{}), cpath...)
331331
if !found || err != nil {
332332
return "", false, err
333333
}
334+
index, err := strconv.Atoi(m[2])
335+
if err != nil && m[2] != "last" {
336+
return "", false, fmt.Errorf("invalid array index: %s", m[2])
337+
}
338+
if m[2] == "last" {
339+
index = len(slice) - 1
340+
}
334341
if len(slice) <= index {
335342
return "", false, fmt.Errorf("index out of range")
336343
}

0 commit comments

Comments
 (0)