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