github.com/jaylevin/jenkins-library@v1.230.4/pkg/docker/container.go (about)

     1  package docker
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"regexp"
     7  	"strings"
     8  
     9  	containerName "github.com/google/go-containerregistry/pkg/name"
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  // ContainerRegistryFromURL provides the registry part of a complete registry url including the port
    14  func ContainerRegistryFromURL(registryURL string) (string, error) {
    15  	u, err := url.ParseRequestURI(registryURL)
    16  	if err != nil {
    17  		return "", errors.Wrap(err, "invalid registry url")
    18  	}
    19  	if len(u.Host) == 0 {
    20  		return "", fmt.Errorf("invalid registry url")
    21  	}
    22  	return u.Host, nil
    23  }
    24  
    25  // ContainerRegistryFromImage provides the registry part of a full image name
    26  func ContainerRegistryFromImage(fullImage string) (string, error) {
    27  	ref, err := containerName.ParseReference(strings.ToLower(fullImage))
    28  	if err != nil {
    29  		return "", errors.Wrap(err, "failed to parse image name")
    30  	}
    31  	return ref.Context().RegistryStr(), nil
    32  }
    33  
    34  // ContainerImageNameTagFromImage provides the name & tag part of a full image name
    35  func ContainerImageNameTagFromImage(fullImage string) (string, error) {
    36  	ref, err := containerName.ParseReference(strings.ToLower(fullImage))
    37  	if err != nil {
    38  		return "", errors.Wrap(err, "failed to parse image name")
    39  	}
    40  	registryOnly := fmt.Sprintf("%v/", ref.Context().RegistryStr())
    41  	return strings.ReplaceAll(fullImage, registryOnly, ""), nil
    42  }
    43  
    44  // ContainerImageNameFromImage returns the image name of a given docker reference
    45  func ContainerImageNameFromImage(fullImage string) (string, error) {
    46  	imageNameTag, err := ContainerImageNameTagFromImage(fullImage)
    47  
    48  	if err != nil {
    49  		return "", err
    50  	}
    51  
    52  	r := regexp.MustCompile(`([^:@]+)`)
    53  	m := r.FindStringSubmatch(imageNameTag)
    54  
    55  	return m[0], nil
    56  }