export.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package container
  2. import (
  3. "errors"
  4. "io"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/client"
  7. "github.com/docker/docker/cli"
  8. "github.com/spf13/cobra"
  9. )
  10. type exportOptions struct {
  11. container string
  12. output string
  13. }
  14. // NewExportCommand creates a new `docker export` command
  15. func NewExportCommand(dockerCli *client.DockerCli) *cobra.Command {
  16. var opts exportOptions
  17. cmd := &cobra.Command{
  18. Use: "export [OPTIONS] CONTAINER",
  19. Short: "Export a container's filesystem as a tar archive",
  20. Args: cli.ExactArgs(1),
  21. RunE: func(cmd *cobra.Command, args []string) error {
  22. opts.container = args[0]
  23. return runExport(dockerCli, opts)
  24. },
  25. }
  26. flags := cmd.Flags()
  27. flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT")
  28. return cmd
  29. }
  30. func runExport(dockerCli *client.DockerCli, opts exportOptions) error {
  31. if opts.output == "" && dockerCli.IsTerminalOut() {
  32. return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.")
  33. }
  34. clnt := dockerCli.Client()
  35. responseBody, err := clnt.ContainerExport(context.Background(), opts.container)
  36. if err != nil {
  37. return err
  38. }
  39. defer responseBody.Close()
  40. if opts.output == "" {
  41. _, err := io.Copy(dockerCli.Out(), responseBody)
  42. return err
  43. }
  44. return client.CopyToFile(opts.output, responseBody)
  45. }