create.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package volume
  2. import (
  3. "fmt"
  4. volumetypes "github.com/docker/docker/api/types/volume"
  5. "github.com/docker/docker/cli"
  6. "github.com/docker/docker/cli/command"
  7. "github.com/docker/docker/opts"
  8. runconfigopts "github.com/docker/docker/runconfig/opts"
  9. "github.com/spf13/cobra"
  10. "golang.org/x/net/context"
  11. )
  12. type createOptions struct {
  13. name string
  14. driver string
  15. driverOpts opts.MapOpts
  16. labels opts.ListOpts
  17. }
  18. func newCreateCommand(dockerCli command.Cli) *cobra.Command {
  19. opts := createOptions{
  20. driverOpts: *opts.NewMapOpts(nil, nil),
  21. labels: opts.NewListOpts(opts.ValidateEnv),
  22. }
  23. cmd := &cobra.Command{
  24. Use: "create [OPTIONS] [VOLUME]",
  25. Short: "Create a volume",
  26. Args: cli.RequiresMaxArgs(1),
  27. RunE: func(cmd *cobra.Command, args []string) error {
  28. if len(args) == 1 {
  29. if opts.name != "" {
  30. return fmt.Errorf("Conflicting options: either specify --name or provide positional arg, not both\n")
  31. }
  32. opts.name = args[0]
  33. }
  34. return runCreate(dockerCli, opts)
  35. },
  36. }
  37. flags := cmd.Flags()
  38. flags.StringVarP(&opts.driver, "driver", "d", "local", "Specify volume driver name")
  39. flags.StringVar(&opts.name, "name", "", "Specify volume name")
  40. flags.Lookup("name").Hidden = true
  41. flags.VarP(&opts.driverOpts, "opt", "o", "Set driver specific options")
  42. flags.Var(&opts.labels, "label", "Set metadata for a volume")
  43. return cmd
  44. }
  45. func runCreate(dockerCli command.Cli, opts createOptions) error {
  46. client := dockerCli.Client()
  47. volReq := volumetypes.VolumesCreateBody{
  48. Driver: opts.driver,
  49. DriverOpts: opts.driverOpts.GetAll(),
  50. Name: opts.name,
  51. Labels: runconfigopts.ConvertKVStringsToMap(opts.labels.GetAll()),
  52. }
  53. vol, err := client.VolumeCreate(context.Background(), volReq)
  54. if err != nil {
  55. return err
  56. }
  57. fmt.Fprintf(dockerCli.Out(), "%s\n", vol.Name)
  58. return nil
  59. }