-
Notifications
You must be signed in to change notification settings - Fork 423
/
Copy pathconfig.go
802 lines (716 loc) · 25.6 KB
/
config.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
package config
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"reflect"
"regexp"
"strings"
"github.com/chigopher/pathlib"
"github.com/jinzhu/copier"
"github.com/mitchellh/mapstructure"
"github.com/rs/zerolog"
"github.com/spf13/viper"
"github.com/vektra/mockery/v2/pkg/logging"
"github.com/vektra/mockery/v2/pkg/stackerr"
"golang.org/x/tools/go/packages"
"gopkg.in/yaml.v3"
)
var (
ErrNoConfigFile = fmt.Errorf("no config file exists")
ErrNoGoFilesFoundInRoot = fmt.Errorf("no go files found in root search path")
ErrPkgNotFound = fmt.Errorf("package not found in config")
)
type Interface struct {
Config Config `mapstructure:"config"`
}
type Config struct {
All bool `mapstructure:"all"`
BuildTags string `mapstructure:"tags"`
Case string `mapstructure:"case"`
Config string `mapstructure:"config"`
Cpuprofile string `mapstructure:"cpuprofile"`
Dir string `mapstructure:"dir"`
DisableConfigSearch bool `mapstructure:"disable-config-search"`
DisableVersionString bool `mapstructure:"disable-version-string"`
DryRun bool `mapstructure:"dry-run"`
ExcludeRegex string `mapstructure:"exclude-regex"`
Exported bool `mapstructure:"exported"`
FileName string `mapstructure:"filename"`
IncludeAutoGenerated bool `mapstructure:"include-auto-generated"`
IncludeRegex string `mapstructure:"include-regex"`
InPackage bool `mapstructure:"inpackage"`
InPackageSuffix bool `mapstructure:"inpackage-suffix"`
KeepTree bool `mapstructure:"keeptree"`
LogLevel string `mapstructure:"log-level"`
MockName string `mapstructure:"mockname"`
Name string `mapstructure:"name"`
Note string `mapstructure:"note"`
Outpkg string `mapstructure:"outpkg"`
Output string `mapstructure:"output"`
Packages map[string]interface{} `mapstructure:"packages"`
Packageprefix string `mapstructure:"packageprefix"`
Print bool `mapstructure:"print"`
Profile string `mapstructure:"profile"`
Quiet bool `mapstructure:"quiet"`
Recursive bool `mapstructure:"recursive"`
Exclude []string `mapstructure:"exclude"`
SrcPkg string `mapstructure:"srcpkg"`
BoilerplateFile string `mapstructure:"boilerplate-file"`
// StructName overrides the name given to the mock struct and should only be nonempty
// when generating for an exact match (non regex expression in -name).
StructName string `mapstructure:"structname"`
TestOnly bool `mapstructure:"testonly"`
UnrollVariadic bool `mapstructure:"unroll-variadic"`
Version bool `mapstructure:"version"`
WithExpecter bool `mapstructure:"with-expecter"`
ReplaceType []string `mapstructure:"replace-type"`
// Viper throws away case-sensitivity when it marshals into this struct. This
// destroys necessary information we need, specifically around interface names.
// So, we re-read the config into this map outside of viper.
// https://github.com/spf13/viper/issues/1014
_cfgAsMap map[string]any
pkgConfigCache map[string]*Config
}
func NewConfigFromViper(v *viper.Viper) (*Config, error) {
c := &Config{
Config: v.ConfigFileUsed(),
}
packageList, err := c.GetPackages(context.Background())
if err != nil {
return c, fmt.Errorf("failed to get packages: %w", err)
}
// Set defaults
if len(packageList) == 0 {
v.SetDefault("case", "camel")
v.SetDefault("dir", ".")
v.SetDefault("output", "./mocks")
} else {
v.SetDefault("dir", "mocks/{{.PackagePath}}")
v.SetDefault("filename", "mock_{{.InterfaceName}}.go")
v.SetDefault("include-auto-generated", true)
v.SetDefault("mockname", "Mock{{.InterfaceName}}")
v.SetDefault("outpkg", "{{.PackageName}}")
v.SetDefault("with-expecter", true)
v.SetDefault("dry-run", false)
v.SetDefault("log-level", "info")
}
if err := v.UnmarshalExact(c); err != nil {
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
}
return c, nil
}
func (c *Config) Initialize(ctx context.Context) error {
log := zerolog.Ctx(ctx)
if err := c.discoverRecursivePackages(ctx); err != nil {
return fmt.Errorf("failed to discover recursive packages: %w", err)
}
log.Trace().Msg("merging in config")
if err := c.mergeInConfig(ctx); err != nil {
return err
}
return nil
}
// CfgAsMap reads in the config file and returns a map representation, instead of a
// struct representation. This is mainly needed because viper throws away case-sensitivity
// in the `packages` section, which won't work when defining interface names 😞
func (c *Config) CfgAsMap(ctx context.Context) (map[string]any, error) {
log := zerolog.Ctx(ctx)
configPath := pathlib.NewPath(c.Config)
if c._cfgAsMap == nil {
log.Debug().Msgf("config map is nil, reading: %v", configPath)
newCfg := make(map[string]any)
fileBytes, err := os.ReadFile(configPath.String())
if err != nil {
if os.IsNotExist(err) {
log.Debug().Msg("config file doesn't exist, returning empty config map")
return map[string]any{}, nil
}
return nil, stackerr.NewStackErrf(err, "failed to read file: %v", configPath)
}
if err := yaml.Unmarshal(fileBytes, newCfg); err != nil {
return nil, stackerr.NewStackErrf(err, "failed to unmarshal yaml")
}
c._cfgAsMap = newCfg
}
return c._cfgAsMap, nil
}
func (c *Config) getDecoder(result any) (*mapstructure.Decoder, error) {
return mapstructure.NewDecoder(&mapstructure.DecoderConfig{
ErrorUnused: true,
Result: result,
IgnoreUntaggedFields: true,
})
}
// GetPackages returns a list of the packages that are defined in
// the `packages` config section.
func (c *Config) GetPackages(ctx context.Context) ([]string, error) {
// NOTE: The reason why we can't rely on viper to get the
// values in the `packages` section is because viper throws
// away maps with no values. Our config allows empty maps,
// so this breaks our logic. We need to manually parse this section
// instead. See: https://github.com/spf13/viper/issues/819
log := zerolog.Ctx(ctx)
cfgMap, err := c.CfgAsMap(ctx)
if err != nil {
return nil, err
}
packagesSection, ok := cfgMap["packages"]
if !ok {
log.Debug().Msg("packages section is not defined")
return []string{}, nil
}
packageSection, ok := packagesSection.(map[string]any)
if !ok {
msg := "packages section is of the wrong type"
log.Error().Msg(msg)
return []string{}, fmt.Errorf(msg)
}
packageList := []string{}
for key := range packageSection {
packageList = append(packageList, key)
}
return packageList, nil
}
func (c *Config) getPackageConfigMap(ctx context.Context, packageName string) (map[string]any, error) {
cfgMap, err := c.CfgAsMap(ctx)
if err != nil {
return nil, err
}
packageSection := cfgMap["packages"].(map[string]any)
configUnmerged, ok := packageSection[packageName]
if !ok {
return nil, ErrPkgNotFound
}
configAsMap, isMap := configUnmerged.(map[string]any)
if isMap {
return configAsMap, nil
}
return map[string]any{}, nil
}
func (c *Config) GetPackageConfig(ctx context.Context, packageName string) (*Config, error) {
log := zerolog.Ctx(ctx)
if c.pkgConfigCache == nil {
log.Debug().Msg("package cache is nil")
c.pkgConfigCache = make(map[string]*Config)
} else if pkgConf, ok := c.pkgConfigCache[packageName]; ok {
log.Debug().Msgf("package cache is not nil, returning cached result")
return pkgConf, nil
}
pkgConfig := reflect.New(reflect.ValueOf(c).Elem().Type()).Interface()
if err := copier.Copy(pkgConfig, c); err != nil {
return nil, fmt.Errorf("failed to copy config: %w", err)
}
pkgConfigTyped := pkgConfig.(*Config)
configMap, err := c.getPackageConfigMap(ctx, packageName)
if err != nil {
return nil, stackerr.NewStackErrf(err, "unable to get map config for package")
}
configSection, ok := configMap["config"]
if !ok {
log.Debug().Msg("config section not provided for package")
return pkgConfigTyped, nil
}
decoder, err := c.getDecoder(pkgConfigTyped)
if err != nil {
return nil, stackerr.NewStackErrf(err, "failed to get decoder")
}
if err := decoder.Decode(configSection); err != nil {
return nil, err
}
c.pkgConfigCache[packageName] = pkgConfigTyped
return pkgConfigTyped, nil
}
func (c *Config) ExcludePath(path string) bool {
for _, ex := range c.Exclude {
if strings.HasPrefix(path, ex) {
return true
}
}
return false
}
func (c *Config) ShouldGenerateInterface(ctx context.Context, packageName, interfaceName string) (bool, error) {
pkgConfig, err := c.GetPackageConfig(ctx, packageName)
if err != nil {
return false, fmt.Errorf("getting package config: %w", err)
}
log := zerolog.Ctx(ctx)
if pkgConfig.All {
if pkgConfig.IncludeRegex != "" {
log.Warn().Msg("interface config has both `all` and `include-regex` set: `include-regex` will be ignored")
}
if pkgConfig.ExcludeRegex != "" {
log.Warn().Msg("interface config has both `all` and `exclude-regex` set: `exclude-regex` will be ignored")
}
return true, nil
}
interfacesSection, err := c.getInterfacesSection(ctx, packageName)
if err != nil {
return false, fmt.Errorf("getting interfaces section: %w", err)
}
_, interfaceExists := interfacesSection[interfaceName]
if interfaceExists {
return true, nil
}
includeRegex := pkgConfig.IncludeRegex
excludeRegex := pkgConfig.ExcludeRegex
if includeRegex == "" {
if excludeRegex != "" {
log.Warn().Msg("interface config has `exclude-regex` set but not `include-regex`: `exclude-regex` will be ignored")
}
return false, nil
}
includedByRegex, err := regexp.MatchString(includeRegex, interfaceName)
if err != nil {
return false, fmt.Errorf("evaluating `include-regex`: %w", err)
}
if !includedByRegex {
return false, nil
}
if excludeRegex == "" {
return true, nil
}
excludedByRegex, err := regexp.MatchString(excludeRegex, interfaceName)
if err != nil {
return false, fmt.Errorf("evaluating `exclude-regex`: %w", err)
}
return !excludedByRegex, nil
}
func (c *Config) getInterfacesSection(ctx context.Context, packageName string) (map[string]any, error) {
pkgMap, err := c.getPackageConfigMap(ctx, packageName)
if err != nil {
return nil, err
}
interfaceSection, exists := pkgMap["interfaces"]
if !exists {
return make(map[string]any), nil
}
mapConfig, ok := interfaceSection.(map[string]any)
if !ok {
return nil, fmt.Errorf("interfaces section has type %T, expected map[string]any", interfaceSection)
}
return mapConfig, nil
}
func (c *Config) GetInterfaceConfig(ctx context.Context, packageName string, interfaceName string) ([]*Config, error) {
log := zerolog.
Ctx(ctx).
With().
Str(logging.LogKeyQualifiedName, packageName).
Str(logging.LogKeyInterface, interfaceName).
Logger()
ctx = log.WithContext(ctx)
configs := []*Config{}
pkgConfig, err := c.GetPackageConfig(ctx, packageName)
if err != nil {
return nil, stackerr.NewStackErrf(err, "failed to get config for package when iterating over interface")
}
interfacesSection, err := c.getInterfacesSection(ctx, packageName)
if err != nil {
return nil, err
}
// Copy the package-level config to our interface-level config
pkgConfigCopy := reflect.New(reflect.ValueOf(pkgConfig).Elem().Type()).Interface()
if err := copier.Copy(pkgConfigCopy, pkgConfig); err != nil {
return nil, stackerr.NewStackErrf(err, "failed to create a copy of package config")
}
baseConfigTyped := pkgConfigCopy.(*Config)
interfaceSection, ok := interfacesSection[interfaceName]
if !ok {
log.Debug().Msg("interface not defined in package configuration")
return []*Config{baseConfigTyped}, nil
}
interfaceSectionTyped, ok := interfaceSection.(map[string]any)
if !ok {
// check if it's an empty map... sometimes we just want to "enable"
// the interface but not provide any additional config beyond what
// is provided at the package level
if reflect.ValueOf(&interfaceSection).Elem().IsZero() {
return []*Config{baseConfigTyped}, nil
}
msgString := "bad type provided for interface config"
log.Error().Msgf(msgString)
return nil, stackerr.NewStackErr(errors.New(msgString))
}
configSection, ok := interfaceSectionTyped["config"]
if ok {
log.Debug().Msg("config section exists for interface")
// if `config` is provided, we'll overwrite the values in our
// baseConfigTyped struct to act as the "new" base config.
// This will allow us to set the default values for the interface
// but override them further for each mock defined in the
// `configs` section.
decoder, err := c.getDecoder(baseConfigTyped)
if err != nil {
return nil, stackerr.NewStackErrf(err, "unable to create mapstructure decoder")
}
if err := decoder.Decode(configSection); err != nil {
return nil, stackerr.NewStackErrf(err, "unable to decode interface config")
}
} else {
log.Debug().Msg("config section for interface doesn't exist")
}
configsSection, ok := interfaceSectionTyped["configs"]
if ok {
log.Debug().Msg("configs section exists for interface")
configsSectionTyped := configsSection.([]any)
for _, configMap := range configsSectionTyped {
// Create a copy of the package-level config
currentInterfaceConfig := reflect.New(reflect.ValueOf(baseConfigTyped).Elem().Type()).Interface()
if err := copier.Copy(currentInterfaceConfig, baseConfigTyped); err != nil {
return nil, stackerr.NewStackErrf(err, "failed to copy package config")
}
// decode the new values into the struct
decoder, err := c.getDecoder(currentInterfaceConfig)
if err != nil {
return nil, stackerr.NewStackErrf(err, "unable to create mapstructure decoder")
}
if err := decoder.Decode(configMap); err != nil {
return nil, stackerr.NewStackErrf(err, "unable to decode interface config")
}
configs = append(configs, currentInterfaceConfig.(*Config))
}
return configs, nil
}
log.Debug().Msg("configs section doesn't exist for interface")
if len(configs) == 0 {
configs = append(configs, baseConfigTyped)
}
return configs, nil
}
// addSubPkgConfig injects the given pkgPath into the `packages` config section.
// You specify a parentPkgPath to inherit the config from.
func (c *Config) addSubPkgConfig(ctx context.Context, subPkgPath string, parentPkgPath string) error {
log := zerolog.Ctx(ctx).With().
Str("parent-package", parentPkgPath).
Str("sub-package", subPkgPath).Logger()
log.Trace().Msg("adding sub-package to config map")
parentPkgConfig, err := c.getPackageConfigMap(ctx, parentPkgPath)
if err != nil {
log.Err(err).
Msg("failed to get package config for parent package")
return fmt.Errorf("failed to get package config: %w", err)
}
log.Trace().Msg("getting config")
cfg, err := c.CfgAsMap(ctx)
if err != nil {
return fmt.Errorf("failed to get configuration map: %w", err)
}
log.Trace().Msg("getting packages section")
packagesSection := cfg["packages"].(map[string]any)
// Don't overwrite any config that already exists
_, pkgExists := packagesSection[subPkgPath]
if !pkgExists {
log.Trace().Msg("sub-package doesn't exist in config")
packagesSection[subPkgPath] = map[string]any{}
newPkgSection := packagesSection[subPkgPath].(map[string]any)
newPkgSection["config"] = parentPkgConfig["config"]
} else {
log.Trace().Msg("sub-package exists in config")
// The sub-package exists in config. Check if it has its
// own `config` section and merge with the parent package
// if so.
subPkgConfig, err := c.getPackageConfigMap(ctx, subPkgPath)
if err != nil {
log.Err(err).Msg("could not get child package config")
return fmt.Errorf("failed to get sub-package config: %w", err)
}
for key, val := range parentPkgConfig {
if _, keyInSubPkg := subPkgConfig[key]; !keyInSubPkg {
subPkgConfig[key] = val
}
}
}
return nil
}
func isAutoGenerated(path *pathlib.Path) (bool, error) {
file, err := path.OpenFile(os.O_RDONLY)
if err != nil {
return false, stackerr.NewStackErr(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
if strings.Contains(text, "DO NOT EDIT") {
return true, nil
} else if strings.HasPrefix(text, "package ") {
break
}
}
return false, nil
}
func (c *Config) subPackages(
ctx context.Context,
pkgPath string,
pkgConfig *Config,
currentDepth int,
) ([]string, error) {
log := zerolog.Ctx(ctx)
pkgs, err := packages.Load(&packages.Config{
Mode: packages.NeedName | packages.NeedFiles,
}, pkgPath)
if err != nil {
return nil, fmt.Errorf("failed to load packages: %w", err)
}
pkg := pkgs[0]
if currentDepth == 0 && len(pkg.GoFiles) == 0 {
log.Error().
Err(ErrNoGoFilesFoundInRoot).
Str("documentation", logging.DocsURL("/notes/#error-no-go-files-found-in-root-search-path")).
Msg("package contains no go files")
return nil, ErrNoGoFilesFoundInRoot
}
representativeFile := pathlib.NewPath(pkg.GoFiles[0])
searchRoot := representativeFile.Parent()
packageRootName := pathlib.NewPath(pkg.PkgPath)
packageRootPath := searchRoot
subPackages := []string{}
walker, err := pathlib.NewWalk(
searchRoot,
pathlib.WalkAlgorithm(pathlib.AlgorithmBasic),
pathlib.WalkFollowSymlinks(false),
pathlib.WalkVisitDirs(false),
pathlib.WalkVisitFiles(true),
)
if err != nil {
return nil, fmt.Errorf("failed to create filesystem walker: %w", err)
}
visitedDirs := map[string]any{}
subdirectoriesWithGoFiles := []*pathlib.Path{}
// We consider the searchRoot to already be visited because
// we know it's already in the configuration.
visitedDirs[searchRoot.String()] = nil
// Walk the filesystem path, starting at the root of the package we've
// been given. Note that this will always work because Golang downloads
// the package when we call `packages.Load`
walkErr := walker.Walk(func(path *pathlib.Path, info os.FileInfo, err error) error {
if err != nil {
return err
}
_, haveVisitedDir := visitedDirs[path.Parent().String()]
if !haveVisitedDir && strings.HasSuffix(path.Name(), ".go") {
if !c.IncludeAutoGenerated {
autoGenerated, err := isAutoGenerated(path)
if err != nil {
log.Err(err).Stringer("path", path).Msg("failed to determine if file is auto-generated")
return err
}
if autoGenerated {
log.Debug().Stringer("path", path).Msg("skipping file as auto-generated")
return nil
}
}
l := log.With().Stringer("path", path.Parent()).Logger()
l.Debug().Msg("subdirectory has a .go file, adding this path to packages config")
subdirectoriesWithGoFiles = append(subdirectoriesWithGoFiles, path.Parent())
visitedDirs[path.Parent().String()] = nil
}
return nil
})
if walkErr != nil {
return nil, fmt.Errorf("error occurred during filesystem walk: %w", walkErr)
}
// Parse the subdirectories we found into their respective fully qualified
// package paths
for _, d := range subdirectoriesWithGoFiles {
relativeFilesystemPath, err := d.RelativeTo(packageRootPath)
if err != nil {
log.Err(err).Stringer("root", packageRootPath).Stringer("subRoot", d).Msg("failed to make subroot relative to root")
return nil, fmt.Errorf("failed to make subroot relative to root: %w", err)
}
absolutePackageName := packageRootName.Join(relativeFilesystemPath.Parts()...)
subPackages = append(subPackages, absolutePackageName.String())
}
return subPackages, nil
}
// discoverRecursivePackages parses the provided config for packages marked as
// recursive and recurses the file tree to find all sub-packages.
func (c *Config) discoverRecursivePackages(ctx context.Context) error {
log := zerolog.Ctx(ctx)
recursivePackages := map[string]*Config{}
packageList, err := c.GetPackages(ctx)
if err != nil {
return fmt.Errorf("failed to get packages: %w", err)
}
for _, pkg := range packageList {
pkgConfig, err := c.GetPackageConfig(ctx, pkg)
if err != nil {
return fmt.Errorf("failed to get package config: %w", err)
}
if pkgConfig.Recursive {
recursivePackages[pkg] = pkgConfig
}
}
if len(recursivePackages) == 0 {
return nil
}
for pkgPath, conf := range recursivePackages {
pkgLog := log.With().Str("package-path", pkgPath).Logger()
pkgCtx := pkgLog.WithContext(ctx)
pkgLog.Debug().Msg("discovering sub-packages")
subPkgs, err := c.subPackages(pkgCtx, pkgPath, conf, 0)
if err != nil {
return fmt.Errorf("failed to get subpackages: %w", err)
}
for _, subPkg := range subPkgs {
subPkgLog := pkgLog.With().Str("sub-package", subPkg).Logger()
subPkgCtx := subPkgLog.WithContext(pkgCtx)
if len(conf.Exclude) > 0 {
p := pathlib.NewPath(subPkg)
relativePath, err := p.RelativeToStr(pkgPath)
if err != nil {
return stackerr.NewStackErrf(err, "failed to get path for %s relative to %s", subPkg, pkgPath)
}
if conf.ExcludePath(relativePath.String()) {
subPkgLog.Info().Msg("subpackage is excluded")
continue
}
}
subPkgLog.Debug().Msg("adding sub-package config")
if err := c.addSubPkgConfig(subPkgCtx, subPkg, pkgPath); err != nil {
subPkgLog.Err(err).Msg("failed to add sub-package config")
return fmt.Errorf("failed to add sub-package config: %w", err)
}
}
}
log.Trace().Msg("done discovering recursive packages")
return nil
}
func contains[T comparable](slice []T, elem T) bool {
for _, element := range slice {
if elem == element {
return true
}
}
return false
}
// mergeInConfig takes care of merging inheritable configuration
// in the config map. For example, it merges default config, then
// package-level config, then interface-level config.
func (c *Config) mergeInConfig(ctx context.Context) error {
log := zerolog.Ctx(ctx)
log.Trace().Msg("getting packages")
pkgs, err := c.GetPackages(ctx)
if err != nil {
return err
}
log.Trace().Msg("getting default config")
defaultCfg, err := c.CfgAsMap(ctx)
if err != nil {
return err
}
for _, pkgPath := range pkgs {
pkgLog := log.With().Str("package-path", pkgPath).Logger()
pkgLog.Trace().Msg("merging for package")
packageConfig, err := c.getPackageConfigMap(ctx, pkgPath)
if err != nil {
pkgLog.Err(err).Msg("failed to get package config")
return fmt.Errorf("failed to get package config: %w", err)
}
configSectionUntyped, configExists := packageConfig["config"]
if !configExists {
packageConfig["config"] = defaultCfg
continue
}
packageConfigSection := configSectionUntyped.(map[string]any)
for key, value := range defaultCfg {
if contains([]string{"packages", "config"}, key) {
continue
}
_, keyExists := packageConfigSection[key]
if !keyExists {
packageConfigSection[key] = value
}
}
interfaces, err := c.getInterfacesForPackage(ctx, pkgPath)
if err != nil {
return fmt.Errorf("failed to get interfaces for package: %w", err)
}
for _, interfaceName := range interfaces {
interfacesSection, err := c.getInterfacesSection(ctx, pkgPath)
if err != nil {
return err
}
interfaceSectionUntyped, exists := interfacesSection[interfaceName]
if !exists {
continue
}
interfaceSection, ok := interfaceSectionUntyped.(map[string]any)
if !ok {
// assume interfaceSection value is nil
continue
}
interfaceConfigSectionUntyped, exists := interfaceSection["config"]
if !exists {
interfaceSection["config"] = map[string]any{}
}
interfaceConfigSection, ok := interfaceConfigSectionUntyped.(map[string]any)
if !ok {
// Assume this interface's value in the map is nil. Just skip it.
continue
}
for key, value := range packageConfigSection {
if key == "packages" {
continue
}
if _, keyExists := interfaceConfigSection[key]; !keyExists {
interfaceConfigSection[key] = value
}
}
}
}
return nil
}
func (c *Config) getInterfacesForPackage(ctx context.Context, pkgPath string) ([]string, error) {
interfaces := []string{}
packageMap, err := c.getPackageConfigMap(ctx, pkgPath)
if err != nil {
return nil, err
}
interfacesUntyped, exists := packageMap["interfaces"]
if !exists {
return interfaces, nil
}
interfacesMap := interfacesUntyped.(map[string]any)
for key := range interfacesMap {
interfaces = append(interfaces, key)
}
return interfaces, nil
}
func (c *Config) TagName(name string) string {
field, ok := reflect.TypeOf(c).Elem().FieldByName(name)
if !ok {
panic(fmt.Sprintf("unknown config field: %s", name))
}
return string(field.Tag.Get("mapstructure"))
}
// LogUnsupportedPackagesConfig is a method that will help aid migrations to the
// packages config feature. This is intended to be a temporary measure until v3
// when we can remove all legacy config options.
func (c *Config) LogUnsupportedPackagesConfig(ctx context.Context) {
log := zerolog.Ctx(ctx)
unsupportedOptions := make(map[string]any)
for _, name := range []string{"Name", "KeepTree", "Case", "Output", "TestOnly"} {
value := reflect.ValueOf(c).Elem().FieldByName(name)
var valueAsString string
if value.Kind().String() == "bool" {
valueAsString = fmt.Sprintf("%v", value.Bool())
}
if value.Kind().String() == "string" {
valueAsString = value.String()
}
if !value.IsZero() {
unsupportedOptions[c.TagName(name)] = valueAsString
}
}
if len(unsupportedOptions) == 0 {
return
}
l := log.With().
Dict("unsupported-fields", zerolog.Dict().Fields(unsupportedOptions)).
Str("url", logging.DocsURL("/configuration/#parameter-descriptions")).
Logger()
l.Error().Msg("use of unsupported options detected. mockery behavior is undefined.")
}