From 8cad03474a47e4f1e65569dbdfb50ed7be743c19 Mon Sep 17 00:00:00 2001 From: Mark Hudnall Date: Mon, 14 Sep 2020 16:51:27 -0700 Subject: [PATCH] Fix a panic when settings files don't exist yet --- main.go | 8 ++++++-- pkg/plaid_cli/plaid_cli.go | 19 +++++++++---------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/main.go b/main.go index 018fcf9..9de828d 100644 --- a/main.go +++ b/main.go @@ -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 diff --git a/pkg/plaid_cli/plaid_cli.go b/pkg/plaid_cli/plaid_cli.go index 912e0ac..d21b7d6 100644 --- a/pkg/plaid_cli/plaid_cli.go +++ b/pkg/plaid_cli/plaid_cli.go @@ -3,6 +3,7 @@ package plaid_cli import ( "encoding/json" "io/ioutil" + "log" "os" "path/filepath" ) @@ -14,24 +15,26 @@ 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 @@ -39,8 +42,6 @@ func (d *Data) loadAliases() error { for alias, itemID := range aliases { d.BackAliases[itemID] = alias } - - return nil } func (d *Data) tokensPath() string { @@ -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 {