github.com/olljanat/moby@v1.13.1/cli/command/volume/prune.go (about)

     1  package volume
     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  	units "github.com/docker/go-units"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type pruneOptions struct {
    16  	force bool
    17  }
    18  
    19  // NewPruneCommand returns a new cobra prune command for volumes
    20  func NewPruneCommand(dockerCli *command.DockerCli) *cobra.Command {
    21  	var opts pruneOptions
    22  
    23  	cmd := &cobra.Command{
    24  		Use:   "prune [OPTIONS]",
    25  		Short: "Remove all unused volumes",
    26  		Args:  cli.NoArgs,
    27  		RunE: func(cmd *cobra.Command, args []string) error {
    28  			spaceReclaimed, output, err := runPrune(dockerCli, opts)
    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  		Tags: map[string]string{"version": "1.25"},
    39  	}
    40  
    41  	flags := cmd.Flags()
    42  	flags.BoolVarP(&opts.force, "force", "f", false, "Do not prompt for confirmation")
    43  
    44  	return cmd
    45  }
    46  
    47  const warning = `WARNING! This will remove all volumes not used by at least one container.
    48  Are you sure you want to continue?`
    49  
    50  func runPrune(dockerCli *command.DockerCli, opts pruneOptions) (spaceReclaimed uint64, output string, err error) {
    51  	if !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
    52  		return
    53  	}
    54  
    55  	report, err := dockerCli.Client().VolumesPrune(context.Background(), filters.Args{})
    56  	if err != nil {
    57  		return
    58  	}
    59  
    60  	if len(report.VolumesDeleted) > 0 {
    61  		output = "Deleted Volumes:\n"
    62  		for _, id := range report.VolumesDeleted {
    63  			output += id + "\n"
    64  		}
    65  		spaceReclaimed = report.SpaceReclaimed
    66  	}
    67  
    68  	return
    69  }
    70  
    71  // RunPrune calls the Volume Prune API
    72  // This returns the amount of space reclaimed and a detailed output string
    73  func RunPrune(dockerCli *command.DockerCli) (uint64, string, error) {
    74  	return runPrune(dockerCli, pruneOptions{force: true})
    75  }