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