list.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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/docker/compose-cli/api/client"
  22. "github.com/docker/compose-cli/api/compose"
  23. "github.com/docker/compose-cli/cli/formatter"
  24. )
  25. func listCommand() *cobra.Command {
  26. opts := composeOptions{}
  27. lsCmd := &cobra.Command{
  28. Use: "ls",
  29. Short: "List running compose projects",
  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 runList(ctx context.Context, opts composeOptions) error {
  38. c, err := client.NewWithDefaultLocalBackend(ctx)
  39. if err != nil {
  40. return err
  41. }
  42. stackList, err := c.ComposeService().List(ctx, opts.ProjectName)
  43. if err != nil {
  44. return err
  45. }
  46. if opts.Quiet {
  47. for _, s := range stackList {
  48. fmt.Println(s.Name)
  49. }
  50. return nil
  51. }
  52. view := viewFromStackList(stackList)
  53. return formatter.Print(view, opts.Format, os.Stdout, func(w io.Writer) {
  54. for _, stack := range view {
  55. _, _ = fmt.Fprintf(w, "%s\t%s\n", stack.Name, stack.Status)
  56. }
  57. }, "NAME", "STATUS")
  58. }
  59. type stackView struct {
  60. Name string
  61. Status string
  62. }
  63. func viewFromStackList(stackList []compose.Stack) []stackView {
  64. retList := make([]stackView, len(stackList))
  65. for i, s := range stackList {
  66. retList[i] = stackView{
  67. Name: s.Name,
  68. Status: strings.TrimSpace(fmt.Sprintf("%s %s", s.Status, s.Reason)),
  69. }
  70. }
  71. return retList
  72. }