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

     1  package container
     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  	units "github.com/docker/go-units"
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  type pruneOptions struct {
    15  	force  bool
    16  	filter opts.FilterOpt
    17  }
    18  
    19  // NewPruneCommand returns a new cobra prune command for containers
    20  func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
    21  	options := pruneOptions{filter: opts.NewFilterOpt()}
    22  
    23  	cmd := &cobra.Command{
    24  		Use:   "prune [OPTIONS]",
    25  		Short: "Remove all stopped containers",
    26  		Args:  cli.NoArgs,
    27  		RunE: func(cmd *cobra.Command, args []string) error {
    28  			spaceReclaimed, output, err := runPrune(dockerCli, options)
    29  			if err != nil {
    30  				return err
    31  			}
    32  			if output != "" {
    33  				fmt.Fprintln(dockerCli.Out(), output)
    34  			}
    35  			fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
    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 stopped containers.
    49  Are you sure you want to continue?`
    50  
    51  func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) {
    52  	pruneFilters := command.PruneFilters(dockerCli, options.filter.Value())
    53  
    54  	if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
    55  		return 0, "", nil
    56  	}
    57  
    58  	report, err := dockerCli.Client().ContainersPrune(context.Background(), pruneFilters)
    59  	if err != nil {
    60  		return 0, "", err
    61  	}
    62  
    63  	if len(report.ContainersDeleted) > 0 {
    64  		output = "Deleted Containers:\n"
    65  		for _, id := range report.ContainersDeleted {
    66  			output += id + "\n"
    67  		}
    68  		spaceReclaimed = report.SpaceReclaimed
    69  	}
    70  
    71  	return spaceReclaimed, output, nil
    72  }
    73  
    74  // RunPrune calls the Container Prune API
    75  // This returns the amount of space reclaimed and a detailed output string
    76  func RunPrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) {
    77  	return runPrune(dockerCli, pruneOptions{force: true, filter: filter})
    78  }