1/* 2Copyright © LiquidWeb 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16package instance 17 18import ( 19 "bytes" 20 "encoding/json" 21 "fmt" 22 23 "github.com/spf13/viper" 24 25 "github.com/liquidweb/liquidweb-cli/types/cmd" 26) 27 28func (client *Client) RemoveContext(context string) error { 29 // review this function once Unset (or similar) in viper is available 30 // https://github.com/spf13/viper/pull/519 31 if context == "" { 32 return fmt.Errorf("context cannot be empty") 33 } 34 35 currentContext := client.Viper.GetString("liquidweb.api.current_context") 36 if context == currentContext { 37 return fmt.Errorf("cannot remove context currently set as current context") 38 } 39 40 if err := ValidateContext(context, client.Viper); err != nil { 41 return fmt.Errorf("context %s doesnt exist, cannot remove", context) 42 } 43 44 // save current config into a map, then delete requested context 45 cfgMap := client.Viper.AllSettings() 46 delete(cfgMap["liquidweb"].(map[string]interface{})["api"].(map[string]interface{})["contexts"].(map[string]interface{}), context) 47 48 // json encode modified map 49 encodedCfg, err := json.MarshalIndent(cfgMap, "", " ") 50 if err != nil { 51 return err 52 } 53 54 // read newly encoded config back into viper 55 if err := client.Viper.ReadConfig(bytes.NewBuffer(encodedCfg)); err != nil { 56 return err 57 } 58 59 // write the new viper configuration to file 60 if err := client.Viper.WriteConfig(); err != nil { 61 return err 62 } 63 64 return nil 65} 66 67func ValidateContext(wantedContext string, vp *viper.Viper) error { 68 var isValid bool 69 contexts := vp.GetStringMap("liquidweb.api.contexts") 70 for _, contextInter := range contexts { 71 var context cmdTypes.AuthContext 72 if err := CastFieldTypes(contextInter, &context); err != nil { 73 return err 74 } 75 76 if context.ContextName == wantedContext { 77 isValid = true 78 break 79 } 80 } 81 82 if !isValid { 83 return fmt.Errorf("given context [%s] is not a valid context", wantedContext) 84 } 85 86 return nil 87} 88