github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/cmd/podmanV2/volumes/prune.go (about)

     1  package volumes
     2  
     3  import (
     4  	"bufio"
     5  	"context"
     6  	"fmt"
     7  	"os"
     8  	"strings"
     9  
    10  	"github.com/containers/libpod/cmd/podmanV2/registry"
    11  	"github.com/containers/libpod/cmd/podmanV2/utils"
    12  	"github.com/containers/libpod/pkg/domain/entities"
    13  	"github.com/pkg/errors"
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  var (
    18  	volumePruneDescription = `Volumes that are not currently owned by a container will be removed.
    19  
    20    The command prompts for confirmation which can be overridden with the --force flag.
    21    Note all data will be destroyed.`
    22  	pruneCommand = &cobra.Command{
    23  		Use:   "prune",
    24  		Args:  cobra.NoArgs,
    25  		Short: "Remove all unused volumes",
    26  		Long:  volumePruneDescription,
    27  		RunE:  prune,
    28  	}
    29  )
    30  
    31  var (
    32  	pruneOptions entities.VolumePruneOptions
    33  )
    34  
    35  func init() {
    36  	registry.Commands = append(registry.Commands, registry.CliCommand{
    37  		Mode:    []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
    38  		Command: pruneCommand,
    39  		Parent:  volumeCmd,
    40  	})
    41  	flags := pruneCommand.Flags()
    42  	flags.BoolVarP(&pruneOptions.Force, "force", "f", false, "Do not prompt for confirmation")
    43  }
    44  
    45  func prune(cmd *cobra.Command, args []string) error {
    46  	var (
    47  		errs utils.OutputErrors
    48  	)
    49  	// Prompt for confirmation if --force is not set
    50  	if !pruneOptions.Force {
    51  		reader := bufio.NewReader(os.Stdin)
    52  		fmt.Println("WARNING! This will remove all volumes not used by at least one container.")
    53  		fmt.Print("Are you sure you want to continue? [y/N] ")
    54  		answer, err := reader.ReadString('\n')
    55  		if err != nil {
    56  			return errors.Wrapf(err, "error reading input")
    57  		}
    58  		if strings.ToLower(answer)[0] != 'y' {
    59  			return nil
    60  		}
    61  	}
    62  	responses, err := registry.ContainerEngine().VolumePrune(context.Background(), pruneOptions)
    63  	if err != nil {
    64  		return err
    65  	}
    66  	for _, r := range responses {
    67  		if r.Err == nil {
    68  			fmt.Println(r.Id)
    69  		} else {
    70  			errs = append(errs, r.Err)
    71  		}
    72  	}
    73  	return errs.PrintErrors()
    74  }