...

Source file src/sigs.k8s.io/cli-utils/pkg/object/validation/collector.go

Documentation: sigs.k8s.io/cli-utils/pkg/object/validation

     1  // Copyright 2021 The Kubernetes Authors.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package validation
     5  
     6  import (
     7  	"errors"
     8  
     9  	"sigs.k8s.io/cli-utils/pkg/multierror"
    10  	"sigs.k8s.io/cli-utils/pkg/object"
    11  )
    12  
    13  // Collector simplifies collecting validation errors from multiple sources and
    14  // extracting the IDs of the invalid objects.
    15  type Collector struct {
    16  	Errors     []error
    17  	InvalidIds object.ObjMetadataSet
    18  }
    19  
    20  // Collect unwraps MultiErrors, adds them to Errors, extracts invalid object
    21  // IDs from validation.Error, and adds them to InvalidIds.
    22  func (c *Collector) Collect(err error) {
    23  	errs := multierror.Unwrap(err)
    24  	c.InvalidIds = c.InvalidIds.Union(extractInvalidIds(errs))
    25  	c.Errors = append(c.Errors, errs...)
    26  }
    27  
    28  // ToError returns the list of errors as a single error.
    29  func (c *Collector) ToError() error {
    30  	return multierror.Wrap(c.Errors...)
    31  }
    32  
    33  // FilterInvalidObjects returns a set of objects that does not contain any
    34  // invalid objects, based on the collected InvalidIds.
    35  func (c *Collector) FilterInvalidObjects(objs object.UnstructuredSet) object.UnstructuredSet {
    36  	var diff object.UnstructuredSet
    37  	for _, obj := range objs {
    38  		if !c.InvalidIds.Contains(object.UnstructuredToObjMetadata(obj)) {
    39  			diff = append(diff, obj)
    40  		}
    41  	}
    42  	return diff
    43  }
    44  
    45  // FilterInvalidIds returns a set of object ID that does not contain any
    46  // invalid IDs, based on the collected InvalidIds.
    47  func (c *Collector) FilterInvalidIds(ids object.ObjMetadataSet) object.ObjMetadataSet {
    48  	return ids.Diff(c.InvalidIds)
    49  }
    50  
    51  // extractInvalidIds extracts invalid object IDs from a list of possible
    52  // validation.Error.
    53  func extractInvalidIds(errs []error) object.ObjMetadataSet {
    54  	var invalidIds object.ObjMetadataSet
    55  	for _, err := range errs {
    56  		// unwrap recursively looking for a validation.Error
    57  		var vErr *Error
    58  		if errors.As(err, &vErr) {
    59  			invalidIds = invalidIds.Union(vErr.Identifiers())
    60  		}
    61  	}
    62  	return invalidIds
    63  }
    64  

View as plain text