github.com/xeptore/docker-cli@v20.10.14+incompatible/cli/command/config/create.go (about)

     1  package config
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"io/ioutil"
     8  
     9  	"github.com/docker/cli/cli"
    10  	"github.com/docker/cli/cli/command"
    11  	"github.com/docker/cli/opts"
    12  	"github.com/docker/docker/api/types/swarm"
    13  	"github.com/docker/docker/pkg/system"
    14  	"github.com/pkg/errors"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  // CreateOptions specifies some options that are used when creating a config.
    19  type CreateOptions struct {
    20  	Name           string
    21  	TemplateDriver string
    22  	File           string
    23  	Labels         opts.ListOpts
    24  }
    25  
    26  func newConfigCreateCommand(dockerCli command.Cli) *cobra.Command {
    27  	createOpts := CreateOptions{
    28  		Labels: opts.NewListOpts(opts.ValidateLabel),
    29  	}
    30  
    31  	cmd := &cobra.Command{
    32  		Use:   "create [OPTIONS] CONFIG file|-",
    33  		Short: "Create a config from a file or STDIN",
    34  		Args:  cli.ExactArgs(2),
    35  		RunE: func(cmd *cobra.Command, args []string) error {
    36  			createOpts.Name = args[0]
    37  			createOpts.File = args[1]
    38  			return RunConfigCreate(dockerCli, createOpts)
    39  		},
    40  	}
    41  	flags := cmd.Flags()
    42  	flags.VarP(&createOpts.Labels, "label", "l", "Config labels")
    43  	flags.StringVar(&createOpts.TemplateDriver, "template-driver", "", "Template driver")
    44  	flags.SetAnnotation("template-driver", "version", []string{"1.37"})
    45  
    46  	return cmd
    47  }
    48  
    49  // RunConfigCreate creates a config with the given options.
    50  func RunConfigCreate(dockerCli command.Cli, options CreateOptions) error {
    51  	client := dockerCli.Client()
    52  	ctx := context.Background()
    53  
    54  	var in io.Reader = dockerCli.In()
    55  	if options.File != "-" {
    56  		file, err := system.OpenSequential(options.File)
    57  		if err != nil {
    58  			return err
    59  		}
    60  		in = file
    61  		defer file.Close()
    62  	}
    63  
    64  	configData, err := ioutil.ReadAll(in)
    65  	if err != nil {
    66  		return errors.Errorf("Error reading content from %q: %v", options.File, err)
    67  	}
    68  
    69  	spec := swarm.ConfigSpec{
    70  		Annotations: swarm.Annotations{
    71  			Name:   options.Name,
    72  			Labels: opts.ConvertKVStringsToMap(options.Labels.GetAll()),
    73  		},
    74  		Data: configData,
    75  	}
    76  	if options.TemplateDriver != "" {
    77  		spec.Templating = &swarm.Driver{
    78  			Name: options.TemplateDriver,
    79  		}
    80  	}
    81  	r, err := client.ConfigCreate(ctx, spec)
    82  	if err != nil {
    83  		return err
    84  	}
    85  
    86  	fmt.Fprintln(dockerCli.Out(), r.ID)
    87  	return nil
    88  }