github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/image/import.go (about) 1 package image 2 3 import ( 4 "context" 5 "os" 6 "strings" 7 8 "github.com/docker/cli/cli" 9 "github.com/docker/cli/cli/command" 10 dockeropts "github.com/docker/cli/opts" 11 "github.com/docker/docker/api/types" 12 "github.com/docker/docker/pkg/jsonmessage" 13 "github.com/spf13/cobra" 14 ) 15 16 type importOptions struct { 17 source string 18 reference string 19 changes dockeropts.ListOpts 20 message string 21 platform string 22 } 23 24 // NewImportCommand creates a new `docker import` command 25 func NewImportCommand(dockerCli command.Cli) *cobra.Command { 26 var options importOptions 27 28 cmd := &cobra.Command{ 29 Use: "import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]", 30 Short: "Import the contents from a tarball to create a filesystem image", 31 Args: cli.RequiresMinArgs(1), 32 RunE: func(cmd *cobra.Command, args []string) error { 33 options.source = args[0] 34 if len(args) > 1 { 35 options.reference = args[1] 36 } 37 return runImport(dockerCli, options) 38 }, 39 Annotations: map[string]string{ 40 "aliases": "docker image import, docker import", 41 }, 42 } 43 44 flags := cmd.Flags() 45 46 options.changes = dockeropts.NewListOpts(nil) 47 flags.VarP(&options.changes, "change", "c", "Apply Dockerfile instruction to the created image") 48 flags.StringVarP(&options.message, "message", "m", "", "Set commit message for imported image") 49 command.AddPlatformFlag(flags, &options.platform) 50 51 return cmd 52 } 53 54 func runImport(dockerCli command.Cli, options importOptions) error { 55 var source types.ImageImportSource 56 switch { 57 case options.source == "-": 58 // import from STDIN 59 source = types.ImageImportSource{ 60 Source: dockerCli.In(), 61 SourceName: options.source, 62 } 63 case strings.HasPrefix(options.source, "https://"), strings.HasPrefix(options.source, "http://"): 64 // import from a remote source (handled by the daemon) 65 source = types.ImageImportSource{ 66 SourceName: options.source, 67 } 68 default: 69 // import from a local file 70 file, err := os.Open(options.source) 71 if err != nil { 72 return err 73 } 74 defer file.Close() 75 source = types.ImageImportSource{ 76 Source: file, 77 SourceName: "-", 78 } 79 } 80 81 responseBody, err := dockerCli.Client().ImageImport(context.Background(), source, options.reference, types.ImageImportOptions{ 82 Message: options.message, 83 Changes: options.changes.GetAll(), 84 Platform: options.platform, 85 }) 86 if err != nil { 87 return err 88 } 89 defer responseBody.Close() 90 91 return jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil) 92 }