Skip to content

Commit

Permalink
fix: config read
Browse files Browse the repository at this point in the history
  • Loading branch information
gi8lino committed Dec 14, 2023
1 parent 9e98ee6 commit d6acec6
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 5 deletions.
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (
)

const (
version = "v0.0.5"
version = "v0.0.6"
)

var (
Expand Down
11 changes: 9 additions & 2 deletions internal/config/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"fmt"
"os"

"github.com/mitchellh/mapstructure"

Expand All @@ -20,12 +21,18 @@ import (
// - error
// An error if reading or unmarshalling the configuration fails.
func (c *Config) Read(configPath string) error {

if _, err := os.Stat(configPath); os.IsNotExist(err) {
// No configuration file found
return nil
}

// Set the Viper config file path
viper.SetConfigFile(configPath)

// Read the config file
if err := viper.ReadInConfig(); err == nil {
return nil
if err := viper.ReadInConfig(); err != nil {
return fmt.Errorf("Failed to read config file: %v", err)
}

if err := viper.Unmarshal(c, func(d *mapstructure.DecoderConfig) {
Expand Down
23 changes: 21 additions & 2 deletions internal/config/read_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestReadConfig(t *testing.T) {
content := `
server:
api:
skipInsecureVerify: "true"
skipInsecureVerify: true
`
filePath, err := createTempFile(content)
if err != nil {
Expand All @@ -43,13 +43,32 @@ server:
err = config.Read(filePath.Name())
assert.NoError(t, err)
assert.Equal(t, true, config.Server.Api.SkipInsecureVerify)
assert.Equal(t, "", config.Server.Api.Token.Get())
})

t.Run("Validate token", func(t *testing.T) {
content := `
server:
api:
token: token
`
filePath, err := createTempFile(content)
if err != nil {
t.Fatalf("Failed to create temp file: %v", err)
}
defer os.Remove(filePath.Name())

config := &Config{}
err = config.Read(filePath.Name())
assert.NoError(t, err)
assert.Equal(t, "token", config.Server.Api.Token.Get())
})

// Test reading a non-existent file
t.Run("Invalid file path", func(t *testing.T) {
config := &Config{}
err := config.Read("path/to/non_existent.yaml")
assert.Error(t, err)
assert.Nil(t, err)
})

t.Run("Invalid YAML", func(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions internal/config/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,6 @@ func customTokenDecodeHook(from reflect.Type, to reflect.Type, data interface{})
// Initialize a Token with the decoded string
var token Token
token.Set(tokenValue)

return token, nil
}

0 comments on commit d6acec6

Please sign in to comment.