ps.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. "sort"
  20. "strings"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/compose-cli/api/client"
  23. "github.com/docker/compose-cli/formatter"
  24. )
  25. func psCommand() *cobra.Command {
  26. opts := composeOptions{}
  27. psCmd := &cobra.Command{
  28. Use: "ps",
  29. Short: "List containers",
  30. RunE: func(cmd *cobra.Command, args []string) error {
  31. return runPs(cmd.Context(), opts)
  32. },
  33. }
  34. psCmd.Flags().StringVar(&opts.WorkingDir, "workdir", "", "Work dir")
  35. psCmd.Flags().StringArrayVarP(&opts.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  36. addComposeCommonFlags(psCmd.Flags(), &opts)
  37. return psCmd
  38. }
  39. func runPs(ctx context.Context, opts composeOptions) error {
  40. c, err := client.NewWithDefaultLocalBackend(ctx)
  41. if err != nil {
  42. return err
  43. }
  44. projectName, err := opts.toProjectName()
  45. if err != nil {
  46. return err
  47. }
  48. containers, err := c.ComposeService().Ps(ctx, projectName)
  49. if err != nil {
  50. return err
  51. }
  52. if opts.Quiet {
  53. for _, s := range containers {
  54. fmt.Println(s.ID)
  55. }
  56. return nil
  57. }
  58. sort.Slice(containers, func(i, j int) bool {
  59. return containers[i].Name < containers[j].Name
  60. })
  61. return formatter.Print(containers, opts.Format, os.Stdout,
  62. func(w io.Writer) {
  63. for _, container := range containers {
  64. var ports []string
  65. for _, p := range container.Publishers {
  66. if p.URL == "" {
  67. ports = append(ports, fmt.Sprintf("%d/%s", p.TargetPort, p.Protocol))
  68. } else {
  69. ports = append(ports, fmt.Sprintf("%s->%d/%s", p.URL, p.TargetPort, p.Protocol))
  70. }
  71. }
  72. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", container.Name, container.Service, container.State, strings.Join(ports, ", "))
  73. }
  74. },
  75. "NAME", "SERVICE", "STATE", "PORTS")
  76. }