This repository has been archived by the owner on Mar 24, 2022. It is now read-only.
forked from cppforlife/bosh-provisioner
/
render_properties.go
80 lines (64 loc) · 2.11 KB
/
render_properties.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
package erbrenderer
import (
"encoding/json"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
"bytes"
bpdep "github.com/cppforlife/bosh-provisioner/deployment"
bpreljob "github.com/cppforlife/bosh-provisioner/release/job"
)
type RenderProperties struct {
relJob bpreljob.Job
instance bpdep.Instance
}
func NewRenderProperties(relJob bpreljob.Job, instance bpdep.Instance) RenderProperties {
return RenderProperties{relJob: relJob, instance: instance}
}
// AsMap returns job and instance properties merged together.
func (p RenderProperties) AsMap() (map[string]interface{}, error) {
result, err := p.deepCopyInstanceProperties()
if err != nil {
return result, err
}
for _, prop := range p.relJob.Properties {
p.copyProperty(prop.Name, prop.Default, result)
}
return result, nil
}
// copyProperty fills in property in dst with value if it's not already set.
func (p RenderProperties) copyProperty(path string, value interface{}, dst map[string]interface{}) {
pathParts := strings.Split(path, ".")
for i, part := range pathParts {
if dstNested, ok := dst[part]; ok { // Found section; check if modified
if dstNestedMap, ok := dstNested.(map[string]interface{}); ok {
dst = dstNestedMap
} else {
break // Not a section; cannot modify
}
} else if len(pathParts)-1 == i { // Last property path part
dst[part] = value
} else {
m := map[string]interface{}{}
dst[part] = m
dst = m
}
}
}
// deepCopyInstanceProperties makes a deep copy of instance properties.
// Always returns an initialized map even if instance properties are nil.
func (p RenderProperties) deepCopyInstanceProperties() (map[string]interface{}, error) {
result := map[string]interface{}{}
if p.instance.Properties == nil {
return result, nil
}
b, err := json.Marshal(p.instance.Properties)
if err != nil {
return result, bosherr.WrapError(err, "Marshalling instance properties")
}
decoder := json.NewDecoder(bytes.NewReader(b))
decoder.UseNumber()
if err := decoder.Decode(&result); err != nil {
return result, bosherr.WrapError(err, "Unmarshalling instance properties")
}
return result, nil
}