-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterp.go
More file actions
500 lines (485 loc) · 11.9 KB
/
interp.go
File metadata and controls
500 lines (485 loc) · 11.9 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package ox
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"fmt"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"unicode"
"github.com/xo/ox/strcase"
)
var (
// DefaultLookup retrieves keys from the [Context]'s config loaders.
DefaultLookup = func(ctx *Context, typ ConfigType, key string) (any, error) {
if ctx.Override != nil {
switch v, ok, err := ctx.Override(typ, key); {
case err != nil:
return nil, err
case ok:
return v, nil
}
}
if ctx.Loader != nil {
switch v, ok, err := ctx.Loader(ctx, typ, key); {
case err != nil:
return nil, err
case ok:
return v, nil
}
}
return nil, nil
}
// DefaultInterpolate is the default interpolation func.
DefaultInterpolate = InterpolateVar
// DefaultOps are default ops used by [InterpolateVar].
DefaultOps = map[string]func(string, string) (string, error){
// prefix trim
"#": func(s, v string) (string, error) {
return strings.TrimPrefix(s, v), nil
},
// suffix trim
"%": func(s, v string) (string, error) {
return strings.TrimSuffix(s, v), nil
},
// replace one
"/": func(s, v string) (string, error) {
str, rep, ok := strings.Cut(v, "/")
if !ok {
return "", fmt.Errorf("%w %q: missing /", ErrInvalidOp, v)
}
re, err := regexp.Compile(str)
if err != nil {
return "", fmt.Errorf("%w invalid regexp %q: %w", ErrInvalidOp, str, err)
}
if m := re.FindStringIndex(s); m != nil {
return string(slices.Replace([]byte(s), m[0], m[1], []byte(rep)...)), nil
}
return s, nil
},
// replace all
"//": func(s, v string) (string, error) {
str, rep, ok := strings.Cut(v, "/")
if !ok {
return "", fmt.Errorf("%w %q: missing /", ErrInvalidOp, v)
}
re, err := regexp.Compile(str)
if err != nil {
return "", fmt.Errorf("%w invalid regexp %q: %w", ErrInvalidOp, str, err)
}
return re.ReplaceAllString(s, rep), nil
},
// substring
":": func(s, idx string) (string, error) {
start, end, single, v := 0, len(s), true, idx
if i := strings.Index(v, ":"); i != -1 {
switch i, ok := parseInt(v[i+1:]); {
case !ok:
return "", fmt.Errorf("%w index %q", ErrInvalidOp, idx)
case 0 <= i:
end = i
default:
end = end + i
}
single, v = false, v[:i]
}
switch i, ok := parseInt(v); {
case !ok:
return "", fmt.Errorf("%w index %q", ErrInvalidOp, idx)
case !single && 0 <= i:
start = i
case !single:
start = len(s) + i
case single && 0 <= i:
start = i
case single:
start = len(s) + i
}
switch { // indices check
case len(s) < end, end < start, start < 0:
return "", fmt.Errorf("%w index %q", ErrInvalidOp, idx)
}
return s[start:end], nil
},
// default
":-": func(s, v string) (string, error) {
if s == "" {
return v, nil
}
return s, nil
},
// apply filter
"|": func(s, v string) (string, error) {
f, ok := DefaultFilters[strings.TrimSpace(v)]
if !ok {
return "", fmt.Errorf("%w: %q", ErrInvalidFilter, v)
}
return f(s), nil
},
// default
"||": func(s, v string) (string, error) {
if s == "" {
return v, nil
}
return s, nil
},
}
// DefaultOpFormatFunc is the default op format func used by [InterpolateVar].
DefaultOpFormatFunc = func(format string, v any) (any, error) {
return fmt.Sprintf(format, v), nil
}
// DefaultFilters are default filters used by [InterpolateVar].
DefaultFilters = map[string]func(string) string{
"lower": strings.ToLower,
"upper": strings.ToUpper,
"camel": strcase.ForceCamelIdentifier,
"snake": strcase.ToSnake,
"ident": strcase.ToIdentifier,
"kebab": strcase.ToKebab,
"trim": strings.TrimSpace,
"base": filepath.Base,
"dir": filepath.Dir,
"md5": func(s string) string {
b := md5.Sum([]byte(s))
return fmt.Sprintf("%x", string(b[:]))
},
"sha1": func(s string) string {
b := sha1.Sum([]byte(s))
return fmt.Sprintf("%x", string(b[:]))
},
"sha256": func(s string) string {
b := sha256.Sum256([]byte(s))
return fmt.Sprintf("%x", string(b[:]))
},
"sha512": func(s string) string {
b := sha512.Sum512([]byte(s))
return fmt.Sprintf("%x", string(b[:]))
},
}
)
// InterpolateVar interpolates variables based on registered config loaders
// defined on the [Context].
//
// Interplates variables of the form:
//
// $KEY
// ${KEY}
// ${KEY|filter}
// ${KEY||default|filter}
// $TYPE{KEY}
// $TYPE{KEY|filter}
// $TYPE{KEY||default|filter}
// ${TYPE::KEY}
// ${TYPE::KEY|filter}
// ${TYPE::KEY||default|filter}
// ${KEY%str}
// ${KEY%%str}
// ${KEY@str}
// ${KEY^str}
// ${KEY^^str}
// ${KEY/str/rep}
// ${KEY//str/rep}
// ${KEY:offset}
// ${KEY:offset:length}
// ${KEY^}
// ${KEY^^}
// ${KEY,}
// ${KEY,,}
//
// Where the above are:
//
// KEY - the key name
// TYPE - the config loader type
// default - a default value
// filter - a filter defined in [DefaultFilters]
// str - a string
// rep - a replacement string
// offset - a offset into the string; negative values are allowed
// length - a length from the offset
//
// See [DefaultKeyLoader] for the list of specially recognized keys.
//
// Built-in filters (see [DefaultFilters]):
//
// lower - lower case
// upper - upper case
// camel - camel case
// snake - snake case
// ident - ident case
// kebab - kebab case
// trim - trim space
// base - file path base
// dir - file path dir
// md5 - md5 hash
// sha1 - sha1 hash
// sha256 - sha256 hash
// sha512 - sha512 hash
//
// Built-in Bash-like string variable operators (see [DefaultOps]):
//
// #, ##, %, %%, /, //, ^, ^^, :
//
// A special Go formatting operator, @, is also provided that applies Go's
// standard formatting. That is, a key such as `${KEY@%f}` will be interpolated
// as the equivalent of `fmt.Sprintf("%f", <key value>)`.
//
// Interpolation examples:
//
// $APPNAME
// ${APPNAME|upper}
// $ENV{MY_VALUE|lower||default_value}
// ${env::MY_VALUE|lower||default_value}
// $YAML{a.key.path|upper}
// ${yaml::a.key.path||default_value|upper}
// ${\$.store.book[*].author}
// ${APPVERSION#v}
// ${my_rate@%e}
// ${MY_VALUE//foo/bar||default_value|upper}
// ${env::MY_VALUE%foo|upper}
func InterpolateVar(ctx *Context, v any) (any, error) {
str, ok := v.(string)
if !ok || str == "" {
return v, nil
}
var sb strings.Builder
r := []rune(str)
for i, n := 0, len(r); i < n; i++ {
switch {
case r[i] == '\\':
if c := peek(r, i+1, n); c != 0 {
_, _ = sb.WriteRune(c)
}
i++
continue
case r[i] != '$':
_, _ = sb.WriteRune(r[i])
continue
}
// read var
typ, key, extent, bracket, end := readVar(r, i, n)
// fmt.Fprintf(os.Stderr, "type: %q key: %q, transform: %t end: %d\n", typ, key, transform, end)
if end == -1 || (typ == "" && key == "") {
_ = sb.WriteByte('$')
continue
}
// fmt.Fprintf(os.Stderr, "captured: %q type: %q key: %q trans: %t\n", string(r[i:end]), typ, key, transform)
s, err := lookup(ctx, ConfigType(strings.ToLower(typ)), key, bracket)
switch {
case errors.Is(err, ErrUnknownKey):
// empty string
case err != nil:
formatVarError(&sb, typ, key, extent, bracket, err)
default:
_, _ = sb.WriteString(s)
}
i = end - 1
}
return sb.String(), nil
}
// formatVarError formats a var error to the string builder.
func formatVarError(sb *strings.Builder, typ, key string, extent, bracket bool, err error) {
_, _ = sb.WriteString("!(ERROR: $")
if !extent {
_ = sb.WriteByte('{')
}
_, _ = sb.WriteString(typ)
if extent && bracket && typ != "" {
_ = sb.WriteByte('{')
}
if typ != "" && !extent {
_, _ = sb.WriteString("::")
}
_, _ = sb.WriteString(key)
if extent && bracket && typ == "" {
_ = sb.WriteByte('{')
}
if bracket {
_ = sb.WriteByte('}')
}
_, _ = fmt.Fprintf(sb, ": %v)", err)
}
// lookup retrieves a type/key from the context, and transforms it if
// applicable.
func lookup(ctx *Context, typ ConfigType, key string, transform bool) (string, error) {
var ops string
if i := strings.IndexFunc(key, isOp); i != -1 && transform {
key, ops = key[:i], key[i:]
}
// lookup
v, err := ctx.Lookup(ctx, typ, key)
switch {
case errors.Is(err, ErrUnknownKey):
v = ""
case err != nil:
return "", err
}
// apply transforms
if transform && len(ops) != 0 {
if v, err = apply(v, ops); err != nil {
return "", err
}
}
return marshal[string](v)
}
// apply applies the string ops to the string.
func apply(v any, ops string) (any, error) {
var op, str string
for ops != "" {
op, str, ops = readOp(ops)
// fmt.Fprintf(os.Stderr, " op: %q str: %q ops: %q\n", op, str, ops)
switch f, ok := DefaultOps[op]; {
case op == "@":
var err error
if v, err = DefaultOpFormatFunc(str, v); err != nil {
return nil, err
}
case !ok && len(op) == 2:
if f, ok = DefaultOps[op[:1]]; !ok {
return nil, fmt.Errorf("%w: %w %q", ErrNotImplemented, ErrInvalidOp, op)
}
op, str = op[:1], op[1:]+str
case !ok:
return nil, fmt.Errorf("%w: %w %q", ErrNotImplemented, ErrInvalidOp, op)
default:
s, err := asString[string](v)
if err != nil {
return nil, err
}
if v, err = f(s, str); err != nil {
return nil, err
}
}
}
return v, nil
}
// readVar reads a var in r.
func readVar(r []rune, i, n int) (string, string, bool, bool, int) {
// fmt.Fprintf(os.Stderr, "readvar: %q\n", string(r[i:n]))
var typ, key string
var extent bool
c := peek(r, i+1, n)
switch {
case 'A' <= c && c <= 'Z':
typ, i = readType(r, i+1, n)
c = peek(r, i, n)
extent = true
case c == '{':
i++
}
bracket := false
if c == '{' {
// open bracket
if key, i = readBracket(r, i+1, n); i == -1 {
return "", "", false, false, -1
}
bracket = true
}
// if empty type, cut type at :: if within {} -- ie, ${typ::key}
if typ == "" && key != "" && bracket {
if s, after, ok := strings.Cut(key, "::"); ok {
typ, key = s, after
}
}
switch {
case typ == "" && key == "":
return "", "", false, false, n
case key == "":
typ, key = "", typ
}
return typ, key, extent, bracket, min(i, n)
}
// readType reads a variable type between '$' and '{'.
func readType(r []rune, i, n int) (string, int) {
start := i
for ; i < n; i++ {
if r[i] != '_' && !unicode.IsUpper(r[i]) && !unicode.IsDigit(r[i]) {
break
}
}
return string(r[start:i]), i
}
// readBracket reads until the first unescaped '$' or '}', or breaks when a
// newline ('\n', '\r') is encountered.
func readBracket(r []rune, i, n int) (string, int) {
var v []rune
var c, prev rune
for ; i < n; i++ {
switch c = r[i]; {
case c == '\n', c == '\r':
return "", -1
case prev != '\\' && c == '$':
return "", -1
case prev != '\\' && c == '}':
return string(v), i + 1
case prev == '\\':
prev = c
fallthrough
case c != '\\':
v = append(v, r[i])
default:
prev = c
}
}
return "", -1
}
// readOp reads the next op from ops.
func readOp(ops string) (string, string, string) {
op, ops := ops[0:1], ops[1:]
f := rune(op[0])
if len(ops) != 0 && isOpSecond(rune(ops[0]), f) {
op += string(ops[0])
ops = ops[1:]
}
if f != '%' && f != '#' && f != '^' && f != '@' {
if i := opIndex(ops, f); i != -1 {
return op, ops[:i], ops[i:]
}
}
return op, ops, ""
}
// opIndex returns the index for the next op. For '/' and ':' continues to the
// next op.
func opIndex(ops string, op rune) int {
if i := strings.IndexFunc(ops, isOp); i != -1 {
switch c := rune(ops[i]); {
case
op == '/' && op == c,
op == ':' && op == c:
if j := strings.IndexFunc(ops[i+1:], isOp); j != -1 {
return i + j + 1
}
default:
return i
}
}
return -1
}
// isOp returns true if r is an allowed op character.
func isOp(r rune) bool {
switch r {
case '#', '%', '^', ':', '/', '|', '@':
return true
}
return false
}
// isOpSecond returns true if r is an allowed second op character.
func isOpSecond(r, f rune) bool {
if (f == '#' || f == '%' || f == '^' || f == '@') && f != r {
return false
}
switch r {
case '#', '%', '^', ':', '/', '|', '@', '?', '=', '+', '-':
return true
}
return false
}
// parseInt parses an int.
func parseInt(s string) (int, bool) {
i, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
return int(i), err == nil
}