Skip to content

Commit

Permalink
fixes 4123; added length check on originalFields of kustomizationFile…
Browse files Browse the repository at this point in the history
… to prevent panic when kustomization file began with a comment(or a blank line) followed by a document separator
  • Loading branch information
m-Bilal committed Sep 12, 2021
1 parent 402f6ca commit 12c177a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion kustomize/commands/internal/kustfile/kustomizationfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
}
Expand Down
47 changes: 47 additions & 0 deletions kustomize/commands/internal/kustfile/kustomizationfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 12c177a

Please sign in to comment.