github.com/DaAlbrecht/cf-cli@v0.0.0-20231128151943-1fe19bb400b9/util/manifestparser/parser.go (about)

     1  package manifestparser
     2  
     3  import (
     4  	"errors"
     5  	"io/ioutil"
     6  
     7  	"github.com/cloudfoundry/bosh-cli/director/template"
     8  	"gopkg.in/yaml.v2"
     9  )
    10  
    11  type ManifestParser struct{}
    12  
    13  // InterpolateAndParse reads the manifest at the provided paths, interpolates
    14  // variables if a vars file is provided, and sets the current manifest to the
    15  // resulting manifest.
    16  // For manifests with only 1 application, appName will override the name of the
    17  // single app defined.
    18  // For manifests with multiple applications, appName will filter the
    19  // applications and leave only a single application in the resulting parsed
    20  // manifest structure.
    21  func (m ManifestParser) InterpolateManifest(pathToManifest string, pathsToVarsFiles []string, vars []template.VarKV) ([]byte, error) {
    22  	rawManifest, err := ioutil.ReadFile(pathToManifest)
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  
    27  	tpl := template.NewTemplate(rawManifest)
    28  	fileVars := template.StaticVariables{}
    29  
    30  	for _, path := range pathsToVarsFiles {
    31  		rawVarsFile, ioerr := ioutil.ReadFile(path)
    32  		if ioerr != nil {
    33  			return nil, ioerr
    34  		}
    35  
    36  		var sv template.StaticVariables
    37  
    38  		err = yaml.Unmarshal(rawVarsFile, &sv)
    39  		if err != nil {
    40  			return nil, InvalidYAMLError{Err: err}
    41  		}
    42  
    43  		for k, v := range sv {
    44  			fileVars[k] = v
    45  		}
    46  	}
    47  
    48  	for _, kv := range vars {
    49  		fileVars[kv.Name] = kv.Value
    50  	}
    51  
    52  	rawManifest, err = tpl.Evaluate(fileVars, nil, template.EvaluateOpts{ExpectAllKeys: true})
    53  	if err != nil {
    54  		return nil, InterpolationError{Err: err}
    55  	}
    56  
    57  	return rawManifest, nil
    58  }
    59  
    60  func (m ManifestParser) ParseManifest(pathToManifest string, rawManifest []byte) (Manifest, error) {
    61  	var parsedManifest Manifest
    62  	err := yaml.Unmarshal(rawManifest, &parsedManifest)
    63  	if err != nil {
    64  		return Manifest{}, &yaml.TypeError{}
    65  	}
    66  
    67  	if len(parsedManifest.Applications) == 0 {
    68  		return Manifest{}, errors.New("Manifest must have at least one application.")
    69  	}
    70  
    71  	parsedManifest.PathToManifest = pathToManifest
    72  
    73  	return parsedManifest, nil
    74  }
    75  
    76  func (m ManifestParser) MarshalManifest(manifest Manifest) ([]byte, error) {
    77  	return yaml.Marshal(manifest)
    78  }