remove.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package image
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/client"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/engine-api/types"
  9. "github.com/spf13/cobra"
  10. )
  11. type removeOptions struct {
  12. force bool
  13. noPrune bool
  14. }
  15. // NewRemoveCommand create a new `docker remove` command
  16. func NewRemoveCommand(dockerCli *client.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 runRemove(dockerCli *client.DockerCli, opts removeOptions, images []string) error {
  32. client := dockerCli.Client()
  33. ctx := context.Background()
  34. options := types.ImageRemoveOptions{
  35. Force: opts.force,
  36. PruneChildren: !opts.noPrune,
  37. }
  38. var errs []string
  39. for _, image := range images {
  40. dels, err := client.ImageRemove(ctx, image, options)
  41. if err != nil {
  42. errs = append(errs, err.Error())
  43. } else {
  44. for _, del := range dels {
  45. if del.Deleted != "" {
  46. fmt.Fprintf(dockerCli.Out(), "Deleted: %s\n", del.Deleted)
  47. } else {
  48. fmt.Fprintf(dockerCli.Out(), "Untagged: %s\n", del.Untagged)
  49. }
  50. }
  51. }
  52. }
  53. if len(errs) > 0 {
  54. return fmt.Errorf("%s", strings.Join(errs, "\n"))
  55. }
  56. return nil
  57. }