prune.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package image
  2. import (
  3. "fmt"
  4. "golang.org/x/net/context"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/cli"
  7. "github.com/docker/docker/cli/command"
  8. units "github.com/docker/go-units"
  9. "github.com/spf13/cobra"
  10. )
  11. type pruneOptions struct {
  12. force bool
  13. all bool
  14. }
  15. // NewPruneCommand returns a new cobra prune command for images
  16. func NewPruneCommand(dockerCli *command.DockerCli) *cobra.Command {
  17. var opts pruneOptions
  18. cmd := &cobra.Command{
  19. Use: "prune [OPTIONS]",
  20. Short: "Remove unused images",
  21. Args: cli.NoArgs,
  22. RunE: func(cmd *cobra.Command, args []string) error {
  23. spaceReclaimed, output, err := runPrune(dockerCli, opts)
  24. if err != nil {
  25. return err
  26. }
  27. if output != "" {
  28. fmt.Fprintln(dockerCli.Out(), output)
  29. }
  30. fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
  31. return nil
  32. },
  33. Tags: map[string]string{"version": "1.25"},
  34. }
  35. flags := cmd.Flags()
  36. flags.BoolVarP(&opts.force, "force", "f", false, "Do not prompt for confirmation")
  37. flags.BoolVarP(&opts.all, "all", "a", false, "Remove all unused images, not just dangling ones")
  38. return cmd
  39. }
  40. const (
  41. allImageWarning = `WARNING! This will remove all images without at least one container associated to them.
  42. Are you sure you want to continue?`
  43. danglingWarning = `WARNING! This will remove all dangling images.
  44. Are you sure you want to continue?`
  45. )
  46. func runPrune(dockerCli *command.DockerCli, opts pruneOptions) (spaceReclaimed uint64, output string, err error) {
  47. warning := danglingWarning
  48. if opts.all {
  49. warning = allImageWarning
  50. }
  51. if !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
  52. return
  53. }
  54. report, err := dockerCli.Client().ImagesPrune(context.Background(), types.ImagesPruneConfig{
  55. DanglingOnly: !opts.all,
  56. })
  57. if err != nil {
  58. return
  59. }
  60. if len(report.ImagesDeleted) > 0 {
  61. output = "Deleted Images:\n"
  62. for _, st := range report.ImagesDeleted {
  63. if st.Untagged != "" {
  64. output += fmt.Sprintln("untagged:", st.Untagged)
  65. } else {
  66. output += fmt.Sprintln("deleted:", st.Deleted)
  67. }
  68. }
  69. spaceReclaimed = report.SpaceReclaimed
  70. }
  71. return
  72. }
  73. // RunPrune calls the Image Prune API
  74. // This returns the amount of space reclaimed and a detailed output string
  75. func RunPrune(dockerCli *command.DockerCli, all bool) (uint64, string, error) {
  76. return runPrune(dockerCli, pruneOptions{force: true, all: all})
  77. }