github.com/ph/moby@v1.13.1/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 prune` 19 func NewPruneCommand(dockerCli *command.DockerCli) *cobra.Command { 20 var opts pruneOptions 21 22 cmd := &cobra.Command{ 23 Use: "prune [OPTIONS]", 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 Tags: map[string]string{"version": "1.25"}, 30 } 31 32 flags := cmd.Flags() 33 flags.BoolVarP(&opts.force, "force", "f", false, "Do not prompt for confirmation") 34 flags.BoolVarP(&opts.all, "all", "a", false, "Remove all unused images not just dangling ones") 35 36 return cmd 37 } 38 39 const ( 40 warning = `WARNING! This will remove: 41 - all stopped containers 42 - all volumes not used by at least one container 43 - all networks not used by at least one container 44 %s 45 Are you sure you want to continue?` 46 47 danglingImageDesc = "- all dangling images" 48 allImageDesc = `- all images without at least one container associated to them` 49 ) 50 51 func runPrune(dockerCli *command.DockerCli, opts pruneOptions) error { 52 var message string 53 54 if opts.all { 55 message = fmt.Sprintf(warning, allImageDesc) 56 } else { 57 message = fmt.Sprintf(warning, danglingImageDesc) 58 } 59 60 if !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), message) { 61 return nil 62 } 63 64 var spaceReclaimed uint64 65 66 for _, pruneFn := range []func(dockerCli *command.DockerCli) (uint64, string, error){ 67 prune.RunContainerPrune, 68 prune.RunVolumePrune, 69 prune.RunNetworkPrune, 70 } { 71 spc, output, err := pruneFn(dockerCli) 72 if err != nil { 73 return err 74 } 75 spaceReclaimed += spc 76 if output != "" { 77 fmt.Fprintln(dockerCli.Out(), output) 78 } 79 } 80 81 spc, output, err := prune.RunImagePrune(dockerCli, opts.all) 82 if err != nil { 83 return err 84 } 85 if spc > 0 { 86 spaceReclaimed += spc 87 fmt.Fprintln(dockerCli.Out(), output) 88 } 89 90 fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed))) 91 92 return nil 93 }