Skip to content
This repository was archived by the owner on Nov 27, 2023. It is now read-only.

Commit 924d792

Browse files
committed
showcase simpler command design by using API options as cobra flags target
Signed-off-by: Nicolas De Loof <[email protected]>
1 parent 82f35d1 commit 924d792

File tree

2 files changed

+19
-20
lines changed

2 files changed

+19
-20
lines changed

cli/cmd/compose/compose.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,20 @@ type projectOptions struct {
8787
EnvFile string
8888
}
8989

90+
// ProjectFunc does stuff within a types.Project
91+
type ProjectFunc func(ctx context.Context, project *types.Project) error
92+
93+
// WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
94+
func (o *projectOptions) WithServices(services []string, fn ProjectFunc) func(cmd *cobra.Command, args []string) error {
95+
return Adapt(func(ctx context.Context, strings []string) error {
96+
project, err := o.toProject(services)
97+
if err != nil {
98+
return err
99+
}
100+
return fn(ctx, project)
101+
})
102+
}
103+
90104
func (o *projectOptions) addProjectFlags(f *pflag.FlagSet) {
91105
f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
92106
f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")

cli/cmd/compose/kill.go

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,26 +18,21 @@ package compose
1818

1919
import (
2020
"context"
21+
"os"
2122

23+
"github.com/compose-spec/compose-go/types"
2224
"github.com/spf13/cobra"
2325

2426
"github.com/docker/compose-cli/api/compose"
2527
)
2628

27-
type killOptions struct {
28-
*projectOptions
29-
Signal string
30-
}
31-
3229
func killCommand(p *projectOptions, backend compose.Service) *cobra.Command {
33-
opts := killOptions{
34-
projectOptions: p,
35-
}
30+
var opts compose.KillOptions
3631
cmd := &cobra.Command{
3732
Use: "kill [options] [SERVICE...]",
3833
Short: "Force stop service containers.",
39-
RunE: Adapt(func(ctx context.Context, args []string) error {
40-
return runKill(ctx, backend, opts, args)
34+
RunE: p.WithServices(os.Args, func(ctx context.Context, project *types.Project) error {
35+
return backend.Kill(ctx, project, opts)
4136
}),
4237
}
4338

@@ -46,13 +41,3 @@ func killCommand(p *projectOptions, backend compose.Service) *cobra.Command {
4641

4742
return cmd
4843
}
49-
50-
func runKill(ctx context.Context, backend compose.Service, opts killOptions, services []string) error {
51-
project, err := opts.toProject(services)
52-
if err != nil {
53-
return err
54-
}
55-
return backend.Kill(ctx, project, compose.KillOptions{
56-
Signal: opts.Signal,
57-
})
58-
}

0 commit comments

Comments
 (0)