1
0
mirror of https://github.com/docker/compose.git synced 2025-04-07 19:55:07 +02:00

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

Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
This commit is contained in:
Nicolas De Loof 2021-06-03 15:30:05 +02:00
parent 82f35d1bac
commit 924d7925d6
No known key found for this signature in database
GPG Key ID: 9858809D6F8F6E7E
2 changed files with 19 additions and 20 deletions
cli/cmd/compose

@ -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")

@ -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,
})
}