diff --git a/cli/command/container/rm.go b/cli/command/container/rm.go index 171e8e81e9e4..e1f095decbaa 100644 --- a/cli/command/container/rm.go +++ b/cli/command/container/rm.go @@ -18,6 +18,7 @@ type rmOptions struct { rmVolumes bool rmLink bool force bool + all bool // <-- Added this field for the --all option containers []string } @@ -45,12 +46,31 @@ func NewRmCommand(dockerCli command.Cli) *cobra.Command { flags.BoolVarP(&opts.rmVolumes, "volumes", "v", false, "Remove anonymous volumes associated with the container") flags.BoolVarP(&opts.rmLink, "link", "l", false, "Remove the specified link") flags.BoolVarP(&opts.force, "force", "f", false, "Force the removal of a running container (uses SIGKILL)") + flags.BoolVarP(&opts.all, "all", "a", false, "Remove all containers (both running and stopped)") // <-- Added this line + return cmd } func runRm(ctx context.Context, dockerCli command.Cli, opts *rmOptions) error { var errs []string - errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, ctrID string) error { + var containersToRemove []string + + // If --all is specified, fetch all container IDs + if opts.all { + // Use Docker API to get all containers (use the appropriate options) + containers, err := dockerCli.Client().ContainerList(ctx, container.ListOptions{All: true}) + if err != nil { + return err + } + for _, ctr := range containers { + containersToRemove = append(containersToRemove, ctr.ID) // Add container ID to the list + } + } else { + containersToRemove = opts.containers // Use specified containers + } + + // Use the same parallel operation for removing containers + errChan := parallelOperation(ctx, containersToRemove, func(ctx context.Context, ctrID string) error { ctrID = strings.Trim(ctrID, "/") if ctrID == "" { return errors.New("Container name cannot be empty") @@ -62,7 +82,7 @@ func runRm(ctx context.Context, dockerCli command.Cli, opts *rmOptions) error { }) }) - for _, name := range opts.containers { + for _, name := range containersToRemove { if err := <-errChan; err != nil { if opts.force && errdefs.IsNotFound(err) { fmt.Fprintln(dockerCli.Err(), err)