瀏覽代碼

check service names based on project, not running containers

Signed-off-by: Nicolas De Loof <[email protected]>
Nicolas De Loof 2 年之前
父節點
當前提交
9bd9f1765c
共有 2 個文件被更改,包括 21 次插入10 次删除
  1. 10 10
      cmd/compose/ps.go
  2. 11 0
      pkg/e2e/ps_test.go

+ 10 - 10
cmd/compose/ps.go

@@ -96,6 +96,16 @@ func runPs(ctx context.Context, streams api.Streams, backend api.Service, servic
 	if err != nil {
 		return err
 	}
+
+	if project != nil && len(services) > 0 {
+		names := project.ServiceNames()
+		for _, service := range services {
+			if !utils.StringContains(names, service) {
+				return fmt.Errorf("no such service: %s", service)
+			}
+		}
+	}
+
 	containers, err := backend.Ps(ctx, name, api.PsOptions{
 		Project:  project,
 		All:      opts.All,
@@ -105,16 +115,6 @@ func runPs(ctx context.Context, streams api.Streams, backend api.Service, servic
 		return err
 	}
 
-SERVICES:
-	for _, s := range services {
-		for _, c := range containers {
-			if c.Service == s {
-				continue SERVICES
-			}
-		}
-		return fmt.Errorf("no such service: %s", s)
-	}
-
 	if len(opts.Status) != 0 {
 		containers = filterByStatus(containers, opts.Status)
 	}

+ 11 - 0
pkg/e2e/ps_test.go

@@ -23,6 +23,7 @@ import (
 
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+	"gotest.tools/v3/icmd"
 
 	"github.com/docker/compose/v2/pkg/api"
 )
@@ -108,4 +109,14 @@ func TestPs(t *testing.T) {
 		assert.Equal(t, 4, len(lines))
 	})
 
+	t.Run("ps unknown", func(t *testing.T) {
+		res := c.RunDockerComposeCmd(t, "--project-name", projectName, "stop")
+		assert.NoError(t, res.Error)
+
+		res = c.RunDockerComposeCmd(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "ps", "nginx")
+		res.Assert(t, icmd.Success)
+
+		res = c.RunDockerComposeCmdNoCheck(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "ps", "unknown")
+		res.Assert(t, icmd.Expected{ExitCode: 1, Err: "no such service: unknown"})
+	})
 }