github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/cmd/podman/export.go (about)

     1  package main
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/containers/libpod/cmd/podman/cliconfig"
     7  	"github.com/containers/libpod/cmd/podman/shared/parse"
     8  	"github.com/containers/libpod/pkg/adapter"
     9  	"github.com/pkg/errors"
    10  	"github.com/spf13/cobra"
    11  	"golang.org/x/crypto/ssh/terminal"
    12  )
    13  
    14  var (
    15  	exportCommand     cliconfig.ExportValues
    16  	exportDescription = "Exports container's filesystem contents as a tar archive" +
    17  		" and saves it on the local machine."
    18  
    19  	_exportCommand = &cobra.Command{
    20  		Use:   "export [flags] CONTAINER",
    21  		Short: "Export container's filesystem contents as a tar archive",
    22  		Long:  exportDescription,
    23  		RunE: func(cmd *cobra.Command, args []string) error {
    24  			exportCommand.InputArgs = args
    25  			exportCommand.GlobalFlags = MainGlobalOpts
    26  			exportCommand.Remote = remoteclient
    27  			return exportCmd(&exportCommand)
    28  		},
    29  		Example: `podman export ctrID > myCtr.tar
    30    podman export --output="myCtr.tar" ctrID`,
    31  	}
    32  )
    33  
    34  func init() {
    35  	exportCommand.Command = _exportCommand
    36  	exportCommand.SetHelpTemplate(HelpTemplate())
    37  	exportCommand.SetUsageTemplate(UsageTemplate())
    38  	flags := exportCommand.Flags()
    39  	flags.StringVarP(&exportCommand.Output, "output", "o", "", "Write to a specified file (default: stdout, which must be redirected)")
    40  }
    41  
    42  // exportCmd saves a container to a tarball on disk
    43  func exportCmd(c *cliconfig.ExportValues) error {
    44  	runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand)
    45  	if err != nil {
    46  		return errors.Wrapf(err, "could not get runtime")
    47  	}
    48  	defer runtime.DeferredShutdown(false)
    49  
    50  	args := c.InputArgs
    51  	if len(args) == 0 {
    52  		return errors.Errorf("container id must be specified")
    53  	}
    54  	if len(args) > 1 {
    55  		return errors.Errorf("too many arguments given, need 1 at most.")
    56  	}
    57  
    58  	output := c.Output
    59  	if runtime.Remote && len(output) == 0 {
    60  		return errors.New("remote client usage must specify an output file (-o)")
    61  	}
    62  
    63  	if len(output) == 0 {
    64  		file := os.Stdout
    65  		if terminal.IsTerminal(int(file.Fd())) {
    66  			return errors.Errorf("refusing to export to terminal. Use -o flag or redirect")
    67  		}
    68  		output = "/dev/stdout"
    69  	}
    70  
    71  	if err := parse.ValidateFileName(output); err != nil {
    72  		return err
    73  	}
    74  	return runtime.Export(args[0], output)
    75  }