github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/volume_prune.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "fmt" 21 "strings" 22 23 "github.com/containerd/nerdctl/pkg/api/types" 24 "github.com/containerd/nerdctl/pkg/clientutil" 25 "github.com/containerd/nerdctl/pkg/cmd/volume" 26 "github.com/spf13/cobra" 27 ) 28 29 func newVolumePruneCommand() *cobra.Command { 30 volumePruneCommand := &cobra.Command{ 31 Use: "prune [flags]", 32 Short: "Remove all unused local volumes", 33 Args: cobra.NoArgs, 34 RunE: volumePruneAction, 35 SilenceUsage: true, 36 SilenceErrors: true, 37 } 38 volumePruneCommand.Flags().BoolP("all", "a", false, "Remove all unused volumes, not just anonymous ones") 39 volumePruneCommand.Flags().BoolP("force", "f", false, "Do not prompt for confirmation") 40 return volumePruneCommand 41 } 42 43 func processVolumePruneOptions(cmd *cobra.Command) (types.VolumePruneOptions, error) { 44 globalOptions, err := processRootCmdFlags(cmd) 45 if err != nil { 46 return types.VolumePruneOptions{}, err 47 } 48 49 all, err := cmd.Flags().GetBool("all") 50 if err != nil { 51 return types.VolumePruneOptions{}, err 52 } 53 54 force, err := cmd.Flags().GetBool("force") 55 if err != nil { 56 return types.VolumePruneOptions{}, err 57 } 58 59 options := types.VolumePruneOptions{ 60 GOptions: globalOptions, 61 All: all, 62 Force: force, 63 Stdout: cmd.OutOrStdout(), 64 } 65 return options, nil 66 } 67 68 func volumePruneAction(cmd *cobra.Command, _ []string) error { 69 options, err := processVolumePruneOptions(cmd) 70 if err != nil { 71 return err 72 } 73 74 if !options.Force { 75 var confirm string 76 msg := "This will remove all local volumes not used by at least one container." 77 msg += "\nAre you sure you want to continue? [y/N] " 78 fmt.Fprintf(options.Stdout, "WARNING! %s", msg) 79 fmt.Fscanf(cmd.InOrStdin(), "%s", &confirm) 80 81 if strings.ToLower(confirm) != "y" { 82 return nil 83 } 84 } 85 86 client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), options.GOptions.Namespace, options.GOptions.Address) 87 if err != nil { 88 return err 89 } 90 defer cancel() 91 92 return volume.Prune(ctx, client, options) 93 }