Skip to content

Commit

Permalink
pass 0 to let go parse the base value (#229)
Browse files Browse the repository at this point in the history
  • Loading branch information
abice authored Dec 18, 2023
1 parent f2bc4fe commit 28240c6
Show file tree
Hide file tree
Showing 8 changed files with 202 additions and 28 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ fmt:
-$(GO) fmt ./...

test: gen-test generate
$(GO) test -v -race -coverprofile=coverage.out ./...
$(GO) test -v -race --tags=example ./example
$(GO) test -v -race -shuffle on -coverprofile=coverage.out ./...
$(GO) test -v -race -shuffle on --tags=example ./example

cover: gen-test test
$(GO) tool cover -html=coverage.out -o coverage.html
Expand Down
20 changes: 20 additions & 0 deletions example/diff_base.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package example

//go:generate ../bin/go-enum --forcelower -b example

/*
ENUM(
B3 = 03
B4 = 04
B5 = 5
B6 = 0b110
B7 = 0b111
B8 = 0x08
B9 = 0x09
B10 = 0x0B
B11 = 0x2B
)
*/
type DiffBase int
87 changes: 87 additions & 0 deletions example/diff_base_enum.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 60 additions & 0 deletions example/diff_base_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//go:build example
// +build example

package example

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestDiffBase(t *testing.T) {
tests := map[string]struct {
actual int
expected DiffBase
}{
"DiffBaseB3": {
actual: 3,
expected: DiffBaseB3,
},
"DiffBaseB4": {
actual: 4,
expected: DiffBaseB4,
},
"DiffBaseB5": {
actual: 5,
expected: DiffBaseB5,
},
"DiffBaseB6": {
actual: 6,
expected: DiffBaseB6,
},
"DiffBaseB7": {
actual: 7,
expected: DiffBaseB7,
},
"DiffBaseB8": {
actual: 8,
expected: DiffBaseB8,
},
"DiffBaseB9": {
actual: 9,
expected: DiffBaseB9,
},
"DiffBaseB10": {
actual: 11,
expected: DiffBaseB10,
},
"DiffBaseB11": {
actual: 43,
expected: DiffBaseB11,
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
assert.Equal(t, int(tc.expected), tc.actual)
})
}
}
35 changes: 20 additions & 15 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ const (
parseCommentPrefix = `//`
)

var replacementNames = map[string]string{}

