Skip to content

Commit

Permalink
Add character aliases as CLI options (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
abice authored Sep 6, 2021
1 parent acf2ee0 commit b4be01e
Show file tree
Hide file tree
Showing 6 changed files with 134 additions and 18 deletions.
35 changes: 22 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ I took the output of the [Stringer](https://godoc.org/golang.org/x/tools/cmd/str

``` shell
go-enum --help

NAME:
go-enum - An enum generator for go

USAGE:
go-enum [global options] [arguments...]

VERSION:
x.y.z

GLOBAL OPTIONS:
--file value, -f value The file(s) to generate enums. Use more than one flag for more files.
--noprefix Prevents the constants generated from having the Enum as a prefix. (default: false)
Expand All @@ -40,7 +44,9 @@ GLOBAL OPTIONS:
--sqlnullint Adds a Null{{ENUM}} type for marshalling a nullable int value to sql (default: false)
--sqlnullstr Adds a Null{{ENUM}} type for marshalling a nullable string value to sql. If sqlnullint is specified too, it will be Null{{ENUM}}Str (default: false)
--template value, -t value Additional template file(s) to generate enums. Use more than one flag for more files. Templates will be executed in alphabetical order.
--alias value, -a value Adds or replaces aliases for a non alphanumeric value that needs to be accounted for. [Format should be "key:value,key2:value2", or specify multiple entries, or both!]
--help, -h show help (default: false)
--version, -v print the version (default: false)
```
### Syntax
Expand Down Expand Up @@ -108,8 +114,11 @@ type Color int32
The generated code will look something like:
``` go
// Code generated by go-enum
// DO NOT EDIT!
// Code generated by go-enum DO NOT EDIT.
// Version: example
// Revision: example
// Build Date: example
// Built By: example
package example
Expand All @@ -119,28 +128,28 @@ import (
)
const (
// ColorBlack is a Color of type Black
// ColorBlack is a Color of type Black.
ColorBlack Color = iota
// ColorWhite is a Color of type White
// ColorWhite is a Color of type White.
ColorWhite
// ColorRed is a Color of type Red
// ColorRed is a Color of type Red.
ColorRed
// ColorGreen is a Color of type Green
// ColorGreen is a Color of type Green.
// Green starts with 33
ColorGreen Color = iota + 30
// ColorBlue is a Color of type Blue
// ColorBlue is a Color of type Blue.
ColorBlue
// ColorGrey is a Color of type Grey
// ColorGrey is a Color of type Grey.
ColorGrey
// ColorYellow is a Color of type Yellow
// ColorYellow is a Color of type Yellow.
ColorYellow
// ColorBlueGreen is a Color of type Blue-Green
// ColorBlueGreen is a Color of type Blue-Green.
ColorBlueGreen
// ColorRedOrange is a Color of type Red-Orange
// ColorRedOrange is a Color of type Red-Orange.
ColorRedOrange
// ColorYellowGreen is a Color of type Yellow_green
// ColorYellowGreen is a Color of type Yellow_green.
ColorYellowGreen
// ColorRedOrangeBlue is a Color of type Red-Orange-Blue
// ColorRedOrangeBlue is a Color of type Red-Orange-Blue.
ColorRedOrangeBlue
)
Expand Down
4 changes: 3 additions & 1 deletion example/animal.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
//go:generate ../bin/go-enum -f=$GOFILE
//go:generate ../bin/go-enum -f=$GOFILE -a "+:Plus,#:Sharp"

package example

// Animal x ENUM(
// Cat,
// Dog,
// Fish
// Fish++
// Fish#
// )
type Animal int32
16 changes: 12 additions & 4 deletions example/animal_enum.go

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

30 changes: 30 additions & 0 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ 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 @@ -168,6 +172,28 @@ func (g *Generator) WithSQLNullStr() *Generator {
return g
}

// ParseAliases is used to add aliases to replace during name sanitization.
func ParseAliases(aliases []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)
}
aliasMap[parts[0]] = parts[1]
}
}

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

return nil
}

// WithTemplates is used to provide the filenames of additional templates.
func (g *Generator) WithTemplates(filenames ...string) *Generator {
for _, ut := range template.Must(g.t.ParseFiles(filenames...)).Templates() {
Expand Down Expand Up @@ -371,6 +397,10 @@ func sanitizeValue(value string) string {

name := value

for k, v := range replacementNames {
name = strings.ReplaceAll(name, k, v)
}

// If the start character is not a unicode letter (this check includes the case of '_')
// then we need to add an exported prefix, so tack on a 'X' at the beginning
if !(unicode.IsLetter(rune(name[0]))) {
Expand Down
56 changes: 56 additions & 0 deletions generator/generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,59 @@ func TestCustomPrefixExampleFile(t *testing.T) {
fmt.Println(string(imported))
}
}

func TestAliasParsing(t *testing.T) {
tests := map[string]struct {
input []string
resultingMap map[string]string
err error
}{
"no aliases": {
resultingMap: map[string]string{},
},
"multiple arrays": {
input: []string{
`!:Bang,a:a`,
`@:AT`,
`&:AND,|:OR`,
},
resultingMap: map[string]string{
"a": "a",
"!": "Bang",
"@": "AT",
"&": "AND",
"|": "OR",
},
},
"more types": {
input: []string{
`*:star,+:PLUS`,
`-:less`,
`#:HASH,!:Bang`,
},
resultingMap: map[string]string{
"*": "star",
"+": "PLUS",
"-": "less",
"#": "HASH",
"!": "Bang",
},
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
defer func() {
replacementNames = map[string]string{}
}()
err := ParseAliases(tc.input)
if tc.err != nil {
require.Error(t, err)
require.EqualError(t, err, tc.err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.resultingMap, replacementNames)
}
})
}
}
11 changes: 11 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type rootT struct {
SQLNullInt bool
Ptr bool
TemplateFileNames cli.StringSlice
Aliases cli.StringSlice
}

func main() {
Expand All @@ -49,6 +50,7 @@ func main() {
Name: "go-enum",
Usage: "An enum generator for go",
HideHelpCommand: true,
Version: version,
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "file",
Expand Down Expand Up @@ -123,8 +125,17 @@ func main() {
Usage: "Additional template file(s) to generate enums. Use more than one flag for more files. Templates will be executed in alphabetical order.",
Destination: &argv.TemplateFileNames,
},
&cli.StringSliceFlag{
Name: "alias",
Aliases: []string{"a"},
Usage: "Adds or replaces aliases for a non alphanumeric value that needs to be accounted for. [Format should be \"key:value,key2:value2\", or specify multiple entries, or both!]",
Destination: &argv.Aliases,
},
},
Action: func(ctx *cli.Context) error {
if err := generator.ParseAliases(argv.Aliases.Value()); err != nil {
return err
}
for _, fileOption := range argv.FileNames.Value() {

g := generator.NewGenerator()
Expand Down

0 comments on commit b4be01e

Please sign in to comment.