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