github.com/giantswarm/apiextensions/v2@v2.6.2/pkg/id/id.go (about)

     1  package id
     2  
     3  import (
     4  	"math/rand"
     5  	"regexp"
     6  	"strconv"
     7  	"time"
     8  )
     9  
    10  const (
    11  	// IDChars represents the character set used to generate cluster IDs.
    12  	// (does not contain 1 and l, to avoid confusion)
    13  	IDChars = "023456789abcdefghijkmnopqrstuvwxyz"
    14  	// IDLength represents the number of characters used to create a cluster ID.
    15  	IDLength = 5
    16  )
    17  
    18  func Generate() string {
    19  	compiledRegexp, _ := regexp.Compile("^[a-z]+$")
    20  
    21  	for {
    22  		letterRunes := []rune(IDChars)
    23  		b := make([]rune, IDLength)
    24  		rand.Seed(time.Now().UnixNano())
    25  		for i := range b {
    26  			b[i] = letterRunes[rand.Intn(len(letterRunes))]
    27  		}
    28  
    29  		id := string(b)
    30  
    31  		if _, err := strconv.Atoi(id); err == nil {
    32  			// ID is made up of numbers only, which we want to avoid.
    33  			continue
    34  		}
    35  
    36  		matched := compiledRegexp.MatchString(id)
    37  		if matched {
    38  			// ID is made up of letters only, which we also avoid.
    39  			continue
    40  		}
    41  
    42  		return id
    43  	}
    44  }