Skip to content

Commit

Permalink
Add "last" element handling in nested arrays (#80)
Browse files Browse the repository at this point in the history
* Add "last" element handlign in nested arrays

* Increase version

* Possible fix

---------

Co-authored-by: Cezar Antohe <[email protected]>
  • Loading branch information
CezarAntohe83 and CezarAntohe authored Oct 17, 2023
1 parent c5b133b commit c4b2491
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.5.0-unstable
1.5.1-unstable
21 changes: 14 additions & 7 deletions pkg/client/controllers/servicemetadatawatcher_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ package controllers
import (
"context"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"

registryv1 "github.com/adobe/cluster-registry/pkg/api/registry/v1"
registryv1alpha1 "github.com/adobe/cluster-registry/pkg/api/registry/v1alpha1"
jsonpatch "github.com/evanphx/json-patch/v5"
Expand All @@ -25,17 +31,12 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/json"
"reflect"
"regexp"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/controller"
crevent "sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"strconv"
"strings"
"time"

ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand Down Expand Up @@ -320,17 +321,23 @@ func createServiceMetadataPatch(serviceId string, namespace string, field string
// path is a list of keys separated by dots, e.g. "spec.template.spec.containers[0].image"
// if the field is a slice, the last key must be in the form of "key[index]"
func getNestedString(object interface{}, path []string) (string, bool, error) {
re := regexp.MustCompile(`^(.*)\[(\d+)]$`)
re := regexp.MustCompile(`^(.*)\[(\d+|[a-z]+)]$`)
var cpath []string
for i, key := range path {
m := re.FindStringSubmatch(key)
if len(m) > 0 {
cpath = append(cpath, m[1])
index, _ := strconv.Atoi(m[2])
slice, found, err := unstructured.NestedSlice(object.(map[string]interface{}), cpath...)
if !found || err != nil {
return "", false, err
}
index, err := strconv.Atoi(m[2])
if err != nil && m[2] != "last" {
return "", false, fmt.Errorf("invalid array index: %s", m[2])
}
if m[2] == "last" {
index = len(slice) - 1
}
if len(slice) <= index {
return "", false, fmt.Errorf("index out of range")
}
Expand Down

0 comments on commit c4b2491

Please sign in to comment.