Skip to content

Commit

Permalink
allow accessing labels and annotations in vars
Browse files Browse the repository at this point in the history
  • Loading branch information
Liujingfang1 committed Nov 13, 2018
1 parent 38b7f42 commit 51e9fec
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 2 deletions.
71 changes: 71 additions & 0 deletions k8sdeps/kunstruct/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package kunstruct provides unstructured from api machinery and factory for creating unstructured
package kunstruct

import (
"fmt"
"strings"
)

func parseFields(path string) ([]string, error) {
if !strings.Contains(path, "[") {
return strings.Split(path, "."), nil
}

var fields []string
start := 0
insideParentheses := false
for i := range path {
switch path[i] {
case '.':
if !insideParentheses {
fields = append(fields, path[start:i])
start = i + 1
}
case '[':
if !insideParentheses {
if i == start {
start = i + 1
} else {
fields = append(fields, path[start:i])
start = i + 1
}
insideParentheses = true
} else {
return nil, fmt.Errorf("nested parentheses are not allowed: %s", path)
}
case ']':
if insideParentheses {
fields = append(fields, path[start:i])
start = i + 1
insideParentheses = false
} else {
return nil, fmt.Errorf("Invalid field path %s", path)
}
}
}
if start < len(path)-1 {
fields = append(fields, path[start:])
}
for i, f := range fields {
if strings.HasPrefix(f, "\"") || strings.HasPrefix(f, "'") {
fields[i] = strings.Trim(f, "\"'")
}
}
return fields, nil
}
7 changes: 5 additions & 2 deletions k8sdeps/kunstruct/kunstruct.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ package kunstruct
import (
"encoding/json"
"fmt"
"strings"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
Expand Down Expand Up @@ -80,8 +79,12 @@ func (fs *UnstructAdapter) SetMap(m map[string]interface{}) {

// GetFieldValue returns value at the given fieldpath.
func (fs *UnstructAdapter) GetFieldValue(path string) (string, error) {
fields, err := parseFields(path)
if err != nil {
return "", err
}
s, found, err := unstructured.NestedString(
fs.UnstructuredContent(), strings.Split(path, ".")...)
fs.UnstructuredContent(), fields...)
if found || err != nil {
return s, err
}
Expand Down

0 comments on commit 51e9fec

Please sign in to comment.