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

     1  package main
     2  
     3  import (
     4  	"github.com/containers/libpod/cmd/podman/cliconfig"
     5  	"github.com/containers/libpod/pkg/adapter"
     6  	"github.com/pkg/errors"
     7  	"github.com/spf13/cobra"
     8  )
     9  
    10  var (
    11  	volumeRmCommand     cliconfig.VolumeRmValues
    12  	volumeRmDescription = `Remove one or more existing volumes.
    13  
    14    By default only volumes that are not being used by any containers will be removed. To remove the volumes anyways, use the --force flag.`
    15  	_volumeRmCommand = &cobra.Command{
    16  		Use:     "rm [flags] VOLUME [VOLUME...]",
    17  		Aliases: []string{"remove"},
    18  		Short:   "Remove one or more volumes",
    19  		Long:    volumeRmDescription,
    20  		RunE: func(cmd *cobra.Command, args []string) error {
    21  			volumeRmCommand.InputArgs = args
    22  			volumeRmCommand.GlobalFlags = MainGlobalOpts
    23  			volumeRmCommand.Remote = remoteclient
    24  			return volumeRmCmd(&volumeRmCommand)
    25  		},
    26  		Example: `podman volume rm myvol1 myvol2
    27    podman volume rm --all
    28    podman volume rm --force myvol`,
    29  	}
    30  )
    31  
    32  func init() {
    33  	volumeRmCommand.Command = _volumeRmCommand
    34  	volumeRmCommand.SetHelpTemplate(HelpTemplate())
    35  	volumeRmCommand.SetUsageTemplate(UsageTemplate())
    36  	flags := volumeRmCommand.Flags()
    37  	flags.BoolVarP(&volumeRmCommand.All, "all", "a", false, "Remove all volumes")
    38  	flags.BoolVarP(&volumeRmCommand.Force, "force", "f", false, "Remove a volume by force, even if it is being used by a container")
    39  }
    40  
    41  func volumeRmCmd(c *cliconfig.VolumeRmValues) error {
    42  	var err error
    43  
    44  	if (len(c.InputArgs) > 0 && c.All) || (len(c.InputArgs) < 1 && !c.All) {
    45  		return errors.New("choose either one or more volumes or all")
    46  	}
    47  
    48  	runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand)
    49  	if err != nil {
    50  		return errors.Wrapf(err, "error creating libpod runtime")
    51  	}
    52  	defer runtime.DeferredShutdown(false)
    53  	deletedVolumeNames, deletedVolumeErrors, err := runtime.RemoveVolumes(getContext(), c)
    54  	if err != nil {
    55  		return err
    56  	}
    57  	return printCmdResults(deletedVolumeNames, deletedVolumeErrors)
    58  }