-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilters.go
More file actions
507 lines (436 loc) · 14 KB
/
Copy pathfilters.go
File metadata and controls
507 lines (436 loc) · 14 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
501
502
503
504
505
506
507
package jinja
import (
"encoding/base64"
"fmt"
"html"
"os"
"reflect"
"strings"
)
// FilterFunc defines the signature for a filter function.
// input is the value to be filtered.
// args are the arguments passed to the filter.
type FilterFunc func(input interface{}, args ...interface{}) (interface{}, error)
// GlobalFilters stores the registered filter functions.
var GlobalFilters map[string]FilterFunc
// defaultFilter implements the 'default' Jinja filter.
// If the input value is undefined, it returns the default_value. Otherwise, it returns the input value.
// The default filter does NOT trigger on falsy values like empty strings, empty slices, or false booleans.
// It only triggers when the variable is truly undefined.
func defaultFilter(input interface{}, args ...interface{}) (interface{}, error) {
if len(args) == 0 {
return nil, fmt.Errorf("default filter requires at least one argument (the default value)")
}
// TODO: The spec allows a second boolean argument to default filter for strict undefined check.
// e.g., {{ my_var | default("val", true) }} only defaults if my_var is undefined, not if it's just falsy.
// This is not implemented yet. We are implementing the common one-argument behavior.
defaultValue := args[0]
if input == nil || input == Undefined {
return defaultValue, nil
}
if _, isOmit := input.(OmitType); isOmit {
return Omit, nil
}
return input, nil
}
// joinFilter implements the 'join' Jinja filter.
// It joins the elements of a sequence (array, slice) with a given delimiter.
// Usage: {{ ['a', 'b', 'c'] | join(',') }} -> "a,b,c"
func joinFilter(input interface{}, args ...interface{}) (interface{}, error) {
// Default delimiter is an empty string if not specified
delimiter := ""
if len(args) > 0 {
if delim, ok := args[0].(string); ok {
delimiter = delim
} else {
return nil, fmt.Errorf("join filter delimiter must be a string")
}
}
if input == nil {
return "", nil
}
val := reflect.ValueOf(input)
switch val.Kind() {
case reflect.Slice, reflect.Array:
length := val.Len()
elements := make([]string, 0, length)
for i := 0; i < length; i++ {
itemVal := val.Index(i).Interface()
// Convert each element to string
elements = append(elements, fmt.Sprintf("%v", itemVal))
}
return strings.Join(elements, delimiter), nil
case reflect.String:
// If the input is already a string, return it unchanged
return input, nil
default:
return nil, fmt.Errorf("join filter requires a sequence (array, slice) as input, got %T", input)
}
}
// upperFilter implements the 'upper' Jinja filter.
// It converts a string to uppercase.
// Usage: {{ 'Hello' | upper }} -> "HELLO"
func upperFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return "", nil
}
switch v := input.(type) {
case string:
return strings.ToUpper(v), nil
default:
// Try to convert to string
str := fmt.Sprintf("%v", input)
return strings.ToUpper(str), nil
}
}
// lowerFilter implements the 'lower' Jinja filter.
// It converts a string to lowercase.
// Usage: {{ 'Hello' | lower }} -> "hello"
func lowerFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return "", nil
}
switch v := input.(type) {
case string:
return strings.ToLower(v), nil
default:
// Try to convert to string
str := fmt.Sprintf("%v", input)
return strings.ToLower(str), nil
}
}
// capitalizeFilter implements the 'capitalize' Jinja filter.
// It capitalizes the first character of a string and lowercases the rest.
// Usage: {{ 'hello world' | capitalize }} -> "Hello world"
func capitalizeFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return "", nil
}
var str string
switch v := input.(type) {
case string:
str = v
default:
// Try to convert to string
str = fmt.Sprintf("%v", input)
}
if str == "" {
return "", nil
}
// Capitalize first letter, lowercase the rest
return strings.ToUpper(str[:1]) + strings.ToLower(str[1:]), nil
}
// replaceFilter implements the 'replace' Jinja filter.
// It replaces occurrences of a substring with another.
// Usage: {{ 'Hello World' | replace('Hello', 'Hi') }} -> "Hi World"
func replaceFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return "", nil
}
if len(args) < 2 {
return nil, fmt.Errorf("replace filter requires two arguments: old substring and new substring")
}
old, ok1 := args[0].(string)
new, ok2 := args[1].(string)
if !ok1 || !ok2 {
return nil, fmt.Errorf("replace filter arguments must be strings")
}
// If args[2] exists and is an int, it's the count of replacements
count := -1 // default: replace all
if len(args) > 2 {
if countVal, ok := args[2].(int); ok {
count = countVal
}
}
var str string
switch v := input.(type) {
case string:
str = v
default:
// Try to convert to string
str = fmt.Sprintf("%v", input)
}
return strings.Replace(str, old, new, count), nil
}
// trimFilter implements the 'trim' Jinja filter.
// It removes leading and trailing whitespace or specified characters.
// Usage: {{ ' Hello ' | trim }} -> "Hello"
// Usage: {{ 'Hello World' | trim('Hld') }} -> "ello Wor"
func trimFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return "", nil
}
var str string
switch v := input.(type) {
case string:
str = v
default:
// Try to convert to string
str = fmt.Sprintf("%v", input)
}
// If no cutset is provided, trim whitespace
if len(args) == 0 {
return strings.TrimSpace(str), nil
}
// If cutset is provided, use it
cutset, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("trim filter cutset argument must be a string")
}
return strings.Trim(str, cutset), nil
}
// listFilter implements the 'list' Jinja filter.
// It converts a value to a list. If the input is a string, it returns a list of characters.
// Usage: {{ 'abc' | list }} -> ['a', 'b', 'c']
func listFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return []interface{}{}, nil
}
val := reflect.ValueOf(input)
switch val.Kind() {
case reflect.String:
str := val.String()
result := make([]interface{}, 0, len(str))
for _, ch := range str {
result = append(result, string(ch))
}
return result, nil
case reflect.Slice, reflect.Array:
// If already a slice or array, return a copy to ensure it's []interface{}
length := val.Len()
result := make([]interface{}, length)
for i := 0; i < length; i++ {
result[i] = val.Index(i).Interface()
}
return result, nil
default:
// For other types, return a single-item list containing the input
return []interface{}{input}, nil
}
}
// escapeFilter implements the 'escape' Jinja filter.
// It escapes special characters in HTML (&, <, >, ", ').
// Usage: {{ '<div>' | escape }} -> "<div>"
func escapeFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return "", nil
}
var str string
switch v := input.(type) {
case string:
str = v
default:
// Try to convert to string
str = fmt.Sprintf("%v", input)
}
return html.EscapeString(str), nil
}
// mapFilter implements the 'map' Jinja filter.
// It applies a filter to each item in a sequence and returns a list of results.
// Usage: {{ [1, 2, 3] | map('upper') }} -> ["1", "2", "3"]
// Usage: {{ ['a', 'b'] | map('upper') }} -> ["A", "B"]
func mapFilter(input interface{}, args ...interface{}) (interface{}, error) {
if len(args) < 1 {
return nil, fmt.Errorf("map filter requires at least one argument (the filter name)")
}
// Get the filter name from the first argument
filterName, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("map filter first argument must be a string (filter name)")
}
// Look up the filter function
filterFunc, exists := GlobalFilters[filterName]
if !exists {
return nil, fmt.Errorf("filter '%s' not found", filterName)
}
// Additional arguments to pass to the filter function
filterArgs := args[1:]
// Check if input is nil
if input == nil {
return []interface{}{}, nil
}
val := reflect.ValueOf(input)
switch val.Kind() {
case reflect.Slice, reflect.Array:
length := val.Len()
result := make([]interface{}, 0, length)
for i := 0; i < length; i++ {
itemVal := val.Index(i).Interface()
// Apply the filter to each item
filteredItem, err := filterFunc(itemVal, filterArgs...)
if err != nil {
return nil, fmt.Errorf("error applying filter '%s' to item: %v", filterName, err)
}
result = append(result, filteredItem)
}
return result, nil
default:
// For non-sequence types, apply the filter to the input directly
return filterFunc(input, filterArgs...)
}
}
// itemsFilter implements the 'items' Jinja filter.
// It converts a dictionary/map into a list of key-value pairs.
// Usage: {{ {'a': 1, 'b': 2} | items }} -> [('a', 1), ('b', 2)]
func itemsFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return []interface{}{}, nil
}
val := reflect.ValueOf(input)
// Only process map types
if val.Kind() != reflect.Map {
return nil, fmt.Errorf("items filter requires a dictionary/map as input, got %T", input)
}
// Get all keys from the map
keys := val.MapKeys()
result := make([]interface{}, 0, len(keys))
// For each key, create a tuple (key, value) and add to result
for _, key := range keys {
value := val.MapIndex(key)
pair := []interface{}{key.Interface(), value.Interface()}
result = append(result, pair)
}
return result, nil
}
// lookupFilter implements the 'lookup' Ansible filter.
// It retrieves data from external sources based on lookup type.
// Usage: {{ lookup('file', '/path/to/file') }}
// Usage: {{ lookup('env', 'HOME') }}
//
// IMPORTANT: In Ansible, lookup functions ALWAYS execute on the control node
// (the machine running the playbook), regardless of where the task is executing
// or if it's delegated to a remote host. This is different from regular
// Jinja expressions which are evaluated in the context of the target host.
func lookupFilter(input interface{}, args ...interface{}) (interface{}, error) {
// For the lookup filter, the input is actually the first argument (lookup type)
// and the remaining args are passed to the specific lookup function
if input == nil {
return nil, fmt.Errorf("lookup filter requires a lookup type as input")
}
// Convert input to string
lookupType, ok := input.(string)
if !ok {
return nil, fmt.Errorf("lookup filter requires a string as lookup type, got %T", input)
}
switch lookupType {
case "file":
if len(args) < 1 {
return nil, fmt.Errorf("file lookup requires a file path argument")
}
filePath, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("file lookup requires a string as file path, got %T", args[0])
}
// Read the file content from control node
content, err := readFileContent(filePath)
if err != nil {
return nil, fmt.Errorf("error reading file '%s' on control node: %v", filePath, err)
}
return content, nil
case "env":
if len(args) < 1 {
return nil, fmt.Errorf("env lookup requires an environment variable name")
}
envVar, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("env lookup requires a string as environment variable name, got %T", args[0])
}
// Get the environment variable from control node
value := os.Getenv(envVar)
return value, nil
// Add more lookup types as needed
default:
return nil, fmt.Errorf("unsupported lookup type: %s", lookupType)
}
}
// Helper function to read file content
func readFileContent(filePath string) (string, error) {
content, err := os.ReadFile(filePath)
if err != nil {
return "", err
}
return string(content), nil
}
// b64decodeFilter implements the 'b64decode' filter.
// It decodes a base64 encoded string.
// Usage: {{ encoded_string | b64decode }}
func b64decodeFilter(input interface{}, args ...interface{}) (interface{}, error) {
if input == nil {
return "", nil
}
var str string
switch v := input.(type) {
case string:
str = v
default:
// Try to convert to string
str = fmt.Sprintf("%v", input)
}
decoded, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return nil, fmt.Errorf("failed to decode base64 string: %v", err)
}
return string(decoded), nil
}
// toMap is a helper function to convert an interface to a map[string]interface{}
func toMap(val interface{}) (map[string]interface{}, error) {
if val == nil {
return map[string]interface{}{}, nil
}
if m, ok := val.(map[string]interface{}); ok {
return m, nil
}
rv := reflect.ValueOf(val)
if rv.Kind() != reflect.Map {
return nil, fmt.Errorf("cannot convert %T to map", val)
}
result := make(map[string]interface{})
iter := rv.MapRange()
for iter.Next() {
key := fmt.Sprintf("%v", iter.Key().Interface())
result[key] = iter.Value().Interface()
}
return result, nil
}
// unionFilter implements the 'union' filter, which merges two dictionaries.
func unionFilter(input interface{}, args ...interface{}) (interface{}, error) {
if len(args) == 0 {
return nil, fmt.Errorf("union filter requires a dictionary as an argument")
}
inputMap, err := toMap(input)
if err != nil {
return nil, fmt.Errorf("union filter input must be a dictionary, got %T: %w", input, err)
}
otherMap, err := toMap(args[0])
if err != nil {
return nil, fmt.Errorf("union filter argument must be a dictionary, got %T: %w", args[0], err)
}
// Create a new map to avoid modifying the original
result := make(map[string]interface{})
for k, v := range inputMap {
result[k] = v
}
for k, v := range otherMap {
result[k] = v
}
return result, nil
}
func init() {
// Initialize GlobalFilters after all filter functions are defined
GlobalFilters = map[string]FilterFunc{
"default": defaultFilter,
"join": joinFilter,
"upper": upperFilter,
"union": unionFilter,
"lower": lowerFilter,
"capitalize": capitalizeFilter,
"replace": replaceFilter,
"trim": trimFilter,
"list": listFilter,
"escape": escapeFilter,
"map": mapFilter,
"items": itemsFilter,
"lookup": lookupFilter,
"b64decode": b64decodeFilter,
}
}