mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-05 07:26:55 +00:00
feat: add a package to convert unstructured into typed (#8484)
Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
This commit is contained in:
parent
ae1fa9b260
commit
4046315dac
3 changed files with 66 additions and 0 deletions
|
@ -0,0 +1,6 @@
|
|||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: prod-bus-app1
|
||||
labels:
|
||||
purpose: production
|
18
cmd/cli/kubectl-kyverno/resource/convert/convert.go
Normal file
18
cmd/cli/kubectl-kyverno/resource/convert/convert.go
Normal file
|
@ -0,0 +1,18 @@
|
|||
package convert
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
func Into[T any](untyped unstructured.Unstructured, result *T) error {
|
||||
return runtime.DefaultUnstructuredConverter.FromUnstructuredWithValidation(untyped.UnstructuredContent(), result, true)
|
||||
}
|
||||
|
||||
func To[T any](untyped unstructured.Unstructured) (*T, error) {
|
||||
var result T
|
||||
if err := Into(untyped, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &result, nil
|
||||
}
|
42
cmd/cli/kubectl-kyverno/resource/convert/convert_test.go
Normal file
42
cmd/cli/kubectl-kyverno/resource/convert/convert_test.go
Normal file
|
@ -0,0 +1,42 @@
|
|||
package convert
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
func TestTo(t *testing.T) {
|
||||
{
|
||||
data, err := os.ReadFile("../../_testdata/policies/check-image.yaml")
|
||||
require.NoError(t, err)
|
||||
|
||||
json, err := yaml.YAMLToJSON(data)
|
||||
require.NoError(t, err)
|
||||
|
||||
var untyped unstructured.Unstructured
|
||||
require.NoError(t, untyped.UnmarshalJSON(json))
|
||||
|
||||
typed, err := To[corev1.ConfigMap](untyped)
|
||||
require.Nil(t, typed)
|
||||
require.Error(t, err)
|
||||
}
|
||||
{
|
||||
data, err := os.ReadFile("../../_testdata/resources/namespace.yaml")
|
||||
require.NoError(t, err)
|
||||
|
||||
json, err := yaml.YAMLToJSON(data)
|
||||
require.NoError(t, err)
|
||||
|
||||
var untyped unstructured.Unstructured
|
||||
require.NoError(t, untyped.UnmarshalJSON(json))
|
||||
|
||||
typed, err := To[corev1.Namespace](untyped)
|
||||
require.NotNil(t, typed)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
Loading…
Add table
Reference in a new issue