From 9cd571279d195d6a02b5103f0301d8310dd4338d Mon Sep 17 00:00:00 2001 From: Pedro Silva Date: Thu, 16 Jan 2020 18:23:50 +0000 Subject: [PATCH] Extensionless files only allowed when config type is set (#827) * Only consider files without extension if the config type is explicitly specified * Hides unused variable in test * First check for config type then for file without extension --- README.md | 3 ++- viper.go | 6 ++++-- viper_test.go | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2bb54fa..a574677 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ where a configuration file is expected. ```go viper.SetConfigName("config") // name of config file (without extension) +viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name viper.AddConfigPath("/etc/appname/") // path to look for the config file in viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths viper.AddConfigPath(".") // optionally look for config in the working directory @@ -124,7 +125,7 @@ if err := viper.ReadInConfig(); err != nil { // Config file found and successfully parsed ``` -*NOTE:* You can also have a file without an extension and specify the format programmaticaly. For those configuration files that lie in the home of the user without any extension like `.bashrc` +*NOTE [since 1.6]:* You can also have a file without an extension and specify the format programmaticaly. For those configuration files that lie in the home of the user without any extension like `.bashrc` ### Writing Config Files diff --git a/viper.go b/viper.go index eb2f517..265eae7 100644 --- a/viper.go +++ b/viper.go @@ -1976,8 +1976,10 @@ func (v *Viper) searchInPath(in string) (filename string) { } } - if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b { - return filepath.Join(in, v.configName) + if v.configType != "" { + if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b { + return filepath.Join(in, v.configName) + } } return "" diff --git a/viper_test.go b/viper_test.go index fcd1b0e..f9dc34a 100644 --- a/viper_test.go +++ b/viper_test.go @@ -307,11 +307,29 @@ func TestBasics(t *testing.T) { assert.NoError(t, err) } +func TestSearchInPath_WithoutConfigTypeSet(t *testing.T) { + filename := ".dotfilenoext" + path := "/tmp" + file := filepath.Join(path, filename) + SetConfigName(filename) + AddConfigPath(path) + _, createErr := v.fs.Create(file) + defer func() { + _ = v.fs.Remove(file) + }() + assert.NoError(t, createErr) + _, err := v.getConfigFile() + // unless config type is set, files without extension + // are not considered + assert.Error(t, err) +} + func TestSearchInPath(t *testing.T) { filename := ".dotfilenoext" path := "/tmp" file := filepath.Join(path, filename) SetConfigName(filename) + SetConfigType("yaml") AddConfigPath(path) _, createErr := v.fs.Create(file) defer func() {