/
interpolation.go
89 lines (71 loc) · 1.69 KB
/
interpolation.go
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
package interpolation
import (
"fmt"
"github.com/aanand/compose-file/template"
"github.com/aanand/compose-file/types"
)
func Interpolate(config types.Dict, section string, mapping template.Mapping) (types.Dict, error) {
out := types.Dict{}
for name, item := range config {
if item == nil {
out[name] = nil
continue
}
interpolatedItem, err := interpolateSectionItem(name, item.(types.Dict), section, mapping)
if err != nil {
return nil, err
}
out[name] = interpolatedItem
}
return out, nil
}
func interpolateSectionItem(
name string,
item types.Dict,
section string,
mapping template.Mapping,
) (types.Dict, error) {
out := types.Dict{}
for key, value := range item {
interpolatedValue, err := recursiveInterpolate(value, mapping)
if err != nil {
return nil, fmt.Errorf(
"Invalid interpolation format for %#v option in %s %#v: %#v",
key, section, name, err.Template,
)
}
out[key] = interpolatedValue
}
return out, nil
}
func recursiveInterpolate(
value interface{},
mapping template.Mapping,
) (interface{}, *template.InvalidTemplateError) {
switch value := value.(type) {
case string:
return template.Substitute(value, mapping)
case types.Dict:
out := types.Dict{}
for key, elem := range value {
interpolatedElem, err := recursiveInterpolate(elem, mapping)
if err != nil {
return nil, err
}
out[key] = interpolatedElem
}
return out, nil
case []interface{}:
out := make([]interface{}, len(value))
for i, elem := range value {
interpolatedElem, err := recursiveInterpolate(elem, mapping)
if err != nil {
return nil, err
}
out[i] = interpolatedElem
}
return out, nil
default:
return value, nil
}
}