remove.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package image
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. "github.com/spf13/cobra"
  10. )
  11. type removeOptions struct {
  12. force bool
  13. noPrune bool
  14. }
  15. // NewRemoveCommand creates a new `docker remove` command
  16. func NewRemoveCommand(dockerCli *command.DockerCli) *cobra.Command {
  17. var opts removeOptions
  18. cmd := &cobra.Command{
  19. Use: "rmi [OPTIONS] IMAGE [IMAGE...]",
  20. Short: "Remove one or more images",
  21. Args: cli.RequiresMinArgs(1),
  22. RunE: func(cmd *cobra.Command, args []string) error {
  23. return runRemove(dockerCli, opts, args)
  24. },
  25. }
  26. flags := cmd.Flags()
  27. flags.BoolVarP(&opts.force, "force", "f", false, "Force removal of the image")
  28. flags.BoolVar(&opts.noPrune, "no-prune", false, "Do not delete untagged parents")
  29. return cmd
  30. }
  31. func newRemoveCommand(dockerCli *command.DockerCli) *cobra.Command {
  32. cmd := *NewRemoveCommand(dockerCli)
  33. cmd.Aliases = []string{"rmi", "remove"}
  34. cmd.Use = "rm [OPTIONS] IMAGE [IMAGE...]"
  35. return &cmd
  36. }
  37. func runRemove(dockerCli *command.DockerCli, opts removeOptions, images []string) error {
  38. client := dockerCli.Client()
  39. ctx := context.Background()
  40. options := types.ImageRemoveOptions{
  41. Force: opts.force,
  42. PruneChildren: !opts.noPrune,
  43. }
  44. var errs []string
  45. for _, image := range images {
  46. dels, err := client.ImageRemove(ctx, image, options)
  47. if err != nil {
  48. errs = append(errs, err.Error())
  49. } else {
  50. for _, del := range dels {
  51. if del.Deleted != "" {
  52. fmt.Fprintf(dockerCli.Out(), "Deleted: %s\n", del.Deleted)
  53. } else {
  54. fmt.Fprintf(dockerCli.Out(), "Untagged: %s\n", del.Untagged)
  55. }
  56. }
  57. }
  58. }
  59. if len(errs) > 0 {
  60. return fmt.Errorf("%s", strings.Join(errs, "\n"))
  61. }
  62. return nil
  63. }