github.com/olljanat/moby@v1.13.1/cli/command/image/remove.go (about)

     1  package image
     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 removeOptions struct {
    16  	force   bool
    17  	noPrune bool
    18  }
    19  
    20  // NewRemoveCommand creates a new `docker remove` command
    21  func NewRemoveCommand(dockerCli *command.DockerCli) *cobra.Command {
    22  	var opts removeOptions
    23  
    24  	cmd := &cobra.Command{
    25  		Use:   "rmi [OPTIONS] IMAGE [IMAGE...]",
    26  		Short: "Remove one or more images",
    27  		Args:  cli.RequiresMinArgs(1),
    28  		RunE: func(cmd *cobra.Command, args []string) error {
    29  			return runRemove(dockerCli, opts, args)
    30  		},
    31  	}
    32  
    33  	flags := cmd.Flags()
    34  
    35  	flags.BoolVarP(&opts.force, "force", "f", false, "Force removal of the image")
    36  	flags.BoolVar(&opts.noPrune, "no-prune", false, "Do not delete untagged parents")
    37  
    38  	return cmd
    39  }
    40  
    41  func newRemoveCommand(dockerCli *command.DockerCli) *cobra.Command {
    42  	cmd := *NewRemoveCommand(dockerCli)
    43  	cmd.Aliases = []string{"rmi", "remove"}
    44  	cmd.Use = "rm [OPTIONS] IMAGE [IMAGE...]"
    45  	return &cmd
    46  }
    47  
    48  func runRemove(dockerCli *command.DockerCli, opts removeOptions, images []string) error {
    49  	client := dockerCli.Client()
    50  	ctx := context.Background()
    51  
    52  	options := types.ImageRemoveOptions{
    53  		Force:         opts.force,
    54  		PruneChildren: !opts.noPrune,
    55  	}
    56  
    57  	var errs []string
    58  	for _, image := range images {
    59  		dels, err := client.ImageRemove(ctx, image, options)
    60  		if err != nil {
    61  			errs = append(errs, err.Error())
    62  		} else {
    63  			for _, del := range dels {
    64  				if del.Deleted != "" {
    65  					fmt.Fprintf(dockerCli.Out(), "Deleted: %s\n", del.Deleted)
    66  				} else {
    67  					fmt.Fprintf(dockerCli.Out(), "Untagged: %s\n", del.Untagged)
    68  				}
    69  			}
    70  		}
    71  	}
    72  
    73  	if len(errs) > 0 {
    74  		return fmt.Errorf("%s", strings.Join(errs, "\n"))
    75  	}
    76  	return nil
    77  }