github.com/kunnos/engine@v1.13.1/cli/command/network/prune.go (about)

     1  package network
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"golang.org/x/net/context"
     7  
     8  	"github.com/docker/docker/api/types/filters"
     9  	"github.com/docker/docker/cli"
    10  	"github.com/docker/docker/cli/command"
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  type pruneOptions struct {
    15  	force bool
    16  }
    17  
    18  // NewPruneCommand returns a new cobra prune command for networks
    19  func NewPruneCommand(dockerCli *command.DockerCli) *cobra.Command {
    20  	var opts pruneOptions
    21  
    22  	cmd := &cobra.Command{
    23  		Use:   "prune [OPTIONS]",
    24  		Short: "Remove all unused networks",
    25  		Args:  cli.NoArgs,
    26  		RunE: func(cmd *cobra.Command, args []string) error {
    27  			output, err := runPrune(dockerCli, opts)
    28  			if err != nil {
    29  				return err
    30  			}
    31  			if output != "" {
    32  				fmt.Fprintln(dockerCli.Out(), output)
    33  			}
    34  			return nil
    35  		},
    36  		Tags: map[string]string{"version": "1.25"},
    37  	}
    38  
    39  	flags := cmd.Flags()
    40  	flags.BoolVarP(&opts.force, "force", "f", false, "Do not prompt for confirmation")
    41  
    42  	return cmd
    43  }
    44  
    45  const warning = `WARNING! This will remove all networks not used by at least one container.
    46  Are you sure you want to continue?`
    47  
    48  func runPrune(dockerCli *command.DockerCli, opts pruneOptions) (output string, err error) {
    49  	if !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
    50  		return
    51  	}
    52  
    53  	report, err := dockerCli.Client().NetworksPrune(context.Background(), filters.Args{})
    54  	if err != nil {
    55  		return
    56  	}
    57  
    58  	if len(report.NetworksDeleted) > 0 {
    59  		output = "Deleted Networks:\n"
    60  		for _, id := range report.NetworksDeleted {
    61  			output += id + "\n"
    62  		}
    63  	}
    64  
    65  	return
    66  }
    67  
    68  // RunPrune calls the Network Prune API
    69  // This returns the amount of space reclaimed and a detailed output string
    70  func RunPrune(dockerCli *command.DockerCli) (uint64, string, error) {
    71  	output, err := runPrune(dockerCli, pruneOptions{force: true})
    72  	return 0, output, err
    73  }