Skip to content

Commit

Permalink
ts/ast: Add regexp Ident validator
Browse files Browse the repository at this point in the history
  • Loading branch information
sam boyer committed May 19, 2022
1 parent 555fcd2 commit c119b17
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,10 +444,15 @@ func orEnum(v cue.Value) ([]ts.Expr, error) {
return nil, valError(v, "typescript enums may only be generated from a disjunction of concrete strings or numbers")
}

id := ts.Ident(strings.Title(text))
if id.Validate() != nil {
return nil, valError(v, "title casing of enum member %q produces an invalid typescript identifier; memberNames must be explicitly given in @cuetsy attribute", text)
}

fields = append(fields, tsast.AssignExpr{
// Simple mapping of all enum values (which we are assuming are in
// lowerCamelCase) to corresponding CamelCase
Name: ts.Ident(strings.Title(text)),
Name: id,
Value: tsprintConcrete(dv),
})
}
Expand Down
16 changes: 16 additions & 0 deletions ts/ast/ast.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package ast

import (
"errors"
"fmt"
"regexp"
"strings"
)

Expand Down Expand Up @@ -96,6 +98,10 @@ type Ident struct {
As string
}

var identRegexp = regexp.MustCompile("^[a-zA-Z_$][0-9a-zA-Z_$]*$")

var ErrBadIdent = errors.New("typescript idents must contain only alphanumeric characters")

func (i Ident) ident() {}
func (i Ident) expr() {}
func (i Ident) String() string {
Expand All @@ -107,6 +113,16 @@ func (i Ident) String() string {
return n
}

func (i Ident) Validate() error {
if !identRegexp.MatchString(i.Name) {
return ErrBadIdent
}
if i.As != "" && !identRegexp.MatchString(i.Name) {
return ErrBadIdent
}
return nil
}

func None() Expr {
return Ident{}
}
Expand Down

0 comments on commit c119b17

Please sign in to comment.