use_context.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package config
  14. import (
  15. "errors"
  16. "fmt"
  17. "io"
  18. "github.com/spf13/cobra"
  19. "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
  20. clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
  21. )
  22. type useContextOptions struct {
  23. configAccess clientcmd.ConfigAccess
  24. contextName string
  25. }
  26. func NewCmdConfigUseContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
  27. options := &useContextOptions{configAccess: configAccess}
  28. cmd := &cobra.Command{
  29. Use: "use-context CONTEXT_NAME",
  30. Short: "Sets the current-context in a kubeconfig file",
  31. Long: `Sets the current-context in a kubeconfig file`,
  32. Run: func(cmd *cobra.Command, args []string) {
  33. if !options.complete(cmd) {
  34. return
  35. }
  36. err := options.run()
  37. if err != nil {
  38. fmt.Fprintf(out, "%v\n", err)
  39. } else {
  40. fmt.Fprintf(out, "switched to context %q.\n", options.contextName)
  41. }
  42. },
  43. }
  44. return cmd
  45. }
  46. func (o useContextOptions) run() error {
  47. config, err := o.configAccess.GetStartingConfig()
  48. if err != nil {
  49. return err
  50. }
  51. err = o.validate(config)
  52. if err != nil {
  53. return err
  54. }
  55. config.CurrentContext = o.contextName
  56. if err := clientcmd.ModifyConfig(o.configAccess, *config, true); err != nil {
  57. return err
  58. }
  59. return nil
  60. }
  61. func (o *useContextOptions) complete(cmd *cobra.Command) bool {
  62. endingArgs := cmd.Flags().Args()
  63. if len(endingArgs) != 1 {
  64. cmd.Help()
  65. return false
  66. }
  67. o.contextName = endingArgs[0]
  68. return true
  69. }
  70. func (o useContextOptions) validate(config *clientcmdapi.Config) error {
  71. if len(o.contextName) == 0 {
  72. return errors.New("you must specify a current-context")
  73. }
  74. for name := range config.Contexts {
  75. if name == o.contextName {
  76. return nil
  77. }
  78. }
  79. return fmt.Errorf("no context exists with the name: %q.", o.contextName)
  80. }