gitlab.com/sparetimecoders/build-tools@v0.1.0/pkg/registry/registry.go (about)

     1  package registry
     2  
     3  import (
     4  	"bufio"
     5  	"context"
     6  	"docker.io/go-docker/api/types"
     7  	"encoding/json"
     8  	"errors"
     9  	"fmt"
    10  	"gitlab.com/sparetimecoders/build-tools/pkg/docker"
    11  	"io"
    12  )
    13  
    14  type Registry interface {
    15  	Configured() bool
    16  	Name() string
    17  	Login(client docker.Client, out io.Writer) error
    18  	GetAuthInfo() string
    19  	RegistryUrl() string
    20  	Create(repository string) error
    21  	PushImage(client docker.Client, auth, image string, out, eout io.Writer) error
    22  }
    23  
    24  type responsetype struct {
    25  	Status      string `json:"status"`
    26  	ErrorDetail *struct {
    27  		Message string `json:"message"`
    28  	} `json:"errorDetail"`
    29  	Error          string `json:"error"`
    30  	ProgressDetail *struct {
    31  		Current int64 `json:"current"`
    32  		Total   int64 `json:"total"`
    33  	} `json:"progressDetail"`
    34  	Progress string `json:"progress"`
    35  	Id       string `json:"id"`
    36  	Aux      *struct {
    37  		Tag    string `json:"Tag"`
    38  		Digest string `json:"Digest"`
    39  		Size   int64  `json:"Size"`
    40  	} `json:"aux"`
    41  }
    42  
    43  type dockerRegistry struct{}
    44  
    45  func (dockerRegistry) PushImage(client docker.Client, auth, image string, ow, eout io.Writer) error {
    46  	if out, err := client.ImagePush(context.Background(), image, types.ImagePushOptions{All: true, RegistryAuth: auth}); err != nil {
    47  		return err
    48  	} else {
    49  		scanner := bufio.NewScanner(out)
    50  		for scanner.Scan() {
    51  			r := &responsetype{}
    52  			response := scanner.Bytes()
    53  			if err := json.Unmarshal(response, &r); err != nil {
    54  				_, _ = fmt.Fprintf(eout, "Unable to parse response: %s, Error: %v\n", string(response), err)
    55  				return err
    56  			} else {
    57  				if len(r.Status) != 0 {
    58  					if len(r.Id) == 0 {
    59  						_, _ = fmt.Fprintln(ow, r.Status)
    60  					} else if len(r.Progress) == 0 {
    61  						_, _ = fmt.Fprintf(ow, "%s: %s\n", r.Id, r.Status)
    62  					} else {
    63  						_, _ = fmt.Fprintf(ow, "%s: %s %s\n", r.Id, r.Status, r.Progress)
    64  					}
    65  				} else if r.ErrorDetail != nil {
    66  					return errors.New(r.ErrorDetail.Message)
    67  				}
    68  			}
    69  		}
    70  
    71  		return nil
    72  	}
    73  }