Skip to content

Commit

Permalink
Add error log for unsupported config
Browse files Browse the repository at this point in the history
This commit will log an error message if unsupported config is being used. I have chosen not to cause mockery to return an error code because it's possible that configs using unsupported parameters are working just fine, so we don't want to break those users. Instead, the log message should hopefully get their attention, and the attention of anyone trying to migrate to packages. Also removed is the conditional used to enter into the `packages` code path. Previously it asserted that `Config.Name == ""` but this was causing more confusion than it needed to.

This fixes #685
  • Loading branch information
LandonTClipp committed Aug 4, 2023
1 parent 2046503 commit 72eb146
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 16 deletions.
1 change: 0 additions & 1 deletion .mockery.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
quiet: False
keeptree: True
disable-version-string: True
with-expecter: True
mockname: "{{.InterfaceName}}"
Expand Down
8 changes: 5 additions & 3 deletions cmd/mockery.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func NewRootCmd() *cobra.Command {
pFlags.StringVar(&cfgFile, "config", "", "config file to use")
pFlags.String("name", "", "name or matching regular expression of interface to generate mock for")
pFlags.Bool("print", false, "print the generated mock to stdout")
pFlags.String("output", "./mocks", "directory to write mocks to")
pFlags.String("output", "", "directory to write mocks to")
pFlags.String("outpkg", "mocks", "name of generated package")
pFlags.String("packageprefix", "", "prefix for the generated package name, it is ignored if outpkg is also specified.")
pFlags.String("dir", "", "directory to search for interfaces")
Expand All @@ -64,7 +64,7 @@ func NewRootCmd() *cobra.Command {
pFlags.Bool("inpackage", false, "generate a mock that goes inside the original package")
pFlags.Bool("inpackage-suffix", false, "use filename '_mock' suffix instead of 'mock_' prefix for InPackage mocks")
pFlags.Bool("testonly", false, "generate a mock in a _test.go file")
pFlags.String("case", "camel", "name the mocked file using casing convention [camel, snake, underscore]")
pFlags.String("case", "", "name the mocked file using casing convention [camel, snake, underscore]")
pFlags.String("note", "", "comment to insert into prologue of each generated file")
pFlags.String("cpuprofile", "", "write cpu profile to file")
pFlags.Bool("version", false, "prints the installed version of mockery")
Expand Down Expand Up @@ -230,7 +230,9 @@ func (r *RootApp) Run() error {
if err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("failed to determine configured packages: %w", err)
}
if len(configuredPackages) != 0 && r.Config.Name == "" {
if len(configuredPackages) != 0 {
r.Config.LogUnsupportedPackagesConfig(ctx)

configuredPackages, err := r.Config.GetPackages(ctx)
if err != nil {
return fmt.Errorf("failed to get package from config: %w", err)
Expand Down
42 changes: 42 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ func NewConfigFromViper(v *viper.Viper) (*Config, error) {

// Set defaults
if len(packages) == 0 {
v.SetDefault("case", "camel")
v.SetDefault("dir", ".")
v.SetDefault("output", "./mocks")
} else {
v.SetDefault("dir", "mocks/{{.PackagePath}}")
v.SetDefault("filename", "mock_{{.InterfaceName}}.go")
Expand Down Expand Up @@ -702,3 +704,43 @@ func (c *Config) getInterfacesForPackage(ctx context.Context, pkgPath string) ([
}
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))

Check warning on line 711 in pkg/config/config.go

View check run for this annotation

Codecov / codecov/patch

pkg/config/config.go#L708-L711

Added lines #L708 - L711 were not covered by tests
}
return string(field.Tag.Get("mapstructure"))

Check warning on line 713 in pkg/config/config.go

View check run for this annotation

Codecov / codecov/patch

pkg/config/config.go#L713

Added line #L713 was not covered by tests
}

// 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()
}

Check warning on line 730 in pkg/config/config.go

View check run for this annotation

Codecov / codecov/patch

pkg/config/config.go#L719-L730

Added lines #L719 - L730 were not covered by tests

if !value.IsZero() {
unsupportedOptions[c.TagName(name)] = valueAsString
}

Check warning on line 734 in pkg/config/config.go

View check run for this annotation

Codecov / codecov/patch

pkg/config/config.go#L732-L734

Added lines #L732 - L734 were not covered by tests
}
if len(unsupportedOptions) == 0 {
return
}

Check warning on line 738 in pkg/config/config.go

View check run for this annotation

Codecov / codecov/patch

pkg/config/config.go#L736-L738

Added lines #L736 - L738 were not covered by tests

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.")

Check warning on line 744 in pkg/config/config.go

View check run for this annotation

Codecov / codecov/patch

pkg/config/config.go#L740-L744

Added lines #L740 - L744 were not covered by tests

}
15 changes: 3 additions & 12 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -700,18 +700,9 @@ func TestNewConfigFromViper(t *testing.T) {
return viper.New()
},
want: &Config{
Dir: ".",
},
},
{
name: "dir set",
v: func(t *testing.T) *viper.Viper {
v := viper.New()
v.Set("dir", "foobar")
return v
},
want: &Config{
Dir: "foobar",
Case: "camel",
Dir: ".",
Output: "./mocks",
},
},
{
Expand Down
2 changes: 2 additions & 0 deletions pkg/outputter.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,8 @@ func (m *Outputter) Generate(ctx context.Context, iface *Interface) error {
}

for _, interfaceConfig := range interfaceConfigs {
interfaceConfig.LogUnsupportedPackagesConfig(ctx)

log.Debug().Msg("getting mock generator")

if err := parseConfigTemplates(ctx, interfaceConfig, iface); err != nil {
Expand Down

0 comments on commit 72eb146

Please sign in to comment.