github.1git.de/docker/cli@v26.1.3+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/docker/cli/cli/command/completion" 10 "github.com/pkg/errors" 11 "github.com/spf13/cobra" 12 ) 13 14 type exportOptions struct { 15 container string 16 output string 17 } 18 19 // NewExportCommand creates a new `docker export` command 20 func NewExportCommand(dockerCli command.Cli) *cobra.Command { 21 var opts exportOptions 22 23 cmd := &cobra.Command{ 24 Use: "export [OPTIONS] CONTAINER", 25 Short: "Export a container's filesystem as a tar archive", 26 Args: cli.ExactArgs(1), 27 RunE: func(cmd *cobra.Command, args []string) error { 28 opts.container = args[0] 29 return runExport(cmd.Context(), dockerCli, opts) 30 }, 31 Annotations: map[string]string{ 32 "aliases": "docker container export, docker export", 33 }, 34 ValidArgsFunction: completion.ContainerNames(dockerCli, true), 35 } 36 37 flags := cmd.Flags() 38 39 flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") 40 41 return cmd 42 } 43 44 func runExport(ctx context.Context, dockerCli command.Cli, opts exportOptions) error { 45 if opts.output == "" && dockerCli.Out().IsTerminal() { 46 return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") 47 } 48 49 if err := command.ValidateOutputPath(opts.output); err != nil { 50 return errors.Wrap(err, "failed to export container") 51 } 52 53 clnt := dockerCli.Client() 54 55 responseBody, err := clnt.ContainerExport(ctx, opts.container) 56 if err != nil { 57 return err 58 } 59 defer responseBody.Close() 60 61 if opts.output == "" { 62 _, err := io.Copy(dockerCli.Out(), responseBody) 63 return err 64 } 65 66 return command.CopyToFile(opts.output, responseBody) 67 }