github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/cli/command/network/prune.go (about)

     1  package network
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/docker/cli/cli"
     8  	"github.com/docker/cli/cli/command"
     9  	"github.com/docker/cli/opts"
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  type pruneOptions struct {
    14  	force  bool
    15  	filter opts.FilterOpt
    16  }
    17  
    18  // NewPruneCommand returns a new cobra prune command for networks
    19  func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
    20  	options := pruneOptions{filter: opts.NewFilterOpt()}
    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, options)
    28  			if err != nil {
    29  				return err
    30  			}
    31  			if output != "" {
    32  				fmt.Fprintln(dockerCli.Out(), output)
    33  			}
    34  			return nil
    35  		},
    36  		Annotations: map[string]string{"version": "1.25"},
    37  	}
    38  
    39  	flags := cmd.Flags()
    40  	flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation")
    41  	flags.Var(&options.filter, "filter", "Provide filter values (e.g. 'until=<timestamp>')")
    42  
    43  	return cmd
    44  }
    45  
    46  const warning = `WARNING! This will remove all custom networks not used by at least one container.
    47  Are you sure you want to continue?`
    48  
    49  func runPrune(dockerCli command.Cli, options pruneOptions) (output string, err error) {
    50  	pruneFilters := command.PruneFilters(dockerCli, options.filter.Value())
    51  
    52  	if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
    53  		return "", nil
    54  	}
    55  
    56  	report, err := dockerCli.Client().NetworksPrune(context.Background(), pruneFilters)
    57  	if err != nil {
    58  		return "", err
    59  	}
    60  
    61  	if len(report.NetworksDeleted) > 0 {
    62  		output = "Deleted Networks:\n"
    63  		for _, id := range report.NetworksDeleted {
    64  			output += id + "\n"
    65  		}
    66  	}
    67  
    68  	return output, nil
    69  }
    70  
    71  // RunPrune calls the Network Prune API
    72  // This returns the amount of space reclaimed and a detailed output string
    73  func RunPrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) {
    74  	output, err := runPrune(dockerCli, pruneOptions{force: true, filter: filter})
    75  	return 0, output, err
    76  }