current_context.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/spf13/cobra"
  18. "k8s.io/client-go/tools/clientcmd"
  19. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  20. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  21. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  22. )
  23. // CurrentContextOptions holds the command-line options for 'config current-context' sub command
  24. type CurrentContextOptions struct {
  25. ConfigAccess clientcmd.ConfigAccess
  26. }
  27. var (
  28. currentContextLong = templates.LongDesc(`
  29. Displays the current-context`)
  30. currentContextExample = templates.Examples(`
  31. # Display the current-context
  32. kubectl config current-context`)
  33. )
  34. // NewCmdConfigCurrentContext returns a Command instance for 'config current-context' sub command
  35. func NewCmdConfigCurrentContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
  36. options := &CurrentContextOptions{ConfigAccess: configAccess}
  37. cmd := &cobra.Command{
  38. Use: "current-context",
  39. Short: i18n.T("Displays the current-context"),
  40. Long: currentContextLong,
  41. Example: currentContextExample,
  42. Run: func(cmd *cobra.Command, args []string) {
  43. cmdutil.CheckErr(RunCurrentContext(out, options))
  44. },
  45. }
  46. return cmd
  47. }
  48. // RunCurrentContext performs the execution of 'config current-context' sub command
  49. func RunCurrentContext(out io.Writer, options *CurrentContextOptions) error {
  50. config, err := options.ConfigAccess.GetStartingConfig()
  51. if err != nil {
  52. return err
  53. }
  54. if config.CurrentContext == "" {
  55. err = fmt.Errorf("current-context is not set")
  56. return err
  57. }
  58. fmt.Fprintf(out, "%s\n", config.CurrentContext)
  59. return nil
  60. }