github.com/mutagen-io/mutagen@v0.18.0-rc1/pkg/selection/names.go (about)

     1  package selection
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"unicode"
     7  
     8  	"github.com/google/uuid"
     9  )
    10  
    11  // EnsureNameValid ensures that a name is valid for use as a session name. Empty
    12  // names are treated as valid.
    13  func EnsureNameValid(name string) error {
    14  	// Loop over the string and ensure that its characters are allowed. We allow
    15  	// letters, numbers, and dashses, but we require that the identifier starts
    16  	// with a letter. We disallow underscores to avoid colliding with internal
    17  	// identifiers. If a name contains dashes, then we enforce that it isn't a
    18  	// UUID to avoid collisions with legacy session identifiers.
    19  	var containsDash bool
    20  	for i, r := range name {
    21  		if unicode.IsLetter(r) {
    22  			continue
    23  		} else if i == 0 {
    24  			return errors.New("name does not start with Unicode letter")
    25  		} else if unicode.IsNumber(r) {
    26  			continue
    27  		} else if r == '-' {
    28  			containsDash = true
    29  			continue
    30  		}
    31  		return fmt.Errorf("invalid name character at index %d: '%c'", i, r)
    32  	}
    33  
    34  	// If the name contains a dash, then ensure that it isn't a UUID.
    35  	if containsDash {
    36  		if _, err := uuid.Parse(name); err == nil {
    37  			return errors.New("name must not be a UUID")
    38  		}
    39  	}
    40  
    41  	// Disallow "defaults" as a name since it is used as a special key in YAML
    42  	// files.
    43  	if name == "defaults" {
    44  		return errors.New(`"defaults" is disallowed as a name`)
    45  	}
    46  
    47  	// Success.
    48  	return nil
    49  }