Skip to content

Commit

Permalink
Extensionless files only allowed when config type is set (#827)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
pedromss authored and sagikazarmark committed Jan 16, 2020
1 parent 06ab5a4 commit 9cd5712
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -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
Expand All @@ -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

Expand Down
6 changes: 4 additions & 2 deletions viper.go
Expand Up @@ -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 ""
Expand Down
18 changes: 18 additions & 0 deletions viper_test.go
Expand Up @@ -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() {
Expand Down

0 comments on commit 9cd5712

Please sign in to comment.