-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfigtree.go
1939 lines (1778 loc) · 52 KB
/
figtree.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 figtree
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
"emperror.dev/errors"
"github.com/coryb/walky"
"github.com/fatih/camelcase"
"gopkg.in/yaml.v3"
)
type Logger interface {
Debugf(format string, args ...interface{})
}
type nullLogger struct{}
func (*nullLogger) Debugf(string, ...interface{}) {}
var Log Logger = &nullLogger{}
func defaultApplyChangeSet(changeSet map[string]*string) error {
for k, v := range changeSet {
if v != nil {
os.Setenv(k, *v)
} else {
os.Unsetenv(k)
}
}
return nil
}
type CreateOption func(*FigTree)
func WithHome(home string) CreateOption {
return func(f *FigTree) {
f.home = home
}
}
func WithCwd(cwd string) CreateOption {
return func(f *FigTree) {
f.workDir = cwd
}
}
func WithEnvPrefix(env string) CreateOption {
return func(f *FigTree) {
f.envPrefix = env
}
}
func WithConfigDir(dir string) CreateOption {
return func(f *FigTree) {
f.configDir = dir
}
}
type ChangeSetFunc func(map[string]*string) error
func WithApplyChangeSet(apply ChangeSetFunc) CreateOption {
return func(f *FigTree) {
f.applyChangeSet = apply
}
}
type PreProcessor func(*yaml.Node) error
func WithPreProcessor(pp PreProcessor) CreateOption {
return func(f *FigTree) {
f.preProcessor = pp
}
}
type FilterOut func(*yaml.Node) bool
func WithFilterOut(filt FilterOut) CreateOption {
return func(f *FigTree) {
f.filterOut = filt
}
}
func defaultFilterOut(f *FigTree) FilterOut {
configStop := false
return func(config *yaml.Node) bool {
// if previous parse found a stop we should abort here
if configStop {
return true
}
// now check if current doc has a stop, looking for:
// ```
// config:
// stop: true|false
// ```
if pragma := walky.GetKey(config, "config"); pragma != nil {
if stop := walky.GetKey(pragma, "stop"); stop != nil {
configStop, _ = strconv.ParseBool(stop.Value)
}
}
// even if current doc has a stop, we should continue to
// process it, we dont want to process the "next" document
return false
}
}
func WithoutExec() CreateOption {
return func(f *FigTree) {
f.exec = false
}
}
type FigTree struct {
home string
workDir string
configDir string
envPrefix string
preProcessor PreProcessor
applyChangeSet ChangeSetFunc
exec bool
filterOut FilterOut
}
func NewFigTree(opts ...CreateOption) *FigTree {
wd, _ := os.Getwd()
fig := &FigTree{
home: os.Getenv("HOME"),
workDir: wd,
envPrefix: "FIGTREE",
applyChangeSet: defaultApplyChangeSet,
exec: true,
}
for _, opt := range opts {
opt(fig)
}
return fig
}
func (f *FigTree) WithHome(home string) {
WithHome(home)(f)
}
func (f *FigTree) WithCwd(cwd string) {
WithCwd(cwd)(f)
}
func (f *FigTree) WithEnvPrefix(env string) {
WithEnvPrefix(env)(f)
}
func (f *FigTree) WithConfigDir(dir string) {
WithConfigDir(dir)(f)
}
func (f *FigTree) WithPreProcessor(pp PreProcessor) {
WithPreProcessor(pp)(f)
}
func (f *FigTree) WithFilterOut(filt FilterOut) {
WithFilterOut(filt)(f)
}
func (f *FigTree) WithApplyChangeSet(apply ChangeSetFunc) {
WithApplyChangeSet(apply)(f)
}
func (f *FigTree) WithIgnoreChangeSet() {
WithApplyChangeSet(func(_ map[string]*string) error {
return nil
})(f)
}
func (f *FigTree) WithoutExec() {
WithoutExec()(f)
}
func (f *FigTree) Copy() *FigTree {
cp := *f
return &cp
}
func (f *FigTree) LoadAllConfigs(configFile string, options interface{}) error {
if f.configDir != "" {
configFile = path.Join(f.configDir, configFile)
}
paths := FindParentPaths(f.home, f.workDir, configFile)
paths = append([]string{fmt.Sprintf("/etc/%s", configFile)}, paths...)
configSources := []ConfigSource{}
// iterate paths in reverse
for i := len(paths) - 1; i >= 0; i-- {
file := paths[i]
cs, err := f.ReadFile(file)
if err != nil {
return err
}
if cs == nil {
// no file contents to parse, file likely does not exist
continue
}
configSources = append(configSources, *cs)
}
return f.LoadAllConfigSources(configSources, options)
}
type ConfigSource struct {
Config *yaml.Node
Filename string
}
func (f *FigTree) LoadAllConfigSources(sources []ConfigSource, options interface{}) error {
m := NewMerger()
filterOut := f.filterOut
if filterOut == nil {
filterOut = defaultFilterOut(f)
}
for _, source := range sources {
// automatically skip empty configs
if source.Config == nil || source.Config.IsZero() {
continue
}
skip := filterOut(source.Config)
if skip {
continue
}
m.sourceFile = source.Filename
err := f.loadConfigSource(m, source.Config, options)
if err != nil {
return err
}
m.advance()
}
return nil
}
func (f *FigTree) LoadConfigSource(config *yaml.Node, source string, options interface{}) error {
m := NewMerger(WithSourceFile(source))
return f.loadConfigSource(m, config, options)
}
func sourceLine(file string, node *yaml.Node) string {
if node.Line > 0 {
return fmt.Sprintf("%s:%d:%d", file, node.Line, node.Column)
}
return file
}
func (f *FigTree) loadConfigSource(m *Merger, config *yaml.Node, options interface{}) error {
if !reflect.ValueOf(options).IsValid() {
return errors.Errorf("options argument [%#v] is not valid", options)
}
var err error
if f.preProcessor != nil {
err = f.preProcessor(config)
if err != nil {
return errors.Wrapf(err, "failed to process config file %s", sourceLine(m.sourceFile, config))
}
}
err = config.Decode(m)
if err != nil {
return errors.WithStack(walky.ErrFilename(err, m.sourceFile))
}
_, err = m.mergeStructs(
reflect.ValueOf(options),
newMergeSource(walky.UnwrapDocument(config)),
false,
)
if err != nil {
return err
}
changeSet := f.PopulateEnv(options)
return f.applyChangeSet(changeSet)
}
func (f *FigTree) LoadConfig(file string, options interface{}) error {
cs, err := f.ReadFile(file)
if err != nil {
return err
}
if cs == nil {
// no file contents to parse, file likely does not exist
return nil
}
return f.LoadConfigSource(cs.Config, cs.Filename, options)
}
// ReadFile will return a ConfigSource for given file path. If the
// file is executable (and WithoutExec was not used), it will execute
// the file and return the stdout otherwise it will return the file
// contents directly.
func (f *FigTree) ReadFile(file string) (*ConfigSource, error) {
absFile := file
if !filepath.IsAbs(file) {
absFile = filepath.Clean(filepath.Join(f.workDir, file))
}
rel, err := filepath.Rel(f.workDir, absFile)
if err != nil {
rel = file
}
var node yaml.Node
if stat, err := os.Stat(absFile); err == nil {
if stat.Mode()&0o111 == 0 || !f.exec {
Log.Debugf("Reading config %s", absFile)
fh, err := os.Open(absFile)
if err != nil {
return nil, errors.Wrapf(err, "failed to open %s", rel)
}
defer fh.Close()
decoder := yaml.NewDecoder(fh)
if err := decoder.Decode(&node); err != nil && !errors.Is(err, io.EOF) {
return nil, errors.WithStack(walky.ErrFilename(err, file))
}
} else {
Log.Debugf("Found Executable Config file: %s", absFile)
// it is executable, so run it and try to parse the output
cmd := exec.Command(absFile)
stdout := bytes.NewBufferString("")
cmd.Stdout = stdout
cmd.Stderr = bytes.NewBufferString("")
if err := cmd.Run(); err != nil {
return nil, errors.Wrapf(err, "%s is executable, but it failed to execute:\n%s", file, cmd.Stderr)
}
rel += "[stdout]"
if err := yaml.Unmarshal(stdout.Bytes(), &node); err != nil {
return nil, err
}
}
return &ConfigSource{
Config: &node,
Filename: rel,
}, nil
}
return nil, nil
}
func FindParentPaths(homedir, cwd, fileName string) []string {
paths := make([]string, 0)
if filepath.IsAbs(fileName) {
// dont recursively look for files when fileName is an abspath
_, err := os.Stat(fileName)
if err == nil {
paths = append(paths, fileName)
}
return paths
}
// special case if homedir is not in current path then check there anyway
if homedir != "" && !strings.HasPrefix(cwd, homedir) {
file := path.Join(homedir, fileName)
if _, err := os.Stat(file); err == nil {
paths = append(paths, filepath.FromSlash(file))
}
}
var dir string
for _, part := range strings.Split(cwd, string(os.PathSeparator)) {
if part == "" && dir == "" {
dir = "/"
} else {
dir = path.Join(dir, part)
}
file := path.Join(dir, fileName)
if _, err := os.Stat(file); err == nil {
paths = append(paths, filepath.FromSlash(file))
}
}
return paths
}
func (f *FigTree) FindParentPaths(fileName string) []string {
return FindParentPaths(f.home, f.workDir, fileName)
}
var camelCaseWords = regexp.MustCompile("[0-9A-Za-z]+")
func camelCase(name string) string {
words := camelCaseWords.FindAllString(name, -1)
for i, word := range words {
words[i] = strings.Title(word)
}
return strings.Join(words, "")
}
type Merger struct {
sourceFile string
preserveMap map[string]struct{}
Config ConfigOptions `json:"config,omitempty" yaml:"config,omitempty"`
ignore []string
}
type MergeOption func(*Merger)
func WithSourceFile(source string) MergeOption {
return func(m *Merger) {
m.sourceFile = source
}
}
func PreserveMap(keys ...string) MergeOption {
return func(m *Merger) {
for _, key := range keys {
m.preserveMap[key] = struct{}{}
}
}
}
func NewMerger(options ...MergeOption) *Merger {
m := &Merger{
sourceFile: "merge",
preserveMap: make(map[string]struct{}),
}
for _, opt := range options {
opt(m)
}
return m
}
// advance will move all the current overwrite properties to
// the ignore properties, then reset the overwrite properties.
// This is used after a document has be processed so the next
// document does not modify overwritten fields.
func (m *Merger) advance() {
for _, overwrite := range m.Config.Overwrite {
found := false
for _, ignore := range m.ignore {
if ignore == overwrite {
found = true
break
}
}
if !found {
m.ignore = append(m.ignore, overwrite)
}
}
m.Config.Overwrite = nil
}
// Merge will attempt to merge the data from src into dst. src and dst may each
// be either a map or a struct. Structs do not need to have the same structure,
// but any field name that exists in both structs will must be the same type.
func Merge(dst, src interface{}) error {
dstValue := reflect.ValueOf(dst)
if dstValue.Kind() == reflect.Struct {
return errors.New("dst argument cannot be a struct (should be *struct)")
}
m := NewMerger()
_, err := m.mergeStructs(dstValue, newMergeSource(reflect.ValueOf(src)), false)
return err
}
// MakeMergeStruct will take multiple structs and return a pointer to a zero value for the
// anonymous struct that has all the public fields from all the structs merged into one struct.
// If there are multiple structs with the same field names, the first appearance of that name
// will be used.
func MakeMergeStruct(structs ...interface{}) interface{} {
m := NewMerger()
return m.MakeMergeStruct(structs...)
}
func (m *Merger) MakeMergeStruct(structs ...interface{}) interface{} {
values := []reflect.Value{}
for _, data := range structs {
values = append(values, reflect.ValueOf(data))
}
return m.makeMergeStruct(values...).Interface()
}
func inlineField(field reflect.StructField) bool {
if tag := field.Tag.Get("figtree"); tag != "" {
return strings.HasSuffix(tag, ",inline")
}
if tag := field.Tag.Get("yaml"); tag != "" {
return strings.HasSuffix(tag, ",inline")
}
return false
}
func (m *Merger) makeMergeStruct(values ...reflect.Value) reflect.Value {
foundFields := map[string]reflect.StructField{}
for i := 0; i < len(values); i++ {
v := values[i]
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
typ := v.Type()
var field reflect.StructField
if typ.Kind() == reflect.Struct {
for j := 0; j < typ.NumField(); j++ {
field = typ.Field(j)
if field.PkgPath != "" {
// unexported field, skip
continue
}
field.Name = CanonicalFieldName(field)
if f, ok := foundFields[field.Name]; ok {
if f.Type.Kind() == reflect.Struct && field.Type.Kind() == reflect.Struct {
if fName, fieldName := f.Type.Name(), field.Type.Name(); fName == "" || fieldName == "" || fName != fieldName {
// we have 2 fields with the same name and they are both structs, so we need
// to merge the existing struct with the new one in case they are different
newval := m.makeMergeStruct(reflect.New(f.Type).Elem(), reflect.New(field.Type).Elem()).Elem()
f.Type = newval.Type()
foundFields[field.Name] = f
}
}
// field already found, skip
continue
}
if inlineField(field) {
// insert inline after this value, it will have a higher
// "type" priority than later values
values = append(values[:i+1], append([]reflect.Value{v.Field(j)}, values[i+1:]...)...)
continue
}
foundFields[field.Name] = field
}
} else if typ.Kind() == reflect.Map {
for _, key := range v.MapKeys() {
keyval := reflect.ValueOf(v.MapIndex(key).Interface())
if _, ok := m.preserveMap[key.String()]; !ok {
if keyval.Kind() == reflect.Ptr && keyval.Elem().Kind() == reflect.Map {
keyval = m.makeMergeStruct(keyval.Elem())
} else if keyval.Kind() == reflect.Map {
keyval = m.makeMergeStruct(keyval).Elem()
}
}
var t reflect.Type
if !keyval.IsValid() {
// this nonsense is to create a generic `interface{}` type. There is
// probably an easier to do this, but it eludes me at the moment.
var dummy interface{}
t = reflect.ValueOf(&dummy).Elem().Type()
} else {
t = reflect.ValueOf(keyval.Interface()).Type()
}
field = reflect.StructField{
Name: camelCase(key.String()),
Type: t,
Tag: reflect.StructTag(fmt.Sprintf(`json:"%s" yaml:"%s"`, key.String(), key.String())),
}
if f, ok := foundFields[field.Name]; ok {
if f.Type.Kind() == reflect.Struct && t.Kind() == reflect.Struct {
if fName, tName := f.Type.Name(), t.Name(); fName == "" || tName == "" || fName != tName {
// we have 2 fields with the same name and they are both structs, so we need
// to merge the existig struct with the new one in case they are different
newval := m.makeMergeStruct(reflect.New(f.Type).Elem(), reflect.New(t).Elem()).Elem()
f.Type = newval.Type()
foundFields[field.Name] = f
}
}
// field already found, skip
continue
}
foundFields[field.Name] = field
}
}
}
fields := []reflect.StructField{}
for _, value := range foundFields {
fields = append(fields, value)
}
sort.Slice(fields, func(i, j int) bool {
return fields[i].Name < fields[j].Name
})
newType := reflect.StructOf(fields)
return reflect.New(newType)
}
func (m *Merger) mapToStruct(src reflect.Value) (reflect.Value, error) {
if src.Kind() != reflect.Map {
return reflect.Value{}, nil
}
dest := m.makeMergeStruct(src)
if dest.Kind() == reflect.Ptr {
dest = dest.Elem()
}
for _, key := range src.MapKeys() {
structFieldName := camelCase(key.String())
keyval := reflect.ValueOf(src.MapIndex(key).Interface())
// skip invalid (ie nil) key values
if !keyval.IsValid() {
continue
}
switch {
case keyval.Kind() == reflect.Ptr && keyval.Elem().Kind() == reflect.Map:
keyval, err := m.mapToStruct(keyval.Elem())
if err != nil {
return reflect.Value{}, err
}
_, err = m.mergeStructs(dest.FieldByName(structFieldName), newMergeSource(reflect.ValueOf(keyval.Addr().Interface())), false)
if err != nil {
return reflect.Value{}, err
}
case keyval.Kind() == reflect.Map:
keyval, err := m.mapToStruct(keyval)
if err != nil {
return reflect.Value{}, err
}
_, err = m.mergeStructs(dest.FieldByName(structFieldName), newMergeSource(reflect.ValueOf(keyval.Interface())), false)
if err != nil {
return reflect.Value{}, err
}
default:
dest.FieldByName(structFieldName).Set(reflect.ValueOf(keyval.Interface()))
}
}
return dest, nil
}
func structToMap(src mergeSource) (mergeSource, error) {
if !src.isStruct() {
return src, nil
}
newMap := reflect.ValueOf(map[string]interface{}{})
reflectedStruct, _, err := src.reflect()
if err != nil {
return mergeSource{}, err
}
typ := reflectedStruct.Type()
for i := 0; i < typ.NumField(); i++ {
structField := typ.Field(i)
if structField.PkgPath != "" {
// skip private fields
continue
}
name := yamlFieldName(structField)
newMap.SetMapIndex(reflect.ValueOf(name), reflectedStruct.Field(i))
}
return newMergeSource(newMap), nil
}
type ConfigOptions struct {
Overwrite []string `json:"overwrite,omitempty" yaml:"overwrite,omitempty"`
}
func yamlFieldName(sf reflect.StructField) string {
if tag, ok := sf.Tag.Lookup("yaml"); ok {
// with yaml:"foobar,omitempty"
// we just want to the "foobar" part
parts := strings.Split(tag, ",")
if parts[0] != "" && parts[0] != "-" {
return parts[0]
}
}
// guess the field name from reversing camel case
// so "FooBar" becomes "foo-bar"
parts := camelcase.Split(sf.Name)
for i := range parts {
parts[i] = strings.ToLower(parts[i])
}
return strings.Join(parts, "-")
}
// CanonicalFieldName will return the the field name that will be used with
// merging maps and structs where the name casing/formatting may not
// be consistent. If the field uses tag `figtree:",name=MyName"` then
// that name will be used instead of the default contention.
func CanonicalFieldName(sf reflect.StructField) string {
if tag, ok := sf.Tag.Lookup("figtree"); ok {
for _, part := range strings.Split(tag, ",") {
if strings.HasPrefix(part, "name=") {
return strings.TrimPrefix(part, "name=")
}
}
}
// For consistency with YAML data, determine a canonical field name
// based on the YAML tag. Do not rely on the Go struct field name unless
// there is no YAML tag.
return camelCase(yamlFieldName(sf))
}
func (m *Merger) mustOverwrite(name string) bool {
for _, prop := range m.Config.Overwrite {
if name == prop {
return true
}
}
return false
}
func (m *Merger) mustIgnore(name string) bool {
for _, prop := range m.ignore {
if name == prop {
return true
}
}
return false
}
func isZeroOrDefaultOption(v reflect.Value) bool {
if option := toOption(v); option != nil {
// an option can only be `zero` if it is undefined
if !option.IsDefined() {
return true
}
return option.IsDefault()
}
return false
}
func toOption(v reflect.Value) option {
v = indirect(v)
if !v.IsValid() {
return nil
}
if !v.CanAddr() {
tmp := reflect.New(v.Type()).Elem()
tmp.Set(v)
v = tmp
}
if option, ok := v.Addr().Interface().(option); ok {
return option
}
return nil
}
func indirect(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Pointer {
v = v.Elem()
}
return v
}
func uninterface(v reflect.Value) reflect.Value {
if v.Kind() == reflect.Interface {
return v.Elem()
}
return v
}
func isZero(v reflect.Value) bool {
v = indirect(v)
if !v.IsValid() {
return true
}
if option := toOption(v); option != nil {
return !option.IsDefined()
}
return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
}
func isSame(v1, v2 reflect.Value) bool {
v1Valid := v1.IsValid()
v2Valid := v2.IsValid()
if !v1Valid && !v2Valid {
return true
}
if !v1Valid || !v2Valid {
return false
}
return reflect.DeepEqual(v1.Interface(), v2.Interface())
}
type notAssignableError struct {
dstType reflect.Type
srcType reflect.Type
sourceLocation SourceLocation
}
func (e notAssignableError) Error() string {
return fmt.Sprintf("%s: %s is not assignable to %s", e.sourceLocation, e.srcType, e.dstType)
}
var stringType = reflect.ValueOf("").Type()
type assignOptions struct {
// Overwrite will attempt to replace the destination with the source
// even if the dest is already a valid (non-zero, non-default) value.
Overwrite bool
// srcIsDefault is used internally when we are provided src as an Option
// and we unwrap the option and recursively assign the raw value to dest.
srcIsDefault bool
// destIsDefault is used internally when we are provided dest as an Option
// and we unwrap the option and recursively try to assign src to the raw
// value.
destIsDefault bool
// sourceLocation is used internally to track the source file
// name/line/column when that data is available. This is set
// when we recursively call assignValue after unwrapping src Option.
sourceLocation SourceLocation
}
// assignValue will attempt to assign src to dest. If there is no errors, the
// bool return value will indicate if the assignment happened, which will be
// false when the trying to assign to a non-zero, or non-default value (without
// Overwrite set)
func (m *Merger) assignValue(dest reflect.Value, src mergeSource, opts assignOptions) (bool, error) {
reflectedSrc, coord, err := src.reflect()
if err != nil {
return false, walky.ErrFilename(err, m.sourceFile)
}
Log.Debugf("assignValue: %#v to %#v [opts: %#v]\n", reflectedSrc, dest, opts)
if !dest.IsValid() || !reflectedSrc.IsValid() {
return false, nil
}
// Not much we can do here if dest is unsettable, this will happen if
// dest comes from a map without copying first. This is a programmer error.
if !dest.CanSet() {
return false, errors.Errorf("Cannot assign %#v to unsettable value %#v", reflectedSrc, dest)
}
// if we have a pointer value, deref (and create if nil)
if dest.Kind() == reflect.Pointer {
if dest.IsNil() {
dest.Set(reflect.New(dest.Type().Elem()))
}
dest = dest.Elem()
}
// if src is a pointer, deref, return if nil and not overwriting
if reflectedSrc.Kind() == reflect.Pointer {
reflectedSrc = reflectedSrc.Elem()
// reflectedSrc might be invalid if it was Nil so lets handle that now
if !reflectedSrc.IsValid() {
if opts.Overwrite {
dest.Set(reflectedSrc)
return true, nil
}
return false, nil
}
}
// check to see if we can convert src to dest type before we check to see
// if is assignable. We cannot assign float32 to float64, but we can
// convert float32 to float64 and then assign. Note we skip conversion
// to strings since almost anything can be converted to a string
if dest.Kind() != reflect.String && reflectedSrc.CanConvert(dest.Type()) {
reflectedSrc = reflectedSrc.Convert(dest.Type())
}
// if the source is an option, get the raw value of the option
// and try to assign that to the dest. assignValue does not require
// the source to be addressable, but in order to check for the option
// interface we might have to make the source addressable via a copy.
addressableSrc := reflectedSrc
if !addressableSrc.CanAddr() {
addressableSrc = reflect.New(reflectedSrc.Type()).Elem()
addressableSrc.Set(reflectedSrc)
}
if option := toOption(addressableSrc); option != nil {
srcOptionValue := reflect.ValueOf(option.GetValue())
opts.sourceLocation = option.GetSource()
opts.srcIsDefault = option.IsDefault()
return m.assignValue(dest, newMergeSource(srcOptionValue), opts)
}
// if dest is an option type, then try to assign directly to the
// raw option value and then populate the option object
if dest.CanAddr() {
if option := toOption(dest); option != nil {
destOptionValue := reflect.ValueOf(option.GetValue())
if !destOptionValue.IsValid() {
// this will happen when we have an Option[any], and
// GetValue returns nil as the default value
if _, ok := dest.Interface().(Option[any]); ok {
// since we want an `any` we should be good with
// just creating the src type
destOptionValue = reflect.New(reflectedSrc.Type()).Elem()
}
}
if !destOptionValue.CanSet() {
destOptionValue = reflect.New(destOptionValue.Type()).Elem()
}
opts.destIsDefault = option.IsDefault()
ok, err := m.assignValue(destOptionValue, src, opts)
if err != nil {
return false, err
}
if ok {
if err := option.SetValue(destOptionValue.Interface()); err != nil {
return false, err
}
source := opts.sourceLocation
if source.Name == "" {
source.Name = m.sourceFile
}
if coord != nil {
source.Location = coord
}
option.SetSource(source)
}
return ok, nil
}
}
// if we are assigning to a yaml.Node then try to preserve the raw
// yaml.Node input, otherwise encode the src into the Node.
if node, ok := dest.Interface().(yaml.Node); ok {
if src.node != nil {
dest.Set(reflect.ValueOf(*src.node))
return true, nil
}
if err := node.Encode(reflectedSrc.Interface()); err != nil {
return false, errors.WithStack(err)
}
dest.Set(reflect.ValueOf(node))
return true, nil
}
if reflectedSrc.Type().AssignableTo(dest.Type()) {
shouldAssignDest := opts.Overwrite || isZero(dest) || (opts.destIsDefault && !opts.srcIsDefault)
if shouldAssignDest {
switch reflectedSrc.Kind() {
case reflect.Map:
// maps are mutable, so create a brand new shiny one
dup := reflect.New(reflectedSrc.Type()).Elem()
ok, err := m.mergeMaps(dup, src, opts.Overwrite)
if err != nil {
return false, err
}
if ok {
dest.Set(dup)
}
return ok, nil
case reflect.Slice:
if reflectedSrc.IsNil() {
dest.Set(reflectedSrc)
} else {
// slices are mutable, so create a brand new shiny one
cp := reflect.MakeSlice(reflectedSrc.Type(), reflectedSrc.Len(), reflectedSrc.Len())
reflect.Copy(cp, reflectedSrc)
dest.Set(cp)
}
default:
dest.Set(reflectedSrc)
}
return true, nil
}
return false, nil
}
if dest.Kind() == reflect.Bool && reflectedSrc.Kind() == reflect.String {
b, err := strconv.ParseBool(reflectedSrc.Interface().(string))
if err != nil {
return false, errors.Wrapf(err, "%s is not assignable to %s, invalid bool value %#v", reflectedSrc.Type(), dest.Type(), reflectedSrc)
}
dest.Set(reflect.ValueOf(b))
return true, nil
}
if dest.Kind() == reflect.String && reflectedSrc.Kind() != reflect.String && stringType.AssignableTo(dest.Type()) {
switch reflectedSrc.Kind() {
case reflect.Array, reflect.Slice, reflect.Map:
return false, errors.WithStack(
notAssignableError{
srcType: reflectedSrc.Type(),
dstType: dest.Type(),
sourceLocation: NewSource(m.sourceFile, WithLocation(coord)),
},
)
case reflect.Struct:
// we generally dont want to assign structs to a string
// unless that struct is an option struct in which case
// we use convert the value
if option := toOption(reflectedSrc); option != nil {
dest.Set(reflect.ValueOf(fmt.Sprint(option.GetValue())))
}
return false, errors.WithStack(
notAssignableError{
srcType: reflectedSrc.Type(),
dstType: dest.Type(),
sourceLocation: NewSource(m.sourceFile, WithLocation(coord)),
},
)
default:
// if we have a scalar node we want to convert to a string, just use
// the literal value tokenized from the document, this will
// allow values like `False` to be preserved as a case-sensitive
// string rather than being converted to a bool, the back to a string.
if src.node != nil && src.node.Kind == yaml.ScalarNode {
dest.Set(reflect.ValueOf(src.node.Value))