// Generator is responsible for generating validation files for the given in a go source file.
type Generator struct {
Version string
Expand Down Expand Up @@ -56,6 +54,7 @@ type Generator struct {
forceUpper bool
noComments bool
buildTags []string
replacementNames map[string]string
}

// Enum holds data for a discovered enum in the parsed source
Expand Down Expand Up @@ -90,6 +89,7 @@ func NewGenerator() *Generator {
t: template.New("generator"),
fileSet: token.NewFileSet(),
noPrefix: false,
replacementNames: map[string]string{},
}

funcs := sprig.TxtFuncMap()
Expand Down Expand Up @@ -224,30 +224,35 @@ func (g *Generator) WithBuildTags(tags ...string) *Generator {
return g
}

// WithAliases will set up aliases for the generator.
func (g *Generator) WithAliases(aliases map[string]string) *Generator {
if aliases == nil {
return g
}
g.replacementNames = aliases
return g
}

func (g *Generator) anySQLEnabled() bool {
return g.sql || g.sqlNullStr || g.sqlint || g.sqlNullInt
}

// ParseAliases is used to add aliases to replace during name sanitization.
func ParseAliases(aliases []string) error {
func ParseAliases(aliases []string) (map[string]string, error) {
aliasMap := map[string]string{}

for _, str := range aliases {
kvps := strings.Split(str, ",")
for _, kvp := range kvps {
parts := strings.Split(kvp, ":")
if len(parts) != 2 {
return fmt.Errorf("invalid formatted alias entry %q, must be in the format \"key:value\"", kvp)
return nil, fmt.Errorf("invalid formatted alias entry %q, must be in the format \"key:value\"", kvp)
}
aliasMap[parts[0]] = parts[1]
}
}

for k, v := range aliasMap {
replacementNames[k] = v
}

return nil
return aliasMap, nil
}

// WithTemplates is used to provide the filenames of additional templates.
Expand Down Expand Up @@ -438,23 +443,23 @@ func (g *Generator) parseEnum(ts *ast.TypeSpec) (*Enum, error) {
valueStr = dataVal
rawName = value[:equalIndex]
if enum.Type == "string" {
if parsed, err := strconv.ParseInt(dataVal, 10, 64); err == nil {
if parsed, err := strconv.ParseInt(dataVal, 0, 64); err == nil {
data = parsed
valueStr = rawName
}
if isQuoted(dataVal) {
valueStr = trimQuotes(dataVal)
}
} else if unsigned {
newData, err := strconv.ParseUint(dataVal, 10, 64)
newData, err := strconv.ParseUint(dataVal, 0, 64)
if err != nil {
err = fmt.Errorf("failed parsing the data part of enum value '%s': %w", value, err)
fmt.Println(err)
return nil, err
}
data = newData
} else {
newData, err := strconv.ParseInt(dataVal, 10, 64)
newData, err := strconv.ParseInt(dataVal, 0, 64)
if err != nil {
err = fmt.Errorf("failed parsing the data part of enum value '%s': %w", value, err)
fmt.Println(err)
Expand All @@ -473,7 +478,7 @@ func (g *Generator) parseEnum(ts *ast.TypeSpec) (*Enum, error) {
prefixedName := name
if name != skipHolder {
prefixedName = enum.Prefix + name
prefixedName = sanitizeValue(prefixedName)
prefixedName = g.sanitizeValue(prefixedName)
if !g.leaveSnakeCase {
prefixedName = snakeToCamelCase(prefixedName)
}
Expand Down Expand Up @@ -526,14 +531,14 @@ func unescapeComment(comment string) string {
// identifier syntax as described here: https://golang.org/ref/spec#Identifiers
// identifier = letter { letter | unicode_digit }
// where letter can be unicode_letter or '_'
func sanitizeValue(value string) string {
func (g *Generator) sanitizeValue(value string) string {
// Keep skip value holders
if value == skipHolder {
return skipHolder
}

replacedValue := value
for k, v := range replacementNames {
for k, v := range g.replacementNames {
replacedValue = strings.ReplaceAll(replacedValue, k, v)
}

Expand Down
11 changes: 5 additions & 6 deletions generator/generator_1.18_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,10 +217,7 @@ func Test118AliasParsing(t *testing.T) {

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
defer func() {
replacementNames = map[string]string{}
}()
err := ParseAliases(tc.input)
replacementNames, err := ParseAliases(tc.input)
if tc.err != nil {
require.Error(t, err)
require.EqualError(t, err, tc.err.Error())
Expand Down Expand Up @@ -306,9 +303,11 @@ func Test118Aliasing(t *testing.T) {
// ENUM(a,b,CDEF) with some extra text
type Animal int
`
aliases, err := ParseAliases([]string{"CDEF:C"})
require.NoError(t, err)
g := NewGenerator().
WithoutSnakeToCamel()
_ = ParseAliases([]string{"CDEF:C"})
WithoutSnakeToCamel().
WithAliases(aliases)
f, err := parser.ParseFile(g.fileSet, "TestRequiredErrors", input, parser.ParseComments)
assert.Nil(t, err, "Error parsing no struct input")

Expand Down
9 changes: 5 additions & 4 deletions generator/generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,7 @@ func TestAliasParsing(t *testing.T) {

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
replacementNames = map[string]string{}
err := ParseAliases(tc.input)
replacementNames, err := ParseAliases(tc.input)
if tc.err != nil {
require.Error(t, err)
require.EqualError(t, err, tc.err.Error())
Expand Down Expand Up @@ -327,9 +326,11 @@ func TestAliasing(t *testing.T) {
// ENUM(a,b,CDEF) with some extra text
type Animal int
`
aliases, err := ParseAliases([]string{"CDEF:C"})
require.NoError(t, err)
g := NewGenerator().
WithoutSnakeToCamel()
_ = ParseAliases([]string{"CDEF:C"})
WithoutSnakeToCamel().
WithAliases(aliases)
f, err := parser.ParseFile(g.fileSet, "TestRequiredErrors", input, parser.ParseComments)
assert.Nil(t, err, "Error parsing no struct input")

Expand Down
4 changes: 3 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,8 @@ func main() {
},
},
Action: func(ctx *cli.Context) error {
if err := generator.ParseAliases(argv.Aliases.Value()); err != nil {
aliases, err := generator.ParseAliases(argv.Aliases.Value())
if err != nil {
return err
}
for _, fileOption := range argv.FileNames.Value() {
Expand All @@ -188,6 +189,7 @@ func main() {
g.BuiltBy = builtBy

g.WithBuildTags(argv.BuildTags.Value()...)
g.WithAliases(aliases)

if argv.NoPrefix {
g.WithNoPrefix()
Expand Down

0 comments on commit 28240c6

Please sign in to comment.