github.com/google/yamlfmt@v0.12.2-0.20240514121411-7f77800e2681/feature.go (about)

     1  // Copyright 2022 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package yamlfmt
    16  
    17  import "fmt"
    18  
    19  type FeatureFunc func([]byte) ([]byte, error)
    20  
    21  type Feature struct {
    22  	Name         string
    23  	BeforeAction FeatureFunc
    24  	AfterAction  FeatureFunc
    25  }
    26  
    27  type FeatureList []Feature
    28  
    29  type FeatureApplyMode string
    30  
    31  var (
    32  	FeatureApplyBefore FeatureApplyMode = "Before"
    33  	FeatureApplyAfter  FeatureApplyMode = "After"
    34  )
    35  
    36  type FeatureApplyError struct {
    37  	err         error
    38  	featureName string
    39  	mode        FeatureApplyMode
    40  }
    41  
    42  func (e *FeatureApplyError) Error() string {
    43  	return fmt.Sprintf("Feature %s %sAction failed with error: %v", e.featureName, e.mode, e.err)
    44  }
    45  
    46  func (e *FeatureApplyError) Unwrap() error {
    47  	return e.err
    48  }
    49  
    50  func (fl FeatureList) ApplyFeatures(input []byte, mode FeatureApplyMode) ([]byte, error) {
    51  	// Declare err here so the result variable doesn't get shadowed in the loop
    52  	var err error
    53  	result := make([]byte, len(input))
    54  	copy(result, input)
    55  	for _, feature := range fl {
    56  		if mode == FeatureApplyBefore {
    57  			if feature.BeforeAction != nil {
    58  				result, err = feature.BeforeAction(result)
    59  			}
    60  		} else {
    61  			if feature.AfterAction != nil {
    62  				result, err = feature.AfterAction(result)
    63  			}
    64  		}
    65  
    66  		if err != nil {
    67  			return nil, &FeatureApplyError{
    68  				err:         err,
    69  				featureName: feature.Name,
    70  				mode:        mode,
    71  			}
    72  		}
    73  	}
    74  	return result, nil
    75  }