github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/container_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/container" 26 "github.com/spf13/cobra" 27 ) 28 29 func newContainerPruneCommand() *cobra.Command { 30 containerPruneCommand := &cobra.Command{ 31 Use: "prune [flags]", 32 Short: "Remove all stopped containers", 33 Args: cobra.NoArgs, 34 RunE: containerPruneAction, 35 SilenceUsage: true, 36 SilenceErrors: true, 37 } 38 containerPruneCommand.Flags().BoolP("force", "f", false, "Do not prompt for confirmation") 39 return containerPruneCommand 40 } 41 42 func processContainerPruneOptions(cmd *cobra.Command) (types.ContainerPruneOptions, error) { 43 globalOptions, err := processRootCmdFlags(cmd) 44 if err != nil { 45 return types.ContainerPruneOptions{}, err 46 } 47 48 return types.ContainerPruneOptions{ 49 GOptions: globalOptions, 50 Stdout: cmd.OutOrStdout(), 51 }, nil 52 } 53 54 func grantPrunePermission(cmd *cobra.Command) (bool, error) { 55 force, err := cmd.Flags().GetBool("force") 56 if err != nil { 57 return false, err 58 } 59 60 if !force { 61 var confirm string 62 msg := "This will remove all stopped containers." 63 msg += "\nAre you sure you want to continue? [y/N] " 64 fmt.Fprintf(cmd.OutOrStdout(), "WARNING! %s", msg) 65 fmt.Fscanf(cmd.InOrStdin(), "%s", &confirm) 66 67 if strings.ToLower(confirm) != "y" { 68 return false, nil 69 } 70 } 71 return true, nil 72 } 73 74 func containerPruneAction(cmd *cobra.Command, _ []string) error { 75 options, err := processContainerPruneOptions(cmd) 76 if err != nil { 77 return err 78 } 79 80 if ok, err := grantPrunePermission(cmd); err != nil { 81 return err 82 } else if !ok { 83 return nil 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 container.Prune(ctx, client, options) 93 }