Skip to content

Commit

Permalink
starting to replace viper with koanf
Browse files Browse the repository at this point in the history
  • Loading branch information
LandonTClipp committed Jan 4, 2025
1 parent 63a89c1 commit 42a1482
Show file tree
Hide file tree
Showing 10 changed files with 145 additions and 89 deletions.
14 changes: 13 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,25 @@ require (
require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/knadh/koanf/maps v0.1.1 // indirect
github.com/knadh/koanf/parsers/yaml v0.1.0 // indirect
github.com/knadh/koanf/providers/env v1.0.0 // indirect
github.com/knadh/koanf/providers/file v1.1.2 // indirect
github.com/knadh/koanf/providers/posflag v0.1.0 // indirect
github.com/knadh/koanf/v2 v2.1.2 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/magiconair/properties v1.8.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/rogpeppe/go-internal v1.9.0 // indirect
github.com/sagikazarmark/locafero v0.6.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
Expand All @@ -41,7 +53,7 @@ require (
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 // indirect
golang.org/x/mod v0.22.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/sys v0.29.0 // indirect
golang.org/x/text v0.21.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
Expand Down
22 changes: 22 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ github.com/chigopher/pathlib v0.19.1 h1:RoLlUJc0CqBGwq239cilyhxPNLXTK+HXoASGyGzn
github.com/chigopher/pathlib v0.19.1/go.mod h1:tzC1dZLW8o33UQpWkNkhvPwL5n4yyFRFm/jL1YGWFvY=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
Expand All @@ -20,6 +23,18 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
github.com/knadh/koanf/maps v0.1.1 h1:G5TjmUh2D7G2YWf5SQQqSiHRJEjaicvU0KpypqB3NIs=
github.com/knadh/koanf/maps v0.1.1/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
github.com/knadh/koanf/parsers/yaml v0.1.0 h1:ZZ8/iGfRLvKSaMEECEBPM1HQslrZADk8fP1XFUxVI5w=
github.com/knadh/koanf/parsers/yaml v0.1.0/go.mod h1:cvbUDC7AL23pImuQP0oRw/hPuccrNBS2bps8asS0CwY=
github.com/knadh/koanf/providers/env v1.0.0 h1:ufePaI9BnWH+ajuxGGiJ8pdTG0uLEUWC7/HDDPGLah0=
github.com/knadh/koanf/providers/env v1.0.0/go.mod h1:mzFyRZueYhb37oPmC1HAv/oGEEuyvJDA98r3XAa8Gak=
github.com/knadh/koanf/providers/file v1.1.2 h1:aCC36YGOgV5lTtAFz2qkgtWdeQsgfxUkxDOe+2nQY3w=
github.com/knadh/koanf/providers/file v1.1.2/go.mod h1:/faSBcv2mxPVjFrXck95qeoyoZ5myJ6uxN8OOVNJJCI=
github.com/knadh/koanf/providers/posflag v0.1.0 h1:mKJlLrKPcAP7Ootf4pBZWJ6J+4wHYujwipe7Ie3qW6U=
github.com/knadh/koanf/providers/posflag v0.1.0/go.mod h1:SYg03v/t8ISBNrMBRMlojH8OsKowbkXV7giIbBVgbz0=
github.com/knadh/koanf/v2 v2.1.2 h1:I2rtLRqXRy1p01m/utEtpZSSA6dcJbgGVuE27kW2PzQ=
github.com/knadh/koanf/v2 v2.1.2/go.mod h1:Gphfaen0q1Fc1HTgJgSTC4oRX9R2R5ErYMZJy8fLJBo=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
Expand All @@ -35,12 +50,17 @@ github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
Expand Down Expand Up @@ -85,6 +105,8 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
Expand Down
6 changes: 4 additions & 2 deletions internal/cmd/mockery.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
pkg "github.com/vektra/mockery/v3/internal"
"github.com/vektra/mockery/v3/internal/logging"
Expand All @@ -29,6 +30,8 @@ func NewRootCmd() (*cobra.Command, error) {
if err != nil && !errors.Is(err, ErrCfgFileNotFound) {
return nil, err
}

var pFlags *pflag.FlagSet
cmd := &cobra.Command{
Use: "mockery",
Short: "Generate mock objects for your Golang interfaces",
Expand All @@ -44,8 +47,7 @@ func NewRootCmd() (*cobra.Command, error) {
}
},
}

pFlags := cmd.PersistentFlags()
pFlags = cmd.PersistentFlags()
pFlags.StringVar(&cfgFile, "config", "", "config file to use")
pFlags.String("tags", "", "space-separated list of additional build tags to load packages")
pFlags.String("mock-build-tags", "", "set the build tags of the generated mocks. Read more about the format: https://pkg.go.dev/cmd/go#hdr-Build_constraints")
Expand Down
12 changes: 8 additions & 4 deletions internal/cmd/showconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import (
"context"
"fmt"
"io"
"os"

koanfYAML "github.com/knadh/koanf/parsers/yaml"
"github.com/kr/pretty"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/vektra/mockery/v3/internal"
pkg "github.com/vektra/mockery/v3/internal"
"github.com/vektra/mockery/v3/internal/logging"
"github.com/vektra/mockery/v3/internal/stackerr"
"gopkg.in/yaml.v3"
Expand All @@ -20,11 +21,14 @@ func NewShowConfigCmd() *cobra.Command {
Short: "Show the yaml config",
Long: `Print out a yaml representation of the yaml config file. This does not show config from exterior sources like CLI, environment etc.`,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := getConfig(nil, nil)
conf, k, err := pkg.NewConfig(nil, nil)
if err != nil {
return err
}
return showConfig(cmd, args, cfg, os.Stdout)
b, _ := k.Marshal(koanfYAML.Parser())
fmt.Println(string(b))
pretty.Print(conf)
return nil
},
}
}
Expand Down
113 changes: 92 additions & 21 deletions internal/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ import (
"github.com/chigopher/pathlib"
"github.com/go-viper/mapstructure/v2"
"github.com/jinzhu/copier"
koanfYAML "github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/providers/posflag"
"github.com/knadh/koanf/v2"
"github.com/rs/zerolog"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/vektra/mockery/v3/internal/logging"
"github.com/vektra/mockery/v3/internal/stackerr"
Expand All @@ -26,28 +31,43 @@ import (
"gopkg.in/yaml.v3"
)

type RootConfig struct {
Config
Packages map[string]PackageConfig `koanf:"packages"`
}

type PackageConfig struct {
Config Config `koanf:"config"`
Interfaces map[string]InterfaceConfig `koanf:"interfaces"`
}

type InterfaceConfig struct {
Config Config `koanf:"config"`
Configs []Config `koanf:"configs"`
}

type Config struct {
All bool `mapstructure:"all"`
Anchors map[string]any `mapstructure:"_anchors"`
BoilerplateFile string `mapstructure:"boilerplate-file"`
BuildTags string `mapstructure:"tags"`
Config string `mapstructure:"config"`
Dir string `mapstructure:"dir"`
Exclude []string `mapstructure:"exclude"`
ExcludeRegex string `mapstructure:"exclude-regex"`
FileName string `mapstructure:"filename"`
Formatter string `mapstructure:"formatter"`
IncludeRegex string `mapstructure:"include-regex"`
LogLevel string `mapstructure:"log-level"`
MockBuildTags string `mapstructure:"mock-build-tags"`
MockName string `mapstructure:"mockname"`
PkgName string `mapstructure:"pkgname"`
Packages map[string]interface{} `mapstructure:"packages"`
Recursive bool `mapstructure:"recursive"`
Template string `mapstructure:"template"`
TemplateData map[string]any `mapstructure:"template-data"`
UnrollVariadic bool `mapstructure:"unroll-variadic"`
Version bool `mapstructure:"version"`
All bool `koanf:"all"`
Anchors map[string]any `koanf:"_anchors"`
BoilerplateFile string `koanf:"boilerplate-file"`
BuildTags string `koanf:"tags"`
Config string `koanf:"config"`
Dir string `koanf:"dir"`
Exclude []string `koanf:"exclude"`
ExcludeRegex string `koanf:"exclude-regex"`
FileName string `koanf:"filename"`
Formatter string `koanf:"formatter"`
IncludeRegex string `koanf:"include-regex"`
LogLevel string `koanf:"log-level"`
MockBuildTags string `koanf:"mock-build-tags"`
MockName string `koanf:"mockname"`
PkgName string `koanf:"pkgname"`
Packages map[string]interface{} `koanf:"packages"`
Recursive bool `koanf:"recursive"`
Template string `koanf:"template"`
TemplateData map[string]any `koanf:"template-data"`
UnrollVariadic bool `koanf:"unroll-variadic"`
Version bool `koanf:"version"`
// 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.
Expand All @@ -56,6 +76,57 @@ type Config struct {
pkgConfigCache map[string]*Config
}

func findConfig() (*pathlib.Path, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("getting current working directory: %w", err)
}
currentPath := pathlib.NewPath(cwd)
for len(currentPath.Parts()) != 1 {
for _, confName := range []string{".mockery.yaml", ".mockery.yml"} {
configPath := currentPath.Join(confName)
isFile, err := configPath.Exists()
if err != nil {
return nil, fmt.Errorf("checking if %s is file: %w", configPath.String(), err)
}
if isFile {
return configPath, nil
}
}
currentPath = currentPath.Parent()
}
return nil, errors.New("mockery config file not found")
}

func NewConfig(configFile *pathlib.Path, flags *pflag.FlagSet) (*RootConfig, *koanf.Koanf, error) {
// 2. Flags
// 3. Config file
var err error
var rootConfig RootConfig
k := koanf.New("::")
if configFile == nil {
configFile, err = findConfig()
if err != nil {
return nil, k, fmt.Errorf("discovering mockery config: %w", err)
}
}

if flags != nil {
if err := k.Load(posflag.Provider(flags, ".", k), nil); err != nil {
return nil, k, fmt.Errorf("loading flags: %w", err)
}
}

if err := k.Load(file.Provider(configFile.String()), koanfYAML.Parser()); err != nil {
return nil, k, fmt.Errorf("loading config file: %w", err)
}

if err := k.Unmarshal("", &rootConfig); err != nil {
return nil, k, fmt.Errorf("unmarshalling config: %w", err)
}
return &rootConfig, k, nil
}

func NewConfigFromViper(v *viper.Viper) (*Config, error) {
c := &Config{
Config: v.ConfigFileUsed(),
Expand Down
4 changes: 2 additions & 2 deletions internal/fixtures/expecter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ func TestExpecter(t *testing.T) {
require.True(t, runCalled)

// Call again panic
require.Panics(t, func() {
assert.Panics(t, func() {
expMock.NoArg()
})
}, "call did not panic")
expMock.AssertExpectations(t)
})

Expand Down
5 changes: 0 additions & 5 deletions internal/fixtures/issue845/interface.go

This file was deleted.

40 changes: 0 additions & 40 deletions internal/fixtures/issue845/interface_test.go

This file was deleted.

14 changes: 2 additions & 12 deletions internal/fixtures/type_alias/interface_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,10 @@ func TestTypeAlias(t *testing.T) {
filepath string
expectedRegex string
}{
{
name: "With alias resolved",
filepath: "./mock_InterfaceWithResolvedAlias_test.go",
expectedRegex: `func \((_?[a-zA-Z]*)+ \*InterfaceWithResolvedAlias\) Foo\(\) int {`,
},
{
name: "With alias unresolved",
filepath: "./mock_InterfaceWithUnresolvedAlias_test.go",
expectedRegex: `func \((_?[a-zA-Z]*)+ \*InterfaceWithUnresolvedAlias\) Foo\(\) type_alias.Type {`,
},
{
name: "Alias to type with underlying struct with resolve-type-alias: True",
filepath: "./mock_Interface2WithResolvedAlias_test.go",
expectedRegex: `func \(_m \*Interface2WithResolvedAlias\) F\(_a0 int, _a1 subpkg.S, _a2 subpkg.S\) {`,
filepath: "./mocks_test.go",
expectedRegex: `func \(_mock \*MockInterface1\) Foo\(\) Type {`,
},
} {
t.Run(tt.name, func(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func TestTemplateMockFuncs(t *testing.T) {
})

t.Run("ImportStatement", func(t *testing.T) {
f := TemplateMockFuncs["ImportStatement"].(func(*Package) string)
f := TemplateMockFuncs["importStatement"].(func(*Package) string)
pkg := NewPackage(types.NewPackage("xyz", "xyz"))
if f(pkg) != `"xyz"` {
t.Errorf("ImportStatement(...): want: `\"xyz\"`; got: `%s`", f(pkg))
Expand All @@ -30,7 +30,7 @@ func TestTemplateMockFuncs(t *testing.T) {
})

t.Run("SyncPkgQualifier", func(t *testing.T) {
f := TemplateMockFuncs["SyncPkgQualifier"].(func([]*Package) string)
f := TemplateMockFuncs["syncPkgQualifier"].(func([]*Package) string)
if f(nil) != "sync" {
t.Errorf("SyncPkgQualifier(...): want: `sync`; got: `%s`", f(nil))
}
Expand Down

0 comments on commit 42a1482

Please sign in to comment.