github.com/google/yamlfmt@v0.12.2-0.20240514121411-7f77800e2681/formatters/basic/features.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 basic
    16  
    17  import (
    18  	"github.com/braydonk/yaml"
    19  	"github.com/google/yamlfmt"
    20  	"github.com/google/yamlfmt/formatters/basic/anchors"
    21  	"github.com/google/yamlfmt/internal/hotfix"
    22  )
    23  
    24  func ConfigureFeaturesFromConfig(config *Config) yamlfmt.FeatureList {
    25  	features := []yamlfmt.Feature{}
    26  	if config.RetainLineBreaks || config.RetainLineBreaksSingle {
    27  		lineSep, err := config.LineEnding.Separator()
    28  		if err != nil {
    29  			lineSep = "\n"
    30  		}
    31  		featLineBreak := hotfix.MakeFeatureRetainLineBreak(lineSep, config.RetainLineBreaksSingle)
    32  		features = append(features, featLineBreak)
    33  	}
    34  	return features
    35  }
    36  
    37  // These features will directly use the `yaml.Node` type and
    38  // as such are specific to this formatter.
    39  type YAMLFeatureFunc func(yaml.Node) error
    40  type YAMLFeatureList []YAMLFeatureFunc
    41  
    42  func (y YAMLFeatureList) ApplyFeatures(node yaml.Node) error {
    43  	for _, f := range y {
    44  		if err := f(node); err != nil {
    45  			return err
    46  		}
    47  	}
    48  	return nil
    49  }
    50  
    51  func ConfigureYAMLFeaturesFromConfig(config *Config) YAMLFeatureList {
    52  	var features YAMLFeatureList
    53  	if config.DisallowAnchors {
    54  		features = append(features, anchors.Check)
    55  	}
    56  	return features
    57  }