From ce37a6ba0c24627af4e5d79e2d8ce19401dbde8a Mon Sep 17 00:00:00 2001 From: Hiroaki Kobayashi Date: Fri, 21 Sep 2018 21:37:15 +0900 Subject: [PATCH] use token at config.json --- cmd/todoist/cmd/config.go | 7 ++----- cmd/util/common.go | 25 ++++++++++++++++++++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/cmd/todoist/cmd/config.go b/cmd/todoist/cmd/config.go index 4c613ae..72361eb 100644 --- a/cmd/todoist/cmd/config.go +++ b/cmd/todoist/cmd/config.go @@ -4,6 +4,7 @@ import ( "bufio" "encoding/json" "fmt" + "github.com/kobtea/go-todoist/cmd/util" "github.com/spf13/cobra" "io/ioutil" "os" @@ -11,10 +12,6 @@ import ( "strings" ) -type config struct { - Token string `json:"token"` -} - // configCmd represents the config command var configCmd = &cobra.Command{ Use: "config", @@ -26,7 +23,7 @@ var configCmd = &cobra.Command{ return err } } - var c config + var c util.Config file := path.Join(dir, "config.json") if b, err := ioutil.ReadFile(file); err != nil { // initial config diff --git a/cmd/util/common.go b/cmd/util/common.go index c1382a6..8f397f1 100644 --- a/cmd/util/common.go +++ b/cmd/util/common.go @@ -2,14 +2,37 @@ package util import ( "context" + "encoding/json" "github.com/kobtea/go-todoist/todoist" "github.com/spf13/viper" + "io/ioutil" + "os" ) +type Config struct { + Token string `json:"token"` +} + +func resolveToken() string { + if s := viper.GetString("TODOIST_TOKEN"); len(s) != 0 { + return s + } + file := os.ExpandEnv("$HOME/.go-todoist/config.json") + if b, err := ioutil.ReadFile(file); err != nil { + return "" + } else { + var c Config + if err = json.Unmarshal(b, &c); err != nil { + return "" + } + return c.Token + } +} + func NewClient() (*todoist.Client, error) { return todoist.NewClient( "", - viper.GetString("TODOIST_TOKEN"), + resolveToken(), "*", "", nil)