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

     1  package utils
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  
     7  	"sigs.k8s.io/yaml"
     8  )
     9  
    10  // SanitizeName sanitizes the name in accordance with the below rules
    11  // 1. contain no more than 253 characters
    12  // 2. contain only lowercase alphanumeric characters, '-' or '.'
    13  // 3. start and end with an alphanumeric character
    14  func SanitizeName(name string) string {
    15  	invalidDNSNameChars := regexp.MustCompile("[^-a-z0-9.]")
    16  	maxDNSNameLength := 253
    17  
    18  	name = strings.ToLower(name)
    19  	name = invalidDNSNameChars.ReplaceAllString(name, "-")
    20  	if len(name) > maxDNSNameLength {
    21  		name = name[:maxDNSNameLength]
    22  	}
    23  
    24  	return strings.Trim(name, "-.")
    25  }
    26  
    27  // This has been copied from helm and may be removed as soon as it is retrofited in sprig
    28  // toYAML takes an interface, marshals it to yaml, and returns a string. It will
    29  // always return a string, even on marshal error (empty string).
    30  //
    31  // This is designed to be called from a template.
    32  func toYAML(v any) (string, error) {
    33  	data, err := yaml.Marshal(v)
    34  	if err != nil {
    35  		// Swallow errors inside of a template.
    36  		return "", err
    37  	}
    38  	return strings.TrimSuffix(string(data), "\n"), nil
    39  }
    40  
    41  // This has been copied from helm and may be removed as soon as it is retrofited in sprig
    42  // fromYAML converts a YAML document into a map[string]any.
    43  //
    44  // This is not a general-purpose YAML parser, and will not parse all valid
    45  // YAML documents. Additionally, because its intended use is within templates
    46  // it tolerates errors. It will insert the returned error message string into
    47  // m["Error"] in the returned map.
    48  func fromYAML(str string) (map[string]any, error) {
    49  	m := map[string]any{}
    50  
    51  	if err := yaml.Unmarshal([]byte(str), &m); err != nil {
    52  		return nil, err
    53  	}
    54  	return m, nil
    55  }
    56  
    57  // This has been copied from helm and may be removed as soon as it is retrofited in sprig
    58  // fromYAMLArray converts a YAML array into a []any.
    59  //
    60  // This is not a general-purpose YAML parser, and will not parse all valid
    61  // YAML documents. Additionally, because its intended use is within templates
    62  // it tolerates errors. It will insert the returned error message string as
    63  // the first and only item in the returned array.
    64  func fromYAMLArray(str string) ([]any, error) {
    65  	a := []any{}
    66  
    67  	if err := yaml.Unmarshal([]byte(str), &a); err != nil {
    68  		return nil, err
    69  	}
    70  	return a, nil
    71  }