github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/compose_rm.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/clientutil" 24 "github.com/containerd/nerdctl/pkg/cmd/compose" 25 "github.com/containerd/nerdctl/pkg/composer" 26 "github.com/spf13/cobra" 27 ) 28 29 func newComposeRemoveCommand() *cobra.Command { 30 var composeRemoveCommand = &cobra.Command{ 31 Use: "rm [flags] [SERVICE...]", 32 Short: "Remove stopped service containers", 33 RunE: composeRemoveAction, 34 SilenceUsage: true, 35 SilenceErrors: true, 36 } 37 composeRemoveCommand.Flags().BoolP("force", "f", false, "Do not prompt for confirmation") 38 composeRemoveCommand.Flags().BoolP("stop", "s", false, "Stop containers before removing") 39 composeRemoveCommand.Flags().BoolP("volumes", "v", false, "Remove anonymous volumes associated with containers") 40 return composeRemoveCommand 41 } 42 43 func composeRemoveAction(cmd *cobra.Command, args []string) error { 44 globalOptions, err := processRootCmdFlags(cmd) 45 if err != nil { 46 return err 47 } 48 force, err := cmd.Flags().GetBool("force") 49 if err != nil { 50 return err 51 } 52 if !force { 53 var confirm string 54 services := "all" 55 if len(args) != 0 { 56 services = strings.Join(args, ",") 57 } 58 msg := fmt.Sprintf("This will remove all stopped containers from services: %s.", services) 59 msg += "\nAre you sure you want to continue? [y/N] " 60 fmt.Fprintf(cmd.OutOrStdout(), "WARNING! %s", msg) 61 fmt.Fscanf(cmd.InOrStdin(), "%s", &confirm) 62 63 if strings.ToLower(confirm) != "y" { 64 return nil 65 } 66 } 67 68 stop, err := cmd.Flags().GetBool("stop") 69 if err != nil { 70 return err 71 } 72 volumes, err := cmd.Flags().GetBool("volumes") 73 if err != nil { 74 return err 75 } 76 77 client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), globalOptions.Namespace, globalOptions.Address) 78 if err != nil { 79 return err 80 } 81 defer cancel() 82 options, err := getComposeOptions(cmd, globalOptions.DebugFull, globalOptions.Experimental) 83 if err != nil { 84 return err 85 } 86 c, err := compose.New(client, globalOptions, options, cmd.OutOrStdout(), cmd.ErrOrStderr()) 87 if err != nil { 88 return err 89 } 90 91 rmOpts := composer.RemoveOptions{ 92 Stop: stop, 93 Volumes: volumes, 94 } 95 return c.Remove(ctx, rmOpts, args) 96 }