import.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package image
  2. import (
  3. "io"
  4. "os"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. dockeropts "github.com/docker/docker/opts"
  10. "github.com/docker/docker/pkg/jsonmessage"
  11. "github.com/docker/docker/pkg/urlutil"
  12. "github.com/spf13/cobra"
  13. )
  14. type importOptions struct {
  15. source string
  16. reference string
  17. changes dockeropts.ListOpts
  18. message string
  19. }
  20. // NewImportCommand creates a new `docker import` command
  21. func NewImportCommand(dockerCli *command.DockerCli) *cobra.Command {
  22. var opts importOptions
  23. cmd := &cobra.Command{
  24. Use: "import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]",
  25. Short: "Import the contents from a tarball to create a filesystem image",
  26. Args: cli.RequiresMinArgs(1),
  27. RunE: func(cmd *cobra.Command, args []string) error {
  28. opts.source = args[0]
  29. if len(args) > 1 {
  30. opts.reference = args[1]
  31. }
  32. return runImport(dockerCli, opts)
  33. },
  34. }
  35. flags := cmd.Flags()
  36. opts.changes = dockeropts.NewListOpts(nil)
  37. flags.VarP(&opts.changes, "change", "c", "Apply Dockerfile instruction to the created image")
  38. flags.StringVarP(&opts.message, "message", "m", "", "Set commit message for imported image")
  39. return cmd
  40. }
  41. func runImport(dockerCli *command.DockerCli, opts importOptions) error {
  42. var (
  43. in io.Reader
  44. srcName = opts.source
  45. )
  46. if opts.source == "-" {
  47. in = dockerCli.In()
  48. } else if !urlutil.IsURL(opts.source) {
  49. srcName = "-"
  50. file, err := os.Open(opts.source)
  51. if err != nil {
  52. return err
  53. }
  54. defer file.Close()
  55. in = file
  56. }
  57. source := types.ImageImportSource{
  58. Source: in,
  59. SourceName: srcName,
  60. }
  61. options := types.ImageImportOptions{
  62. Message: opts.message,
  63. Changes: opts.changes.GetAll(),
  64. }
  65. clnt := dockerCli.Client()
  66. responseBody, err := clnt.ImageImport(context.Background(), source, opts.reference, options)
  67. if err != nil {
  68. return err
  69. }
  70. defer responseBody.Close()
  71. return jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil)
  72. }