github.com/hazelops/ize@v1.1.12-0.20230915191306-97d7c0e48f11/internal/docker/registry.go (about)

     1  package docker
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  
     9  	"github.com/docker/docker/api/types"
    10  	"github.com/docker/docker/client"
    11  	"github.com/docker/docker/pkg/jsonmessage"
    12  )
    13  
    14  type Registry struct {
    15  	Registry string
    16  	Token    string
    17  	Platform string
    18  }
    19  
    20  func NewRegistry(registry, token, platform string) Registry {
    21  	return Registry{
    22  		Registry: registry,
    23  		Token:    token,
    24  		Platform: platform,
    25  	}
    26  }
    27  
    28  func (r *Registry) Push(ctx context.Context, w io.Writer, image string, tags []string) error {
    29  	if len(tags) == 0 {
    30  		tags = []string{"latest"}
    31  	}
    32  
    33  	cli, err := client.NewClientWithOpts(client.FromEnv)
    34  	if err != nil {
    35  		return fmt.Errorf("unable to create Docker client: %s", err)
    36  	}
    37  
    38  	if len(tags) > 1 {
    39  		for i := 1; i < len(tags); i++ {
    40  			err = cli.ImageTag(context.Background(), image+":"+tags[0], fmt.Sprintf("%s/%s:%s", r.Registry, image, tags[i]))
    41  			if err != nil {
    42  				return err
    43  			}
    44  		}
    45  	}
    46  
    47  	resp, err := cli.ImagePush(ctx, image+":"+tags[0], types.ImagePushOptions{
    48  		RegistryAuth: r.Token,
    49  		All:          true,
    50  		Platform:     r.Platform,
    51  	})
    52  	if err != nil {
    53  		return fmt.Errorf("unable to push image: %s", err)
    54  	}
    55  
    56  	var termFd uintptr
    57  	if f, ok := w.(*os.File); ok {
    58  		termFd = f.Fd()
    59  	}
    60  
    61  	err = jsonmessage.DisplayJSONMessagesStream(
    62  		resp,
    63  		w,
    64  		termFd,
    65  		true,
    66  		nil,
    67  	)
    68  	if err != nil {
    69  		return fmt.Errorf("unable to stream push logs to the terminal: %s", err)
    70  	}
    71  
    72  	return nil
    73  }