-
Notifications
You must be signed in to change notification settings - Fork 19
/
template.go
204 lines (182 loc) · 4.57 KB
/
template.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
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
package template
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strings"
"github.com/mandelsoft/goutils/errors"
"github.com/mandelsoft/vfs/pkg/vfs"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
"github.com/open-component-model/ocm/pkg/runtime"
utils2 "github.com/open-component-model/ocm/pkg/utils"
)
type Values map[string]interface{}
type Templater interface {
Process(data string, values Values) (string, error)
}
// Options defines the options for cli templating.
type Options struct {
Default string
Mode string
UseEnv bool
Templater Templater
Vars Values
}
func (o *Options) DefaultMode() string {
if o.Default == "" {
return "subst"
}
return o.Default
}
func (o *Options) AddFlags(fs *pflag.FlagSet) {
fs.StringVarP(&o.Mode, "templater", "", o.DefaultMode(),
fmt.Sprintf("templater to use (%s)", strings.Join(DefaultRegistry().KnownTypeNames(), ", ")))
fs.BoolVarP(&o.UseEnv, "addenv", "", false, "access environment for templating")
}
func (o *Options) Complete(fs vfs.FileSystem) error {
var err error
if o.Vars == nil {
o.Vars = Values{}
}
if o.Mode == "" {
o.Mode = o.DefaultMode()
}
if o.UseEnv {
for _, v := range os.Environ() {
if i := strings.Index(v, "="); i > 0 {
value := v[i+1:]
name := strings.TrimSpace(v[0:i])
o.Vars[name] = value
}
}
}
o.Templater, err = DefaultRegistry().Create(o.Mode, fs)
if err != nil {
return err
}
return nil
}
// Usage prints out the usage for templating.
func (o *Options) Usage() string {
return `
All yaml/json defined resources can be templated.
Variables are specified as regular arguments following the syntax <code><name>=<value></code>.
Additionally settings can be specified by a yaml file using the <code>--settings <file></code>
option. With the option <code>--addenv</code> environment variables are added to the binding.
Values are overwritten in the order environment, settings file, command line settings.
Note: Variable names are case-sensitive.
Example:
<pre>
<command> <options> -- MY_VAL=test <args>
</pre>
` + Usage(DefaultRegistry())
}
// FilterSettings parses commandline argument variables.
// it returns all non variable arguments.
func (o *Options) FilterSettings(args ...string) []string {
var addArgs []string
if o.Vars == nil {
o.Vars = Values{}
}
for _, arg := range args {
if i := strings.Index(arg, "="); i > 0 {
value := arg[i+1:]
name := strings.TrimSpace(arg[0:i])
o.Vars[name] = value
continue
}
addArgs = append(addArgs, arg)
}
return addArgs
}
func (o *Options) ParseSettings(fs vfs.FileSystem, paths ...string) error {
if o.Vars == nil {
o.Vars = Values{}
}
for _, path := range paths {
vars, err := ReadYAMLSettings(fs, path)
if err != nil {
return errors.Wrapf(err, "cannot read env file %q", path)
}
for k, v := range vars {
o.Vars[k] = v
}
}
return nil
}
// Execute templates a string with the parsed vars.
func (o *Options) Execute(data string) (string, error) {
return o.Templater.Process(data, o.Vars)
}
func ReadYAMLSettings(fs vfs.FileSystem, path string) (Values, error) {
result := Values{}
data, err := utils2.ReadFile(path, fs)
if err != nil {
return nil, err
}
err = runtime.DefaultYAMLEncoding.Unmarshal(data, &result)
if err != nil {
return nil, err
}
return result, nil
}
func ReadSimpleSettings(fs vfs.FileSystem, path string) (map[string]string, error) {
var (
part []byte
prefix bool
)
result := map[string]string{}
file, err := fs.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte, 0, 1024))
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
line := strings.TrimSpace(buffer.String())
if line != "" && !strings.HasPrefix(line, "#") {
i := strings.Index(line, "=")
if i <= 0 {
return nil, errors.Newf("invalid variable syntax %q", line)
}
result[strings.TrimSpace(line[:i])] = strings.TrimSpace(line[i+1:])
}
buffer.Reset()
}
}
if errors.Is(err, io.EOF) {
err = nil
}
return result, err
}
func SplitYamlDocuments(data []byte) ([][]byte, error) {
decoder := yaml.NewDecoder(bytes.NewBuffer(data))
list := [][]byte{}
i := 0
for {
var tmp interface{}
i++
err := decoder.Decode(&tmp)
if err != nil {
if !errors.Is(err, io.EOF) {
return nil, errors.Wrapf(err, "cannot parse document %d", i)
}
break
}
out, err := yaml.Marshal(tmp)
if err != nil {
return nil, errors.Wrapf(err, "cannot marshal document %d", i)
}
list = append(list, out)
}
return list, nil
}