github.1git.de/docker/cli@v26.1.3+incompatible/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/docker/docker/errdefs" 11 "github.com/pkg/errors" 12 "github.com/spf13/cobra" 13 ) 14 15 type pruneOptions struct { 16 force bool 17 filter opts.FilterOpt 18 } 19 20 // NewPruneCommand returns a new cobra prune command for networks 21 func NewPruneCommand(dockerCli command.Cli) *cobra.Command { 22 options := pruneOptions{filter: opts.NewFilterOpt()} 23 24 cmd := &cobra.Command{ 25 Use: "prune [OPTIONS]", 26 Short: "Remove all unused networks", 27 Args: cli.NoArgs, 28 RunE: func(cmd *cobra.Command, args []string) error { 29 output, err := runPrune(cmd.Context(), dockerCli, options) 30 if err != nil { 31 return err 32 } 33 if output != "" { 34 fmt.Fprintln(dockerCli.Out(), output) 35 } 36 return nil 37 }, 38 Annotations: map[string]string{"version": "1.25"}, 39 } 40 41 flags := cmd.Flags() 42 flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation") 43 flags.Var(&options.filter, "filter", `Provide filter values (e.g. "until=<timestamp>")`) 44 45 return cmd 46 } 47 48 const warning = `WARNING! This will remove all custom networks not used by at least one container. 49 Are you sure you want to continue?` 50 51 func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (output string, err error) { 52 pruneFilters := command.PruneFilters(dockerCli, options.filter.Value()) 53 54 if !options.force { 55 r, err := command.PromptForConfirmation(ctx, dockerCli.In(), dockerCli.Out(), warning) 56 if err != nil { 57 return "", err 58 } 59 if !r { 60 return "", errdefs.Cancelled(errors.New("network prune cancelled has been cancelled")) 61 } 62 } 63 64 report, err := dockerCli.Client().NetworksPrune(ctx, pruneFilters) 65 if err != nil { 66 return "", err 67 } 68 69 if len(report.NetworksDeleted) > 0 { 70 output = "Deleted Networks:\n" 71 for _, id := range report.NetworksDeleted { 72 output += id + "\n" 73 } 74 } 75 76 return output, nil 77 } 78 79 // RunPrune calls the Network Prune API 80 // This returns the amount of space reclaimed and a detailed output string 81 func RunPrune(ctx context.Context, dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { 82 output, err := runPrune(ctx, dockerCli, pruneOptions{force: true, filter: filter}) 83 return 0, output, err 84 }