github.com/docker/cnab-to-oci@v0.3.0-beta4/cmd/cnab-to-oci/pull.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"os"
     8  
     9  	"github.com/docker/cnab-to-oci/remotes"
    10  	"github.com/docker/distribution/reference"
    11  	"github.com/docker/go/canonical/json"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type pullOptions struct {
    16  	bundle             string
    17  	relocationMap      string
    18  	targetRef          string
    19  	insecureRegistries []string
    20  }
    21  
    22  func pullCmd() *cobra.Command {
    23  	var opts pullOptions
    24  	cmd := &cobra.Command{
    25  		Use:   "pull <ref> [options]",
    26  		Short: "Pulls an image reference",
    27  		Args:  cobra.ExactArgs(1),
    28  		RunE: func(cmd *cobra.Command, args []string) error {
    29  			opts.targetRef = args[0]
    30  			return runPull(opts)
    31  		},
    32  	}
    33  
    34  	cmd.Flags().StringVar(&opts.bundle, "bundle", "pulled.json", "bundle output file (- to print on standard output)")
    35  	cmd.Flags().StringVar(&opts.relocationMap, "relocation-map", "relocation-map.json", "relocation map output file (- to print on standard output)")
    36  	cmd.Flags().StringSliceVar(&opts.insecureRegistries, "insecure-registries", nil, "Use plain HTTP for those registries")
    37  	return cmd
    38  }
    39  
    40  func runPull(opts pullOptions) error {
    41  	ref, err := reference.ParseNormalizedNamed(opts.targetRef)
    42  	if err != nil {
    43  		return err
    44  	}
    45  
    46  	b, relocationMap, err := remotes.Pull(context.Background(), ref, createResolver(opts.insecureRegistries))
    47  	if err != nil {
    48  		return err
    49  	}
    50  	if err := writeOutput(opts.bundle, b); err != nil {
    51  		return err
    52  	}
    53  	return writeOutput(opts.relocationMap, relocationMap)
    54  }
    55  
    56  func writeOutput(file string, data interface{}) error {
    57  	bytes, err := json.MarshalCanonical(data)
    58  	if err != nil {
    59  		return err
    60  	}
    61  	if file == "-" {
    62  		fmt.Fprintln(os.Stdout, string(bytes))
    63  		return nil
    64  	}
    65  	return ioutil.WriteFile(file, bytes, 0644)
    66  }