prune.go 2.2 KB

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