github.com/docker/buildx@v0.14.1-0.20240514123050-afcb609966dc/store/util.go (about) 1 package store 2 3 import ( 4 "os" 5 "regexp" 6 "strings" 7 8 "github.com/docker/docker/pkg/namesgenerator" 9 "github.com/pkg/errors" 10 ) 11 12 var namePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9\.\-_]*$`) 13 14 type errInvalidName struct { 15 error 16 } 17 18 func (e *errInvalidName) Error() string { 19 return e.error.Error() 20 } 21 22 func (e *errInvalidName) Unwrap() error { 23 return e.error 24 } 25 26 func IsErrInvalidName(err error) bool { 27 _, ok := err.(*errInvalidName) 28 return ok 29 } 30 31 func ValidateName(s string) (string, error) { 32 if !namePattern.MatchString(s) { 33 return "", &errInvalidName{ 34 errors.Errorf("invalid name %s, name needs to start with a letter and may not contain symbols, except ._-", s), 35 } 36 } 37 return strings.ToLower(s), nil 38 } 39 40 func GenerateName(txn *Txn) (string, error) { 41 var name string 42 for i := 0; i < 6; i++ { 43 name = namesgenerator.GetRandomName(i) 44 if _, err := txn.NodeGroupByName(name); err != nil { 45 if !os.IsNotExist(errors.Cause(err)) { 46 return "", err 47 } 48 } else { 49 continue 50 } 51 return name, nil 52 } 53 return "", errors.Errorf("failed to generate random name") 54 }