remove.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package volume
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/docker/docker/cli"
  6. "github.com/docker/docker/cli/command"
  7. "github.com/spf13/cobra"
  8. "golang.org/x/net/context"
  9. )
  10. type removeOptions struct {
  11. force bool
  12. volumes []string
  13. }
  14. func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
  15. var opts removeOptions
  16. cmd := &cobra.Command{
  17. Use: "rm [OPTIONS] VOLUME [VOLUME...]",
  18. Aliases: []string{"remove"},
  19. Short: "Remove one or more volumes",
  20. Long: removeDescription,
  21. Example: removeExample,
  22. Args: cli.RequiresMinArgs(1),
  23. RunE: func(cmd *cobra.Command, args []string) error {
  24. opts.volumes = args
  25. return runRemove(dockerCli, &opts)
  26. },
  27. }
  28. flags := cmd.Flags()
  29. flags.BoolVarP(&opts.force, "force", "f", false, "Force the removal of one or more volumes")
  30. flags.SetAnnotation("force", "version", []string{"1.25"})
  31. return cmd
  32. }
  33. func runRemove(dockerCli command.Cli, opts *removeOptions) error {
  34. client := dockerCli.Client()
  35. ctx := context.Background()
  36. var errs []string
  37. for _, name := range opts.volumes {
  38. if err := client.VolumeRemove(ctx, name, opts.force); err != nil {
  39. errs = append(errs, err.Error())
  40. continue
  41. }
  42. fmt.Fprintf(dockerCli.Out(), "%s\n", name)
  43. }
  44. if len(errs) > 0 {
  45. return fmt.Errorf("%s", strings.Join(errs, "\n"))
  46. }
  47. return nil
  48. }
  49. var removeDescription = `
  50. Remove one or more volumes. You cannot remove a volume that is in use by a container.
  51. `
  52. var removeExample = `
  53. $ docker volume rm hello
  54. hello
  55. `