Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix error when trying to run apikey sub-commands #478

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion cmd/apikey/apikey_current.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ var apikeyCurrentCmd = &cobra.Command{
Short: "Set the current API key",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
config.LoadConfig(config.GetConfigFilename())

index, err := apiKeyFind(args[0])
if err != nil {
utility.Error("Unable find the API key %s", err.Error())
Expand All @@ -26,6 +28,5 @@ var apikeyCurrentCmd = &cobra.Command{
config.SaveConfig()
fmt.Printf("Set the default API Key to be %s\n", utility.Green(index))
}

},
}
2 changes: 2 additions & 0 deletions cmd/apikey/apikey_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ If you wish to use a custom format, the available fields are:

Example: civo apikey ls -o custom -f "Name: Key"`,
Run: func(cmd *cobra.Command, args []string) {
config.LoadConfig(config.GetConfigFilename())

keys := make([]string, 0, len(config.Current.APIKeys))
for k := range config.Current.APIKeys {
keys = append(keys, k)
Expand Down
3 changes: 2 additions & 1 deletion cmd/apikey/apikey_remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ var apikeyRemoveCmd = &cobra.Command{
Args: cobra.MinimumNArgs(1),
Example: "civo apikey remove NAME",
Run: func(cmd *cobra.Command, args []string) {
config.LoadConfig(config.GetConfigFilename())

index, err := apiKeyFind(args[0])
if err != nil {
utility.Error("Unable to find the API key %s", err.Error())
Expand Down Expand Up @@ -49,6 +51,5 @@ var apikeyRemoveCmd = &cobra.Command{
} else {
fmt.Println("Operation aborted.")
}

},
}
11 changes: 11 additions & 0 deletions cmd/apikey/apikey_save.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,17 @@ var apikeySaveCmd = &cobra.Command{
apiKey = apiKeyEnv
}

if config.Current.APIKeys == nil {
filename := config.GetConfigFilename()
err := config.CheckConfigFile(filename)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}

config.ProcessConfig(filename)
}

config.Current.APIKeys[name] = apiKey
if config.Current.Meta.DefaultRegion == "" {
client, err := civogo.NewClientWithURL(apiKey, config.Current.Meta.URL, "")
Expand Down
2 changes: 2 additions & 0 deletions cmd/apikey/apikey_show.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ If you wish to use a custom format, the available fields are:
* key
`,
Run: func(cmd *cobra.Command, args []string) {
config.LoadConfig(config.GetConfigFilename())

keys := make([]string, 0, len(config.Current.APIKeys))
for k := range config.Current.APIKeys {
keys = append(keys, k)
Expand Down
7 changes: 5 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ as instances and Kubernetes clusters at Civo.com.`,
cmd.Help()
}
},
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if cmd.Parent().Use != "apikey" {
config.ReadConfig()
}
},
}

// completionCmd represents the completion command
Expand Down Expand Up @@ -126,8 +131,6 @@ func Execute() {
}

func init() {
cobra.OnInitialize(config.ReadConfig)

rootCmd.AddCommand(completionCmd)
completionCmd.AddCommand(completionBashCmd)
completionCmd.AddCommand(completionZshCmd)
Expand Down
68 changes: 49 additions & 19 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,26 +37,44 @@ var Filename string

// ReadConfig reads in config file and ENV variables if set.
func ReadConfig() {
filename, found := os.LookupEnv("CIVO_CONFIG")
if found {
Filename = filename
filename := GetConfigFilename()
if filename != "" {
LoadConfig(filename)
ProcessConfig(filename)
} else {
fmt.Println("No configuration file found")
os.Exit(1)
}
}

if Filename != "" {
loadConfig(Filename)
} else {
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
loadConfig(fmt.Sprintf("%s/%s", home, ".civo.json"))
// Function to retrieve the config filename from environment variable or default
func GetConfigFilename() string {
if filename, found := os.LookupEnv("CIVO_CONFIG"); found {
return filename
}

homeDir := getHomeDir()
if homeDir != "" {
return fmt.Sprintf("%s/%s", homeDir, ".civo.json")
}

return ""
}

// Function to get the home directory of the current user
func getHomeDir() string {
home, err := homedir.Dir()
if err != nil {
fmt.Println("Error retrieving home directory:", err)
os.Exit(1)
}

return home
}

func loadConfig(filename string) {
func LoadConfig(filename string) {
var err error
err = checkConfigFile(filename)
err = CheckConfigFile(filename)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
Expand Down Expand Up @@ -87,6 +105,9 @@ func loadConfig(filename string) {
os.Exit(1)
}
}
}

func ProcessConfig(filename string) {
if Current.APIKeys == nil {
Current.APIKeys = map[string]string{}
}
Expand All @@ -97,12 +118,14 @@ func loadConfig(filename string) {
}

if Current.Meta.CurrentAPIKey != "" && Current.RegionToFeatures == nil {
Current.RegionToFeatures, err = regionsToFeature()
regionstoFeature, err := regionsToFeature()
if err != nil {
fmt.Printf("Error getting supported regions to feature %s \n", err)
os.Exit(1)
}

Current.RegionToFeatures = regionstoFeature

dataBytes, err := json.Marshal(Current)
if err != nil {
fmt.Printf("Error parsing JSON %s \n", err)
Expand All @@ -120,11 +143,13 @@ func loadConfig(filename string) {
Current.Meta.LatestReleaseCheck = time.Now()

if Current.Meta.CurrentAPIKey != "" {
Current.RegionToFeatures, err = regionsToFeature()
regionFeatures, err := regionsToFeature()
if err != nil {
fmt.Printf("Error getting supported regions to feature %s \n", err)
os.Exit(1)
}

Current.RegionToFeatures = regionFeatures
}

dataBytes, err := json.Marshal(Current)
Expand All @@ -140,7 +165,6 @@ func loadConfig(filename string) {
}
common.CheckVersionUpdate()
}

}

// SaveConfig saves the current configuration back out to a JSON file in
Expand Down Expand Up @@ -178,7 +202,7 @@ func SaveConfig() {

}

func checkConfigFile(filename string) error {
func CheckConfigFile(filename string) error {
curr := Config{APIKeys: map[string]string{}}
curr.Meta = Metadata{
Admin: false,
Expand All @@ -187,7 +211,8 @@ func checkConfigFile(filename string) error {
LastCmdExecuted: time.Now(),
}

if Current.Meta.CurrentAPIKey != "" {
currApiKey := Current.Meta.CurrentAPIKey
if currApiKey != "" {
var err error
curr.RegionToFeatures, err = regionsToFeature()
if err != nil {
Expand Down Expand Up @@ -229,6 +254,11 @@ func checkConfigFile(filename string) error {
os.Exit(1)
}

Current = curr
if currApiKey != "" {
Current.Meta.CurrentAPIKey = currApiKey
}

return nil
}

Expand Down