github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/network/disconnect.go (about)

     1  package network
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/docker/cli/cli"
     7  	"github.com/docker/cli/cli/command"
     8  	"github.com/docker/cli/cli/command/completion"
     9  	"github.com/docker/docker/api/types"
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  type disconnectOptions struct {
    14  	network   string
    15  	container string
    16  	force     bool
    17  }
    18  
    19  func newDisconnectCommand(dockerCli command.Cli) *cobra.Command {
    20  	opts := disconnectOptions{}
    21  
    22  	cmd := &cobra.Command{
    23  		Use:   "disconnect [OPTIONS] NETWORK CONTAINER",
    24  		Short: "Disconnect a container from a network",
    25  		Args:  cli.ExactArgs(2),
    26  		RunE: func(cmd *cobra.Command, args []string) error {
    27  			opts.network = args[0]
    28  			opts.container = args[1]
    29  			return runDisconnect(cmd.Context(), dockerCli, opts)
    30  		},
    31  		ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
    32  			if len(args) == 0 {
    33  				return completion.NetworkNames(dockerCli)(cmd, args, toComplete)
    34  			}
    35  			network := args[0]
    36  			return completion.ContainerNames(dockerCli, true, isConnected(network))(cmd, args, toComplete)
    37  		},
    38  	}
    39  
    40  	flags := cmd.Flags()
    41  	flags.BoolVarP(&opts.force, "force", "f", false, "Force the container to disconnect from a network")
    42  
    43  	return cmd
    44  }
    45  
    46  func runDisconnect(ctx context.Context, dockerCli command.Cli, opts disconnectOptions) error {
    47  	client := dockerCli.Client()
    48  
    49  	return client.NetworkDisconnect(ctx, opts.network, opts.container, opts.force)
    50  }
    51  
    52  func isConnected(network string) func(types.Container) bool {
    53  	return func(container types.Container) bool {
    54  		if container.NetworkSettings == nil {
    55  			return false
    56  		}
    57  		_, ok := container.NetworkSettings.Networks[network]
    58  		return ok
    59  	}
    60  }
    61  
    62  func not(fn func(types.Container) bool) func(types.Container) bool {
    63  	return func(container types.Container) bool {
    64  		ok := fn(container)
    65  		return !ok
    66  	}
    67  }