Skip to content

Commit

Permalink
Prevent struct names from containing invalid characters (#44).
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h committed Apr 14, 2018
1 parent b396960 commit 3f9ff84
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 9 deletions.
4 changes: 4 additions & 0 deletions cmd/schema-generate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func main() {
}
if len(inputFiles) == 0 {
fmt.Fprintln(os.Stderr, "No input JSON Schema files.")
flag.Usage()
os.Exit(1)
}

Expand Down Expand Up @@ -138,6 +139,9 @@ func getOrderedStructNames(m map[string]generate.Struct) []string {
return keys
}

type _123ABC struct {
}

func output(w io.Writer, structs map[string]generate.Struct, aliases map[string]generate.Field) {
fmt.Fprintln(w, "// Code generated by schema-generate. DO NOT EDIT.")
fmt.Fprintln(w)
Expand Down
21 changes: 12 additions & 9 deletions generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"path"
"sort"
"strings"
"unicode"

"github.com/a-h/generate/jsonschema"
)
Expand Down Expand Up @@ -379,19 +380,23 @@ func getTypeName(reference *url.URL, structType *jsonschema.Schema, n int) strin
func getGolangName(s string) string {
buf := bytes.NewBuffer([]byte{})

for _, v := range splitOnAll(s, '_', ' ', '.', '-', ':') {
for i, v := range splitOnAll(s, isNotAGoNameCharacter) {
if i == 0 && strings.IndexAny(v, "0123456789") == 0 {
// Go types are not allowed to start with a number, lets prefix with an underscore.
buf.WriteRune('_')
}
buf.WriteString(capitaliseFirstLetter(v))
}

return buf.String()
}

func splitOnAll(s string, splitItems ...rune) []string {
func splitOnAll(s string, shouldSplit func(r rune) bool) []string {
rv := []string{}

buf := bytes.NewBuffer([]byte{})
for _, c := range s {
if matches(c, splitItems) {
if shouldSplit(c) {
rv = append(rv, buf.String())
buf.Reset()
} else {
Expand All @@ -405,13 +410,11 @@ func splitOnAll(s string, splitItems ...rune) []string {
return rv
}

func matches(c rune, any []rune) bool {
for _, a := range any {
if a == c {
return true
}
func isNotAGoNameCharacter(r rune) bool {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
return false
}
return false
return true
}

func capitaliseFirstLetter(s string) string {
Expand Down
10 changes: 10 additions & 0 deletions generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,16 @@ func TestThatJavascriptKeyNamesCanBeConvertedToValidGoNames(t *testing.T) {
input: "a:b",
expected: "AB",
},
{
description: "GT and LT are stripped.",
input: "a<b>",
expected: "AB",
},
{
description: "Not allowed to start with a number.",
input: "123ABC",
expected: "_123ABC",
},
}

for _, test := range tests {
Expand Down

0 comments on commit 3f9ff84

Please sign in to comment.