github.com/ali-iotechsys/cli@v20.10.0+incompatible/cli/command/container/export.go (about) 1 package container 2 3 import ( 4 "context" 5 "io" 6 7 "github.com/docker/cli/cli" 8 "github.com/docker/cli/cli/command" 9 "github.com/pkg/errors" 10 "github.com/spf13/cobra" 11 ) 12 13 type exportOptions struct { 14 container string 15 output string 16 } 17 18 // NewExportCommand creates a new `docker export` command 19 func NewExportCommand(dockerCli command.Cli) *cobra.Command { 20 var opts exportOptions 21 22 cmd := &cobra.Command{ 23 Use: "export [OPTIONS] CONTAINER", 24 Short: "Export a container's filesystem as a tar archive", 25 Args: cli.ExactArgs(1), 26 RunE: func(cmd *cobra.Command, args []string) error { 27 opts.container = args[0] 28 return runExport(dockerCli, opts) 29 }, 30 } 31 32 flags := cmd.Flags() 33 34 flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") 35 36 return cmd 37 } 38 39 func runExport(dockerCli command.Cli, opts exportOptions) error { 40 if opts.output == "" && dockerCli.Out().IsTerminal() { 41 return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") 42 } 43 44 if err := command.ValidateOutputPath(opts.output); err != nil { 45 return errors.Wrap(err, "failed to export container") 46 } 47 48 clnt := dockerCli.Client() 49 50 responseBody, err := clnt.ContainerExport(context.Background(), opts.container) 51 if err != nil { 52 return err 53 } 54 defer responseBody.Close() 55 56 if opts.output == "" { 57 _, err := io.Copy(dockerCli.Out(), responseBody) 58 return err 59 } 60 61 return command.CopyToFile(opts.output, responseBody) 62 }