Browse Source

showcase simpler command design by using API options as cobra flags target

Signed-off-by: Nicolas De Loof <[email protected]>
Nicolas De Loof 4 years ago
parent
commit
924d7925d6
2 changed files with 19 additions and 20 deletions
  1. 14 0
      cli/cmd/compose/compose.go
  2. 5 20
      cli/cmd/compose/kill.go

+ 14 - 0
cli/cmd/compose/compose.go

@@ -87,6 +87,20 @@ type projectOptions struct {
 	EnvFile     string
 }
 
+// ProjectFunc does stuff within a types.Project
+type ProjectFunc func(ctx context.Context, project *types.Project) error
+
+// WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
+func (o *projectOptions) WithServices(services []string, fn ProjectFunc) func(cmd *cobra.Command, args []string) error {
+	return Adapt(func(ctx context.Context, strings []string) error {
+		project, err := o.toProject(services)
+		if err != nil {
+			return err
+		}
+		return fn(ctx, project)
+	})
+}
+
 func (o *projectOptions) addProjectFlags(f *pflag.FlagSet) {
 	f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
 	f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")

+ 5 - 20
cli/cmd/compose/kill.go

@@ -18,26 +18,21 @@ package compose
 
 import (
 	"context"
+	"os"
 
+	"github.com/compose-spec/compose-go/types"
 	"github.com/spf13/cobra"
 
 	"github.com/docker/compose-cli/api/compose"
 )
 
-type killOptions struct {
-	*projectOptions
-	Signal string
-}
-
 func killCommand(p *projectOptions, backend compose.Service) *cobra.Command {
-	opts := killOptions{
-		projectOptions: p,
-	}
+	var opts compose.KillOptions
 	cmd := &cobra.Command{
 		Use:   "kill [options] [SERVICE...]",
 		Short: "Force stop service containers.",
-		RunE: Adapt(func(ctx context.Context, args []string) error {
-			return runKill(ctx, backend, opts, args)
+		RunE: p.WithServices(os.Args, func(ctx context.Context, project *types.Project) error {
+			return backend.Kill(ctx, project, opts)
 		}),
 	}
 
@@ -46,13 +41,3 @@ func killCommand(p *projectOptions, backend compose.Service) *cobra.Command {
 
 	return cmd
 }
-
-func runKill(ctx context.Context, backend compose.Service, opts killOptions, services []string) error {
-	project, err := opts.toProject(services)
-	if err != nil {
-		return err
-	}
-	return backend.Kill(ctx, project, compose.KillOptions{
-		Signal: opts.Signal,
-	})
-}