-
Notifications
You must be signed in to change notification settings - Fork 784
/
funcs.go
1158 lines (995 loc) · 30.3 KB
/
funcs.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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package template
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"reflect"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"github.com/BurntSushi/toml"
dep "github.com/hashicorp/consul-template/dependency"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"
)
// now is function that represents the current time in UTC. This is here
// primarily for the tests to override times.
var now = func() time.Time { return time.Now().UTC() }
// datacentersFunc returns or accumulates datacenter dependencies.
func datacentersFunc(b *Brain, used, missing *dep.Set) func(ignore ...bool) ([]string, error) {
return func(i ...bool) ([]string, error) {
result := []string{}
var ignore bool
switch len(i) {
case 0:
ignore = false
case 1:
ignore = i[0]
default:
return result, fmt.Errorf("datacenters: wrong number of arguments, expected 0 or 1"+
", but got %d", len(i))
}
d, err := dep.NewCatalogDatacentersQuery(ignore)
if err != nil {
return result, err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
return value.([]string), nil
}
missing.Add(d)
return result, nil
}
}
// envFunc returns a function which checks the value of an environment variable.
// Invokers can specify their own environment, which takes precedences over any
// real environment variables
func envFunc(env []string) func(string) (string, error) {
return func(s string) (string, error) {
for _, e := range env {
split := strings.SplitN(e, "=", 2)
k, v := split[0], split[1]
if k == s {
return v, nil
}
}
return os.Getenv(s), nil
}
}
// executeTemplateFunc executes the given template in the context of the
// parent. If an argument is specified, it will be used as the context instead.
// This can be used for nested template definitions.
func executeTemplateFunc(t *template.Template) func(string, ...interface{}) (string, error) {
return func(s string, data ...interface{}) (string, error) {
var dot interface{}
switch len(data) {
case 0:
dot = nil
case 1:
dot = data[0]
default:
return "", fmt.Errorf("executeTemplate: wrong number of arguments, expected 1 or 2"+
", but got %d", len(data)+1)
}
var b bytes.Buffer
if err := t.ExecuteTemplate(&b, s, dot); err != nil {
return "", err
}
return b.String(), nil
}
}
// fileFunc returns or accumulates file dependencies.
func fileFunc(b *Brain, used, missing *dep.Set) func(string) (string, error) {
return func(s string) (string, error) {
if len(s) == 0 {
return "", nil
}
d, err := dep.NewFileQuery(s)
if err != nil {
return "", err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
if value == nil {
return "", nil
}
return value.(string), nil
}
missing.Add(d)
return "", nil
}
}
// keyFunc returns or accumulates key dependencies.
func keyFunc(b *Brain, used, missing *dep.Set) func(string) (string, error) {
return func(s string) (string, error) {
if len(s) == 0 {
return "", nil
}
d, err := dep.NewKVGetQuery(s)
if err != nil {
return "", err
}
d.EnableBlocking()
used.Add(d)
if value, ok := b.Recall(d); ok {
if value == nil {
return "", nil
}
return value.(string), nil
}
missing.Add(d)
return "", nil
}
}
// keyExistsFunc returns true if a key exists, false otherwise.
func keyExistsFunc(b *Brain, used, missing *dep.Set) func(string) (bool, error) {
return func(s string) (bool, error) {
if len(s) == 0 {
return false, nil
}
d, err := dep.NewKVGetQuery(s)
if err != nil {
return false, err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
return value != nil, nil
}
missing.Add(d)
return false, nil
}
}
// keyWithDefaultFunc returns or accumulates key dependencies that have a
// default value.
func keyWithDefaultFunc(b *Brain, used, missing *dep.Set) func(string, string) (string, error) {
return func(s, def string) (string, error) {
if len(s) == 0 {
return def, nil
}
d, err := dep.NewKVGetQuery(s)
if err != nil {
return "", err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
if value == nil || value.(string) == "" {
return def, nil
}
return value.(string), nil
}
missing.Add(d)
return def, nil
}
}
// lsFunc returns or accumulates keyPrefix dependencies.
func lsFunc(b *Brain, used, missing *dep.Set) func(string) ([]*dep.KeyPair, error) {
return func(s string) ([]*dep.KeyPair, error) {
result := []*dep.KeyPair{}
if len(s) == 0 {
return result, nil
}
d, err := dep.NewKVListQuery(s)
if err != nil {
return result, err
}
used.Add(d)
// Only return non-empty top-level keys
if value, ok := b.Recall(d); ok {
for _, pair := range value.([]*dep.KeyPair) {
if pair.Key != "" && !strings.Contains(pair.Key, "/") {
result = append(result, pair)
}
}
return result, nil
}
missing.Add(d)
return result, nil
}
}
// nodeFunc returns or accumulates catalog node dependency.
func nodeFunc(b *Brain, used, missing *dep.Set) func(...string) (*dep.CatalogNode, error) {
return func(s ...string) (*dep.CatalogNode, error) {
d, err := dep.NewCatalogNodeQuery(strings.Join(s, ""))
if err != nil {
return nil, err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
return value.(*dep.CatalogNode), nil
}
missing.Add(d)
return nil, nil
}
}
// nodesFunc returns or accumulates catalog node dependencies.
func nodesFunc(b *Brain, used, missing *dep.Set) func(...string) ([]*dep.Node, error) {
return func(s ...string) ([]*dep.Node, error) {
result := []*dep.Node{}
d, err := dep.NewCatalogNodesQuery(strings.Join(s, ""))
if err != nil {
return nil, err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
return value.([]*dep.Node), nil
}
missing.Add(d)
return result, nil
}
}
// secretFunc returns or accumulates secret dependencies from Vault.
func secretFunc(b *Brain, used, missing *dep.Set) func(...string) (*dep.Secret, error) {
return func(s ...string) (*dep.Secret, error) {
var result *dep.Secret
if len(s) == 0 {
return result, nil
}
// TODO: Refactor into separate template functions
path, rest := s[0], s[1:]
data := make(map[string]interface{})
for _, str := range rest {
parts := strings.SplitN(str, "=", 2)
if len(parts) != 2 {
return result, fmt.Errorf("not k=v pair %q", str)
}
k, v := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
data[k] = v
}
var d dep.Dependency
var err error
if len(rest) == 0 {
d, err = dep.NewVaultReadQuery(path)
} else {
d, err = dep.NewVaultWriteQuery(path, data)
}
if err != nil {
return nil, err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
result = value.(*dep.Secret)
return result, nil
}
missing.Add(d)
return result, nil
}
}
// secretsFunc returns or accumulates a list of secret dependencies from Vault.
func secretsFunc(b *Brain, used, missing *dep.Set) func(string) ([]string, error) {
return func(s string) ([]string, error) {
var result []string
if len(s) == 0 {
return result, nil
}
d, err := dep.NewVaultListQuery(s)
if err != nil {
return nil, err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
result = value.([]string)
return result, nil
}
missing.Add(d)
return result, nil
}
}
// serviceFunc returns or accumulates health service dependencies.
func serviceFunc(b *Brain, used, missing *dep.Set) func(...string) ([]*dep.HealthService, error) {
return func(s ...string) ([]*dep.HealthService, error) {
result := []*dep.HealthService{}
if len(s) == 0 || s[0] == "" {
return result, nil
}
d, err := dep.NewHealthServiceQuery(strings.Join(s, "|"))
if err != nil {
return nil, err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
return value.([]*dep.HealthService), nil
}
missing.Add(d)
return result, nil
}
}
// servicesFunc returns or accumulates catalog services dependencies.
func servicesFunc(b *Brain, used, missing *dep.Set) func(...string) ([]*dep.CatalogSnippet, error) {
return func(s ...string) ([]*dep.CatalogSnippet, error) {
result := []*dep.CatalogSnippet{}
d, err := dep.NewCatalogServicesQuery(strings.Join(s, ""))
if err != nil {
return nil, err
}
used.Add(d)
if value, ok := b.Recall(d); ok {
return value.([]*dep.CatalogSnippet), nil
}
missing.Add(d)
return result, nil
}
}
// treeFunc returns or accumulates keyPrefix dependencies.
func treeFunc(b *Brain, used, missing *dep.Set) func(string) ([]*dep.KeyPair, error) {
return func(s string) ([]*dep.KeyPair, error) {
result := []*dep.KeyPair{}
if len(s) == 0 {
return result, nil
}
d, err := dep.NewKVListQuery(s)
if err != nil {
return result, err
}
used.Add(d)
// Only return non-empty top-level keys
if value, ok := b.Recall(d); ok {
for _, pair := range value.([]*dep.KeyPair) {
parts := strings.Split(pair.Key, "/")
if parts[len(parts)-1] != "" {
result = append(result, pair)
}
}
return result, nil
}
missing.Add(d)
return result, nil
}
}
// base64Decode decodes the given string as a base64 string, returning an error
// if it fails.
func base64Decode(s string) (string, error) {
v, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", errors.Wrap(err, "base64Decode")
}
return string(v), nil
}
// base64Encode encodes the given value into a string represented as base64.
func base64Encode(s string) (string, error) {
return base64.StdEncoding.EncodeToString([]byte(s)), nil
}
// base64URLDecode decodes the given string as a URL-safe base64 string.
func base64URLDecode(s string) (string, error) {
v, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return "", errors.Wrap(err, "base64URLDecode")
}
return string(v), nil
}
// base64URLEncode encodes the given string to be URL-safe.
func base64URLEncode(s string) (string, error) {
return base64.URLEncoding.EncodeToString([]byte(s)), nil
}
// byKey accepts a slice of KV pairs and returns a map of the top-level
// key to all its subkeys. For example:
//
// elasticsearch/a //=> "1"
// elasticsearch/b //=> "2"
// redis/a/b //=> "3"
//
// Passing the result from Consul through byTag would yield:
//
// map[string]map[string]string{
// "elasticsearch": &dep.KeyPair{"a": "1"}, &dep.KeyPair{"b": "2"},
// "redis": &dep.KeyPair{"a/b": "3"}
// }
//
// Note that the top-most key is stripped from the Key value. Keys that have no
// prefix after stripping are removed from the list.
func byKey(pairs []*dep.KeyPair) (map[string]map[string]*dep.KeyPair, error) {
m := make(map[string]map[string]*dep.KeyPair)
for _, pair := range pairs {
parts := strings.Split(pair.Key, "/")
top := parts[0]
key := strings.Join(parts[1:], "/")
if key == "" {
// Do not add a key if it has no prefix after stripping.
continue
}
if _, ok := m[top]; !ok {
m[top] = make(map[string]*dep.KeyPair)
}
newPair := *pair
newPair.Key = key
m[top][key] = &newPair
}
return m, nil
}
// byTag is a template func that takes the provided services and
// produces a map based on Service tags.
//
// The map key is a string representing the service tag. The map value is a
// slice of Services which have the tag assigned.
func byTag(in interface{}) (map[string][]interface{}, error) {
m := make(map[string][]interface{})
switch typed := in.(type) {
case nil:
case []*dep.CatalogSnippet:
for _, s := range typed {
for _, t := range s.Tags {
m[t] = append(m[t], s)
}
}
case []*dep.CatalogService:
for _, s := range typed {
for _, t := range s.ServiceTags {
m[t] = append(m[t], s)
}
}
case []*dep.HealthService:
for _, s := range typed {
for _, t := range s.Tags {
m[t] = append(m[t], s)
}
}
default:
return nil, fmt.Errorf("byTag: wrong argument type %T", in)
}
return m, nil
}
// contains is a function that have reverse arguments of "in" and is designed to
// be used as a pipe instead of a function:
//
// {{ l | contains "thing" }}
//
func contains(v, l interface{}) (bool, error) {
return in(l, v)
}
// containsSomeFunc returns functions to implement each of the following:
//
// 1. containsAll - true if (∀x ∈ v then x ∈ l); false otherwise
// 2. containsAny - true if (∃x ∈ v such that x ∈ l); false otherwise
// 3. containsNone - true if (∀x ∈ v then x ∉ l); false otherwise
// 2. containsNotAll - true if (∃x ∈ v such that x ∉ l); false otherwise
//
// ret_true - return true at end of loop for none/all; false for any/notall
// invert - invert block test for all/notall
func containsSomeFunc(retTrue, invert bool) func([]interface{}, interface{}) (bool, error) {
return func(v []interface{}, l interface{}) (bool, error) {
for i := 0; i < len(v); i++ {
if ok, _ := in(l, v[i]); ok != invert {
return !retTrue, nil
}
}
return retTrue, nil
}
}
// explode is used to expand a list of keypairs into a deeply-nested hash.
func explode(pairs []*dep.KeyPair) (map[string]interface{}, error) {
m := make(map[string]interface{})
for _, pair := range pairs {
if err := explodeHelper(m, pair.Key, pair.Value, pair.Key); err != nil {
return nil, errors.Wrap(err, "explode")
}
}
return m, nil
}
// explodeHelper is a recursive helper for explode.
func explodeHelper(m map[string]interface{}, k, v, p string) error {
if strings.Contains(k, "/") {
parts := strings.Split(k, "/")
top := parts[0]
key := strings.Join(parts[1:], "/")
if _, ok := m[top]; !ok {
m[top] = make(map[string]interface{})
}
nest, ok := m[top].(map[string]interface{})
if !ok {
return fmt.Errorf("not a map: %q: %q already has value %q", p, top, m[top])
}
return explodeHelper(nest, key, v, k)
}
if k != "" {
m[k] = v
}
return nil
}
// in searches for a given value in a given interface.
func in(l, v interface{}) (bool, error) {
lv := reflect.ValueOf(l)
vv := reflect.ValueOf(v)
switch lv.Kind() {
case reflect.Array, reflect.Slice:
// if the slice contains 'interface' elements, then the element needs to be extracted directly to examine its type,
// otherwise it will just resolve to 'interface'.
var interfaceSlice []interface{}
if reflect.TypeOf(l).Elem().Kind() == reflect.Interface {
interfaceSlice = l.([]interface{})
}
for i := 0; i < lv.Len(); i++ {
var lvv reflect.Value
if interfaceSlice != nil {
lvv = reflect.ValueOf(interfaceSlice[i])
} else {
lvv = lv.Index(i)
}
switch lvv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
switch vv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if vv.Int() == lvv.Int() {
return true, nil
}
}
case reflect.Float32, reflect.Float64:
switch vv.Kind() {
case reflect.Float32, reflect.Float64:
if vv.Float() == lvv.Float() {
return true, nil
}
}
case reflect.String:
if vv.Type() == lvv.Type() && vv.String() == lvv.String() {
return true, nil
}
}
}
case reflect.String:
if vv.Type() == lv.Type() && strings.Contains(lv.String(), vv.String()) {
return true, nil
}
}
return false, nil
}
// Indent prefixes each line of a string with the specified number of spaces
func indent(spaces int, s string) (string, error) {
if spaces < 0 {
return "", fmt.Errorf("indent value must be a positive integer")
}
var output, prefix []byte
var sp bool
var size int
prefix = []byte(strings.Repeat(" ", spaces))
sp = true
for _, c := range []byte(s) {
if sp && c != '\n' {
output = append(output, prefix...)
size += spaces
}
output = append(output, c)
sp = c == '\n'
size++
}
return string(output[:size]), nil
}
// loop accepts varying parameters and differs its behavior. If given one
// parameter, loop will return a goroutine that begins at 0 and loops until the
// given int, increasing the index by 1 each iteration. If given two parameters,
// loop will return a goroutine that begins at the first parameter and loops
// up to but not including the second parameter.
//
// // Prints 0 1 2 3 4
// for _, i := range loop(5) {
// print(i)
// }
//
// // Prints 5 6 7
// for _, i := range loop(5, 8) {
// print(i)
// }
//
func loop(ints ...int64) (<-chan int64, error) {
var start, stop int64
switch len(ints) {
case 1:
start, stop = 0, ints[0]
case 2:
start, stop = ints[0], ints[1]
default:
return nil, fmt.Errorf("loop: wrong number of arguments, expected 1 or 2"+
", but got %d", len(ints))
}
ch := make(chan int64)
go func() {
for i := start; i < stop; i++ {
ch <- i
}
close(ch)
}()
return ch, nil
}
// join is a version of strings.Join that can be piped
func join(sep string, a []string) (string, error) {
return strings.Join(a, sep), nil
}
// TrimSpace is a version of strings.TrimSpace that can be piped
func trimSpace(s string) (string, error) {
return strings.TrimSpace(s), nil
}
// parseBool parses a string into a boolean
func parseBool(s string) (bool, error) {
if s == "" {
return false, nil
}
result, err := strconv.ParseBool(s)
if err != nil {
return false, errors.Wrap(err, "parseBool")
}
return result, nil
}
// parseFloat parses a string into a base 10 float
func parseFloat(s string) (float64, error) {
if s == "" {
return 0.0, nil
}
result, err := strconv.ParseFloat(s, 10)
if err != nil {
return 0, errors.Wrap(err, "parseFloat")
}
return result, nil
}
// parseInt parses a string into a base 10 int
func parseInt(s string) (int64, error) {
if s == "" {
return 0, nil
}
result, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, errors.Wrap(err, "parseInt")
}
return result, nil
}
// parseJSON returns a structure for valid JSON
func parseJSON(s string) (interface{}, error) {
if s == "" {
return map[string]interface{}{}, nil
}
var data interface{}
if err := json.Unmarshal([]byte(s), &data); err != nil {
return nil, err
}
return data, nil
}
// parseUint parses a string into a base 10 int
func parseUint(s string) (uint64, error) {
if s == "" {
return 0, nil
}
result, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return 0, errors.Wrap(err, "parseUint")
}
return result, nil
}
// plugin executes a subprocess as the given command string. It is assumed the
// resulting command returns JSON which is then parsed and returned as the
// value for use in the template.
func plugin(name string, args ...string) (string, error) {
if name == "" {
return "", nil
}
stdout, stderr := new(bytes.Buffer), new(bytes.Buffer)
// Strip and trim each arg or else some plugins get confused with the newline
// characters
jsons := make([]string, 0, len(args))
for _, arg := range args {
if v := strings.TrimSpace(arg); v != "" {
jsons = append(jsons, v)
}
}
cmd := exec.Command(name, jsons...)
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
return "", fmt.Errorf("exec %q: %s\n\nstdout:\n\n%s\n\nstderr:\n\n%s",
name, err, stdout.Bytes(), stderr.Bytes())
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(30 * time.Second):
if cmd.Process != nil {
if err := cmd.Process.Kill(); err != nil {
return "", fmt.Errorf("exec %q: failed to kill", name)
}
}
<-done // Allow the goroutine to exit
return "", fmt.Errorf("exec %q: did not finish in 30s", name)
case err := <-done:
if err != nil {
return "", fmt.Errorf("exec %q: %s\n\nstdout:\n\n%s\n\nstderr:\n\n%s",
name, err, stdout.Bytes(), stderr.Bytes())
}
}
return strings.TrimSpace(stdout.String()), nil
}
// replaceAll replaces all occurrences of a value in a string with the given
// replacement value.
func replaceAll(f, t, s string) (string, error) {
return strings.Replace(s, f, t, -1), nil
}
// regexReplaceAll replaces all occurrences of a regular expression with
// the given replacement value.
func regexReplaceAll(re, pl, s string) (string, error) {
compiled, err := regexp.Compile(re)
if err != nil {
return "", err
}
return compiled.ReplaceAllString(s, pl), nil
}
// regexMatch returns true or false if the string matches
// the given regular expression
func regexMatch(re, s string) (bool, error) {
compiled, err := regexp.Compile(re)
if err != nil {
return false, err
}
return compiled.MatchString(s), nil
}
// split is a version of strings.Split that can be piped
func split(sep, s string) ([]string, error) {
s = strings.TrimSpace(s)
if s == "" {
return []string{}, nil
}
return strings.Split(s, sep), nil
}
// timestamp returns the current UNIX timestamp in UTC. If an argument is
// specified, it will be used to format the timestamp.
func timestamp(s ...string) (string, error) {
switch len(s) {
case 0:
return now().Format(time.RFC3339), nil
case 1:
if s[0] == "unix" {
return strconv.FormatInt(now().Unix(), 10), nil
}
return now().Format(s[0]), nil
default:
return "", fmt.Errorf("timestamp: wrong number of arguments, expected 0 or 1"+
", but got %d", len(s))
}
}
// toLower converts the given string (usually by a pipe) to lowercase.
func toLower(s string) (string, error) {
return strings.ToLower(s), nil
}
// toJSON converts the given structure into a deeply nested JSON string.
func toJSON(i interface{}) (string, error) {
result, err := json.Marshal(i)
if err != nil {
return "", errors.Wrap(err, "toJSON")
}
return string(bytes.TrimSpace(result)), err
}
// toJSONPretty converts the given structure into a deeply nested pretty JSON
// string.
func toJSONPretty(m map[string]interface{}) (string, error) {
result, err := json.MarshalIndent(m, "", " ")
if err != nil {
return "", errors.Wrap(err, "toJSONPretty")
}
return string(bytes.TrimSpace(result)), err
}
// toTitle converts the given string (usually by a pipe) to titlecase.
func toTitle(s string) (string, error) {
return strings.Title(s), nil
}
// toUpper converts the given string (usually by a pipe) to uppercase.
func toUpper(s string) (string, error) {
return strings.ToUpper(s), nil
}
// toYAML converts the given structure into a deeply nested YAML string.
func toYAML(m map[string]interface{}) (string, error) {
result, err := yaml.Marshal(m)
if err != nil {
return "", errors.Wrap(err, "toYAML")
}
return string(bytes.TrimSpace(result)), nil
}
// toTOML converts the given structure into a deeply nested TOML string.
func toTOML(m map[string]interface{}) (string, error) {
buf := bytes.NewBuffer([]byte{})
enc := toml.NewEncoder(buf)
if err := enc.Encode(m); err != nil {
return "", errors.Wrap(err, "toTOML")
}
result, err := ioutil.ReadAll(buf)
if err != nil {
return "", errors.Wrap(err, "toTOML")
}
return string(bytes.TrimSpace(result)), nil
}
// add returns the sum of a and b.
func add(b, a interface{}) (interface{}, error) {
av := reflect.ValueOf(a)
bv := reflect.ValueOf(b)
switch av.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
switch bv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return av.Int() + bv.Int(), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return av.Int() + int64(bv.Uint()), nil
case reflect.Float32, reflect.Float64:
return float64(av.Int()) + bv.Float(), nil
default:
return nil, fmt.Errorf("add: unknown type for %q (%T)", bv, b)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
switch bv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return int64(av.Uint()) + bv.Int(), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return av.Uint() + bv.Uint(), nil
case reflect.Float32, reflect.Float64:
return float64(av.Uint()) + bv.Float(), nil
default:
return nil, fmt.Errorf("add: unknown type for %q (%T)", bv, b)
}
case reflect.Float32, reflect.Float64:
switch bv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return av.Float() + float64(bv.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return av.Float() + float64(bv.Uint()), nil
case reflect.Float32, reflect.Float64:
return av.Float() + bv.Float(), nil
default:
return nil, fmt.Errorf("add: unknown type for %q (%T)", bv, b)
}
default:
return nil, fmt.Errorf("add: unknown type for %q (%T)", av, a)
}
}
// subtract returns the difference of b from a.
func subtract(b, a interface{}) (interface{}, error) {