list.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 compose
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "os"
  19. "strings"
  20. "github.com/spf13/cobra"
  21. "github.com/spf13/pflag"
  22. "github.com/docker/compose-cli/api/client"
  23. "github.com/docker/compose-cli/api/compose"
  24. "github.com/docker/compose-cli/formatter"
  25. )
  26. func listCommand() *cobra.Command {
  27. opts := composeOptions{}
  28. lsCmd := &cobra.Command{
  29. Use: "ls",
  30. RunE: func(cmd *cobra.Command, args []string) error {
  31. return runList(cmd.Context(), opts)
  32. },
  33. }
  34. addComposeCommonFlags(lsCmd.Flags(), &opts)
  35. return lsCmd
  36. }
  37. func addComposeCommonFlags(f *pflag.FlagSet, opts *composeOptions) {
  38. f.StringVarP(&opts.Name, "project-name", "p", "", "Project name")
  39. f.StringVar(&opts.Format, "format", "", "Format the output. Values: [pretty | json]. (Default: pretty)")
  40. }
  41. func runList(ctx context.Context, opts composeOptions) error {
  42. c, err := client.New(ctx)
  43. if err != nil {
  44. return err
  45. }
  46. stackList, err := c.ComposeService().List(ctx, opts.Name)
  47. if err != nil {
  48. return err
  49. }
  50. view := viewFromStackList(stackList)
  51. return formatter.Print(view, opts.Format, os.Stdout, func(w io.Writer) {
  52. for _, stack := range view {
  53. _, _ = fmt.Fprintf(w, "%s\t%s\n", stack.Name, strings.TrimSpace(
  54. fmt.Sprintf("%s %s", stack.Status, stack.Reason))
  55. }
  56. }, "NAME", "STATUS")
  57. }
  58. type stackView struct {
  59. Name string
  60. Status string
  61. }
  62. func viewFromStackList(stackList []compose.Stack) []stackView {
  63. retList := make([]stackView, len(stackList))
  64. for i, s := range stackList {
  65. retList[i] = stackView{
  66. Name: s.Name,
  67. Status: s.Status,
  68. }
  69. }
  70. return retList
  71. }