github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/cli/command/container/export.go (about)

     1  package container
     2  
     3  import (
     4  	"errors"
     5  	"io"
     6  
     7  	"github.com/docker/docker/cli"
     8  	"github.com/docker/docker/cli/command"
     9  	"github.com/spf13/cobra"
    10  	"golang.org/x/net/context"
    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.DockerCli) *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.DockerCli, 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  }