summaryrefslogtreecommitdiff
path: root/cmd/kpod/save.go
blob: 0f5fcfa4d30323c9fb76f3430ce4531c78c295e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main

import (
	"io"
	"os"

	"github.com/pkg/errors"
	"github.com/projectatomic/libpod/libpod"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
)

var (
	saveFlags = []cli.Flag{
		cli.StringFlag{
			Name:  "output, o",
			Usage: "Write to a file, default is STDOUT",
			Value: "/dev/stdout",
		},
		cli.BoolFlag{
			Name:  "quiet, q",
			Usage: "Suppress the output",
		},
		cli.StringFlag{
			Name:  "format",
			Usage: "Save image to oci-archive",
		},
	}
	saveDescription = `
	Save an image to docker-archive or oci-archive on the local machine.
	Default is docker-archive`

	saveCommand = cli.Command{
		Name:        "save",
		Usage:       "Save image to an archive",
		Description: saveDescription,
		Flags:       saveFlags,
		Action:      saveCmd,
		ArgsUsage:   "",
	}
)

// saveCmd saves the image to either docker-archive or oci
func saveCmd(c *cli.Context) error {
	args := c.Args()
	if len(args) == 0 {
		return errors.Errorf("need at least 1 argument")
	}
	if err := validateFlags(c, saveFlags); err != nil {
		return err
	}

	runtime, err := getRuntime(c)
	if err != nil {
		return errors.Wrapf(err, "could not create runtime")
	}
	defer runtime.Shutdown(false)

	var writer io.Writer
	if !c.Bool("quiet") {
		writer = os.Stdout
	}

	output := c.String("output")
	if output == "/dev/stdout" {
		fi := os.Stdout
		if logrus.IsTerminal(fi) {
			return errors.Errorf("refusing to save to terminal. Use -o flag or redirect")
		}
	}

	var dst string
	switch c.String("format") {
	case libpod.OCIArchive:
		dst = libpod.OCIArchive + ":" + output
	case libpod.DockerArchive:
		fallthrough
	case "":
		dst = libpod.DockerArchive + ":" + output
	default:
		return errors.Errorf("unknown format option %q", c.String("format"))
	}

	saveOpts := libpod.CopyOptions{
		SignaturePolicyPath: "",
		Writer:              writer,
	}

	// only one image is supported for now
	// future pull requests will fix this
	for _, image := range args {
		dest := dst + ":" + image
		if err := runtime.PushImage(image, dest, saveOpts); err != nil {
			if err2 := os.Remove(output); err2 != nil {
				logrus.Errorf("error deleting %q: %v", output, err)
			}
			return errors.Wrapf(err, "unable to save %q", image)
		}
	}
	return nil
}