github.com/argoproj/argo-cd/v3@v3.2.1/cmd/util/applicationset.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"os"
     7  
     8  	"github.com/argoproj/gitops-engine/pkg/utils/kube"
     9  
    10  	argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
    11  	"github.com/argoproj/argo-cd/v3/util/config"
    12  )
    13  
    14  func ConstructApplicationSet(fileURL string) ([]*argoprojiov1alpha1.ApplicationSet, error) {
    15  	if fileURL != "" {
    16  		return constructAppsetFromFileURL(fileURL)
    17  	}
    18  	return nil, nil
    19  }
    20  
    21  func constructAppsetFromFileURL(fileURL string) ([]*argoprojiov1alpha1.ApplicationSet, error) {
    22  	appset := make([]*argoprojiov1alpha1.ApplicationSet, 0)
    23  	// read uri
    24  	err := readAppsetFromURI(fileURL, &appset)
    25  	if err != nil {
    26  		return nil, fmt.Errorf("error reading applicationset from file %s: %w", fileURL, err)
    27  	}
    28  
    29  	return appset, nil
    30  }
    31  
    32  func readAppsetFromURI(fileURL string, appset *[]*argoprojiov1alpha1.ApplicationSet) error {
    33  	readFilePayload := func() ([]byte, error) {
    34  		parsedURL, err := url.ParseRequestURI(fileURL)
    35  		if err != nil || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
    36  			return os.ReadFile(fileURL)
    37  		}
    38  		return config.ReadRemoteFile(fileURL)
    39  	}
    40  
    41  	yml, err := readFilePayload()
    42  	if err != nil {
    43  		return fmt.Errorf("error reading file payload: %w", err)
    44  	}
    45  
    46  	return readAppset(yml, appset)
    47  }
    48  
    49  func readAppset(yml []byte, appsets *[]*argoprojiov1alpha1.ApplicationSet) error {
    50  	yamls, err := kube.SplitYAMLToString(yml)
    51  	if err != nil {
    52  		return fmt.Errorf("error splitting YAML to string: %w", err)
    53  	}
    54  
    55  	for _, yml := range yamls {
    56  		var appset argoprojiov1alpha1.ApplicationSet
    57  		err = config.Unmarshal([]byte(yml), &appset)
    58  		if err != nil {
    59  			return fmt.Errorf("error unmarshalling appset: %w", err)
    60  		}
    61  		*appsets = append(*appsets, &appset)
    62  	}
    63  	// we reach here if there is no error found while reading the Application Set
    64  	return nil
    65  }