github.com/amplia-iiot/yutil@v1.0.1-0.20231229120411-5d96a4c5a136/pkg/merge/content.go (about)

     1  /*
     2  Copyright (c) 2021 amplia-iiot
     3  
     4  Permission is hereby granted, free of charge, to any person obtaining a copy
     5  of this software and associated documentation files (the "Software"), to deal
     6  in the Software without restriction, including without limitation the rights
     7  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     8  copies of the Software, and to permit persons to whom the Software is
     9  furnished to do so, subject to the following conditions:
    10  
    11  The above copyright notice and this permission notice shall be included in all
    12  copies or substantial portions of the Software.
    13  
    14  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    15  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    16  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    17  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    18  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    19  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    20  SOFTWARE.
    21  */
    22  
    23  package merge
    24  
    25  import (
    26  	"errors"
    27  
    28  	"github.com/amplia-iiot/yutil/internal/yaml"
    29  )
    30  
    31  // MergeContents returns the result of merging two yaml contents. A yaml leaf
    32  // node in the 'changes' content takes precedence over and replaces the value in
    33  // the 'base' content.
    34  func MergeContents(base string, changes string) (string, error) {
    35  	baseData, err := yaml.Parse(base)
    36  	if err != nil {
    37  		return "", err
    38  	}
    39  	changesData, err := yaml.Parse(changes)
    40  	if err != nil {
    41  		return "", err
    42  	}
    43  	mergedData, err := yaml.Merge(baseData, changesData)
    44  	if err != nil {
    45  		return "", err
    46  	}
    47  	return yaml.Compose(mergedData)
    48  }
    49  
    50  // MergeAllContents returns the result of merging all yaml contents, which should
    51  // be ordered in ascending level of importance in the hierarchy. A yaml leaf node
    52  // in the last content takes precedence over and replaces the value in any
    53  // previous content.
    54  func MergeAllContents(contents []string) (string, error) {
    55  	if len(contents) < 2 {
    56  		return "", errors.New("slice must contain at least two contents")
    57  	}
    58  	var result string
    59  	var err error
    60  	result = contents[0]
    61  	for i := 1; i < len(contents); i++ {
    62  		result, err = MergeContents(result, contents[i])
    63  		if err != nil {
    64  			return "", err
    65  		}
    66  	}
    67  	return result, nil
    68  }