Skip to content

Commit

Permalink
Merge branch 'master' into fix/v0.2
Browse files Browse the repository at this point in the history
  • Loading branch information
Mengqi Yu committed Jun 25, 2021
2 parents 363e5dd + f9735d8 commit 295d925
Show file tree
Hide file tree
Showing 33 changed files with 232 additions and 82 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[![CI Status](https://github.com/GoogleContainerTools/kpt-functions-catalog/workflows/CI/badge.svg?branch=master&event=push)](https://github.com/GoogleContainerTools/kpt-functions-catalog/actions?query=workflow%3ACI+event%3Apush+branch%3Amaster)

# KPT Functions Catalog
# kpt Functions Catalog

[Documentation]

Expand All @@ -12,7 +12,7 @@

[Code of Conduct]

[Documentation]: https://googlecontainertools.github.io/kpt/guides/consumer/function/
[Documentation]: https://catalog.kpt.dev/
[Contributor Guide]: CONTRIBUTING.md
[Code of Conduct]: CODE_OF_CONDUCT.md
[Release Process]: RELEASING.md
Expand Down
2 changes: 1 addition & 1 deletion examples/ensure-name-substring-imperative/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ $ kpt pkg get https://github.com/GoogleContainerTools/kpt-functions-catalog.git/
Invoke the function by running the following commands:

```shell
$ kpt fn eval ensure-name-substring-imperative --image gcr.io/kpt-fn/ensure-name-substring:unstable -- prepend=prod
$ kpt fn eval ensure-name-substring-imperative --image gcr.io/kpt-fn/ensure-name-substring:unstable -- prepend=prod-
```

The key-value pair(s) provided after `--` will be converted to `ConfigMap` by
Expand Down
12 changes: 6 additions & 6 deletions examples/fix-simple/.expected/diff.patch
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
diff --git a/Kptfile b/Kptfile
index a8e7f27..0d91da2 100644
index a8e7f27..cccb738 100644
--- a/Kptfile
+++ b/Kptfile
@@ -1,20 +1,24 @@
Expand Down Expand Up @@ -37,7 +37,7 @@ index a8e7f27..0d91da2 100644
+pipeline:
+ mutators:
+ - image: gcr.io/kpt-fn/apply-setters:v0.1
+ configPath: setters-config.yaml
+ configPath: setters.yaml
diff --git a/resources.yaml b/resources.yaml
index 9e30767..dae3005 100644
--- a/resources.yaml
Expand All @@ -50,15 +50,15 @@ index 9e30767..dae3005 100644
+ name: the-map # kpt-set: ${name}
data:
some-key: some-value
diff --git a/setters-config.yaml b/setters-config.yaml
diff --git a/setters.yaml b/setters.yaml
new file mode 100644
index 0000000..f39bb00
index 0000000..b67bc21
--- /dev/null
+++ b/setters-config.yaml
+++ b/setters.yaml
@@ -0,0 +1,6 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: setters-config
+ name: setters
+data:
+ name: the-map
2 changes: 1 addition & 1 deletion examples/fix-simple/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ info:
pipeline:
mutators:
- image: gcr.io/kpt-fn/apply-setters:v0.1
configPath: setters-config.yaml
configPath: setters.yaml
```

The transformed package is compatible with kpt 1.0 binary.
Expand Down
2 changes: 1 addition & 1 deletion examples/starlark-validation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ keys in the `ConfigMap`.
Invoke the function by running the following commands:

```shell
$ kpt fn render starlark-validation
$ kpt fn render starlark-validation --results-dir /tmp
```

### Expected result
Expand Down
6 changes: 3 additions & 3 deletions functions/contrib/ts/sops/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion functions/contrib/ts/sops/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"devDependencies": {
"@types/jasmine": "^3.7.6",
"@types/js-yaml": "^3.12.5",
"@types/node": "^14.17.1",
"@types/node": "^14.17.2",
"@types/rw": "file:@types/rw",
"create-kpt-functions": "^0.17.0",
"jasmine": "^3.7.0",
Expand Down
2 changes: 1 addition & 1 deletion functions/go/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func-fmt:

func-lint:
(which $(GOPATH)/bin/golangci-lint || \
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v1.32.2)
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v1.41.1)
cd $(CURRENT_FUNCTION) && $(GOPATH)/bin/golangci-lint run ./...

func-test:
Expand Down
81 changes: 54 additions & 27 deletions functions/go/fix/fixpkg/fix.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"sigs.k8s.io/kustomize/kyaml/fieldmeta"
"sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/kio/filters"
"sigs.k8s.io/kustomize/kyaml/kio/kioutil"
"sigs.k8s.io/kustomize/kyaml/openapi"
"sigs.k8s.io/kustomize/kyaml/sets"
Expand Down Expand Up @@ -55,7 +56,7 @@ type Result struct {
Message string
}

const SettersConfigFileName = "setters-config.yaml"
const SettersConfigFileName = "setters.yaml"

// Filter implements Fix as a yaml.Filter
func (s *Fix) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
Expand Down Expand Up @@ -230,15 +231,18 @@ func (s *Fix) FunctionsInPkg(nodes []*yaml.RNode, pkgPath string) []v1.Function
}
fnSpec := runtimeutil.GetFunctionSpec(node)
if fnSpec != nil {
// in order to make sure there is only one function config per file,
// rename the file with the name(and hash(name)) of the function config resource
fnFileName := fmt.Sprintf("%s.yaml", node.GetName())
// in v1, fn-config must be present in the package directory
// so configPath must be just the file name
fnFileName := filepath.Base(meta.Annotations[kioutil.PathAnnotation])
fnFilePath := filepath.Join(pkgPath, fnFileName)
res = append(res, v1.Function{
Image: fnSpec.Container.Image,
ConfigPath: fnFileName,
})
// move the fn-config to the top level directory of the package
meta.Annotations[kioutil.PathAnnotation] = filepath.Join(pkgPath, fnFileName)
meta.Annotations[kioutil.PathAnnotation] = fnFilePath
delete(meta.Annotations, runtimeutil.FunctionAnnotationKey)
delete(meta.Annotations, "config.k8s.io/function")
err = node.SetAnnotations(meta.Annotations)
Expand Down Expand Up @@ -278,7 +282,7 @@ func (s *Fix) FixKptfile(node *yaml.RNode, functions []v1.Function) (*yaml.RNode
if kf.Pipeline != nil {
for i, fn := range kf.Pipeline.Mutators {
if strings.Contains(fn.Image, "apply-setters:v0.1") && len(fn.ConfigMap) > 0 {
settersConfig, err := ConfigFromSetters(kf.Pipeline.Mutators[0].ConfigMap, settersConfigFilePath)
settersConfig, err := SettersNodeFromSetters(kf.Pipeline.Mutators[0].ConfigMap, settersConfigFilePath)
if err != nil {
return node, err
}
Expand Down Expand Up @@ -392,9 +396,9 @@ func (s *Fix) FixKptfile(node *yaml.RNode, functions []v1.Function) (*yaml.RNode
if len(setters) > 0 {
fn := v1.Function{
Image: "gcr.io/kpt-fn/apply-setters:v0.1",
ConfigPath: "setters-config.yaml",
ConfigPath: SettersConfigFileName,
}
settersConfig, err := ConfigFromSetters(setters, settersConfigFilePath)
settersConfig, err := SettersNodeFromSetters(setters, settersConfigFilePath)
if err != nil {
return node, err
}
Expand Down Expand Up @@ -431,12 +435,12 @@ func (s *Fix) FixKptfile(node *yaml.RNode, functions []v1.Function) (*yaml.RNode
return kNode, err
}

// ConfigFromSetters returns the ConfigMap node with input setters in data field
func ConfigFromSetters(setters map[string]string, path string) (*yaml.RNode, error) {
// SettersNodeFromSetters returns the ConfigMap node with input setters in data field
func SettersNodeFromSetters(setters map[string]string, path string) (*yaml.RNode, error) {
configNode, err := yaml.Parse(fmt.Sprintf(`apiVersion: v1
kind: ConfigMap
metadata:
name: setters-config
name: setters
annotations:
%s: %s
%s: "0"
Expand All @@ -452,28 +456,48 @@ metadata:
sort.Strings(keys)

for _, k := range keys {
v := setters[k]
vNode, err := yaml.Parse(v)
v, err := standardizeArrayValue(setters[k])
if err != nil {
return nil, err
}
if vNode.YNode().Kind == yaml.SequenceNode {
// standardize array values to folded style
vNode.YNode().Style = yaml.FoldedStyle
v, err = vNode.String()
if err != nil {
return nil, err
}
vNode := yaml.NewScalarRNode(v)
if v == "" {
vNode.YNode().Style = yaml.DoubleQuotedStyle
}

err = configNode.PipeE(
yaml.LookupCreate(yaml.ScalarNode, "data", k),
yaml.FieldSetter{Value: yaml.NewScalarRNode(v)})
yaml.FieldSetter{Value: vNode, OverrideStyle: true})
if err != nil {
return nil, err
}
}
return configNode, nil
// format the created resource
_, err = filters.FormatFilter{UseSchema: true}.Filter([]*yaml.RNode{configNode})
return configNode, err
}

// standardizeArrayValue returns the folded style array node string
// e.g. for input value [foo, bar], it returns
// - foo
// - bar
func standardizeArrayValue(val string) (string, error) {
if !strings.HasPrefix(val, "[") {
// the value is either standardized, or is not a sequence node value
return val, nil
}
vNode, err := yaml.Parse(val)
if err != nil {
return val, fmt.Errorf("failed to parse the array node value %q with error %q", val, err.Error())
}
if vNode.YNode().Kind == yaml.SequenceNode {
// standardize array values to folded style
vNode.YNode().Style = yaml.FoldedStyle
val, err = vNode.String()
if err != nil {
return val, fmt.Errorf("failed to serialize the array node value %q with error %q", val, err.Error())
}
}
return val, nil
}

// getPkgPathToSettersSchema returns the, map of pkgPath to the setters schema in Kptfile
Expand Down Expand Up @@ -507,13 +531,16 @@ func (s *Fix) visitMapping(object *yaml.RNode) error {
// return if it is not a sequence node
return nil
}

oldCommentPrefixes := []string{`# {"$kpt-set":"`, `# {"$ref":"#/definitions/io.k8s.cli.`}
comment := node.Key.YNode().LineComment
// # {"$kpt-set":"foo"} must be converted to # kpt-set: ${foo}
if strings.Contains(comment, "$kpt-set") {
comment := strings.TrimPrefix(comment, `# {"$kpt-set":"`)
comment = strings.TrimSuffix(comment, `"}`)
node.Key.YNode().LineComment = fmt.Sprintf("kpt-set: ${%s}", comment)
for _, cp := range oldCommentPrefixes {
// # {"$kpt-set":"foo"} must be converted to # kpt-set: ${foo}
// # {"$ref":"#/definitions/io.k8s.cli.list"} must be converted to # kpt-set: ${list}
if strings.Contains(comment, cp) {
comment := strings.TrimPrefix(comment, cp)
comment = strings.TrimSuffix(comment, `"}`)
node.Key.YNode().LineComment = fmt.Sprintf("kpt-set: ${%s}", comment)
}
}
return nil
})
Expand Down
81 changes: 79 additions & 2 deletions functions/go/fix/fixpkg/fix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ func TestFixV1alpha1ToV1(t *testing.T) {
message: Transformed "packageMetadata" to "info"
- filepath: Kptfile
message: Transformed "upstream" to "upstream" and "upstreamLock"
- filepath: Kptfile
message: Added "gcr.io/kpt-fn/set-annotations:v0.1" to mutators list, please move it to validators section if it is a validator function
- filepath: Kptfile
message: Added "gcr.io/kpt-fn/set-labels:v0.1" to mutators list, please move it to validators section if it is a validator function
- filepath: Kptfile
Expand Down Expand Up @@ -78,11 +80,86 @@ func TestFixV1alpha2ToV1(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, `- filepath: Kptfile
message: Updated apiVersion to kpt.dev/v1
- filepath: setters-config.yaml
- filepath: setters.yaml
message: Moved setters from configMap to configPath
- filepath: hello-world/Kptfile
message: Updated apiVersion to kpt.dev/v1
- filepath: hello-world/setters-config.yaml
- filepath: hello-world/setters.yaml
message: Moved setters from configMap to configPath
`, string(results))
}

