Files
docker-cli/cli/command/container/stop.go
Sebastiaan van Stijn 0adaf6be3b verify that DisableFlagsInUseLine is set for all commands
This replaces the visitAll recursive function with a test that verifies that
the option is set for all commands and subcommands, so that it doesn't have
to be modified at runtime.

We currently still have to loop over all functions for the setValidateArgs
call, but that can be looked at separately.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-01 09:39:46 +02:00

82 lines
2.4 KiB
Go

package container
import (
"context"
"errors"
"fmt"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/moby/moby/api/types/container"
"github.com/spf13/cobra"
)
type stopOptions struct {
signal string
timeout int
timeoutChanged bool
containers []string
}
// newStopCommand creates a new cobra.Command for "docker container stop".
func newStopCommand(dockerCLI command.Cli) *cobra.Command {
var opts stopOptions
cmd := &cobra.Command{
Use: "stop [OPTIONS] CONTAINER [CONTAINER...]",
Short: "Stop one or more running containers",
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if cmd.Flags().Changed("time") && cmd.Flags().Changed("timeout") {
return errors.New("conflicting options: cannot specify both --timeout and --time")
}
opts.containers = args
opts.timeoutChanged = cmd.Flags().Changed("timeout") || cmd.Flags().Changed("time")
return runStop(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container stop, docker stop",
},
ValidArgsFunction: completion.ContainerNames(dockerCLI, false),
DisableFlagsInUseLine: true,
}
flags := cmd.Flags()
flags.StringVarP(&opts.signal, "signal", "s", "", "Signal to send to the container")
flags.IntVarP(&opts.timeout, "timeout", "t", 0, "Seconds to wait before killing the container")
// The --time option is deprecated, but kept for backward compatibility.
flags.IntVar(&opts.timeout, "time", 0, "Seconds to wait before killing the container (deprecated: use --timeout)")
_ = flags.MarkDeprecated("time", "use --timeout instead")
_ = cmd.RegisterFlagCompletionFunc("signal", completeSignals)
return cmd
}
func runStop(ctx context.Context, dockerCLI command.Cli, opts *stopOptions) error {
var timeout *int
if opts.timeoutChanged {
timeout = &opts.timeout
}
apiClient := dockerCLI.Client()
errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error {
return apiClient.ContainerStop(ctx, id, container.StopOptions{
Signal: opts.signal,
Timeout: timeout,
})
})
var errs []error
for _, ctr := range opts.containers {
if err := <-errChan; err != nil {
errs = append(errs, err)
continue
}
_, _ = fmt.Fprintln(dockerCLI.Out(), ctr)
}
return errors.Join(errs...)
}