Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability for mockery to search up to root path for config file #527

Merged
merged 3 commits into from Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
51 changes: 36 additions & 15 deletions cmd/mockery.go
Expand Up @@ -10,6 +10,7 @@ import (
"strings"
"time"

"github.com/chigopher/pathlib"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"github.com/rs/zerolog"
Expand All @@ -28,7 +29,7 @@ var (
)

func init() {
cobra.OnInitialize(initConfig)
cobra.OnInitialize(func() { initConfig(nil, nil) })
}

func NewRootCmd() *cobra.Command {
Expand Down Expand Up @@ -103,33 +104,51 @@ func Execute() {
}
}

func initConfig() {
viper.SetEnvPrefix("mockery")
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
viper.AutomaticEnv()
func initConfig(baseSearchPath *pathlib.Path, viperObj *viper.Viper) {
if baseSearchPath == nil {
currentWorkingDir, err := os.Getwd()
if err != nil {
panic(err)
}
baseSearchPath = pathlib.NewPath(currentWorkingDir)
}
if viperObj == nil {
viperObj = viper.GetViper()
}

viperObj.SetEnvPrefix("mockery")
viperObj.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
viperObj.AutomaticEnv()

if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else if viper.IsSet("config") {
viper.SetConfigFile(viper.GetString("config"))
viperObj.SetConfigFile(cfgFile)
} else if viperObj.IsSet("config") {
viperObj.SetConfigFile(viperObj.GetString("config"))
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
log.Fatal().Err(err).Msgf("Failed to find homedir")
}

// Search config in home directory with name ".cobra" (without extension).
viper.AddConfigPath(".")
viper.AddConfigPath(home)
viper.SetConfigName(".mockery")
currentDir := baseSearchPath

for {
viperObj.AddConfigPath(currentDir.String())
if len(currentDir.Parts()) <= 1 {
break
}
currentDir = currentDir.Parent()
}

viperObj.AddConfigPath(home)
viperObj.SetConfigName(".mockery")
}

// Note we purposely ignore the error. Don't care if we can't find a config file.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintf(os.Stderr, "Using config file: %s\n", viper.ConfigFileUsed())
}
viperObj.ReadInConfig()
viperObj.Set("config", viperObj.ConfigFileUsed())
}

const regexMetadataChars = "\\.+*?()|[]{}^$"
Expand All @@ -143,6 +162,7 @@ func GetRootAppFromViper(v *viper.Viper) (*RootApp, error) {
if err := v.UnmarshalExact(&r.Config); err != nil {
return nil, errors.Wrapf(err, "failed to get config")
}
r.Config.Config = v.ConfigFileUsed()
return r, nil
}

Expand All @@ -164,6 +184,7 @@ func (r *RootApp) Run() error {
}
log = log.With().Bool(logging.LogKeyDryRun, r.Config.DryRun).Logger()
log.Info().Msgf("Starting mockery")
log.Info().Msgf("Using config: %s", r.Config.Config)
ctx := log.WithContext(context.Background())

