github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/image/pull.go (about) 1 package image 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 8 "github.com/docker/cli/cli" 9 "github.com/docker/cli/cli/command" 10 "github.com/docker/cli/cli/command/completion" 11 "github.com/docker/cli/cli/trust" 12 "github.com/docker/distribution/reference" 13 "github.com/pkg/errors" 14 "github.com/spf13/cobra" 15 ) 16 17 // PullOptions defines what and how to pull 18 type PullOptions struct { 19 remote string 20 all bool 21 platform string 22 quiet bool 23 untrusted bool 24 } 25 26 // NewPullCommand creates a new `docker pull` command 27 func NewPullCommand(dockerCli command.Cli) *cobra.Command { 28 var opts PullOptions 29 30 cmd := &cobra.Command{ 31 Use: "pull [OPTIONS] NAME[:TAG|@DIGEST]", 32 Short: "Download an image from a registry", 33 Args: cli.ExactArgs(1), 34 RunE: func(cmd *cobra.Command, args []string) error { 35 opts.remote = args[0] 36 return RunPull(dockerCli, opts) 37 }, 38 Annotations: map[string]string{ 39 "category-top": "5", 40 "aliases": "docker image pull, docker pull", 41 }, 42 ValidArgsFunction: completion.NoComplete, 43 } 44 45 flags := cmd.Flags() 46 47 flags.BoolVarP(&opts.all, "all-tags", "a", false, "Download all tagged images in the repository") 48 flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress verbose output") 49 50 command.AddPlatformFlag(flags, &opts.platform) 51 command.AddTrustVerificationFlags(flags, &opts.untrusted, dockerCli.ContentTrustEnabled()) 52 53 return cmd 54 } 55 56 // RunPull performs a pull against the engine based on the specified options 57 func RunPull(cli command.Cli, opts PullOptions) error { 58 distributionRef, err := reference.ParseNormalizedNamed(opts.remote) 59 switch { 60 case err != nil: 61 return err 62 case opts.all && !reference.IsNameOnly(distributionRef): 63 return errors.New("tag can't be used with --all-tags/-a") 64 case !opts.all && reference.IsNameOnly(distributionRef): 65 distributionRef = reference.TagNameOnly(distributionRef) 66 if tagged, ok := distributionRef.(reference.Tagged); ok && !opts.quiet { 67 fmt.Fprintf(cli.Out(), "Using default tag: %s\n", tagged.Tag()) 68 } 69 } 70 71 ctx := context.Background() 72 imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, nil, AuthResolver(cli), distributionRef.String()) 73 if err != nil { 74 return err 75 } 76 77 // Check if reference has a digest 78 _, isCanonical := distributionRef.(reference.Canonical) 79 if !opts.untrusted && !isCanonical { 80 err = trustedPull(ctx, cli, imgRefAndAuth, opts) 81 } else { 82 err = imagePullPrivileged(ctx, cli, imgRefAndAuth, opts) 83 } 84 if err != nil { 85 if strings.Contains(err.Error(), "when fetching 'plugin'") { 86 return errors.New(err.Error() + " - Use `docker plugin install`") 87 } 88 return err 89 } 90 fmt.Fprintln(cli.Out(), imgRefAndAuth.Reference().String()) 91 return nil 92 }