forked from cloudfoundry-attic/bosh-init
-
Notifications
You must be signed in to change notification settings - Fork 0
/
erb_renderer.go
95 lines (76 loc) · 2.15 KB
/
erb_renderer.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
90
91
92
93
94
95
package erbrenderer
import (
"encoding/json"
"path/filepath"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
type ERBRenderer interface {
Render(srcPath, dstPath string, context TemplateEvaluationContext) error
}
type erbRenderer struct {
fs boshsys.FileSystem
runner boshsys.CmdRunner
logger boshlog.Logger
logTag string
rendererScript string
}
func NewERBRenderer(
fs boshsys.FileSystem,
runner boshsys.CmdRunner,
logger boshlog.Logger,
) ERBRenderer {
return erbRenderer{
fs: fs,
runner: runner,
logger: logger,
logTag: "erbRenderer",
rendererScript: templateEvaluationContextRb,
}
}
func (r erbRenderer) Render(srcPath, dstPath string, context TemplateEvaluationContext) error {
r.logger.Debug(r.logTag, "Rendering template %s", dstPath)
tmpDir, err := r.fs.TempDir("erb-renderer")
if err != nil {
return bosherr.WrapError(err, "Creating temporary directory")
}
defer r.fs.RemoveAll(tmpDir)
rendererScriptPath := filepath.Join(tmpDir, "erb-render.rb")
err = r.writeRendererScript(rendererScriptPath)
if err != nil {
return err
}
contextPath := filepath.Join(tmpDir, "erb-context.json")
err = r.writeContext(contextPath, context)
if err != nil {
return err
}
command := boshsys.Command{
Name: "ruby",
Args: []string{rendererScriptPath, contextPath, srcPath, dstPath},
}
_, _, _, err = r.runner.RunComplexCommand(command)
if err != nil {
return bosherr.WrapError(err, "Running ruby to render templates")
}
return nil
}
func (r erbRenderer) writeRendererScript(scriptPath string) error {
err := r.fs.WriteFileString(scriptPath, r.rendererScript)
if err != nil {
return bosherr.WrapError(err, "Writing renderer script")
}
return nil
}
func (r erbRenderer) writeContext(contextPath string, context TemplateEvaluationContext) error {
contextBytes, err := json.Marshal(context)
if err != nil {
return bosherr.WrapError(err, "Marshalling context")
}
err = r.fs.WriteFileString(contextPath, string(contextBytes))
if err != nil {
return bosherr.WrapError(err, "Writing context")
}
return nil
}