From 12c177a3656434476669becc66acf2dec5b46732 Mon Sep 17 00:00:00 2001 From: m-Bilal Date: Sun, 12 Sep 2021 17:35:23 +0530 Subject: [PATCH] fixes 4123; added length check on originalFields of kustomizationFile to prevent panic when kustomization file began with a comment(or a blank line) followed by a document separator --- .../internal/kustfile/kustomizationfile.go | 2 +- .../kustfile/kustomizationfile_test.go | 47 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/kustomize/commands/internal/kustfile/kustomizationfile.go b/kustomize/commands/internal/kustfile/kustomizationfile.go index 023caae388..0d313d14c7 100644 --- a/kustomize/commands/internal/kustfile/kustomizationfile.go +++ b/kustomize/commands/internal/kustfile/kustomizationfile.go @@ -212,7 +212,7 @@ func (mf *kustomizationFile) parseCommentedFields(content []byte) error { if matched { mf.originalFields = append(mf.originalFields, &commentedField{field: field, comment: squash(comments)}) comments = [][]byte{} - } else if len(comments) > 0 { + } else if len(comments) > 0 && len(mf.originalFields) > 0 { mf.originalFields[len(mf.originalFields)-1].appendComment(squash(comments)) comments = [][]byte{} } diff --git a/kustomize/commands/internal/kustfile/kustomizationfile_test.go b/kustomize/commands/internal/kustfile/kustomizationfile_test.go index dc4801ac43..0326057309 100644 --- a/kustomize/commands/internal/kustfile/kustomizationfile_test.go +++ b/kustomize/commands/internal/kustfile/kustomizationfile_test.go @@ -356,6 +356,53 @@ kind: Kustomization } } +func TestCommentsWithDocumentSeperatorAtBeginning(t *testing.T) { + kustomizationContentWithComments := []byte(` + + +# Some comments +# This is some comment we should preserve +# don't delete it +--- +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +namespace: mynamespace +`) + + expected := []byte(` + + +# Some comments +# This is some comment we should preserve +# don't delete it +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +namespace: mynamespace +`) + fSys := filesys.MakeFsInMemory() + testutils_test.WriteTestKustomizationWith( + fSys, kustomizationContentWithComments) + mf, err := NewKustomizationFile(fSys) + if err != nil { + t.Fatalf("Unexpected Error: %v", err) + } + + kustomization, err := mf.Read() + if err != nil { + t.Fatalf("Unexpected Error: %v", err) + } + if err = mf.Write(kustomization); err != nil { + t.Fatalf("Unexpected Error: %v", err) + } + bytes, _ := fSys.ReadFile(mf.path) + + if diff := cmp.Diff(expected, bytes); diff != "" { + t.Errorf("Mismatch (-expected, +actual):\n%s", diff) + } +} + func TestUnknownFieldInKustomization(t *testing.T) { kContent := []byte(` foo: