github.com/olljanat/moby@v1.13.1/cli/command/image/import.go (about)

     1  package image
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  
     7  	"golang.org/x/net/context"
     8  
     9  	"github.com/docker/docker/api/types"
    10  	"github.com/docker/docker/cli"
    11  	"github.com/docker/docker/cli/command"
    12  	dockeropts "github.com/docker/docker/opts"
    13  	"github.com/docker/docker/pkg/jsonmessage"
    14  	"github.com/docker/docker/pkg/urlutil"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  type importOptions struct {
    19  	source    string
    20  	reference string
    21  	changes   dockeropts.ListOpts
    22  	message   string
    23  }
    24  
    25  // NewImportCommand creates a new `docker import` command
    26  func NewImportCommand(dockerCli *command.DockerCli) *cobra.Command {
    27  	var opts importOptions
    28  
    29  	cmd := &cobra.Command{
    30  		Use:   "import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]",
    31  		Short: "Import the contents from a tarball to create a filesystem image",
    32  		Args:  cli.RequiresMinArgs(1),
    33  		RunE: func(cmd *cobra.Command, args []string) error {
    34  			opts.source = args[0]
    35  			if len(args) > 1 {
    36  				opts.reference = args[1]
    37  			}
    38  			return runImport(dockerCli, opts)
    39  		},
    40  	}
    41  
    42  	flags := cmd.Flags()
    43  
    44  	opts.changes = dockeropts.NewListOpts(nil)
    45  	flags.VarP(&opts.changes, "change", "c", "Apply Dockerfile instruction to the created image")
    46  	flags.StringVarP(&opts.message, "message", "m", "", "Set commit message for imported image")
    47  
    48  	return cmd
    49  }
    50  
    51  func runImport(dockerCli *command.DockerCli, opts importOptions) error {
    52  	var (
    53  		in      io.Reader
    54  		srcName = opts.source
    55  	)
    56  
    57  	if opts.source == "-" {
    58  		in = dockerCli.In()
    59  	} else if !urlutil.IsURL(opts.source) {
    60  		srcName = "-"
    61  		file, err := os.Open(opts.source)
    62  		if err != nil {
    63  			return err
    64  		}
    65  		defer file.Close()
    66  		in = file
    67  	}
    68  
    69  	source := types.ImageImportSource{
    70  		Source:     in,
    71  		SourceName: srcName,
    72  	}
    73  
    74  	options := types.ImageImportOptions{
    75  		Message: opts.message,
    76  		Changes: opts.changes.GetAll(),
    77  	}
    78  
    79  	clnt := dockerCli.Client()
    80  
    81  	responseBody, err := clnt.ImageImport(context.Background(), source, opts.reference, options)
    82  	if err != nil {
    83  		return err
    84  	}
    85  	defer responseBody.Close()
    86  
    87  	return jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil)
    88  }