ls.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. formatter2 "github.com/docker/compose-cli/cmd/formatter"
  21. "github.com/pkg/errors"
  22. "github.com/spf13/cobra"
  23. apicontext "github.com/docker/compose-cli/api/context"
  24. "github.com/docker/compose-cli/api/context/store"
  25. "github.com/docker/compose-cli/cli/mobycli"
  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().StringVar(&opts.format, "format", "", "Format the output. Values: [pretty | json]. (Default: pretty)")
  51. return cmd
  52. }
  53. func runList(cmd *cobra.Command, opts lsOpts) error {
  54. err := opts.validate()
  55. if err != nil {
  56. return err
  57. }
  58. format := strings.ToLower(strings.ReplaceAll(opts.format, " ", ""))
  59. if format != "" && format != formatter2.JSON && format != formatter2.PRETTY && format != formatter2.TemplateLegacyJSON {
  60. mobycli.Exec(cmd.Root())
  61. return nil
  62. }
  63. currentContext := apicontext.Current()
  64. s := store.Instance()
  65. contexts, err := s.List()
  66. if err != nil {
  67. return err
  68. }
  69. sort.Slice(contexts, func(i, j int) bool {
  70. return strings.Compare(contexts[i].Name, contexts[j].Name) == -1
  71. })
  72. if opts.quiet {
  73. for _, c := range contexts {
  74. fmt.Println(c.Name)
  75. }
  76. return nil
  77. }
  78. if opts.json || format == formatter2.JSON {
  79. opts.format = formatter2.JSON
  80. }
  81. if format == formatter2.TemplateLegacyJSON {
  82. opts.format = formatter2.TemplateLegacyJSON
  83. }
  84. view := viewFromContextList(contexts, currentContext)
  85. return formatter2.Print(view, opts.format, os.Stdout,
  86. func(w io.Writer) {
  87. for _, c := range view {
  88. contextName := c.Name
  89. if c.Current {
  90. contextName += " *"
  91. }
  92. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n",
  93. contextName,
  94. c.ContextType,
  95. c.Description,
  96. c.DockerEndpoint,
  97. c.KubernetesEndpoint,
  98. c.StackOrchestrator)
  99. }
  100. },
  101. "NAME", "TYPE", "DESCRIPTION", "DOCKER ENDPOINT", "KUBERNETES ENDPOINT", "ORCHESTRATOR")
  102. }
  103. func getEndpoint(name string, meta map[string]interface{}) string {
  104. endpoints, ok := meta[name]
  105. if !ok {
  106. return ""
  107. }
  108. data, ok := endpoints.(*store.Endpoint)
  109. if !ok {
  110. return ""
  111. }
  112. result := data.Host
  113. if data.DefaultNamespace != "" {
  114. result += fmt.Sprintf(" (%s)", data.DefaultNamespace)
  115. }
  116. return result
  117. }
  118. type contextView struct {
  119. Current bool
  120. Description string
  121. DockerEndpoint string
  122. KubernetesEndpoint string
  123. ContextType string
  124. Name string
  125. StackOrchestrator string
  126. }
  127. func viewFromContextList(contextList []*store.DockerContext, currentContext string) []contextView {
  128. retList := make([]contextView, len(contextList))
  129. for i, c := range contextList {
  130. retList[i] = contextView{
  131. Current: c.Name == currentContext,
  132. Description: c.Metadata.Description,
  133. DockerEndpoint: getEndpoint("docker", c.Endpoints),
  134. KubernetesEndpoint: getEndpoint("kubernetes", c.Endpoints),
  135. Name: c.Name,
  136. ContextType: c.Type(),
  137. StackOrchestrator: c.Metadata.StackOrchestrator,
  138. }
  139. }
  140. return retList
  141. }