github.com/portworx/docker@v1.12.1/api/client/container/rm.go (about)

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