github.phpd.cn/hashicorp/packer@v1.3.2/template/interpolate/i.go (about)

     1  package interpolate
     2  
     3  import (
     4  	"bytes"
     5  	"text/template"
     6  )
     7  
     8  // Context is the context that an interpolation is done in. This defines
     9  // things such as available variables.
    10  type Context struct {
    11  	// Data is the data for the template that is available
    12  	Data interface{}
    13  
    14  	// Funcs are extra functions available in the template
    15  	Funcs map[string]interface{}
    16  
    17  	// UserVariables is the mapping of user variables that the
    18  	// "user" function reads from.
    19  	UserVariables map[string]string
    20  
    21  	// SensitiveVariables is a list of variables to sanitize.
    22  	SensitiveVariables []string
    23  
    24  	// EnableEnv enables the env function
    25  	EnableEnv bool
    26  
    27  	// All the fields below are used for built-in functions.
    28  	//
    29  	// BuildName and BuildType are the name and type, respectively,
    30  	// of the builder being used.
    31  	//
    32  	// TemplatePath is the path to the template that this is being
    33  	// rendered within.
    34  	BuildName    string
    35  	BuildType    string
    36  	TemplatePath string
    37  }
    38  
    39  // Render is shorthand for constructing an I and calling Render.
    40  func Render(v string, ctx *Context) (string, error) {
    41  	return (&I{Value: v}).Render(ctx)
    42  }
    43  
    44  // Validate is shorthand for constructing an I and calling Validate.
    45  func Validate(v string, ctx *Context) error {
    46  	return (&I{Value: v}).Validate(ctx)
    47  }
    48  
    49  // I stands for "interpolation" and is the main interpolation struct
    50  // in order to render values.
    51  type I struct {
    52  	Value string
    53  }
    54  
    55  // Render renders the interpolation with the given context.
    56  func (i *I) Render(ctx *Context) (string, error) {
    57  	tpl, err := i.template(ctx)
    58  	if err != nil {
    59  		return "", err
    60  	}
    61  
    62  	var result bytes.Buffer
    63  	var data interface{}
    64  	if ctx != nil {
    65  		data = ctx.Data
    66  	}
    67  	if err := tpl.Execute(&result, data); err != nil {
    68  		return "", err
    69  	}
    70  
    71  	return result.String(), nil
    72  }
    73  
    74  // Validate validates that the template is syntactically valid.
    75  func (i *I) Validate(ctx *Context) error {
    76  	_, err := i.template(ctx)
    77  	return err
    78  }
    79  
    80  func (i *I) template(ctx *Context) (*template.Template, error) {
    81  	return template.New("root").Funcs(Funcs(ctx)).Parse(i.Value)
    82  }