github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/util/yaml.go (about)

     1  package util
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  
     7  	"github.com/pkg/errors"
     8  
     9  	"gopkg.in/yaml.v2"
    10  )
    11  
    12  // ReadYAMLInto reads data for the given io.ReadCloser - until it hits an error
    13  // or reaches EOF - and attempts to unmarshal the data read into the given
    14  // interface.
    15  func ReadYAMLInto(r io.ReadCloser, data interface{}) error {
    16  	defer r.Close()
    17  	bytes, err := ioutil.ReadAll(r)
    18  	if err != nil {
    19  		return err
    20  	}
    21  	return yaml.Unmarshal(bytes, data)
    22  }
    23  
    24  // UnmarshalYAMLFile reads in the specified file, and unmarshals it
    25  // into the given interface. Returns an error if one is encountered
    26  // in reading the file or if the file does not contain valid YAML.
    27  func UnmarshalYAMLFile(file string, data interface{}) error {
    28  	fileBytes, err := ioutil.ReadFile(file)
    29  	if err != nil {
    30  		return errors.Wrapf(err, "error reading file %v", file)
    31  	}
    32  	if err = yaml.Unmarshal(fileBytes, data); err != nil {
    33  		return errors.Wrapf(err, "error unmarshalling yaml from %v", file)
    34  	}
    35  	return nil
    36  }