...

Source file src/go.einride.tech/aip/resourceid/usersettable.go

Documentation: go.einride.tech/aip/resourceid

     1  package resourceid
     2  
     3  import (
     4  	"fmt"
     5  	"unicode"
     6  
     7  	"github.com/google/uuid"
     8  )
     9  
    10  // ValidateUserSettable validates a user-settable resource ID.
    11  //
    12  // From https://google.aip.dev/122#resource-id-segments:
    13  //
    14  // User-settable resource IDs should conform to RFC-1034; which restricts to letters, numbers, and hyphen,
    15  // with the first character a letter, the last a letter or a number, and a 63 character maximum.
    16  // Additionally, user-settable resource IDs should restrict letters to lower-case.
    17  //
    18  // User-settable IDs should not be permitted to be a UUID (or any value that syntactically appears to be a UUID).
    19  //
    20  // See also: https://google.aip.dev/133#user-specified-ids
    21  func ValidateUserSettable(id string) error {
    22  	if len(id) < 4 || 63 < len(id) {
    23  		return fmt.Errorf("user-settable ID must be between 4 and 63 characters")
    24  	}
    25  	if !unicode.IsLetter(rune(id[0])) {
    26  		return fmt.Errorf("user-settable ID must begin with a letter")
    27  	}
    28  	if id[len(id)-1] == '-' {
    29  		return fmt.Errorf("user-settable ID must end with a letter or number")
    30  	}
    31  	if _, err := uuid.Parse(id); err == nil {
    32  		return fmt.Errorf("user-settable ID must not be a valid UUIDv4")
    33  	}
    34  	for position, character := range id {
    35  		switch character {
    36  		case
    37  			// numbers
    38  			'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    39  			// hyphen
    40  			'-',
    41  			// lower-case
    42  			'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    43  			'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z':
    44  		default:
    45  			return fmt.Errorf(
    46  				"user-settable ID must only contain lowercase, numbers and hyphens (got: '%c' in position %d)",
    47  				character,
    48  				position,
    49  			)
    50  		}
    51  	}
    52  	return nil
    53  }
    54  

View as plain text