Skip to content

Commit

Permalink
Fix a panic when settings files don't exist yet
Browse files Browse the repository at this point in the history
  • Loading branch information
landakram committed Sep 14, 2020
1 parent 7d08063 commit 8cad034
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
8 changes: 6 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,17 @@ func main() {
viper.SetDefault("cli.data_dir", filepath.Join(dir, ".plaid-cli"))

dataDir := viper.GetString("cli.data_dir")
data := plaid_cli.LoadData(dataDir)
data, err := plaid_cli.LoadData(dataDir)

if err != nil {
log.Fatal(err)
}

viper.SetConfigName("config")
viper.SetConfigType("toml")
viper.AddConfigPath(dataDir)
viper.AddConfigPath(".")
err := viper.ReadInConfig()
err = viper.ReadInConfig()
if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
Expand Down
19 changes: 9 additions & 10 deletions pkg/plaid_cli/plaid_cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package plaid_cli
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"path/filepath"
)
Expand All @@ -14,33 +15,33 @@ type Data struct {
BackAliases map[string]string
}

func LoadData(dataDir string) *Data {
func LoadData(dataDir string) (*Data, error) {
os.MkdirAll(filepath.Join(dataDir, "data"), os.ModePerm)

data := &Data{
DataDir: dataDir,
BackAliases: make(map[string]string),
}

data.loadTokens()
data.loadAliases()
return data

return data, nil
}

func (d *Data) loadAliases() error {
func (d *Data) loadAliases() {
var aliases map[string]string = make(map[string]string)
filePath := d.aliasesPath()
err := load(filePath, &aliases)
if err != nil {
return err
log.Printf("Error loading aliases from %s. Assuming empty tokens. Error: %s", d.aliasesPath(), err)
}

d.Aliases = aliases

for alias, itemID := range aliases {
d.BackAliases[itemID] = alias
}

return nil
}

func (d *Data) tokensPath() string {
Expand All @@ -51,17 +52,15 @@ func (d *Data) aliasesPath() string {
return filepath.Join(d.DataDir, "data", "aliases.json")
}

func (d *Data) loadTokens() error {
func (d *Data) loadTokens() {
var tokens map[string]string = make(map[string]string)
filePath := d.tokensPath()
err := load(filePath, &tokens)
if err != nil {
return err
log.Printf("Error loading tokens from %s. Assuming empty tokens. Error: %s", d.tokensPath(), err)
}

d.Tokens = tokens

return nil
}

func load(filePath string, v interface{}) error {
Expand Down

0 comments on commit 8cad034

Please sign in to comment.