Skip to content

Commit

Permalink
fix: creates credential file if not exists
Browse files Browse the repository at this point in the history
  • Loading branch information
Gary Zhu committed Dec 20, 2021
1 parent 3fed99b commit 9be6758
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/

aws-one-punch
aws-one-punch
dist/
34 changes: 28 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
Expand Down Expand Up @@ -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()

Expand All @@ -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
}

0 comments on commit 9be6758

Please sign in to comment.