From 2706883ccce26ddffa6ec50c92c92bfe88d1323b Mon Sep 17 00:00:00 2001 From: Umar Farooq Date: Tue, 30 Nov 2021 19:15:08 +0500 Subject: [PATCH 1/8] added global cache --- ipinfo/cmd_config.go | 53 +++++++++++++++++++++++++++++++ ipinfo/config.go | 70 +++++++++++++++++++++++++++++++++++++++++ ipinfo/init.go | 12 +++++++ ipinfo/ipinfo_client.go | 3 +- ipinfo/main.go | 5 +++ 5 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 ipinfo/cmd_config.go create mode 100644 ipinfo/config.go create mode 100644 ipinfo/init.go diff --git a/ipinfo/cmd_config.go b/ipinfo/cmd_config.go new file mode 100644 index 00000000..a2bb9a30 --- /dev/null +++ b/ipinfo/cmd_config.go @@ -0,0 +1,53 @@ +package main + +import ( + "fmt" + "strings" + + "github.com/spf13/pflag" +) + +func printHelpConfig() { + fmt.Printf( + `Usage: %s config [] [] + +Options: + --cache , -c + enable or disable cache in config file + --help, -h + show help. +`, progBase) +} + +func cmdConfig() error { + var fCache string + var fHelp bool + + pflag.StringVarP(&fCache, "cache", "c", "", "cache enable | disable.") + pflag.BoolVarP(&fHelp, "help", "h", false, "show help.") + pflag.Parse() + + if fHelp { + printHelpConfig() + return nil + } + switch strings.ToLower(fCache) { + case "enable": + gConfig.GlobalCache = true + err := SetConfig(gConfig) + if err != nil { + return err + } + case "disable": + gConfig.GlobalCache = false + err := SetConfig(gConfig) + if err != nil { + return err + } + default: + fmt.Printf("err: invalid argument\n\n") + printHelpConfig() + return nil + } + return nil +} diff --git a/ipinfo/config.go b/ipinfo/config.go new file mode 100644 index 00000000..96d201fd --- /dev/null +++ b/ipinfo/config.go @@ -0,0 +1,70 @@ +package main + +import ( + "encoding/json" + "io/ioutil" + "path/filepath" + + "github.com/ipinfo/cli/lib" +) + +type Config struct { + GlobalCache bool +} + +// init function +func InitConfig() error { + path, err := ConfigPath() + if err != nil { + return err + } + if !lib.FileExists(path) { + gConfig.GlobalCache = true + SetConfig(gConfig) + } + return nil +} + +// returns the path to config file. +func ConfigPath() (string, error) { + confDir, err := getConfigDir() + if err != nil { + return "", err + } + return filepath.Join(confDir, "config.json"), nil +} + +// set the values of config. +func SetConfig(config Config) error { + configPath, err := ConfigPath() + if err != nil { + return err + } + jsonFile, err := json.Marshal(config) + if err != nil { + return err + } + err = ioutil.WriteFile(configPath, jsonFile, 0644) + if err != nil { + return err + } + return nil +} + +// get the values of config. +func GetConfig() (Config, error) { + configPath, err := ConfigPath() + if err != nil { + return Config{}, err + } + file, err := ioutil.ReadFile(configPath) + if err != nil { + return Config{}, err + } + var setting Config + err = json.Unmarshal(file, &setting) + if err != nil { + return Config{}, err + } + return Config{GlobalCache: setting.GlobalCache}, nil +} diff --git a/ipinfo/init.go b/ipinfo/init.go new file mode 100644 index 00000000..87408f64 --- /dev/null +++ b/ipinfo/init.go @@ -0,0 +1,12 @@ +package main + +import "fmt" + +func init() { + InitConfig() + config, err := GetConfig() + if err != nil { + fmt.Println("warn: error in config file.") + } + gConfig = config +} diff --git a/ipinfo/ipinfo_client.go b/ipinfo/ipinfo_client.go index 3d73e78b..b3d7c51d 100644 --- a/ipinfo/ipinfo_client.go +++ b/ipinfo/ipinfo_client.go @@ -19,7 +19,8 @@ func prepareIpinfoClient(tok string) *ipinfo.Client { // attempt to init cache; don't force require it, though. var cache *ipinfo.Cache - if !fNoCache { + + if gConfig.GlobalCache && !fNoCache { boltdbCache, err := NewBoltdbCache() if err != nil { fmt.Printf("warn: cache will not be used: %v", err) diff --git a/ipinfo/main.go b/ipinfo/main.go index 465324d3..1146fe79 100644 --- a/ipinfo/main.go +++ b/ipinfo/main.go @@ -18,6 +18,9 @@ var fHelp bool var fNoCache bool var fNoColor bool +// global config. +var gConfig Config + func main() { var err error var cmd string @@ -65,6 +68,8 @@ func main() { err = cmdRandIP() case cmd == "cache": err = cmdCache() + case cmd == "config": + err = cmdConfig() case cmd == "login": err = cmdLogin() case cmd == "logout": From 09e28daba5b86e659c1ed04f806a1d74785a1884 Mon Sep 17 00:00:00 2001 From: Umar Farooq Date: Wed, 1 Dec 2021 12:17:37 +0500 Subject: [PATCH 2/8] added config file --- ipinfo/cmd_config.go | 56 ++++++++++++++++++++++++++++++----------- ipinfo/cmd_default.go | 1 + ipinfo/config.go | 45 ++++++++++++++++++++++++++++----- ipinfo/init.go | 5 +++- ipinfo/ipinfo_client.go | 4 +-- ipinfo/main.go | 3 --- ipinfo/utils_config.go | 21 ---------------- 7 files changed, 87 insertions(+), 48 deletions(-) delete mode 100644 ipinfo/utils_config.go diff --git a/ipinfo/cmd_config.go b/ipinfo/cmd_config.go index a2bb9a30..9a907da9 100644 --- a/ipinfo/cmd_config.go +++ b/ipinfo/cmd_config.go @@ -9,13 +9,15 @@ import ( func printHelpConfig() { fmt.Printf( - `Usage: %s config [] [] + `Usage: %s config [=] Options: - --cache , -c + cache= enable or disable cache in config file --help, -h show help. +Examples: + %[1]s config cache=disable `, progBase) } @@ -31,21 +33,47 @@ func cmdConfig() error { printHelpConfig() return nil } - switch strings.ToLower(fCache) { - case "enable": - gConfig.GlobalCache = true - err := SetConfig(gConfig) - if err != nil { - return err + + if len(pflag.Args()) < 2 { + printHelpConfig() + return nil + } + + // get arg for config and parsing it. + arg := pflag.Arg(1) + configStr := strings.Split(arg, "=") + if len(configStr) != 2 { + if configStr[0] == "cache" { + fmt.Printf("err: no value provided for %s\n\n", configStr[0]) + printHelpConfig() + return nil } - case "disable": - gConfig.GlobalCache = false - err := SetConfig(gConfig) - if err != nil { - return err + fmt.Printf("err: invalid argument %s\n\n", configStr[0]) + printHelpConfig() + return nil + } + switch strings.ToLower(configStr[0]) { + case "cache": + switch strings.ToLower(configStr[1]) { + case "enable": + gConfig.Cache = true + err := SetConfig(gConfig) + if err != nil { + return err + } + case "disable": + gConfig.Cache = false + err := SetConfig(gConfig) + if err != nil { + return err + } + default: + fmt.Printf("err: %s invalid value for %s\n\n", configStr[1], configStr[0]) + printHelpConfig() + return nil } default: - fmt.Printf("err: invalid argument\n\n") + fmt.Printf("err: invalid argument %s\n\n", configStr[0]) printHelpConfig() return nil } diff --git a/ipinfo/cmd_default.go b/ipinfo/cmd_default.go index 0451b021..ba898d00 100644 --- a/ipinfo/cmd_default.go +++ b/ipinfo/cmd_default.go @@ -31,6 +31,7 @@ Commands: range2ip convert IP ranges to individual IPs within those ranges. randip Generates random IPs. cache manage the cache. + config manage the config. login save an API token session. logout delete your current API token session. completion install or output shell auto-completion script. diff --git a/ipinfo/config.go b/ipinfo/config.go index 96d201fd..9665299e 100644 --- a/ipinfo/config.go +++ b/ipinfo/config.go @@ -3,13 +3,32 @@ package main import ( "encoding/json" "io/ioutil" + "os" "path/filepath" "github.com/ipinfo/cli/lib" ) +// global config. +var gConfig Config + type Config struct { - GlobalCache bool + Cache bool +} + +// gets the global config directory, creating it if necessary. +func getConfigDir() (string, error) { + cdir, err := os.UserConfigDir() + if err != nil { + return "", err + } + + confDir := filepath.Join(cdir, "ipinfo") + if err := os.MkdirAll(confDir, 0700); err != nil { + return "", err + } + + return confDir, nil } // init function @@ -18,9 +37,12 @@ func InitConfig() error { if err != nil { return err } + if !lib.FileExists(path) { - gConfig.GlobalCache = true - SetConfig(gConfig) + err := SetConfig(NewConfig()) + if err != nil { + return err + } } return nil } @@ -34,16 +56,25 @@ func ConfigPath() (string, error) { return filepath.Join(confDir, "config.json"), nil } +// returns config file with default settings. +func NewConfig() Config { + return Config{ + Cache: true, + } +} + // set the values of config. func SetConfig(config Config) error { configPath, err := ConfigPath() if err != nil { return err } + jsonFile, err := json.Marshal(config) if err != nil { return err } + err = ioutil.WriteFile(configPath, jsonFile, 0644) if err != nil { return err @@ -57,14 +88,16 @@ func GetConfig() (Config, error) { if err != nil { return Config{}, err } + file, err := ioutil.ReadFile(configPath) if err != nil { return Config{}, err } - var setting Config - err = json.Unmarshal(file, &setting) + + var config Config + err = json.Unmarshal(file, &config) if err != nil { return Config{}, err } - return Config{GlobalCache: setting.GlobalCache}, nil + return config, nil } diff --git a/ipinfo/init.go b/ipinfo/init.go index 87408f64..08382f2a 100644 --- a/ipinfo/init.go +++ b/ipinfo/init.go @@ -3,7 +3,10 @@ package main import "fmt" func init() { - InitConfig() + err := InitConfig() + if err != nil { + fmt.Println("warn: error in creating config file.") + } config, err := GetConfig() if err != nil { fmt.Println("warn: error in config file.") diff --git a/ipinfo/ipinfo_client.go b/ipinfo/ipinfo_client.go index b3d7c51d..4344d29d 100644 --- a/ipinfo/ipinfo_client.go +++ b/ipinfo/ipinfo_client.go @@ -17,10 +17,8 @@ func prepareIpinfoClient(tok string) *ipinfo.Client { tok, _ = restoreToken() } - // attempt to init cache; don't force require it, though. var cache *ipinfo.Cache - - if gConfig.GlobalCache && !fNoCache { + if gConfig.Cache && !fNoCache { boltdbCache, err := NewBoltdbCache() if err != nil { fmt.Printf("warn: cache will not be used: %v", err) diff --git a/ipinfo/main.go b/ipinfo/main.go index 1146fe79..7886a312 100644 --- a/ipinfo/main.go +++ b/ipinfo/main.go @@ -18,9 +18,6 @@ var fHelp bool var fNoCache bool var fNoColor bool -// global config. -var gConfig Config - func main() { var err error var cmd string diff --git a/ipinfo/utils_config.go b/ipinfo/utils_config.go deleted file mode 100644 index cbf30fd4..00000000 --- a/ipinfo/utils_config.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "path/filepath" - "os" -) - -// gets the global config directory, creating it if necessary. -func getConfigDir() (string, error) { - cdir, err := os.UserConfigDir() - if err != nil { - return "", err - } - - confDir := filepath.Join(cdir, "ipinfo") - if err := os.MkdirAll(confDir, 0700); err != nil { - return "", err - } - - return confDir, nil -} From 400e1f668ebe126f8e3f75cdbf335a62fb37e0fa Mon Sep 17 00:00:00 2001 From: Umar Farooq Date: Wed, 1 Dec 2021 13:33:47 +0500 Subject: [PATCH 3/8] added config file --- ipinfo/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ipinfo/config.go b/ipinfo/config.go index 9665299e..4094136d 100644 --- a/ipinfo/config.go +++ b/ipinfo/config.go @@ -13,7 +13,7 @@ import ( var gConfig Config type Config struct { - Cache bool + Cache bool `json:"cache"` } // gets the global config directory, creating it if necessary. From 149b3b0f62d11280c0a61ef5570480c18efaab76 Mon Sep 17 00:00:00 2001 From: Umar Farooq Date: Wed, 1 Dec 2021 16:05:13 +0500 Subject: [PATCH 4/8] added token config files --- ipinfo/cmd_config.go | 25 +++++++++++----- ipinfo/config.go | 4 ++- ipinfo/ipinfo_client.go | 2 +- ipinfo/utils_session.go | 63 ++++------------------------------------- 4 files changed, 28 insertions(+), 66 deletions(-) diff --git a/ipinfo/cmd_config.go b/ipinfo/cmd_config.go index 9a907da9..2b06e35b 100644 --- a/ipinfo/cmd_config.go +++ b/ipinfo/cmd_config.go @@ -9,15 +9,23 @@ import ( func printHelpConfig() { fmt.Printf( - `Usage: %s config [=] + `Usage: %s config [=] + +Discription: + Change the configurations. + note: In token configuration, validity will not be checked. -Options: - cache= - enable or disable cache in config file - --help, -h - show help. Examples: %[1]s config cache=disable + %[1]s config token=testtoken + +Options: + --help, -h + show help. + +Configurations: + cache= + token= `, progBase) } @@ -43,7 +51,7 @@ func cmdConfig() error { arg := pflag.Arg(1) configStr := strings.Split(arg, "=") if len(configStr) != 2 { - if configStr[0] == "cache" { + if configStr[0] == "cache" || configStr[0] == "token" { fmt.Printf("err: no value provided for %s\n\n", configStr[0]) printHelpConfig() return nil @@ -72,6 +80,9 @@ func cmdConfig() error { printHelpConfig() return nil } + case "token": + saveToken(configStr[1]) + default: fmt.Printf("err: invalid argument %s\n\n", configStr[0]) printHelpConfig() diff --git a/ipinfo/config.go b/ipinfo/config.go index 4094136d..9dd4b57b 100644 --- a/ipinfo/config.go +++ b/ipinfo/config.go @@ -13,7 +13,8 @@ import ( var gConfig Config type Config struct { - Cache bool `json:"cache"` + Cache bool `json:"cache"` + Token string `json:"token"` } // gets the global config directory, creating it if necessary. @@ -60,6 +61,7 @@ func ConfigPath() (string, error) { func NewConfig() Config { return Config{ Cache: true, + Token: "", } } diff --git a/ipinfo/ipinfo_client.go b/ipinfo/ipinfo_client.go index 4344d29d..21c98288 100644 --- a/ipinfo/ipinfo_client.go +++ b/ipinfo/ipinfo_client.go @@ -14,7 +14,7 @@ func prepareIpinfoClient(tok string) *ipinfo.Client { // get token from persistent store. if tok == "" { - tok, _ = restoreToken() + tok = restoreToken() } var cache *ipinfo.Cache diff --git a/ipinfo/utils_session.go b/ipinfo/utils_session.go index 5ab36a07..13f0025e 100644 --- a/ipinfo/utils_session.go +++ b/ipinfo/utils_session.go @@ -1,39 +1,9 @@ package main -import ( - "io/ioutil" - "os" - "path/filepath" -) - -func getTokenFilePath() (string, error) { - confDir, err := getConfigDir() - if err != nil { - return "", err - } - - return filepath.Join(confDir, "token"), nil -} - func saveToken(tok string) error { - tokFilePath, err := getTokenFilePath() - if err != nil { - return err - } - - // open/create if necessary. - tokFile, err := os.OpenFile( - tokFilePath, - os.O_RDWR|os.O_CREATE|os.O_TRUNC, - 0660, - ) - defer tokFile.Close() - if err != nil { - return err - } - // write token. - _, err = tokFile.WriteString(tok) + gConfig.Token = tok + err := SetConfig(gConfig) if err != nil { return err } @@ -42,35 +12,14 @@ func saveToken(tok string) error { } func deleteToken() error { - tokFilePath, err := getTokenFilePath() + gConfig.Token = "" + err := SetConfig(gConfig) if err != nil { return err } - - // remove token file. - if err := os.Remove(tokFilePath); err != nil { - return err - } - return nil } -func restoreToken() (string, error) { - tokFilePath, err := getTokenFilePath() - if err != nil { - return "", err - } - - tokFile, err := os.Open(tokFilePath) - defer tokFile.Close() - if err != nil { - return "", err - } - - tok, err := ioutil.ReadAll(tokFile) - if err != nil { - return "", nil - } - - return string(tok[:]), nil +func restoreToken() string { + return string(gConfig.Token) } From e3e13d8fde078cbc3caef6a6a6361dede8656399 Mon Sep 17 00:00:00 2001 From: Umar Farooq Date: Tue, 7 Dec 2021 14:42:38 +0500 Subject: [PATCH 5/8] refactored config code --- ipinfo/cmd_config.go | 90 ++++++++++++++------------------- ipinfo/cmd_login.go | 3 +- ipinfo/cmd_logout.go | 3 +- ipinfo/config.go | 107 ++++++++++++++++++++++++++++++---------- ipinfo/init.go | 8 +-- ipinfo/ipinfo_client.go | 4 +- ipinfo/utils_session.go | 25 ---------- 7 files changed, 123 insertions(+), 117 deletions(-) delete mode 100644 ipinfo/utils_session.go diff --git a/ipinfo/cmd_config.go b/ipinfo/cmd_config.go index 2b06e35b..f5cb7681 100644 --- a/ipinfo/cmd_config.go +++ b/ipinfo/cmd_config.go @@ -9,84 +9,66 @@ import ( func printHelpConfig() { fmt.Printf( - `Usage: %s config [=] + `Usage: %s config [=...] -Discription: - Change the configurations. - note: In token configuration, validity will not be checked. +Description: + Change the configurations. Examples: - %[1]s config cache=disable - %[1]s config token=testtoken + $ %[1]s config cache=disable + $ %[1]s config token=testtoken cahce=enable Options: - --help, -h + --help, -h show help. Configurations: - cache= - token= + cache= + Control whether the cache is enabled or disabled. + token= + Save a token for use when querying the API. + (Token will not be validated). `, progBase) } func cmdConfig() error { - var fCache string var fHelp bool - pflag.StringVarP(&fCache, "cache", "c", "", "cache enable | disable.") pflag.BoolVarP(&fHelp, "help", "h", false, "show help.") pflag.Parse() - if fHelp { + // get args for config and parsing it. + args := pflag.Args()[1:] + if fHelp || len(args) < 1 { printHelpConfig() return nil } - - if len(pflag.Args()) < 2 { - printHelpConfig() - return nil - } - - // get arg for config and parsing it. - arg := pflag.Arg(1) - configStr := strings.Split(arg, "=") - if len(configStr) != 2 { - if configStr[0] == "cache" || configStr[0] == "token" { - fmt.Printf("err: no value provided for %s\n\n", configStr[0]) - printHelpConfig() - return nil - } - fmt.Printf("err: invalid argument %s\n\n", configStr[0]) - printHelpConfig() - return nil - } - switch strings.ToLower(configStr[0]) { - case "cache": - switch strings.ToLower(configStr[1]) { - case "enable": - gConfig.Cache = true - err := SetConfig(gConfig) - if err != nil { - return err + for _, arg := range args { + configStr := strings.Split(arg, "=") + if len(configStr) != 2 { + if configStr[0] == "cache" || configStr[0] == "token" { + return fmt.Errorf("err: no value provided for key %s", configStr[0]) } - case "disable": - gConfig.Cache = false - err := SetConfig(gConfig) - if err != nil { - return err + return fmt.Errorf("err: invalid key argument %s", configStr[0]) + } + switch strings.ToLower(configStr[0]) { + case "cache": + switch strings.ToLower(configStr[1]) { + case "enable": + gConfig.CacheEnabled = true + case "disable": + gConfig.CacheEnabled = false + default: + return fmt.Errorf("err: invalid value %s for key cache", configStr[1]) } + case "token": + gConfig.Token = configStr[1] default: - fmt.Printf("err: %s invalid value for %s\n\n", configStr[1], configStr[0]) - printHelpConfig() - return nil + return fmt.Errorf("err: invalid key argument %s", configStr[0]) } - case "token": - saveToken(configStr[1]) - - default: - fmt.Printf("err: invalid argument %s\n\n", configStr[0]) - printHelpConfig() - return nil + } + if err := SaveConfig(gConfig); err != nil { + return err } return nil } diff --git a/ipinfo/cmd_login.go b/ipinfo/cmd_login.go index ec31974b..5412c8e4 100644 --- a/ipinfo/cmd_login.go +++ b/ipinfo/cmd_login.go @@ -102,7 +102,8 @@ func cmdLogin() error { } // save token to file. - if err := saveToken(tok); err != nil { + gConfig.Token = tok + if err := SaveConfig(gConfig); err != nil { return err } diff --git a/ipinfo/cmd_logout.go b/ipinfo/cmd_logout.go index 81bf0f78..210d9313 100644 --- a/ipinfo/cmd_logout.go +++ b/ipinfo/cmd_logout.go @@ -35,7 +35,8 @@ func cmdLogout() error { } // delete but don't return an error; just log it. - if err := deleteToken(); err != nil { + gConfig.Token = "" + if err := SaveConfig(gConfig); err != nil { fmt.Println("not logged in") return nil } diff --git a/ipinfo/config.go b/ipinfo/config.go index 9dd4b57b..eca662c7 100644 --- a/ipinfo/config.go +++ b/ipinfo/config.go @@ -13,8 +13,8 @@ import ( var gConfig Config type Config struct { - Cache bool `json:"cache"` - Token string `json:"token"` + CacheEnabled bool `json:"cache_enabled"` + Token string `json:"token"` } // gets the global config directory, creating it if necessary. @@ -32,74 +32,127 @@ func getConfigDir() (string, error) { return confDir, nil } -// init function +// returns the path to the config file. +func ConfigPath() (string, error) { + confDir, err := getConfigDir() + if err != nil { + return "", err + } + + return filepath.Join(confDir, "config.json"), nil +} + +// returns the path to the token file. +func TokenPath() (string, error) { + confDir, err := getConfigDir() + if err != nil { + return "", err + } + + return filepath.Join(confDir, "token"), nil +} + func InitConfig() error { - path, err := ConfigPath() + configpath, err := ConfigPath() + if err != nil { + return err + } + + tokenpath, err := TokenPath() if err != nil { return err } - if !lib.FileExists(path) { - err := SetConfig(NewConfig()) + // create default config if none yet. + if !lib.FileExists(configpath) { + gConfig = NewConfig() + } else { + config, err := ReadConfig() if err != nil { return err } + gConfig = config } - return nil -} -// returns the path to config file. -func ConfigPath() (string, error) { - confDir, err := getConfigDir() - if err != nil { - return "", err + // if token exists, migrate it to config file. + if lib.FileExists(tokenpath) { + token, err := TokentoConfig() + if err != nil { + return err + } + gConfig.Token = token + + // remove the existing token file + if err := os.Remove(tokenpath); err != nil { + return err + } } - return filepath.Join(confDir, "config.json"), nil + if err := SaveConfig(gConfig); err != nil { + return err + } + + return nil } -// returns config file with default settings. +// returns a new, default config. func NewConfig() Config { return Config{ - Cache: true, - Token: "", + CacheEnabled: true, + Token: "", } } -// set the values of config. -func SetConfig(config Config) error { +// migration of token to config file. +// +// might be deleted in future release. +func TokentoConfig() (string, error) { + path, err := TokenPath() + if err != nil { + return "", err + } + token, err := ioutil.ReadFile(path) + if err != nil { + return "", err + } + + return string(token), nil +} + +// save the config to file. +func SaveConfig(config Config) error { configPath, err := ConfigPath() if err != nil { return err } - jsonFile, err := json.Marshal(config) + jsonData, err := json.Marshal(config) if err != nil { return err } - err = ioutil.WriteFile(configPath, jsonFile, 0644) - if err != nil { + if err = ioutil.WriteFile(configPath, jsonData, 0644); err != nil { return err } + return nil } -// get the values of config. -func GetConfig() (Config, error) { +// returns the values of config file. +func ReadConfig() (Config, error) { configPath, err := ConfigPath() if err != nil { return Config{}, err } - file, err := ioutil.ReadFile(configPath) + data, err := ioutil.ReadFile(configPath) if err != nil { return Config{}, err } var config Config - err = json.Unmarshal(file, &config) - if err != nil { + if err = json.Unmarshal(data, &config); err != nil { return Config{}, err } + return config, nil } diff --git a/ipinfo/init.go b/ipinfo/init.go index 08382f2a..1927ecd1 100644 --- a/ipinfo/init.go +++ b/ipinfo/init.go @@ -3,13 +3,7 @@ package main import "fmt" func init() { - err := InitConfig() - if err != nil { + if err := InitConfig(); err != nil { fmt.Println("warn: error in creating config file.") } - config, err := GetConfig() - if err != nil { - fmt.Println("warn: error in config file.") - } - gConfig = config } diff --git a/ipinfo/ipinfo_client.go b/ipinfo/ipinfo_client.go index 21c98288..41ba7a91 100644 --- a/ipinfo/ipinfo_client.go +++ b/ipinfo/ipinfo_client.go @@ -14,11 +14,11 @@ func prepareIpinfoClient(tok string) *ipinfo.Client { // get token from persistent store. if tok == "" { - tok = restoreToken() + tok = gConfig.Token } var cache *ipinfo.Cache - if gConfig.Cache && !fNoCache { + if gConfig.CacheEnabled && !fNoCache { boltdbCache, err := NewBoltdbCache() if err != nil { fmt.Printf("warn: cache will not be used: %v", err) diff --git a/ipinfo/utils_session.go b/ipinfo/utils_session.go deleted file mode 100644 index 13f0025e..00000000 --- a/ipinfo/utils_session.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -func saveToken(tok string) error { - // write token. - gConfig.Token = tok - err := SetConfig(gConfig) - if err != nil { - return err - } - - return nil -} - -func deleteToken() error { - gConfig.Token = "" - err := SetConfig(gConfig) - if err != nil { - return err - } - return nil -} - -func restoreToken() string { - return string(gConfig.Token) -} From f481858ab29f5d0388beea108e7abcf2da2345ef Mon Sep 17 00:00:00 2001 From: Umar Farooq Date: Wed, 8 Dec 2021 10:33:57 +0500 Subject: [PATCH 6/8] refactored config code --- ipinfo/cmd_config.go | 19 ++++++++++------- ipinfo/cmd_logout.go | 8 +++++-- ipinfo/config.go | 50 ++++++++++++++++++++++++-------------------- 3 files changed, 45 insertions(+), 32 deletions(-) diff --git a/ipinfo/cmd_config.go b/ipinfo/cmd_config.go index f5cb7681..589fcde6 100644 --- a/ipinfo/cmd_config.go +++ b/ipinfo/cmd_config.go @@ -16,7 +16,7 @@ Description: Examples: $ %[1]s config cache=disable - $ %[1]s config token=testtoken cahce=enable + $ %[1]s config token=testtoken cache=enable Options: --help, -h @@ -45,21 +45,23 @@ func cmdConfig() error { } for _, arg := range args { configStr := strings.Split(arg, "=") + key := strings.ToLower(configStr[0]) if len(configStr) != 2 { - if configStr[0] == "cache" || configStr[0] == "token" { - return fmt.Errorf("err: no value provided for key %s", configStr[0]) + if key == "cache" || key == "token" { + return fmt.Errorf("err: no value provided for key %s", key) } - return fmt.Errorf("err: invalid key argument %s", configStr[0]) + return fmt.Errorf("err: invalid key argument %s", key) } - switch strings.ToLower(configStr[0]) { + switch key { case "cache": - switch strings.ToLower(configStr[1]) { + val := strings.ToLower(configStr[1]) + switch val { case "enable": gConfig.CacheEnabled = true case "disable": gConfig.CacheEnabled = false default: - return fmt.Errorf("err: invalid value %s for key cache", configStr[1]) + return fmt.Errorf("err: invalid value %s; cache must be 'enabled' or disabled", val) } case "token": gConfig.Token = configStr[1] @@ -67,8 +69,11 @@ func cmdConfig() error { return fmt.Errorf("err: invalid key argument %s", configStr[0]) } } + + // save config in bulk. if err := SaveConfig(gConfig); err != nil { return err } + return nil } diff --git a/ipinfo/cmd_logout.go b/ipinfo/cmd_logout.go index 210d9313..33090653 100644 --- a/ipinfo/cmd_logout.go +++ b/ipinfo/cmd_logout.go @@ -35,12 +35,16 @@ func cmdLogout() error { } // delete but don't return an error; just log it. - gConfig.Token = "" - if err := SaveConfig(gConfig); err != nil { + if gConfig.Token == "" { fmt.Println("not logged in") return nil } + gConfig.Token = "" + if err := SaveConfig(gConfig); err != nil { + return err + } + fmt.Println("logged out") return nil diff --git a/ipinfo/config.go b/ipinfo/config.go index eca662c7..b179d59d 100644 --- a/ipinfo/config.go +++ b/ipinfo/config.go @@ -43,6 +43,8 @@ func ConfigPath() (string, error) { } // returns the path to the token file. +// +// might be deleted in future release as `token` file is deprecated. func TokenPath() (string, error) { confDir, err := getConfigDir() if err != nil { @@ -58,35 +60,36 @@ func InitConfig() error { return err } - tokenpath, err := TokenPath() - if err != nil { - return err - } - // create default config if none yet. if !lib.FileExists(configpath) { gConfig = NewConfig() - } else { - config, err := ReadConfig() - if err != nil { - return err - } - gConfig = config - } - // if token exists, migrate it to config file. - if lib.FileExists(tokenpath) { - token, err := TokentoConfig() + tokenpath, err := TokenPath() if err != nil { return err } - gConfig.Token = token - // remove the existing token file - if err := os.Remove(tokenpath); err != nil { + // if token exists, migrate it to the config file. + if lib.FileExists(tokenpath) { + token, err := ReadTokenFile() + if err != nil { + return err + } + gConfig.Token = token + + // remove the existing token file + if err := os.Remove(tokenpath); err != nil { + return err + } + } + } else { + config, err := ReadConfig() + if err != nil { return err } + gConfig = config } + if err := SaveConfig(gConfig); err != nil { return err } @@ -102,14 +105,15 @@ func NewConfig() Config { } } -// migration of token to config file. +// reads `token` file for migration of token to config file. // -// might be deleted in future release. -func TokentoConfig() (string, error) { +// might be deleted in future release as `token` file is deprecated. +func ReadTokenFile() (string, error) { path, err := TokenPath() if err != nil { return "", err } + token, err := ioutil.ReadFile(path) if err != nil { return "", err @@ -130,7 +134,7 @@ func SaveConfig(config Config) error { return err } - if err = ioutil.WriteFile(configPath, jsonData, 0644); err != nil { + if err := ioutil.WriteFile(configPath, jsonData, 0644); err != nil { return err } @@ -150,7 +154,7 @@ func ReadConfig() (Config, error) { } var config Config - if err = json.Unmarshal(data, &config); err != nil { + if err := json.Unmarshal(data, &config); err != nil { return Config{}, err } From f92cd672e6d2894a09b5d39e62ef7c4d46a5faba Mon Sep 17 00:00:00 2001 From: Umar Farooq Date: Wed, 8 Dec 2021 10:56:59 +0500 Subject: [PATCH 7/8] refactored config code --- ipinfo/cmd_logout.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ipinfo/cmd_logout.go b/ipinfo/cmd_logout.go index 33090653..9df0352d 100644 --- a/ipinfo/cmd_logout.go +++ b/ipinfo/cmd_logout.go @@ -34,7 +34,7 @@ func cmdLogout() error { return nil } - // delete but don't return an error; just log it. + // checks if not logged in. if gConfig.Token == "" { fmt.Println("not logged in") return nil From 61d60bb18a878024bd9fd0f089332784e12fee9e Mon Sep 17 00:00:00 2001 From: Umar Farooq Date: Wed, 8 Dec 2021 16:29:10 +0500 Subject: [PATCH 8/8] refactored config code --- ipinfo/cmd_config.go | 9 +++++++++ ipinfo/completions.go | 1 + 2 files changed, 10 insertions(+) diff --git a/ipinfo/cmd_config.go b/ipinfo/cmd_config.go index 589fcde6..d70011c3 100644 --- a/ipinfo/cmd_config.go +++ b/ipinfo/cmd_config.go @@ -4,9 +4,18 @@ import ( "fmt" "strings" + "github.com/ipinfo/cli/lib/complete" + "github.com/ipinfo/cli/lib/complete/predict" "github.com/spf13/pflag" ) +var completionsConfig = &complete.Command{ + Flags: map[string]complete.Predictor{ + "-h": predict.Nothing, + "--help": predict.Nothing, + }, +} + func printHelpConfig() { fmt.Printf( `Usage: %s config [=...] diff --git a/ipinfo/completions.go b/ipinfo/completions.go index e88ee424..b1f03bb4 100644 --- a/ipinfo/completions.go +++ b/ipinfo/completions.go @@ -21,6 +21,7 @@ var completions = &complete.Command{ "cache": completionsCache, "login": completionsLogin, "logout": completionsLogout, + "config": completionsConfig, "completion": completionsCompletion, "version": completionsVersion, },