1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
|
package interpolate
import (
"fmt"
"reflect"
"strings"
"sync"
"github.com/mitchellh/mapstructure"
"github.com/mitchellh/reflectwalk"
)
// RenderFilter is an option for filtering what gets rendered and
// doesn't within an interface.
type RenderFilter struct {
Include []string
Exclude []string
once sync.Once
excludeSet map[string]struct{}
includeSet map[string]struct{}
}
// RenderMap renders all the strings in the given interface. The
// interface must decode into a map[string]interface{}, but is left
// as an interface{} type to ease backwards compatibility with the way
// arguments are passed around in Packer.
func RenderMap(v interface{}, ctx *Context, f *RenderFilter) (map[string]interface{}, error) {
// First decode it into the map
var m map[string]interface{}
if err := mapstructure.Decode(v, &m); err != nil {
return nil, err
}
// Now go through each value and render it
for k, raw := range m {
// Always validate every field
if err := ValidateInterface(raw, ctx); err != nil {
return nil, fmt.Errorf("invalid '%s': %s", k, err)
}
if !f.include(k) {
continue
}
raw, err := RenderInterface(raw, ctx)
if err != nil {
return nil, fmt.Errorf("render '%s': %s", k, err)
}
m[k] = raw
}
return m, nil
}
// RenderInterface renders any value and returns the resulting value.
func RenderInterface(v interface{}, ctx *Context) (interface{}, error) {
f := func(v string) (string, error) {
return Render(v, ctx)
}
walker := &renderWalker{
F: f,
Replace: true,
}
err := reflectwalk.Walk(v, walker)
if err != nil {
return nil, err
}
if walker.Top != nil {
v = walker.Top
}
return v, nil
}
// ValidateInterface renders any value and returns the resulting value.
func ValidateInterface(v interface{}, ctx *Context) error {
f := func(v string) (string, error) {
return v, Validate(v, ctx)
}
walker := &renderWalker{
F: f,
Replace: false,
}
err := reflectwalk.Walk(v, walker)
if err != nil {
return err
}
return nil
}
// Include checks whether a key should be included.
func (f *RenderFilter) include(k string) bool {
if f == nil {
return true
}
k = strings.ToLower(k)
f.once.Do(f.init)
if len(f.includeSet) > 0 {
_, ok := f.includeSet[k]
return ok
}
if len(f.excludeSet) > 0 {
_, ok := f.excludeSet[k]
return !ok
}
return true
}
func (f *RenderFilter) init() {
f.includeSet = make(map[string]struct{})
for _, v := range f.Include {
f.includeSet[strings.ToLower(v)] = struct{}{}
}
f.excludeSet = make(map[string]struct{})
for _, v := range f.Exclude {
f.excludeSet[strings.ToLower(v)] = struct{}{}
}
}
// renderWalker implements interfaces for the reflectwalk package
// (github.com/mitchellh/reflectwalk) that can be used to automatically
// execute a callback for an interpolation.
type renderWalker struct {
// F is the function to call for every interpolation. It can be nil.
//
// If Replace is true, then the return value of F will be used to
// replace the interpolation.
F renderWalkerFunc
Replace bool
// ContextF is an advanced version of F that also receives the
// location of where it is in the structure. This lets you do
// context-aware validation.
ContextF renderWalkerContextFunc
// Top is the top value of the walk. This might get replaced if the
// top value needs to be modified. It is valid to read after any walk.
// If it is nil, it means the top wasn't replaced.
Top interface{}
key []string
lastValue reflect.Value
loc reflectwalk.Location
cs []reflect.Value
csKey []reflect.Value
csData interface{}
sliceIndex int
unknownKeys []string
}
// renderWalkerFunc is the callback called by interpolationWalk.
// It is called with any interpolation found. It should return a value
// to replace the interpolation with, along with any errors.
//
// If Replace is set to false in renderWalker, then the replace
// value can be anything as it will have no effect.
type renderWalkerFunc func(string) (string, error)
// renderWalkerContextFunc is called by interpolationWalk if
// ContextF is set. This receives both the interpolation and the location
// where the interpolation is.
//
// This callback can be used to validate the location of the interpolation
// within the configuration.
type renderWalkerContextFunc func(reflectwalk.Location, string)
func (w *renderWalker) Enter(loc reflectwalk.Location) error {
w.loc = loc
return nil
}
func (w *renderWalker) Exit(loc reflectwalk.Location) error {
w.loc = reflectwalk.None
switch loc {
case reflectwalk.Map:
w.cs = w.cs[:len(w.cs)-1]
case reflectwalk.MapValue:
w.key = w.key[:len(w.key)-1]
w.csKey = w.csKey[:len(w.csKey)-1]
case reflectwalk.Slice:
// Split any values that need to be split
w.cs = w.cs[:len(w.cs)-1]
case reflectwalk.SliceElem:
w.csKey = w.csKey[:len(w.csKey)-1]
}
return nil
}
func (w *renderWalker) Map(m reflect.Value) error {
w.cs = append(w.cs, m)
return nil
}
func (w *renderWalker) MapElem(m, k, v reflect.Value) error {
w.csData = k
w.csKey = append(w.csKey, k)
w.key = append(w.key, k.String())
w.lastValue = v
return nil
}
func (w *renderWalker) Slice(s reflect.Value) error {
w.cs = append(w.cs, s)
return nil
}
func (w *renderWalker) SliceElem(i int, elem reflect.Value) error {
w.csKey = append(w.csKey, reflect.ValueOf(i))
w.sliceIndex = i
return nil
}
func (w *renderWalker) Primitive(v reflect.Value) error {
setV := v
// We only care about strings
if v.Kind() == reflect.Interface {
setV = v
v = v.Elem()
}
if v.Kind() != reflect.String {
return nil
}
strV := v.String()
if w.ContextF != nil {
w.ContextF(w.loc, strV)
}
if w.F == nil {
return nil
}
replaceVal, err := w.F(strV)
if err != nil {
return fmt.Errorf(
"%s in:\n\n%s",
err, v.String())
}
if w.Replace {
resultVal := reflect.ValueOf(replaceVal)
switch w.loc {
case reflectwalk.MapKey:
m := w.cs[len(w.cs)-1]
// Delete the old value
var zero reflect.Value
m.SetMapIndex(w.csData.(reflect.Value), zero)
// Set the new key with the existing value
m.SetMapIndex(resultVal, w.lastValue)
// Set the key to be the new key
w.csData = resultVal
case reflectwalk.MapValue:
// If we're in a map, then the only way to set a map value is
// to set it directly.
m := w.cs[len(w.cs)-1]
mk := w.csData.(reflect.Value)
m.SetMapIndex(mk, resultVal)
case reflectwalk.WalkLoc:
// At the root element, we can't write that, so we just save it
w.Top = resultVal.Interface()
default:
// Otherwise, we should be addressable
setV.Set(resultVal)
}
}
return nil
}
func (w *renderWalker) removeCurrent() {
// Append the key to the unknown keys
w.unknownKeys = append(w.unknownKeys, strings.Join(w.key, "."))
for i := 1; i <= len(w.cs); i++ {
c := w.cs[len(w.cs)-i]
switch c.Kind() {
case reflect.Map:
// Zero value so that we delete the map key
var val reflect.Value
// Get the key and delete it
k := w.csData.(reflect.Value)
c.SetMapIndex(k, val)
return
}
}
panic("No container found for removeCurrent")
}
func (w *renderWalker) replaceCurrent(v reflect.Value) {
c := w.cs[len(w.cs)-2]
switch c.Kind() {
case reflect.Map:
// Get the key and delete it
k := w.csKey[len(w.csKey)-1]
c.SetMapIndex(k, v)
}
}
|