diff --git a/auth/auth.go b/auth/auth.go index e98c87f..3eb469e 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -8,6 +8,7 @@ import ( "log" "os" "os/exec" + "path" "runtime" "time" @@ -156,7 +157,6 @@ func GetToken(conf *oauth2.Config, token **oauth2.Token, params *params) { log.Fatalf("Error: Unable to retrieve token from the web.\n%v", err) } else { *token = tok - fmt.Printf("%+v", *Token) fmt.Println("qGmail has been successfully authorized.") } } @@ -175,8 +175,7 @@ func getAuthCode(conf *oauth2.Config, authURL string, params *params) { if *mustPaste { fmt.Println("Paste the authorization code here:") if _, err := fmt.Scan(code); err != nil { - fmt.Println() - log.Fatalf("Unable to read authorization code: %v", err) + log.Fatalf("\nUnable to read authorization code: %v", err) } fmt.Println() } else { @@ -198,14 +197,18 @@ func openURL(url string) { } } -func SaveToken(tokenFile string, token *oauth2.Token) { - // can't create a folder - f, err := os.OpenFile(tokenFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - log.Fatalf("Error: Unable to cache oauth token.\n%v", err) +func SaveToken(tokenPath string, token *oauth2.Token) { + tokenFile, _ := json.Marshal(*token) + + // Create parent folders if non-existent. + tokenDir := path.Dir(tokenPath) + if _, err := os.Stat(tokenDir); os.IsNotExist(err) { + os.MkdirAll(tokenDir, os.ModePerm) + } + + if err := ioutil.WriteFile(tokenPath, tokenFile, 0600); err != nil { + log.Fatalf("Error: Unable to cache OAuth token.\n%v", err) } - defer f.Close() - json.NewEncoder(f).Encode(token) } func ReadToken(tokenFile string, token **oauth2.Token) error { diff --git a/config/config.go b/config/config.go index 4c07c63..8a0bbac 100644 --- a/config/config.go +++ b/config/config.go @@ -61,13 +61,19 @@ func init() { *config.TokenFile, _ = homedir.Expand(*config.TokenFile) } -func (conf *conf) read(configFile string) { - if _, err := os.Stat(configFile); os.IsNotExist(err) { - log.Fatal(err) +func (conf *conf) read(configPath string) { + if _, err := os.Stat(configPath); os.IsNotExist(err) { + // If the config file doesn't exist at default path, create it. + if defaultPath, _ := homedir.Expand("~/.config/qgmail/config.json"); configPath == defaultPath { + configFile, _ := json.MarshalIndent(*config, "", "\t") + _ = ioutil.WriteFile(configPath, configFile, 0644) + } else { + log.Fatal(err) + } } else { c := &tmpConf{} - f, _ := os.Open(configFile) + f, _ := os.Open(configPath) defer f.Close() byteValue, _ := ioutil.ReadAll(f) diff --git a/main.go b/main.go index ebe3908..9593694 100644 --- a/main.go +++ b/main.go @@ -27,7 +27,6 @@ func main() { fmt.Println("Authorization token not found. Fetching a new one...") auth.GetToken(oAuthConf, token, auth.Params) auth.SaveToken(tokenFile, *token) - fmt.Printf("%+v", *token) } if !cli.InitMode {