github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/cli/command/image/remove.go (about)

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