Skip to content

Commit

Permalink
Add optional parameter for file backend
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasss committed Aug 22, 2019
1 parent 20131ab commit 51fcea2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
18 changes: 13 additions & 5 deletions backend/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package file
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"

Expand All @@ -14,21 +15,24 @@ import (
// Backend that loads a configuration from a file.
// It supports json and yaml formats.
type Backend struct {
path string
name string
path string
name string
optional bool
}

// NewBackend creates a configuration loader that loads from a file.
// The content will get decoded based on the file extension.
func NewBackend(path string) *Backend {
// If optional parameter is set to true, calling Unmarshal won't return an error if the file doesn't exist.
func NewBackend(path string, optional bool) *Backend {
name := filepath.Ext(path)
if name != "" {
name = name[1:]
}

return &Backend{
path: path,
name: name,
path: path,
name: name,
optional: optional,
}
}

Expand All @@ -37,6 +41,10 @@ func NewBackend(path string) *Backend {
func (b *Backend) Unmarshal(ctx context.Context, to interface{}) error {
f, err := os.Open(b.path)
if err != nil {
if b.optional {
fmt.Printf("failed to open file at path \"%s\": %s\n", b.path, err.Error())
return nil
}
return errors.Wrapf(err, "failed to open file at path \"%s\"", b.path)
}
defer f.Close()
Expand Down
16 changes: 12 additions & 4 deletions backend/file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func TestFileBackend(t *testing.T) {

testLoad := func(t *testing.T, path string) {
var c config
b := file.NewBackend(path)
b := file.NewBackend(path, false)

err := b.Unmarshal(context.Background(), &c)
require.NoError(t, err)
Expand Down Expand Up @@ -90,17 +90,25 @@ timeout = 10
defer cleanup()

var c config
b := file.NewBackend(path)
b := file.NewBackend(path, false)

err := b.Unmarshal(context.Background(), &c)
require.Error(t, err)
})

t.Run("File not found", func(t *testing.T) {
t.Run("Required file not found", func(t *testing.T) {
var c config
b := file.NewBackend("some path")
b := file.NewBackend("some path", false)

err := b.Unmarshal(context.Background(), &c)
require.Error(t, err)
})

t.Run("Optional file not found", func(t *testing.T) {
var c config
b := file.NewBackend("some path", true)

err := b.Unmarshal(context.Background(), &c)
require.NoError(t, err)
})
}

0 comments on commit 51fcea2

Please sign in to comment.