github.com/AliyunContainerService/cli@v0.0.0-20181009023821-814ced4b30d0/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  	clnt := dockerCli.Client()
    45  
    46  	responseBody, err := clnt.ContainerExport(context.Background(), opts.container)
    47  	if err != nil {
    48  		return err
    49  	}
    50  	defer responseBody.Close()
    51  
    52  	if opts.output == "" {
    53  		_, err := io.Copy(dockerCli.Out(), responseBody)
    54  		return err
    55  	}
    56  
    57  	return command.CopyToFile(opts.output, responseBody)
    58  }