github.com/AliyunContainerService/cli@v0.0.0-20181009023821-814ced4b30d0/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/pkg/errors" 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 command.Cli) *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 command.Cli, opts *rmOptions) error { 45 ctx := context.Background() 46 47 var errs []string 48 options := types.ContainerRemoveOptions{ 49 RemoveVolumes: opts.rmVolumes, 50 RemoveLinks: opts.rmLink, 51 Force: opts.force, 52 } 53 54 errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error { 55 container = strings.Trim(container, "/") 56 if container == "" { 57 return errors.New("Container name cannot be empty") 58 } 59 return dockerCli.Client().ContainerRemove(ctx, container, options) 60 }) 61 62 for _, name := range opts.containers { 63 if err := <-errChan; err != nil { 64 errs = append(errs, err.Error()) 65 continue 66 } 67 fmt.Fprintln(dockerCli.Out(), name) 68 } 69 if len(errs) > 0 { 70 return errors.New(strings.Join(errs, "\n")) 71 } 72 return nil 73 }