github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/cli/command/image/save.go (about) 1 package image 2 3 import ( 4 "errors" 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/spf13/cobra" 12 ) 13 14 type saveOptions struct { 15 images []string 16 output string 17 } 18 19 // NewSaveCommand creates a new `docker save` command 20 func NewSaveCommand(dockerCli *command.DockerCli) *cobra.Command { 21 var opts saveOptions 22 23 cmd := &cobra.Command{ 24 Use: "save [OPTIONS] IMAGE [IMAGE...]", 25 Short: "Save one or more images to a tar archive (streamed to STDOUT by default)", 26 Args: cli.RequiresMinArgs(1), 27 RunE: func(cmd *cobra.Command, args []string) error { 28 opts.images = args 29 return runSave(dockerCli, opts) 30 }, 31 } 32 33 flags := cmd.Flags() 34 35 flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") 36 37 return cmd 38 } 39 40 func runSave(dockerCli *command.DockerCli, opts saveOptions) error { 41 if opts.output == "" && dockerCli.Out().IsTerminal() { 42 return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.") 43 } 44 45 responseBody, err := dockerCli.Client().ImageSave(context.Background(), opts.images) 46 if err != nil { 47 return err 48 } 49 defer responseBody.Close() 50 51 if opts.output == "" { 52 _, err := io.Copy(dockerCli.Out(), responseBody) 53 return err 54 } 55 56 return command.CopyToFile(opts.output, responseBody) 57 }