github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/cmd/podman/images_prune.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/containers/libpod/cmd/podman/cliconfig"
    10  	"github.com/containers/libpod/pkg/adapter"
    11  	"github.com/pkg/errors"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  var (
    16  	pruneImagesCommand     cliconfig.PruneImagesValues
    17  	pruneImagesDescription = `Removes all unnamed images from local storage.
    18  
    19    If an image is not being used by a container, it will be removed from the system.`
    20  	_pruneImagesCommand = &cobra.Command{
    21  		Use:   "prune",
    22  		Args:  noSubArgs,
    23  		Short: "Remove unused images",
    24  		Long:  pruneImagesDescription,
    25  		RunE: func(cmd *cobra.Command, args []string) error {
    26  			pruneImagesCommand.InputArgs = args
    27  			pruneImagesCommand.GlobalFlags = MainGlobalOpts
    28  			pruneImagesCommand.Remote = remoteclient
    29  			return pruneImagesCmd(&pruneImagesCommand)
    30  		},
    31  	}
    32  )
    33  
    34  func init() {
    35  	pruneImagesCommand.Command = _pruneImagesCommand
    36  	pruneImagesCommand.SetHelpTemplate(HelpTemplate())
    37  	pruneImagesCommand.SetUsageTemplate(UsageTemplate())
    38  	flags := pruneImagesCommand.Flags()
    39  	flags.BoolVarP(&pruneImagesCommand.All, "all", "a", false, "Remove all unused images, not just dangling ones")
    40  	flags.BoolVarP(&pruneImagesCommand.Force, "force", "f", false, "Do not prompt for confirmation")
    41  	flags.StringArrayVar(&pruneImagesCommand.Filter, "filter", []string{}, "Provide filter values (e.g. 'label=<key>=<value>')")
    42  }
    43  
    44  func pruneImagesCmd(c *cliconfig.PruneImagesValues) error {
    45  	if !c.Force {
    46  		reader := bufio.NewReader(os.Stdin)
    47  		fmt.Printf(`
    48  WARNING! This will remove all dangling images.
    49  Are you sure you want to continue? [y/N] `)
    50  		answer, err := reader.ReadString('\n')
    51  		if err != nil {
    52  			return errors.Wrapf(err, "error reading input")
    53  		}
    54  		if strings.ToLower(answer)[0] != 'y' {
    55  			return nil
    56  		}
    57  	}
    58  	runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand)
    59  	if err != nil {
    60  		return errors.Wrapf(err, "could not get runtime")
    61  	}
    62  	defer runtime.DeferredShutdown(false)
    63  
    64  	// Call prune; if any cids are returned, print them and then
    65  	// return err in case an error also came up
    66  	pruneCids, err := runtime.PruneImages(getContext(), c.All, c.Filter)
    67  	if len(pruneCids) > 0 {
    68  		for _, cid := range pruneCids {
    69  			fmt.Println(cid)
    70  		}
    71  	}
    72  	return err
    73  }