From 36facd30eb01c25d0d1d2b1efa02ad505530f3e0 Mon Sep 17 00:00:00 2001 From: Kostiantyn Kalynovskyi Date: Tue, 16 Jun 2020 16:20:02 -0500 Subject: [PATCH] Add new constructor to create documents The change would allow to build a document object from bytes Change-Id: I15c13a960b4e989cffa4525c85b8f32f2a51a0e1 Relates-To: #238 Relates-To: #279 Closes: #279 --- pkg/document/constants.go | 3 +++ pkg/document/document.go | 12 ++++++++++ pkg/document/document_test.go | 43 +++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+) diff --git a/pkg/document/constants.go b/pkg/document/constants.go index 519428384..a44ad0330 100644 --- a/pkg/document/constants.go +++ b/pkg/document/constants.go @@ -31,6 +31,9 @@ const ( SecretKind = "Secret" BareMetalHostKind = "BareMetalHost" + ConfigMapKind = "ConfigMap" + ConfigMapVersion = "v1" + ClusterctlMetadataKind = "Metadata" ClusterctlMetadataVersion = "v1alpha3" ClusterctlMetadataGroup = "clusterctl.cluster.x-k8s.io" diff --git a/pkg/document/document.go b/pkg/document/document.go index 9b3c3744f..bfa899f4f 100644 --- a/pkg/document/document.go +++ b/pkg/document/document.go @@ -15,6 +15,7 @@ package document import ( + "sigs.k8s.io/kustomize/api/k8sdeps/kunstruct" "sigs.k8s.io/kustomize/api/resource" "sigs.k8s.io/yaml" ) @@ -198,3 +199,14 @@ func NewDocument(r *resource.Resource) (Document, error) { err := doc.SetKustomizeResource(r) return doc, err } + +// NewDocumentFromBytes constructs document from bytes +func NewDocumentFromBytes(b []byte) (Document, error) { + res, err := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl()).FromBytes(b) + if err != nil { + return nil, err + } + doc := &Factory{} + err = doc.SetKustomizeResource(res) + return doc, err +} diff --git a/pkg/document/document_test.go b/pkg/document/document_test.go index dee13be7d..f18967ef3 100644 --- a/pkg/document/document_test.go +++ b/pkg/document/document_test.go @@ -158,3 +158,46 @@ func TestDocument(t *testing.T) { } }) } + +func TestNewDocumentFromBytes(t *testing.T) { + tests := []struct { + name string + stringData string + expectErr bool + expectedDocName string + }{ + { + name: "ConfigMap", + stringData: `apiVersion: v1 +kind: Secret +metadata: + name: control-0-bmc + namespace: metal3 +type: Opaque +stringData: + username: username + password: password`, + expectErr: false, + expectedDocName: "control-0-bmc", + }, + { + name: "Manformed Bytes", + stringData: ` + broken:fas -< + fasd`, + expectErr: true, + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + doc, err := document.NewDocumentFromBytes([]byte(tt.stringData)) + if tt.expectErr { + assert.Error(t, err) + } else { + require.NoError(t, err) + assert.Equal(t, doc.GetName(), tt.expectedDocName) + } + }) + } +}