github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/cnbutils/target_image.go (about)

     1  package cnbutils
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"path/filepath"
     7  	"regexp"
     8  	"strings"
     9  
    10  	"github.com/SAP/jenkins-library/pkg/piperenv"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  type TargetImage struct {
    15  	ContainerImageName string
    16  	ContainerImageTag  string
    17  	ContainerRegistry  *url.URL
    18  }
    19  
    20  func GetTargetImage(imageRegistry, imageName, imageTag, projectID, envRootPath string) (*TargetImage, error) {
    21  	if imageRegistry == "" || imageTag == "" {
    22  		return nil, errors.New("containerRegistryUrl and containerImageTag must be present")
    23  	}
    24  
    25  	targetImage := &TargetImage{
    26  		ContainerImageTag: strings.ReplaceAll(imageTag, "+", "-"),
    27  	}
    28  
    29  	if matched, _ := regexp.MatchString("^(http|https)://.*", imageRegistry); !matched {
    30  		imageRegistry = fmt.Sprintf("https://%s", imageRegistry)
    31  	}
    32  
    33  	url, err := url.ParseRequestURI(imageRegistry)
    34  	if err != nil {
    35  		return nil, errors.Wrap(err, "invalid registry url")
    36  	}
    37  	targetImage.ContainerRegistry = url
    38  
    39  	cpePath := filepath.Join(envRootPath, "commonPipelineEnvironment")
    40  	gitRepository := piperenv.GetResourceParameter(cpePath, "git", "repository")
    41  	githubRepository := piperenv.GetResourceParameter(cpePath, "github", "repository")
    42  
    43  	if imageName != "" {
    44  		targetImage.ContainerImageName = imageName
    45  	} else if projectID != "" {
    46  		name := strings.ReplaceAll(projectID, ".", "-")
    47  		targetImage.ContainerImageName = name
    48  	} else if gitRepository != "" {
    49  		targetImage.ContainerImageName = strings.ReplaceAll(gitRepository, ".", "-")
    50  	} else if githubRepository != "" {
    51  		targetImage.ContainerImageName = strings.ReplaceAll(githubRepository, ".", "-")
    52  	} else {
    53  		return nil, errors.New("failed to derive default for image name")
    54  	}
    55  
    56  	return targetImage, nil
    57  }