github.com/kunnos/engine@v1.13.1/cli/command/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/types" 10 "github.com/docker/docker/cli" 11 "github.com/docker/docker/cli/command" 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.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 *command.DockerCli, 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 if container == "" { 56 return fmt.Errorf("Container name cannot be empty") 57 } 58 container = strings.Trim(container, "/") 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 } else { 66 fmt.Fprintf(dockerCli.Out(), "%s\n", name) 67 } 68 } 69 if len(errs) > 0 { 70 return fmt.Errorf("%s", strings.Join(errs, "\n")) 71 } 72 return nil 73 }