ls.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. /*
  2. Copyright 2020 Docker Compose CLI 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 context
  14. import (
  15. "fmt"
  16. "io"
  17. "os"
  18. "sort"
  19. "strings"
  20. "github.com/pkg/errors"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/compose-cli/cli/mobycli"
  23. apicontext "github.com/docker/compose-cli/context"
  24. "github.com/docker/compose-cli/context/store"
  25. "github.com/docker/compose-cli/formatter"
  26. )
  27. type lsOpts struct {
  28. quiet bool
  29. json bool
  30. format string
  31. }
  32. func (o lsOpts) validate() error {
  33. if o.quiet && o.json {
  34. return errors.New(`cannot combine "quiet" and "json" options`)
  35. }
  36. return nil
  37. }
  38. func listCommand() *cobra.Command {
  39. var opts lsOpts
  40. cmd := &cobra.Command{
  41. Use: "list",
  42. Short: "List available contexts",
  43. Aliases: []string{"ls"},
  44. Args: cobra.NoArgs,
  45. RunE: func(cmd *cobra.Command, args []string) error {
  46. return runList(cmd, opts)
  47. },
  48. }
  49. cmd.Flags().BoolVarP(&opts.quiet, "quiet", "q", false, "Only show context names")
  50. cmd.Flags().BoolVar(&opts.json, "json", false, "Format output as JSON")
  51. cmd.Flags().StringVar(&opts.format, "format", "", "Format the output. Values: [pretty | json]. (Default: pretty)")
  52. _ = cmd.Flags().MarkHidden("json")
  53. return cmd
  54. }
  55. func runList(cmd *cobra.Command, opts lsOpts) error {
  56. err := opts.validate()
  57. if err != nil {
  58. return err
  59. }
  60. if opts.format != "" && opts.format != formatter.JSON && opts.format != formatter.PRETTY {
  61. mobycli.Exec(cmd.Root())
  62. return nil
  63. }
  64. ctx := cmd.Context()
  65. currentContext := apicontext.CurrentContext(ctx)
  66. s := store.ContextStore(ctx)
  67. contexts, err := s.List()
  68. if err != nil {
  69. return err
  70. }
  71. sort.Slice(contexts, func(i, j int) bool {
  72. return strings.Compare(contexts[i].Name, contexts[j].Name) == -1
  73. })
  74. if opts.quiet {
  75. for _, c := range contexts {
  76. fmt.Println(c.Name)
  77. }
  78. return nil
  79. }
  80. view := viewFromContextList(contexts, currentContext)
  81. if opts.json || opts.format == formatter.JSON {
  82. for _, l := range view {
  83. outJSON, err := formatter.ToCompressedJSON(l)
  84. if err != nil {
  85. return err
  86. }
  87. _, _ = fmt.Fprintln(os.Stdout, outJSON)
  88. }
  89. return nil
  90. }
  91. return formatter.Print(view, formatter.PRETTY, os.Stdout,
  92. func(w io.Writer) {
  93. for _, c := range view {
  94. contextName := c.Name
  95. if c.Current {
  96. contextName += " *"
  97. }
  98. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n",
  99. contextName,
  100. c.Type,
  101. c.Description,
  102. c.DockerEndpoint,
  103. c.KubernetesEndpoint,
  104. c.StackOrchestrator)
  105. }
  106. },
  107. "NAME", "TYPE", "DESCRIPTION", "DOCKER ENDPOINT", "KUBERNETES ENDPOINT", "ORCHESTRATOR")
  108. }
  109. func getEndpoint(name string, meta map[string]interface{}) string {
  110. endpoints, ok := meta[name]
  111. if !ok {
  112. return ""
  113. }
  114. data, ok := endpoints.(*store.Endpoint)
  115. if !ok {
  116. return ""
  117. }
  118. result := data.Host
  119. if data.DefaultNamespace != "" {
  120. result += fmt.Sprintf(" (%s)", data.DefaultNamespace)
  121. }
  122. return result
  123. }
  124. type contextView struct {
  125. Current bool
  126. Description string
  127. DockerEndpoint string
  128. KubernetesEndpoint string
  129. Type string
  130. Name string
  131. StackOrchestrator string
  132. }
  133. func viewFromContextList(contextList []*store.DockerContext, currentContext string) []contextView {
  134. retList := make([]contextView, len(contextList))
  135. for i, c := range contextList {
  136. retList[i] = contextView{
  137. Current: c.Name == currentContext,
  138. Description: c.Metadata.Description,
  139. DockerEndpoint: getEndpoint("docker", c.Endpoints),
  140. KubernetesEndpoint: getEndpoint("kubernetes", c.Endpoints),
  141. Name: c.Name,
  142. Type: c.Type(),
  143. StackOrchestrator: c.Metadata.StackOrchestrator,
  144. }
  145. }
  146. return retList
  147. }