/
input.go
369 lines (320 loc) · 9.7 KB
/
input.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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package cogs
import (
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"github.com/drone/envsubst"
"github.com/joho/godotenv"
"github.com/mikefarah/yq/v4/pkg/yqlib"
"github.com/pelletier/go-toml"
"github.com/pkg/errors"
"gopkg.in/yaml.v3"
)
// "." - a single period is a reserved filepath string
// it is used to self-reference the cog file
// this helps avoid breaking generation when the cog file is moved or renamed
const selfPath string = "."
// readFile takes a filepath and returns the byte value of the data within
func readFile(filePath string) ([]byte, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
stats, statsErr := file.Stat()
if statsErr != nil {
return nil, statsErr
}
var size int64 = stats.Size()
bytes := make([]byte, size)
if _, err = file.Read(bytes); err != nil {
return nil, err
}
return bytes, nil
}
// envSubBytes returns a TOML string with environmental substitution applied, call tldr for more:
// $ tldr envsubst
func envSubBytes(bytes []byte) ([]byte, error) {
substEnv, err := envsubst.EvalEnv(string(bytes))
if err != nil {
return nil, err
}
return []byte(substEnv), nil
}
// kindStr maps the yaml node types to strings for error messaging
var kindStr = map[yaml.Kind]string{
0: "None",
yaml.DocumentNode: "DocumentNode",
yaml.SequenceNode: "SequenceNode",
yaml.MappingNode: "MappingNode",
yaml.ScalarNode: "ScalarNode",
yaml.AliasNode: "AliasNode",
}
// Visitor allows a query path to return the underlying value for a given visitor
type Visitor interface {
SetValue(*Link) error
Errors() []error
}
// NewJSONVisitor returns a visitor object that satisfies the Visitor interface
// attempting to turn a supposed JSON byte slice into a *yaml.Node object
func NewJSONVisitor(buf []byte) (Visitor, error) {
var i interface{}
if err := json.Unmarshal(buf, &i); err != nil {
return nil, err
}
// deserialize to yaml.Node
rootNode := &yaml.Node{}
if err := rootNode.Encode(i); err != nil {
return nil, errors.Wrap(err, "NewJSONVisitor")
}
return newVisitor(rootNode), nil
}
// NewYAMLVisitor returns a visitor object that satisfies the Visitor interface
func NewYAMLVisitor(buf []byte) (Visitor, error) {
// deserialize to yaml.Node
rootNode := &yaml.Node{}
if err := yaml.Unmarshal(buf, rootNode); err != nil {
return nil, errors.Wrap(err, "NewYAMLVisitor")
}
return newVisitor(rootNode), nil
}
// NewTOMLVisitor returns a visitor object that satisfies the Visitor interface
// attempting to turn a supposed TOML byte slice into a *yaml.Node object
func NewTOMLVisitor(buf []byte) (Visitor, error) {
var i interface{}
if err := toml.Unmarshal(buf, &i); err != nil {
return nil, errors.Wrap(err, "NewTOMLVisitor")
}
// deserialize to yaml.Node
rootNode := &yaml.Node{}
if err := rootNode.Encode(i); err != nil {
return nil, err
}
return newVisitor(rootNode), nil
}
// NewDotenvVisitor returns a visitor object that satisfies the Visitor interface
// attempting to turn a supposed dotenv byte slice into a *yaml.Node object
func NewDotenvVisitor(buf []byte) (Visitor, error) {
tempMap, err := godotenv.Unmarshal(string(buf))
if err != nil {
return nil, err
}
// deserialize to yaml.Node
rootNode := &yaml.Node{}
if err := rootNode.Encode(tempMap); err != nil {
return nil, err
}
return newVisitor(rootNode), nil
}
func newVisitor(node *yaml.Node) Visitor {
return &visitor{
rootNode: node,
visited: make(map[string]map[string]interface{}),
visitedComplex: make(map[string]interface{}),
evaluator: yqlib.NewAllAtOnceEvaluator(),
missing: make(map[string][]string), // denotes links unable to be found
}
}
type visitor struct {
rootNode *yaml.Node
visited map[string]map[string]interface{}
visitedComplex map[string]interface{}
evaluator yqlib.Evaluator
missing map[string][]string // denotes links unable to be found
}
func (vi *visitor) Errors() []error {
var errs []error
for k, v := range vi.missing {
errMsg := k + ":"
sort.Strings(v)
errMsg = errMsg + "\n " + strings.Join(v, "\n ")
// do not call errors.New because we do not want a
// stack trace to be emitted when "%+v" is called on each error
errs = append(errs, fmt.Errorf(errMsg))
}
if len(errs) > 0 {
return errs
}
return nil
}
func (vi *visitor) getLink(link *Link, searchMap map[string]interface{}) (interface{}, bool) {
if value, ok := searchMap[link.SearchName]; ok {
return value, ok
}
// link is unable to be found in the searchMap at this point
subPath := "."
if link.SubPath != "" {
subPath = link.SubPath
}
errKey := fmt.Sprintf("[%q, %q]", link.Path, subPath)
errVal := fmt.Sprintf("unable to find key %q", link.SearchName)
if !InList(errVal, vi.missing[errKey]) {
vi.missing[errKey] = append(vi.missing[errKey], errVal)
}
return nil, false
}
// SetValue assigns the Value for a given Link using the existing Link.Path and Link.SubPath
func (vi *visitor) SetValue(link *Link) (err error) {
// 1. check if the read type is "complex{}"
if link.readType.isComplex() {
return vi.visitComplex(link)
}
// 2. check if link.SubPath value has been used in a previous SetValue call
if flatMap, ok := vi.visited[link.SubPath]; ok {
if link.Value, ok = vi.getLink(link, flatMap); !ok {
return nil
}
if !IsSimpleValue(link.Value) {
return fmt.Errorf("%s of type %T is not a simple value", link.SearchName, link.Value)
}
return nil
}
// 3. grab the yaml node corresponding to the subpath
node, err := vi.get(link.SubPath)
if err != nil {
return err
}
supportedKind := func() bool {
for _, kind := range []yaml.Kind{yaml.MappingNode, yaml.ScalarNode, yaml.SequenceNode, yaml.DocumentNode} {
if node.Kind == kind {
return true
}
}
return false
}()
if !supportedKind {
return fmt.Errorf("%s: NodeKind/readType unsupported: %s/%s",
link.SearchName, kindStr[node.Kind], link.readType)
}
cachedMap := make(map[string]interface{})
// 4. traverse node based on read type
switch link.readType {
case deferred:
err = node.Decode(cachedMap)
case rJSON, rYAML, rTOML:
err = visitMap(cachedMap, node, link.readType)
case rDotenv:
err = visitDotenv(cachedMap, node)
default:
err = fmt.Errorf("unsupported readType: %s", link.readType)
}
if err != nil {
return errors.Wrap(err, "SetValue")
}
// 5. add value to cache
vi.visited[link.SubPath] = cachedMap
// 6. recurse to access cache
return vi.SetValue(link)
}
// visitComplex handles the rWhole and rJSONComplex read types
func (vi *visitor) visitComplex(link *Link) (err error) {
// 1. check if link.SubPath and readType has been used before
if v, ok := vi.visitedComplex[link.SubPath]; ok {
if link.readType == rWhole {
link.Value = v
return nil
}
complexMap, ok := v.(map[string]interface{})
if !ok {
return fmt.Errorf("path does not resolve to a map: %T", v)
}
if link.Value, ok = vi.getLink(link, complexMap); !ok {
return fmt.Errorf("unable to find %s", link.SearchName)
}
if IsSimpleValue(link.Value) {
return fmt.Errorf("%s of type %T is not a complex value", link.SearchName, link.Value)
}
return nil
}
// 2. grab the yaml node corresponding to the subpath
node, err := vi.get(link.SubPath)
if err != nil {
return err
}
// 3. traverse node based on read type
var i interface{}
switch link.readType {
case rWhole:
err = node.Decode(&i)
case rJSONComplex, rTOMLComplex:
i = make(map[string]interface{})
err = visitComplex(i.(map[string]interface{}), node, link.readType)
default:
err = fmt.Errorf("unsupported readType: %s", link.readType)
}
if err != nil {
return errors.Wrap(err, "visitComplex")
}
// 4. add value to cache
vi.visitedComplex[link.SubPath] = i
// 5. recurse to access cache
return vi.SetValue(link)
}
func (vi *visitor) get(subPath string) (*yaml.Node, error) {
list, err := vi.evaluator.EvaluateNodes(subPath, vi.rootNode)
if err != nil {
return nil, err
}
nodes := []*yqlib.CandidateNode{}
for el := list.Front(); el != nil; el = el.Next() {
n := el.Value.(*yqlib.CandidateNode)
nodes = append(nodes, n)
}
// should only match a single node
if len(nodes) != 1 {
return nil, fmt.Errorf("returned non singular result for path '%s'", subPath)
}
return nodes[0].Node, nil
}
func visitDotenv(cache map[string]interface{}, node *yaml.Node) (err error) {
var strEnv string
if err = node.Decode(&strEnv); err != nil {
var sliceEnv []string
if err := node.Decode(&sliceEnv); err != nil {
return fmt.Errorf("unable to decode node kind %s to dotenv format: %w", kindStr[node.Kind], err)
}
strEnv = strings.Join(sliceEnv, "\n")
}
dotenvMap, err := godotenv.Unmarshal(strEnv)
if err != nil {
return err
}
for k, v := range dotenvMap {
cache[k] = v
}
return err
}
func visitMap(cache map[string]interface{}, node *yaml.Node, rType ReadType) error {
if err := node.Decode(&cache); err == nil {
return nil
}
var strEnv string
if err := node.Decode(&strEnv); err != nil {
var sliceEnv []string
if err := node.Decode(&sliceEnv); err != nil {
return fmt.Errorf("unable to decode node kind: %s to flat JSON format", kindStr[node.Kind])
}
strEnv = strings.Join(sliceEnv, "\n")
}
unmarshal, err := rType.getUnmarshal()
if err != nil {
return errors.Wrap(err, "visitMap")
}
return unmarshal([]byte(strEnv), &cache)
}
func visitComplex(cache map[string]interface{}, node *yaml.Node, rType ReadType) error {
if err := node.Decode(&cache); err == nil {
return nil
}
var strEnv string
if err := node.Decode(&strEnv); err != nil {
return fmt.Errorf("unable to decode node kind: %s to complex JSON format: %w", kindStr[node.Kind], err)
}
unmarshal, err := rType.getUnmarshal()
if err != nil {
return fmt.Errorf("visitComplex: %w", err)
}
return unmarshal([]byte(strEnv), &cache)
}