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