import.go 2.0 KB

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