github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/cmd/podman/volume_prune.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "context" 6 "fmt" 7 "os" 8 "strings" 9 10 "github.com/containers/libpod/cmd/podman/cliconfig" 11 "github.com/containers/libpod/pkg/adapter" 12 "github.com/pkg/errors" 13 "github.com/sirupsen/logrus" 14 "github.com/spf13/cobra" 15 ) 16 17 var ( 18 volumePruneCommand cliconfig.VolumePruneValues 19 volumePruneDescription = `Volumes that are not currently owned by a container will be removed. 20 21 The command prompts for confirmation which can be overridden with the --force flag. 22 Note all data will be destroyed.` 23 _volumePruneCommand = &cobra.Command{ 24 Use: "prune", 25 Args: noSubArgs, 26 Short: "Remove all unused volumes", 27 Long: volumePruneDescription, 28 RunE: func(cmd *cobra.Command, args []string) error { 29 volumePruneCommand.InputArgs = args 30 volumePruneCommand.GlobalFlags = MainGlobalOpts 31 volumePruneCommand.Remote = remoteclient 32 return volumePruneCmd(&volumePruneCommand) 33 }, 34 } 35 ) 36 37 func init() { 38 volumePruneCommand.Command = _volumePruneCommand 39 volumePruneCommand.SetHelpTemplate(HelpTemplate()) 40 volumePruneCommand.SetUsageTemplate(UsageTemplate()) 41 flags := volumePruneCommand.Flags() 42 43 flags.BoolVarP(&volumePruneCommand.Force, "force", "f", false, "Do not prompt for confirmation") 44 } 45 46 func volumePrune(runtime *adapter.LocalRuntime, ctx context.Context) error { 47 prunedNames, prunedErrors := runtime.PruneVolumes(ctx) 48 for _, name := range prunedNames { 49 fmt.Println(name) 50 } 51 if len(prunedErrors) == 0 { 52 return nil 53 } 54 // Grab the last error 55 lastError := prunedErrors[len(prunedErrors)-1] 56 // Remove the last error from the error slice 57 prunedErrors = prunedErrors[:len(prunedErrors)-1] 58 59 for _, err := range prunedErrors { 60 logrus.Errorf("%q", err) 61 } 62 return lastError 63 } 64 65 func volumePruneCmd(c *cliconfig.VolumePruneValues) error { 66 runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand) 67 if err != nil { 68 return errors.Wrapf(err, "error creating libpod runtime") 69 } 70 defer runtime.DeferredShutdown(false) 71 72 // Prompt for confirmation if --force is not set 73 if !c.Force { 74 reader := bufio.NewReader(os.Stdin) 75 fmt.Println("WARNING! This will remove all volumes not used by at least one container.") 76 fmt.Print("Are you sure you want to continue? [y/N] ") 77 answer, err := reader.ReadString('\n') 78 if err != nil { 79 return errors.Wrapf(err, "error reading input") 80 } 81 if strings.ToLower(answer)[0] != 'y' { 82 return nil 83 } 84 } 85 return volumePrune(runtime, getContext()) 86 }