github.com/portworx/docker@v1.12.1/api/client/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/client"
    10  	"github.com/docker/docker/cli"
    11  	"github.com/docker/engine-api/types"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type removeOptions struct {
    16  	force   bool
    17  	noPrune bool
    18  }
    19  
    20  // NewRemoveCommand create a new `docker remove` command
    21  func NewRemoveCommand(dockerCli *client.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 runRemove(dockerCli *client.DockerCli, opts removeOptions, images []string) error {
    42  	client := dockerCli.Client()
    43  	ctx := context.Background()
    44  
    45  	options := types.ImageRemoveOptions{
    46  		Force:         opts.force,
    47  		PruneChildren: !opts.noPrune,
    48  	}
    49  
    50  	var errs []string
    51  	for _, image := range images {
    52  		dels, err := client.ImageRemove(ctx, image, options)
    53  		if err != nil {
    54  			errs = append(errs, err.Error())
    55  		} else {
    56  			for _, del := range dels {
    57  				if del.Deleted != "" {
    58  					fmt.Fprintf(dockerCli.Out(), "Deleted: %s\n", del.Deleted)
    59  				} else {
    60  					fmt.Fprintf(dockerCli.Out(), "Untagged: %s\n", del.Untagged)
    61  				}
    62  			}
    63  		}
    64  	}
    65  
    66  	if len(errs) > 0 {
    67  		return fmt.Errorf("%s", strings.Join(errs, "\n"))
    68  	}
    69  	return nil
    70  }