Skip to content

Commit

Permalink
refactor, improvements: DecodeFile YAML decoder (#167)
Browse files Browse the repository at this point in the history
- Refactor logger initialisation and document decoding to fail fast and return errors immediately
- Enhanced empty doc check
- Add comment to the function
  • Loading branch information
art-tapin committed Jun 15, 2023
1 parent aa18804 commit f2d1ee1
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions pkg/common/yaml_decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"io"

"github.com/go-logr/logr"
Expand All @@ -14,11 +15,17 @@ import (

type DecodeCallback = func(runtime.Object) error

// DecodeFile decodes the provided file data (encoded YAML documents) into Kubernetes objects using the specified scheme,
// and invokes the callback function for each decoded object. Returns an error if any decoding error occurs.
func DecodeFile(ctx context.Context, fileData []byte, scheme *runtime.Scheme, cb DecodeCallback) error {
logger, _ := logr.FromContext(ctx)
logger, logErr := logr.FromContext(ctx)
codec := serializer.NewCodecFactory(scheme)
decoder := codec.UniversalDeserializer()

if logErr != nil {
return logErr
}

// the maximum size used to buffer a doc 5M
buf := make([]byte, 5*1024*1024)
docDecoder := yaml.NewDocumentDecoder(io.NopCloser(bytes.NewReader(fileData)))
Expand All @@ -32,16 +39,16 @@ func DecodeFile(ctx context.Context, fileData []byte, scheme *runtime.Scheme, cb
return err
}

if n == 0 {
// empty docs
if n == 0 || string(fileData) == "---" {
// Skip empty docs
continue
}

docData := buf[:n]
obj, _, err := decoder.Decode(docData, nil, nil)
if err != nil {
logger.Info("Document decode error", "error", err)
continue
return fmt.Errorf("failed to decode document: %w", err)
}

err = cb(obj)
Expand Down

0 comments on commit f2d1ee1

Please sign in to comment.