github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/cli/command/system/prune.go (about)

     1  package system
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/docker/docker/cli"
     7  	"github.com/docker/docker/cli/command"
     8  	"github.com/docker/docker/cli/command/prune"
     9  	units "github.com/docker/go-units"
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  type pruneOptions struct {
    14  	force bool
    15  	all   bool
    16  }
    17  
    18  // NewPruneCommand creates a new cobra.Command for `docker du`
    19  func NewPruneCommand(dockerCli *command.DockerCli) *cobra.Command {
    20  	var opts pruneOptions
    21  
    22  	cmd := &cobra.Command{
    23  		Use:   "prune [COMMAND]",
    24  		Short: "Remove unused data.",
    25  		Args:  cli.NoArgs,
    26  		RunE: func(cmd *cobra.Command, args []string) error {
    27  			return runPrune(dockerCli, opts)
    28  		},
    29  	}
    30  
    31  	flags := cmd.Flags()
    32  	flags.BoolVarP(&opts.force, "force", "f", false, "Do not prompt for confirmation")
    33  	flags.BoolVarP(&opts.all, "all", "a", false, "Remove all unused images not just dangling ones")
    34  
    35  	return cmd
    36  }
    37  
    38  const (
    39  	warning = `WARNING! This will remove:
    40  	- all stopped containers
    41  	- all volumes not used by at least one container
    42  	%s
    43  Are you sure you want to continue?`
    44  
    45  	danglingImageDesc = "- all dangling images"
    46  	allImageDesc      = `- all images without at least one container associated to them`
    47  )
    48  
    49  func runPrune(dockerCli *command.DockerCli, opts pruneOptions) error {
    50  	var message string
    51  
    52  	if opts.all {
    53  		message = fmt.Sprintf(warning, allImageDesc)
    54  	} else {
    55  		message = fmt.Sprintf(warning, danglingImageDesc)
    56  	}
    57  
    58  	if !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), message) {
    59  		return nil
    60  	}
    61  
    62  	var spaceReclaimed uint64
    63  
    64  	for _, pruneFn := range []func(dockerCli *command.DockerCli) (uint64, string, error){
    65  		prune.RunContainerPrune,
    66  		prune.RunVolumePrune,
    67  	} {
    68  		spc, output, err := pruneFn(dockerCli)
    69  		if err != nil {
    70  			return err
    71  		}
    72  		if spc > 0 {
    73  			spaceReclaimed += spc
    74  			fmt.Fprintln(dockerCli.Out(), output)
    75  		}
    76  	}
    77  
    78  	spc, output, err := prune.RunImagePrune(dockerCli, opts.all)
    79  	if err != nil {
    80  		return err
    81  	}
    82  	if spc > 0 {
    83  		spaceReclaimed += spc
    84  		fmt.Fprintln(dockerCli.Out(), output)
    85  	}
    86  
    87  	fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
    88  
    89  	return nil
    90  }