current_context.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. "fmt"
  16. "io"
  17. "github.com/renstrom/dedent"
  18. "github.com/spf13/cobra"
  19. "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
  20. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  21. )
  22. type CurrentContextOptions struct {
  23. ConfigAccess clientcmd.ConfigAccess
  24. }
  25. var (
  26. current_context_long = dedent.Dedent(`
  27. Displays the current-context`)
  28. current_context_example = dedent.Dedent(`
  29. # Display the current-context
  30. kubectl config current-context`)
  31. )
  32. func NewCmdConfigCurrentContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
  33. options := &CurrentContextOptions{ConfigAccess: configAccess}
  34. cmd := &cobra.Command{
  35. Use: "current-context",
  36. Short: "Displays the current-context",
  37. Long: current_context_long,
  38. Example: current_context_example,
  39. Run: func(cmd *cobra.Command, args []string) {
  40. err := RunCurrentContext(out, args, options)
  41. cmdutil.CheckErr(err)
  42. },
  43. }
  44. return cmd
  45. }
  46. func RunCurrentContext(out io.Writer, args []string, options *CurrentContextOptions) error {
  47. config, err := options.ConfigAccess.GetStartingConfig()
  48. if err != nil {
  49. return err
  50. }
  51. if config.CurrentContext == "" {
  52. err = fmt.Errorf("current-context is not set\n")
  53. return err
  54. }
  55. fmt.Fprintf(out, "%s\n", config.CurrentContext)
  56. return nil
  57. }