2018-11-09 09:10:41 -05:00
|
|
|
package context
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/docker/cli/cli"
|
|
|
|
"github.com/docker/cli/cli/command"
|
|
|
|
"github.com/docker/cli/cli/context/store"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
2019-01-21 03:37:20 -05:00
|
|
|
// ExportOptions are the options used for exporting a context
|
|
|
|
type ExportOptions struct {
|
|
|
|
ContextName string
|
|
|
|
Dest string
|
2018-11-09 09:10:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func newExportCommand(dockerCli command.Cli) *cobra.Command {
|
2023-06-21 05:27:41 -04:00
|
|
|
return &cobra.Command{
|
2018-11-09 09:10:41 -05:00
|
|
|
Use: "export [OPTIONS] CONTEXT [FILE|-]",
|
2022-02-23 12:01:24 -05:00
|
|
|
Short: "Export a context to a tar archive FILE or a tar stream on STDOUT.",
|
2018-11-09 09:10:41 -05:00
|
|
|
Args: cli.RequiresRangeArgs(1, 2),
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
2023-06-21 05:27:41 -04:00
|
|
|
opts := &ExportOptions{
|
|
|
|
ContextName: args[0],
|
|
|
|
}
|
2018-11-09 09:10:41 -05:00
|
|
|
if len(args) == 2 {
|
2019-01-21 03:37:20 -05:00
|
|
|
opts.Dest = args[1]
|
2018-11-09 09:10:41 -05:00
|
|
|
} else {
|
2022-02-23 12:01:24 -05:00
|
|
|
opts.Dest = opts.ContextName + ".dockercontext"
|
2018-11-09 09:10:41 -05:00
|
|
|
}
|
2019-01-21 03:37:20 -05:00
|
|
|
return RunExport(dockerCli, opts)
|
2018-11-09 09:10:41 -05:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func writeTo(dockerCli command.Cli, reader io.Reader, dest string) error {
|
|
|
|
var writer io.Writer
|
|
|
|
var printDest bool
|
|
|
|
if dest == "-" {
|
|
|
|
if dockerCli.Out().IsTerminal() {
|
2024-04-26 14:16:51 -04:00
|
|
|
return errors.New("cowardly refusing to export to a terminal, specify a file path")
|
2018-11-09 09:10:41 -05:00
|
|
|
}
|
|
|
|
writer = dockerCli.Out()
|
|
|
|
} else {
|
2022-09-30 13:13:22 -04:00
|
|
|
f, err := os.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600)
|
2018-11-09 09:10:41 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
writer = f
|
|
|
|
printDest = true
|
|
|
|
}
|
|
|
|
if _, err := io.Copy(writer, reader); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if printDest {
|
|
|
|
fmt.Fprintf(dockerCli.Err(), "Written file %q\n", dest)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-01-21 03:37:20 -05:00
|
|
|
// RunExport exports a Docker context
|
|
|
|
func RunExport(dockerCli command.Cli, opts *ExportOptions) error {
|
2020-09-24 10:24:24 -04:00
|
|
|
if err := store.ValidateContextName(opts.ContextName); err != nil && opts.ContextName != command.DefaultContextName {
|
2018-11-09 09:10:41 -05:00
|
|
|
return err
|
|
|
|
}
|
2021-06-16 03:08:42 -04:00
|
|
|
reader := store.Export(opts.ContextName, dockerCli.ContextStore())
|
|
|
|
defer reader.Close()
|
|
|
|
return writeTo(dockerCli, reader, opts.Dest)
|
2018-11-09 09:10:41 -05:00
|
|
|
}
|