Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support multiple document yaml files #143

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 22 additions & 16 deletions pkg/cmd/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,9 +222,11 @@ func (c *commandFlags) Run(cmd *cobra.Command, args []string) error {
for _, path := range files {
fmt.Fprintf(cmd.OutOrStdout(), "\n\033[1m%v\033[0m...", path)
var errs []error
for _, err := range ValidateFile(path, factory) {
if err != nil {
errs = append(errs, err)
for _, validationErrors := range ValidateFile(path, factory) {
for _, err := range validationErrors {
if err != nil {
errs = append(errs, err)
}
}
}
if len(errs) != 0 {
Expand All @@ -238,11 +240,15 @@ func (c *commandFlags) Run(cmd *cobra.Command, args []string) error {
}
}
} else {
res := map[string][]metav1.Status{}
res := map[string][][]metav1.Status{}
for _, path := range files {
for _, err := range ValidateFile(path, factory) {
res[path] = append(res[path], errorToStatus(err))
hasError = hasError || err != nil
for _, errs := range ValidateFile(path, factory) {
statuses := []metav1.Status{}
for _, err := range errs {
statuses = append(statuses, errorToStatus(err))
hasError = hasError || err != nil
}
res[path] = append(res[path], statuses)
}
}
data, e := json.MarshalIndent(res, "", " ")
Expand All @@ -258,29 +264,29 @@ func (c *commandFlags) Run(cmd *cobra.Command, args []string) error {
return nil
}

func ValidateFile(filePath string, resolver *validator.Validator) []error {
func ValidateFile(filePath string, resolver *validator.Validator) [][]error {
fileBytes, err := os.ReadFile(filePath)
if err != nil {
return []error{fmt.Errorf("error reading file: %w", err)}
return [][]error{[]error{fmt.Errorf("error reading file: %w", err)}}
}
if utils.IsYaml(filePath) {
documents, err := utils.SplitYamlDocuments(fileBytes)
if err != nil {
return []error{err}
return [][]error{[]error{err}}
}
var errs []error
var errs [][]error
for _, document := range documents {
var docErrs []error
if utils.IsEmptyYamlDocument(document) {
errs = append(errs, nil)
docErrs = append(docErrs, nil)
} else {
errs = append(errs, ValidateDocument(document, resolver))
docErrs = append(docErrs, ValidateDocument(document, resolver))
}
errs = append(errs, docErrs)
}
return errs
} else {
return []error{
ValidateDocument(fileBytes, resolver),
}
return [][]error{[]error{ValidateDocument(fileBytes, resolver)}}
}
}

Expand Down
10 changes: 6 additions & 4 deletions pkg/cmd/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@ func TestValidationErrorsIndividually(t *testing.T) {
documents, err := utils.SplitYamlDocuments(data)
require.NoError(t, err)

var expected []metav1.Status
var expected [][]metav1.Status
expectedError := false
for _, document := range documents {
docExpected := []metav1.Status{}
if utils.IsEmptyYamlDocument(document) {
expected = append(expected, metav1.Status{Status: metav1.StatusSuccess})
docExpected = append(docExpected, metav1.Status{Status: metav1.StatusSuccess})
} else {
lines := strings.Split(string(document), "\n")

Expand All @@ -77,11 +78,12 @@ func TestValidationErrorsIndividually(t *testing.T) {
t.Fatalf("error parsing leading expectation comment: %v", err)
}

expected = append(expected, expectation)
docExpected = append(docExpected, expectation)
if expectation.Status != "Success" {
expectedError = true
}
}
expected = append(expected, docExpected)
}

rootCmd := cmd.NewRootCommand()
Expand All @@ -101,7 +103,7 @@ func TestValidationErrorsIndividually(t *testing.T) {
assert.NoError(t, err)
}

output := map[string][]metav1.Status{}
output := map[string][][]metav1.Status{}
if err := json.Unmarshal(buf.Bytes(), &output); err != nil {
t.Fatal(err)
}
Expand Down
18 changes: 18 additions & 0 deletions pkg/utils/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,24 @@ import (
type Document = []byte

func SplitYamlDocuments(fileBytes Document) ([]Document, error) {
var toRead int = len(fileBytes)
var documents []Document
decoder := utilyaml.NewDocumentDecoder(io.NopCloser(bufio.NewReader(bytes.NewBuffer(fileBytes))))
for {
document := make(Document, toRead)
n, err := decoder.Read(document)
if err == io.EOF || len(document) == 0 {
break
} else if err != nil {
return nil, err
}
documents = append(documents, Document(document[0:n]))
toRead -= n
}
return documents, nil
}

func SplitYamlDocuments1(fileBytes Document) ([]Document, error) {
var documents [][]byte
reader := utilyaml.NewYAMLReader(bufio.NewReader(bytes.NewBuffer(fileBytes)))
for {
Expand Down
46 changes: 46 additions & 0 deletions pkg/utils/yaml_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package utils

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestSplitDocuments(t *testing.T) {
cases := []struct {
name string
input []byte
expected []Document
expectedError string
}{
{
name: "single document",
input: []byte(`{"key": "value","name":"doc1"}`),
expected: []Document{
Document([]byte(`{"key": "value","name":"doc1"}`)),
},
},
{
name: "multiple documents",
input: []byte(`{"key": "value","name":"doc1"}` + "\n---\n" + `{"key": "value","name":"doc2"}`),
expected: []Document{
Document([]byte(`{"key": "value","name":"doc1"}`)),
Document([]byte(`{"key": "value","name":"doc2"}`)),
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
actual, err := SplitYamlDocuments(tc.input)
if tc.expectedError != "" {
require.ErrorContains(t, err, tc.expectedError)
} else {
require.NoError(t, err)
for i := range actual {
require.Equal(t, string(tc.expected[i]), string(actual[i]))
}
require.Len(t, actual, len(tc.expected))
}
})
}
}
36 changes: 36 additions & 0 deletions testcases/manifests/configmap_multi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# {
# "status": "Success",
# "message": ""
# }
apiVersion: v1
kind: ConfigMap
metadata:
name: successful
data:
key: "123"
---
# {
# "metadata": {},
# "status": "Failure",
# "message": "ConfigMap.core \"failure\" is invalid: data.key: Invalid value: \"integer\": data.key in body must be of type string: \"integer\"",
# "reason": "Invalid",
# "details": {
# "name": "failure",
# "group": "core",
# "kind": "ConfigMap",
# "causes": [
# {
# "reason": "FieldValueTypeInvalid",
# "message": "Invalid value: \"integer\": data.key in body must be of type string: \"integer\"",
# "field": "data.key"
# }
# ]
# },
# "code": 422
# }
apiVersion: v1
kind: ConfigMap
metadata:
name: failure
data:
key: 123