github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/cli/command/image/remove.go (about)

     1  package image
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/docker/docker/api/types/image"
     9  	"github.com/docker/docker/errdefs"
    10  	"github.com/khulnasoft/cli/cli"
    11  	"github.com/khulnasoft/cli/cli/command"
    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(cmd.Context(), dockerCli, opts, args)
    31  		},
    32  		Annotations: map[string]string{
    33  			"aliases": "docker image rm, docker image remove, docker rmi",
    34  		},
    35  	}
    36  
    37  	flags := cmd.Flags()
    38  
    39  	flags.BoolVarP(&opts.force, "force", "f", false, "Force removal of the image")
    40  	flags.BoolVar(&opts.noPrune, "no-prune", false, "Do not delete untagged parents")
    41  
    42  	return cmd
    43  }
    44  
    45  func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
    46  	cmd := *NewRemoveCommand(dockerCli)
    47  	cmd.Aliases = []string{"rmi", "remove"}
    48  	cmd.Use = "rm [OPTIONS] IMAGE [IMAGE...]"
    49  	return &cmd
    50  }
    51  
    52  func runRemove(ctx context.Context, dockerCli command.Cli, opts removeOptions, images []string) error {
    53  	client := dockerCli.Client()
    54  
    55  	options := image.RemoveOptions{
    56  		Force:         opts.force,
    57  		PruneChildren: !opts.noPrune,
    58  	}
    59  
    60  	var errs []string
    61  	fatalErr := false
    62  	for _, img := range images {
    63  		dels, err := client.ImageRemove(ctx, img, options)
    64  		if err != nil {
    65  			if !errdefs.IsNotFound(err) {
    66  				fatalErr = true
    67  			}
    68  			errs = append(errs, err.Error())
    69  		} else {
    70  			for _, del := range dels {
    71  				if del.Deleted != "" {
    72  					fmt.Fprintf(dockerCli.Out(), "Deleted: %s\n", del.Deleted)
    73  				} else {
    74  					fmt.Fprintf(dockerCli.Out(), "Untagged: %s\n", del.Untagged)
    75  				}
    76  			}
    77  		}
    78  	}
    79  
    80  	if len(errs) > 0 {
    81  		msg := strings.Join(errs, "\n")
    82  		if !opts.force || fatalErr {
    83  			return errors.New(msg)
    84  		}
    85  		fmt.Fprintln(dockerCli.Err(), msg)
    86  	}
    87  	return nil
    88  }