github.com/Datadog/cnab-go@v0.3.3-beta1.0.20191007143216-bba4b7e723d0/bundle/replacement/yamlreplacer.go (about)

     1  package replacement
     2  
     3  import (
     4  	yaml "gopkg.in/yaml.v2"
     5  )
     6  
     7  // NewYAMLReplacer creates a Replacer for YAML documents.
     8  func NewYAMLReplacer() Replacer {
     9  	return yamlReplacer{}
    10  }
    11  
    12  type yamlReplacer struct {
    13  }
    14  
    15  func (r yamlReplacer) Replace(source string, selector string, value string) (string, error) {
    16  	dict := make(map[interface{}]interface{})
    17  	err := yaml.Unmarshal([]byte(source), dict)
    18  
    19  	if err != nil {
    20  		return "", err
    21  	}
    22  
    23  	selectorPath := parseSelector(selector)
    24  	err = replaceIn(yamlDocMap(dict), selectorPath, value)
    25  	if err != nil {
    26  		return "", err
    27  	}
    28  
    29  	bytes, err := yaml.Marshal(dict)
    30  	if err != nil {
    31  		return "", err
    32  	}
    33  	return string(bytes), nil
    34  }
    35  
    36  type yamlDocMap map[interface{}]interface{}
    37  
    38  func (m yamlDocMap) get(key string) (interface{}, bool) {
    39  	e, ok := m[key]
    40  	return e, ok
    41  }
    42  
    43  func (m yamlDocMap) set(key string, value interface{}) {
    44  	m[key] = value
    45  }
    46  
    47  func (m yamlDocMap) asInstance(value interface{}) (docmap, bool) {
    48  	if e, ok := value.(map[interface{}]interface{}); ok {
    49  		return yamlDocMap(e), ok
    50  	}
    51  	return yamlDocMap{}, false
    52  }