github.com/Thanhphan1147/cloudfoundry-cli@v7.1.0+incompatible/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) InterpolateAndParse(pathToManifest string, pathsToVarsFiles []string, vars []template.VarKV) (Manifest, error) {
    22  	rawManifest, err := ioutil.ReadFile(pathToManifest)
    23  	if err != nil {
    24  		return Manifest{}, 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 Manifest{}, ioerr
    34  		}
    35  
    36  		var sv template.StaticVariables
    37  
    38  		err = yaml.Unmarshal(rawVarsFile, &sv)
    39  		if err != nil {
    40  			return Manifest{}, 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 Manifest{}, InterpolationError{Err: err}
    55  	}
    56  
    57  	var parsedManifest Manifest
    58  	err = yaml.Unmarshal(rawManifest, &parsedManifest)
    59  	if err != nil {
    60  		return Manifest{}, &yaml.TypeError{}
    61  	}
    62  
    63  	if len(parsedManifest.Applications) == 0 {
    64  		return Manifest{}, errors.New("Manifest must have at least one application.")
    65  	}
    66  
    67  	parsedManifest.PathToManifest = pathToManifest
    68  
    69  	return parsedManifest, nil
    70  }
    71  
    72  func (m ManifestParser) MarshalManifest(manifest Manifest) ([]byte, error) {
    73  	return yaml.Marshal(manifest)
    74  }