github.com/olljanat/moby@v1.13.1/cli/command/image/load.go (about) 1 package image 2 3 import ( 4 "fmt" 5 "io" 6 7 "golang.org/x/net/context" 8 9 "github.com/docker/docker/cli" 10 "github.com/docker/docker/cli/command" 11 "github.com/docker/docker/pkg/jsonmessage" 12 "github.com/docker/docker/pkg/system" 13 "github.com/spf13/cobra" 14 ) 15 16 type loadOptions struct { 17 input string 18 quiet bool 19 } 20 21 // NewLoadCommand creates a new `docker load` command 22 func NewLoadCommand(dockerCli *command.DockerCli) *cobra.Command { 23 var opts loadOptions 24 25 cmd := &cobra.Command{ 26 Use: "load [OPTIONS]", 27 Short: "Load an image from a tar archive or STDIN", 28 Args: cli.NoArgs, 29 RunE: func(cmd *cobra.Command, args []string) error { 30 return runLoad(dockerCli, opts) 31 }, 32 } 33 34 flags := cmd.Flags() 35 36 flags.StringVarP(&opts.input, "input", "i", "", "Read from tar archive file, instead of STDIN") 37 flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress the load output") 38 39 return cmd 40 } 41 42 func runLoad(dockerCli *command.DockerCli, opts loadOptions) error { 43 44 var input io.Reader = dockerCli.In() 45 if opts.input != "" { 46 // We use system.OpenSequential to use sequential file access on Windows, avoiding 47 // depleting the standby list un-necessarily. On Linux, this equates to a regular os.Open. 48 file, err := system.OpenSequential(opts.input) 49 if err != nil { 50 return err 51 } 52 defer file.Close() 53 input = file 54 } 55 56 // To avoid getting stuck, verify that a tar file is given either in 57 // the input flag or through stdin and if not display an error message and exit. 58 if opts.input == "" && dockerCli.In().IsTerminal() { 59 return fmt.Errorf("requested load from stdin, but stdin is empty") 60 } 61 62 if !dockerCli.Out().IsTerminal() { 63 opts.quiet = true 64 } 65 response, err := dockerCli.Client().ImageLoad(context.Background(), input, opts.quiet) 66 if err != nil { 67 return err 68 } 69 defer response.Body.Close() 70 71 if response.Body != nil && response.JSON { 72 return jsonmessage.DisplayJSONMessagesToStream(response.Body, dockerCli.Out(), nil) 73 } 74 75 _, err = io.Copy(dockerCli.Out(), response.Body) 76 return err 77 }