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

     1  package volumes
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/containers/libpod/cmd/podmanV2/registry"
     8  	"github.com/containers/libpod/cmd/podmanV2/utils"
     9  	"github.com/containers/libpod/pkg/domain/entities"
    10  	"github.com/pkg/errors"
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  var (
    15  	volumeRmDescription = `Remove one or more existing volumes.
    16  
    17    By default only volumes that are not being used by any containers will be removed. To remove the volumes anyways, use the --force flag.`
    18  	rmCommand = &cobra.Command{
    19  		Use:     "rm [flags] VOLUME [VOLUME...]",
    20  		Aliases: []string{"remove"},
    21  		Short:   "Remove one or more volumes",
    22  		Long:    volumeRmDescription,
    23  		RunE:    rm,
    24  		Example: `podman volume rm myvol1 myvol2
    25    podman volume rm --all
    26    podman volume rm --force myvol`,
    27  	}
    28  )
    29  
    30  var (
    31  	rmOptions = entities.VolumeRmOptions{}
    32  )
    33  
    34  func init() {
    35  	registry.Commands = append(registry.Commands, registry.CliCommand{
    36  		Mode:    []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
    37  		Command: rmCommand,
    38  		Parent:  volumeCmd,
    39  	})
    40  	flags := rmCommand.Flags()
    41  	flags.BoolVarP(&rmOptions.All, "all", "a", false, "Remove all volumes")
    42  	flags.BoolVarP(&rmOptions.Force, "force", "f", false, "Remove a volume by force, even if it is being used by a container")
    43  }
    44  
    45  func rm(cmd *cobra.Command, args []string) error {
    46  	var (
    47  		errs utils.OutputErrors
    48  	)
    49  	if (len(args) > 0 && rmOptions.All) || (len(args) < 1 && !rmOptions.All) {
    50  		return errors.New("choose either one or more volumes or all")
    51  	}
    52  	responses, err := registry.ContainerEngine().VolumeRm(context.Background(), args, rmOptions)
    53  	if err != nil {
    54  		return err
    55  	}
    56  	for _, r := range responses {
    57  		if r.Err == nil {
    58  			fmt.Println(r.Id)
    59  		} else {
    60  			errs = append(errs, r.Err)
    61  		}
    62  	}
    63  	return errs.PrintErrors()
    64  }