if r.Config.Version {
Expand Down
46 changes: 45 additions & 1 deletion cmd/mockery_test.go
Expand Up @@ -3,8 +3,10 @@ package cmd
import (
"fmt"
"os"
"strings"
"testing"

"github.com/chigopher/pathlib"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -76,7 +78,7 @@ func TestConfigEnvFlags(t *testing.T) {
env(t, "EXPORTED", fmt.Sprint(expected.Exported))
env(t, "WITH_EXPECTER", fmt.Sprint(expected.WithExpecter))

initConfig()
initConfig(nil, nil)

app, err := GetRootAppFromViper(viper.GetViper())
require.NoError(t, err)
Expand All @@ -89,3 +91,45 @@ func env(t *testing.T, key, value string) {
t.Cleanup(func() { os.Unsetenv(key) })
os.Setenv(key, value)
}

func Test_initConfig(t *testing.T) {
tests := []struct {
name string
base_path string
configPath string
}{
{
name: "test config at base directory",
base_path: "1/2/3/4",
configPath: "1/2/3/4/.mockery.yaml",
},
{
name: "test config at upper directory",
base_path: "1/2/3/4",
configPath: "1/.mockery.yaml",
},
{
name: "no config file found",
base_path: "1/2/3/4",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpDir := pathlib.NewPath(t.TempDir())
baseDir := tmpDir.Join(strings.Split(tt.base_path, "/")...)
require.NoError(t, baseDir.MkdirAll())

configPath := pathlib.NewPath("")
if tt.configPath != "" {
configPath = tmpDir.Join(strings.Split(tt.configPath, "/")...)
configPath.WriteFile([]byte("all: True"))
}

viperObj := viper.New()

initConfig(baseDir, viperObj)

assert.Equal(t, configPath.String(), viperObj.ConfigFileUsed())
})
}
}
7 changes: 7 additions & 0 deletions cmd/showconfig.go
Expand Up @@ -18,6 +18,7 @@ func NewShowConfigCmd() *cobra.Command {
This initializes viper and prints out the merged configuration between
config files, environment variables, and CLI flags.`,
RunE: func(cmd *cobra.Command, args []string) error {

config := &config.Config{}
if err := viper.UnmarshalExact(config); err != nil {
return errors.Wrapf(err, "failed to unmarshal config")
Expand All @@ -26,6 +27,12 @@ func NewShowConfigCmd() *cobra.Command {
if err != nil {
return errors.Wrapf(err, "Failed to marshal yaml")
}
log, err := getLogger(config.LogLevel)
if err != nil {
panic(err)
}
log.Info().Msgf("Using config: %s", config.Config)

fmt.Printf("%s", string(out))
return nil
},
Expand Down
1 change: 1 addition & 0 deletions go.mod
Expand Up @@ -3,6 +3,7 @@ module github.com/vektra/mockery/v2
go 1.19

require (
github.com/chigopher/pathlib v0.12.0
github.com/mitchellh/go-homedir v1.1.0
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.27.0
Expand Down
7 changes: 7 additions & 0 deletions go.sum
Expand Up @@ -39,6 +39,8 @@ dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/chigopher/pathlib v0.12.0 h1:1GM7fN/IwXXmOHbd1jkMqHD2wUhYqUvafgxTwmLT/q8=
github.com/chigopher/pathlib v0.12.0/go.mod h1:EJ5UtJ/sK8Nt6q3VWN+EwZLZ3g0afJiG8NegYiQQ/gQ=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
Expand Down Expand Up @@ -150,8 +152,10 @@ github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3v
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pelletier/go-toml/v2 v2.0.2 h1:+jQXlF3scKIcSEKkdHzXhCTDLPFi5r1wnK6yPS+49Gw=
github.com/pelletier/go-toml/v2 v2.0.2/go.mod h1:MovirKjgVRESsAvNZlAjtFwV867yGuwRkXbG66OzopI=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
Expand All @@ -162,6 +166,7 @@ github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.27.0 h1:1T7qCieN22GVc8S4Q2yuexzBb1EqjbgjSH9RohbMjKs=
github.com/rs/zerolog v1.27.0/go.mod h1:7frBqO0oezxmnO7GF86FY++uy8I0Tk/If5ni1G9Qc0U=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/afero v1.4.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/afero v1.8.2 h1:xehSyVa0YnHWsJ49JFljMpg1HX19V6NDZ1fkm1Xznbo=
github.com/spf13/afero v1.8.2/go.mod h1:CtAatgMJh6bJEIs48Ay/FOnkljP3WeGUG0MC1RfAqwo=
github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w=
Expand All @@ -180,6 +185,7 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
Expand All @@ -198,6 +204,7 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
Expand Down
14 changes: 7 additions & 7 deletions mocks/pkg/fixtures/Expecter.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.