github.com/VMitov/casper@v0.4.0/build.go (about)

     1  package casper
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"io/ioutil"
     7  	"text/template"
     8  
     9  	"github.com/miracl/casper/source"
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  var funcMap = template.FuncMap{
    14  	"last":    isLast,
    15  	"notLast": isNotLast,
    16  	"quote":   quote,
    17  }
    18  
    19  // BuildConfig represent a configuration.
    20  type BuildConfig struct {
    21  	Template io.Reader
    22  	Source   source.Getter
    23  }
    24  
    25  // Build creates the config based on the template and the environment files.
    26  func (c BuildConfig) Build() ([]byte, error) {
    27  	// compile the template for the config
    28  	cfgTmplBody, err := ioutil.ReadAll(c.Template)
    29  	if err != nil {
    30  		return nil, errors.Wrap(err, "reading template failed")
    31  	}
    32  
    33  	cfgTmpl, err := template.New("config").
    34  		Funcs(funcMap).
    35  		Parse(string(cfgTmplBody))
    36  	if err != nil {
    37  		return nil, errors.Wrap(err, "template error")
    38  	}
    39  
    40  	var cfg bytes.Buffer
    41  	if err := cfgTmpl.Execute(&cfg, c.Source.Get()); err != nil {
    42  		return nil, errors.Wrap(err, "executing template failed")
    43  	}
    44  
    45  	// convert to string
    46  	cfgStr, err := ioutil.ReadAll(&cfg)
    47  	if err != nil {
    48  		return nil, errors.Wrap(err, "serializing template to string failed")
    49  	}
    50  
    51  	return cfgStr, nil
    52  }