github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/compose_down.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  	"github.com/containerd/nerdctl/pkg/clientutil"
    21  	"github.com/containerd/nerdctl/pkg/cmd/compose"
    22  	"github.com/containerd/nerdctl/pkg/composer"
    23  	"github.com/spf13/cobra"
    24  )
    25  
    26  func newComposeDownCommand() *cobra.Command {
    27  	var composeDownCommand = &cobra.Command{
    28  		Use:           "down",
    29  		Short:         "Remove containers and associated resources",
    30  		Args:          cobra.NoArgs,
    31  		RunE:          composeDownAction,
    32  		SilenceUsage:  true,
    33  		SilenceErrors: true,
    34  	}
    35  	composeDownCommand.Flags().BoolP("volumes", "v", false, "Remove named volumes declared in the `volumes` section of the Compose file and anonymous volumes attached to containers.")
    36  	composeDownCommand.Flags().Bool("remove-orphans", false, "Remove containers for services not defined in the Compose file.")
    37  	return composeDownCommand
    38  }
    39  
    40  func composeDownAction(cmd *cobra.Command, args []string) error {
    41  	globalOptions, err := processRootCmdFlags(cmd)
    42  	if err != nil {
    43  		return err
    44  	}
    45  	volumes, err := cmd.Flags().GetBool("volumes")
    46  	if err != nil {
    47  		return err
    48  	}
    49  	client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), globalOptions.Namespace, globalOptions.Address)
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	removeOrphans, err := cmd.Flags().GetBool("remove-orphans")
    55  	if err != nil {
    56  		return err
    57  	}
    58  	defer cancel()
    59  	options, err := getComposeOptions(cmd, globalOptions.DebugFull, globalOptions.Experimental)
    60  	if err != nil {
    61  		return err
    62  	}
    63  	c, err := compose.New(client, globalOptions, options, cmd.OutOrStdout(), cmd.ErrOrStderr())
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	downOpts := composer.DownOptions{
    69  		RemoveVolumes: volumes,
    70  		RemoveOrphans: removeOrphans,
    71  	}
    72  	return c.Down(ctx, downOpts)
    73  }