...

Source file src/go.einride.tech/aip/reflect/aipreflect/resourcetype.go

Documentation: go.einride.tech/aip/reflect/aipreflect

     1  package aipreflect
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"unicode"
     7  	"unicode/utf8"
     8  )
     9  
    10  // ResourceType represents a resource type name.
    11  type ResourceType string // e.g. pubsub.googleapis.com/Topic.
    12  
    13  // Validate checks that the resource type name is syntactically valid.
    14  func (n ResourceType) Validate() error {
    15  	if strings.Count(string(n), "/") != 1 {
    16  		return fmt.Errorf("validate resource type name '%s': invalid format", n)
    17  	}
    18  	if err := validateServiceName(n.ServiceName()); err != nil {
    19  		return fmt.Errorf("validate resource type name '%s': %w", n, err)
    20  	}
    21  	if err := validateType(n.Type()); err != nil {
    22  		return fmt.Errorf("validate resource type name '%s': %w", n, err)
    23  	}
    24  	return nil
    25  }
    26  
    27  // ServiceName returns the service name of the resource type name.
    28  func (n ResourceType) ServiceName() string {
    29  	if i := strings.LastIndexByte(string(n), '/'); i >= 0 {
    30  		return string(n[:i])
    31  	}
    32  	return ""
    33  }
    34  
    35  // Type returns the type of the resource type name.
    36  func (n ResourceType) Type() string {
    37  	if i := strings.LastIndexByte(string(n), '/'); i >= 0 {
    38  		return string(n[i+1:])
    39  	}
    40  	return ""
    41  }
    42  
    43  func validateServiceName(serviceName string) error {
    44  	if serviceName == "" {
    45  		return fmt.Errorf("service name: empty")
    46  	}
    47  	if !strings.ContainsRune(serviceName, '.') {
    48  		return fmt.Errorf("service name: must be a valid domain name")
    49  	}
    50  	return nil
    51  }
    52  
    53  func validateType(t string) error {
    54  	if t == "" {
    55  		return fmt.Errorf("type: is empty")
    56  	}
    57  	if firstRune, _ := utf8.DecodeRuneInString(t); !unicode.IsUpper(firstRune) {
    58  		return fmt.Errorf("type: must start with an upper-case letter")
    59  	}
    60  	for _, r := range t {
    61  		if !unicode.In(r, unicode.Letter, unicode.Digit) {
    62  			return fmt.Errorf("type: must be UpperCamelCase")
    63  		}
    64  	}
    65  	return nil
    66  }
    67  

View as plain text