2016-06-09 15:38:20 +00:00
|
|
|
package image
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
|
|
|
|
"github.com/docker/docker/cli"
|
2016-09-08 17:11:39 +00:00
|
|
|
"github.com/docker/docker/cli/command"
|
2017-03-28 01:21:59 +00:00
|
|
|
"github.com/pkg/errors"
|
2016-06-09 15:38:20 +00:00
|
|
|
"github.com/spf13/cobra"
|
2017-03-28 01:21:59 +00:00
|
|
|
"golang.org/x/net/context"
|
2016-06-09 15:38:20 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type saveOptions struct {
|
|
|
|
images []string
|
|
|
|
output string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewSaveCommand creates a new `docker save` command
|
2016-09-08 17:11:39 +00:00
|
|
|
func NewSaveCommand(dockerCli *command.DockerCli) *cobra.Command {
|
2016-06-09 15:38:20 +00:00
|
|
|
var opts saveOptions
|
|
|
|
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "save [OPTIONS] IMAGE [IMAGE...]",
|
|
|
|
Short: "Save one or more images to a tar archive (streamed to STDOUT by default)",
|
|
|
|
Args: cli.RequiresMinArgs(1),
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
opts.images = args
|
|
|
|
return runSave(dockerCli, opts)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
flags := cmd.Flags()
|
|
|
|
|
|
|
|
flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT")
|
|
|
|
|
|
|
|
return cmd
|
|
|
|
}
|
|
|
|
|
2016-09-08 17:11:39 +00:00
|
|
|
func runSave(dockerCli *command.DockerCli, opts saveOptions) error {
|
2016-08-29 15:11:29 +00:00
|
|
|
if opts.output == "" && dockerCli.Out().IsTerminal() {
|
2016-06-09 15:38:20 +00:00
|
|
|
return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.")
|
|
|
|
}
|
|
|
|
|
|
|
|
responseBody, err := dockerCli.Client().ImageSave(context.Background(), opts.images)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer responseBody.Close()
|
|
|
|
|
|
|
|
if opts.output == "" {
|
|
|
|
_, err := io.Copy(dockerCli.Out(), responseBody)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-09-08 17:11:39 +00:00
|
|
|
return command.CopyToFile(opts.output, responseBody)
|
2016-06-09 15:38:20 +00:00
|
|
|
}
|