type settersNodeTest struct {
name string
setters map[string]string
path string
expected string
errMsg string
}

var settersNodeFromSettersCases = []settersNodeTest{
{
name: "Create setters file with all types",
path: `foo/bar`,
setters: map[string]string{
"environment": "",
"integer": "10",
"number": "1.1",
"boolean": "true",
"string": "foo",
"region": "us-east-1",
"flow-style-setter": "[dev, prod]",
"folded-style-setter": "- hi\n- hello",
},
expected: `apiVersion: v1
kind: ConfigMap
metadata:
name: setters
annotations:
config.kubernetes.io/index: "0"
config.kubernetes.io/path: foo/bar
data:
boolean: "true"
environment: ""
flow-style-setter: |
- dev
- prod
folded-style-setter: |-
- hi
- hello
integer: "10"
number: "1.1"
region: us-east-1
string: foo
`,
},
{
name: "invalid flow-style sequence node",
path: `foo/bar`,
setters: map[string]string{
"setter": "[dev, prod,",
},
errMsg: `failed to parse the array node value "[dev, prod," with error "yaml: line 1: did not find expected node content"`,
},
}

func TestSettersNodeFromSetters(t *testing.T) {
for i := range settersNodeFromSettersCases {
test := settersNodeFromSettersCases[i]
t.Run(test.name, func(t *testing.T) {
res, err := SettersNodeFromSetters(test.setters, test.path)
if test.errMsg == "" {
assert.NoError(t, err)
} else {
assert.Error(t, err)
assert.Equal(t, test.errMsg, err.Error())
return
}
actual, err := res.String()
assert.NoError(t, err)
if !assert.Equal(t, test.expected, actual) {
t.FailNow()
}
})
}
}
6 changes: 3 additions & 3 deletions functions/go/starlark/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ Here's what you can do in the Starlark script:

- Read resources from `ctx.resource_list`. The `ctx.resource_list` complies with
the [KRM Functions Specification]. You can read the input resources from
`ctx.resource_list[items]` and the `functionConfig` from
`ctx.resource_list[functionConfig]`.
- Write resources to `ctx.resource_list[items]`.
`ctx.resource_list["items"]` and the `functionConfig` from
`ctx.resource_list["functionConfig"]`.
- Write resources to `ctx.resource_list["items"]`.
- Return an error using [`fail`][fail].
- Write error message to stderr using [`print`][print]

Expand Down
2 changes: 1 addition & 1 deletion functions/ts/kubeval/build/kubeval.Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
FROM node:14.15-alpine3.13 as builder

ARG KUBEVAL_VERSION="v0.16.1"
RUN apk add curl && \
RUN apk update && apk add curl && \
curl -sSLf https://github.com/instrumenta/kubeval/releases/download/${KUBEVAL_VERSION}/kubeval-linux-amd64.tar.gz | \
tar xzf - -C /usr/local/bin

Expand Down
Loading

0 comments on commit 295d925

Please sign in to comment.