From 9be675819da22395fbd20c07fe489a10945b4994 Mon Sep 17 00:00:00 2001 From: Gary Zhu Date: Mon, 20 Dec 2021 15:00:51 +1300 Subject: [PATCH] fix: creates credential file if not exists --- .gitignore | 3 ++- main.go | 34 ++++++++++++++++++++++++++++------ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 9991f6b..5b02321 100644 --- a/.gitignore +++ b/.gitignore @@ -16,4 +16,5 @@ # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 .glide/ -aws-one-punch \ No newline at end of file +aws-one-punch +dist/ diff --git a/main.go b/main.go index 58932c2..c79cc62 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "errors" "fmt" "io/ioutil" "log" @@ -216,17 +217,27 @@ func getCredentials(url, token string) (credentials, error) { func updateCredentialFile(c credentials) error { usr, _ := user.Current() - filePath := fmt.Sprintf("%s/.aws/credentials", usr.HomeDir) - // remove the credentials file first - err := os.Remove(filePath) - if err != nil { - return fmt.Errorf("failed to remove existing credentials file %s", err.Error()) + folderPath := fmt.Sprintf("%s/.aws", usr.HomeDir) + if awsFolderExists, _ := pathExists(folderPath); !awsFolderExists { + err := os.Mkdir(folderPath, os.ModePerm) + if err != nil { + return fmt.Errorf("failed to create aws folder %s due to %s", folderPath, err.Error()) + } + } + + filePath := fmt.Sprintf("%s/credentials", folderPath) + // remove credential file if it exists + if exists, _ := pathExists(filePath); exists { + err := os.Remove(filePath) + if err != nil { + return fmt.Errorf("failed to remove existing credentials file %s", err.Error()) + } } // create the credentials file f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { - return fmt.Errorf("failed to create credentials file %s", err.Error()) + return fmt.Errorf("failed to create credentials file %s due to %s", filePath, err.Error()) } defer f.Close() @@ -239,3 +250,14 @@ func updateCredentialFile(c credentials) error { return nil } + +func pathExists(path string) (bool, error) { + _, err := os.Stat(path) + if err == nil { + return true, nil + } + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + return false, err +}