list.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. type lsOptions struct {
  26. Format string
  27. Quiet bool
  28. }
  29. func listCommand() *cobra.Command {
  30. opts := lsOptions{}
  31. lsCmd := &cobra.Command{
  32. Use: "ls",
  33. Short: "List running compose projects",
  34. RunE: func(cmd *cobra.Command, args []string) error {
  35. return runList(cmd.Context(), opts)
  36. },
  37. }
  38. lsCmd.Flags().StringVar(&opts.Format, "format", "pretty", "Format the output. Values: [pretty | json].")
  39. lsCmd.Flags().BoolVarP(&opts.Quiet, "quiet", "q", false, "Only display IDs")
  40. return lsCmd
  41. }
  42. func runList(ctx context.Context, opts lsOptions) error {
  43. c, err := client.NewWithDefaultLocalBackend(ctx)
  44. if err != nil {
  45. return err
  46. }
  47. stackList, err := c.ComposeService().List(ctx, "")
  48. if err != nil {
  49. return err
  50. }
  51. if opts.Quiet {
  52. for _, s := range stackList {
  53. fmt.Println(s.Name)
  54. }
  55. return nil
  56. }
  57. view := viewFromStackList(stackList)
  58. return formatter.Print(view, opts.Format, os.Stdout, func(w io.Writer) {
  59. for _, stack := range view {
  60. _, _ = fmt.Fprintf(w, "%s\t%s\n", stack.Name, stack.Status)
  61. }
  62. }, "NAME", "STATUS")
  63. }
  64. type stackView struct {
  65. Name string
  66. Status string
  67. }
  68. func viewFromStackList(stackList []compose.Stack) []stackView {
  69. retList := make([]stackView, len(stackList))
  70. for i, s := range stackList {
  71. retList[i] = stackView{
  72. Name: s.Name,
  73. Status: strings.TrimSpace(fmt.Sprintf("%s %s", s.Status, s.Reason)),
  74. }
  75. }
  76. return retList
  77. }