github.com/xeptore/docker-cli@v20.10.14+incompatible/cli/command/container/rm.go (about)

     1  package container
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/docker/cli/cli"
     9  	"github.com/docker/cli/cli/command"
    10  	"github.com/docker/docker/api/types"
    11  	"github.com/docker/docker/errdefs"
    12  	"github.com/pkg/errors"
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  type rmOptions struct {
    17  	rmVolumes bool
    18  	rmLink    bool
    19  	force     bool
    20  
    21  	containers []string
    22  }
    23  
    24  // NewRmCommand creates a new cobra.Command for `docker rm`
    25  func NewRmCommand(dockerCli command.Cli) *cobra.Command {
    26  	var opts rmOptions
    27  
    28  	cmd := &cobra.Command{
    29  		Use:   "rm [OPTIONS] CONTAINER [CONTAINER...]",
    30  		Short: "Remove one or more containers",
    31  		Args:  cli.RequiresMinArgs(1),
    32  		RunE: func(cmd *cobra.Command, args []string) error {
    33  			opts.containers = args
    34  			return runRm(dockerCli, &opts)
    35  		},
    36  	}
    37  
    38  	flags := cmd.Flags()
    39  	flags.BoolVarP(&opts.rmVolumes, "volumes", "v", false, "Remove anonymous volumes associated with the container")
    40  	flags.BoolVarP(&opts.rmLink, "link", "l", false, "Remove the specified link")
    41  	flags.BoolVarP(&opts.force, "force", "f", false, "Force the removal of a running container (uses SIGKILL)")
    42  	return cmd
    43  }
    44  
    45  func runRm(dockerCli command.Cli, opts *rmOptions) error {
    46  	ctx := context.Background()
    47  
    48  	var errs []string
    49  	options := types.ContainerRemoveOptions{
    50  		RemoveVolumes: opts.rmVolumes,
    51  		RemoveLinks:   opts.rmLink,
    52  		Force:         opts.force,
    53  	}
    54  
    55  	errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error {
    56  		container = strings.Trim(container, "/")
    57  		if container == "" {
    58  			return errors.New("Container name cannot be empty")
    59  		}
    60  		return dockerCli.Client().ContainerRemove(ctx, container, options)
    61  	})
    62  
    63  	for _, name := range opts.containers {
    64  		if err := <-errChan; err != nil {
    65  			if opts.force && errdefs.IsNotFound(err) {
    66  				fmt.Fprintln(dockerCli.Err(), err)
    67  				continue
    68  			}
    69  			errs = append(errs, err.Error())
    70  			continue
    71  		}
    72  		fmt.Fprintln(dockerCli.Out(), name)
    73  	}
    74  	if len(errs) > 0 {
    75  		return errors.New(strings.Join(errs, "\n"))
    76  	}
    77  	return nil
    78  }