forked from twz123/img
-
Notifications
You must be signed in to change notification settings - Fork 0
/
save.go
99 lines (78 loc) · 2.21 KB
/
save.go
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
package main
import (
"context"
"fmt"
"github.com/spf13/cobra"
"io"
"os"
"github.com/containerd/containerd/namespaces"
"github.com/docker/docker/pkg/term"
"github.com/genuinetools/img/client"
"github.com/moby/buildkit/identity"
"github.com/moby/buildkit/session"
)
// TODO(AkihiroSuda): support OCI archive
const saveUsageShortHelp = `Save an image to a tar archive (streamed to STDOUT by default).`
const saveUsageLongHelp = `Save an image to a tar archive (streamed to STDOUT by default).`
func newSaveCommand() *cobra.Command {
save := &saveCommand{}
cmd := &cobra.Command{
Use: "save [OPTIONS] IMAGE [IMAGE...]",
DisableFlagsInUseLine: true,
SilenceUsage: true,
Short: saveUsageShortHelp,
Long: saveUsageLongHelp,
Args: save.ValidateArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return save.Run(args)
},
}
fs := cmd.Flags()
fs.StringVarP(&save.output, "output", "o", "", "write to a file, instead of STDOUT")
fs.StringVar(&save.format, "format", "docker", "image output format (docker|oci)")
return cmd
}
type saveCommand struct {
output string
format string
}
func (cmd *saveCommand) ValidateArgs(c *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("must pass an image to save")
}
return nil
}
func (cmd *saveCommand) Run(args []string) (err error) {
reexec()
// Create the context.
id := identity.NewID()
ctx := session.NewContext(context.Background(), id)
ctx = namespaces.WithNamespace(ctx, "buildkit")
// Create the client.
c, err := client.New(stateDir, backend, nil)
if err != nil {
return err
}
defer c.Close()
// Create the writer.
writer, err := cmd.writer()
if err != nil {
return err
}
// Loop over the arguments as images and run save.
for _, image := range args {
if err := c.SaveImage(ctx, image, cmd.format, writer); err != nil {
return err
}
}
return nil
}
func (cmd *saveCommand) writer() (io.WriteCloser, error) {
if cmd.output != "" {
return os.Create(cmd.output)
}
if term.IsTerminal(os.Stdout.Fd()) {
return nil, fmt.Errorf("cowardly refusing to save to a terminal. Use the -o flag or redirect")
}
return os.Stdout, nil
}