Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ func Get(fs *pflag.FlagSet) (*Config, error) {

func newDefaultViper() *viper.Viper {
v := viper.New()

v.SetDefault("default.protoPath", []string{""})
v.SetDefault("default.protoFile", []string{""})
v.SetDefault("default.package", "")
Expand Down Expand Up @@ -168,6 +169,13 @@ func newDefaultViper() *viper.Viper {
v.SetDefault("request.certKeyFile", "")
v.SetDefault("request.web", false)

v.SetEnvPrefix("EVANS")
v.SetEnvKeyReplacer(strings.NewReplacer(
".", "_", // for nested values
))
v.AllowEmptyEnv(true)
v.AutomaticEnv()

return v
}

Expand Down
26 changes: 16 additions & 10 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,13 @@ func setupEnv(t *testing.T) (string, string, func()) {
}

mustChdir(t, dir)
oldEnv := os.Getenv("XDG_CONFIG_HOME")
cfgDir := filepath.Join(dir, "config")
os.Setenv("XDG_CONFIG_HOME", cfgDir)
t.Setenv("XDG_CONFIG_HOME", cfgDir)
evansCfgDir := filepath.Join(cfgDir, "evans")
mkdir(t, evansCfgDir)

return dir, evansCfgDir, func() {
mustChdir(t, cwd)
os.Setenv("XDG_CONFIG_HOME", oldEnv)
os.RemoveAll(dir)
viper.Reset()
}
Expand Down Expand Up @@ -172,7 +170,6 @@ func TestLoad(t *testing.T) {
}
}
}

assertWithGolden(t, "create a default global config if both of global and local config are not found",
func(t *testing.T) *Config {
_, _, cleanup := setupEnv(t)
Expand All @@ -185,6 +182,19 @@ func TestLoad(t *testing.T) {
return cfg
})

t.Run("load an environmental variable that overrides local config", func(t *testing.T) {
t.Setenv("EVANS_SERVER_PORT", "9001")

_, _, cleanup := setupEnv(t)
defer cleanup()

cfg := mustGet(t, nil)

if cfg.Server.Port != "9001" {
t.Errorf("port %s not set by os env", cfg.Server.Port)
}
})

assertWithGolden(t, "load a global config if local config is not found", func(t *testing.T) *Config {
oldCWD := getWorkDir(t)

Expand Down Expand Up @@ -329,9 +339,7 @@ func TestEdit(t *testing.T) {
for name, c := range cases {
c := c
t.Run(name, func(t *testing.T) {
oldEnv := os.Getenv("EDITOR")
os.Setenv("EDITOR", c.expectedEditor)
defer os.Setenv("EDITOR", oldEnv)
t.Setenv("EDITOR", c.expectedEditor)

if c.outsideGitRepo {
wd, err := os.Getwd()
Expand Down Expand Up @@ -393,9 +401,7 @@ func TestEditGlobal(t *testing.T) {
for name, c := range cases {
c := c
t.Run(name, func(t *testing.T) {
oldEnv := os.Getenv("EDITOR")
os.Setenv("EDITOR", c.expectedEditor)
defer os.Setenv("EDITOR", oldEnv)
t.Setenv("EDITOR", c.expectedEditor)

var called bool
runEditor = func(editor string, cfgPath string) error {
Expand Down