Skip to content

Commit

Permalink
add global --use-context flag
Browse files Browse the repository at this point in the history
  • Loading branch information
sgsullivan committed Feb 27, 2020
1 parent f93b37a commit 6248678
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 58 deletions.
19 changes: 2 additions & 17 deletions cmd/authUseContext.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
"github.com/spf13/cobra"

"github.com/liquidweb/liquidweb-cli/instance"
"github.com/liquidweb/liquidweb-cli/types/cmd"
)

var authUseContextCmd = &cobra.Command{
Expand All @@ -46,22 +45,8 @@ If you've never setup any contexts, check "auth init".`,
wantedContext := args[0]

// verify wantedContext is valid
isValid := false
contexts := lwCliInst.Viper.GetStringMap("liquidweb.api.contexts")
for _, contextInter := range contexts {
var context cmdTypes.AuthContext
if err := instance.CastFieldTypes(contextInter, &context); err != nil {
lwCliInst.Die(err)
}

if context.ContextName == wantedContext {
isValid = true
break
}
}

if !isValid {
lwCliInst.Die(fmt.Errorf("given context [%s] is not a valid context", wantedContext))
if err := instance.ValidateContext(wantedContext, lwCliInst.Viper); err != nil {
lwCliInst.Die(err)
}

// looks valid, set
Expand Down
11 changes: 11 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (

var cfgFile string
var lwCliInst instance.Client
var useContext string

var rootCmd = &cobra.Command{
Use: "lw",
Expand Down Expand Up @@ -65,6 +66,7 @@ func init() {
cobra.OnInitialize(initConfig)

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.liquidweb-cli.yaml)")
rootCmd.PersistentFlags().StringVar(&useContext, "use-context", "", "forces current context, without persisting the context change")
}

func initConfig() {
Expand All @@ -88,6 +90,15 @@ func initConfig() {
vp.AutomaticEnv()
vp.ReadInConfig()

if useContext != "" {
if err := instance.ValidateContext(useContext, vp); err != nil {
utils.PrintRed("error using auth context:\n\n")
fmt.Printf("%s\n\n", err)
os.Exit(1)
}
vp.Set("liquidweb.api.current_context", useContext)
}

var lwCliInstErr error
lwCliInst, lwCliInstErr = instance.New(vp)
if lwCliInstErr != nil {
Expand Down
89 changes: 89 additions & 0 deletions instance/authContext.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
Copyright © LiquidWeb
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instance

import (
"bytes"
"encoding/json"
"fmt"

"github.com/spf13/viper"

"github.com/liquidweb/liquidweb-cli/types/cmd"
)

func (client *Client) RemoveContext(context string) error {
// this function should be deleted and Unset in viper used instead once
// https://github.com/spf13/viper/pull/519
// is merged or similar functionality is added.
if context == "" {
return fmt.Errorf("context cannot be empty")
}

currentContext := client.Viper.GetString("liquidweb.api.current_context")
if context == currentContext {
return fmt.Errorf("cannot remove context currently set as current context")
}

contexts := client.Viper.GetStringMap("liquidweb.api.contexts")
if _, exists := contexts[context]; !exists {
return fmt.Errorf("context %s doesnt exist, cannot remove", context)
}

// save current config into a map, then delete requested context
cfgMap := client.Viper.AllSettings()
delete(cfgMap["liquidweb"].(map[string]interface{})["api"].(map[string]interface{})["contexts"].(map[string]interface{}), context)

// json encode modified map
encodedCfg, err := json.MarshalIndent(cfgMap, "", " ")
if err != nil {
return err
}

// read newly encoded config back into viper
if err := client.Viper.ReadConfig(bytes.NewBuffer(encodedCfg)); err != nil {
return err
}

// write the new viper configuration to file
if err := client.Viper.WriteConfig(); err != nil {
return err
}

return nil
}

func ValidateContext(wantedContext string, vp *viper.Viper) error {
var isValid bool
contexts := vp.GetStringMap("liquidweb.api.contexts")
for _, contextInter := range contexts {
var context cmdTypes.AuthContext
if err := CastFieldTypes(contextInter, &context); err != nil {
return err
}

if context.ContextName == wantedContext {
isValid = true
break
}
}

if !isValid {
return fmt.Errorf("given context [%s] is not a valid context", wantedContext)
}

return nil
}
41 changes: 0 additions & 41 deletions instance/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,47 +77,6 @@ func (*Client) JsonPrettyPrint(inJson string) (string, error) {
return outJson.String(), nil
}

func (client *Client) RemoveContext(context string) error {
// this function should be deleted and Unset in viper used instead once
// https://github.com/spf13/viper/pull/519
// is merged or similar functionality is added.
if context == "" {
return fmt.Errorf("context cannot be empty")
}

currentContext := client.Viper.GetString("liquidweb.api.current_context")
if context == currentContext {
return fmt.Errorf("cannot remove context currently set as current context")
}

contexts := client.Viper.GetStringMap("liquidweb.api.contexts")
if _, exists := contexts[context]; !exists {
return fmt.Errorf("context %s doesnt exist, cannot remove", context)
}

// save current config into a map, then delete requested context
cfgMap := client.Viper.AllSettings()
delete(cfgMap["liquidweb"].(map[string]interface{})["api"].(map[string]interface{})["contexts"].(map[string]interface{}), context)

// json encode modified map
encodedCfg, err := json.MarshalIndent(cfgMap, "", " ")
if err != nil {
return err
}

// read newly encoded config back into viper
if err := client.Viper.ReadConfig(bytes.NewBuffer(encodedCfg)); err != nil {
return err
}

// write the new viper configuration to file
if err := client.Viper.WriteConfig(); err != nil {
return err
}

return nil
}

func (client *Client) CallLwApiInto(method string, methodArgs map[string]interface{}, obj interface{}) (err error) {
got, err := client.LwCliApiClient.Call(method, methodArgs)
if err != nil {
Expand Down

0 comments on commit 6248678

Please sign in to comment.