This commit is contained in:
Yannick Briffa 2018-03-07 14:16:44 +00:00 committed by GitHub
commit 705c9a8c24
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 9 deletions

View File

@ -72,6 +72,7 @@ The `-type` flag accepts a comma-separated list of types so a single run can
generate methods for multiple types. The default output file is t_jsonenums.go, generate methods for multiple types. The default output file is t_jsonenums.go,
where t is the lower-cased name of the first type listed. The suffix can be where t is the lower-cased name of the first type listed. The suffix can be
overridden with the `-suffix` flag and a prefix may be added with the `-prefix` overridden with the `-suffix` flag and a prefix may be added with the `-prefix`
flag. flag. The `-lower` flag sets the values of the enums in lower case while the `-upper`
sets it in upper case.
This is not an official Google product (experimental or otherwise), it is just code that happens to be owned by Google. This is not an official Google product (experimental or otherwise), it is just code that happens to be owned by Google.

View File

@ -88,9 +88,12 @@ import (
) )
var ( var (
typeNames = flag.String("type", "", "comma-separated list of type names; must be set") typeNames = flag.String("type", "", "comma-separated list of type names; must be set")
outputPrefix = flag.String("prefix", "", "prefix to be added to the output file") outputLower = flag.Bool("lower", false, "set the json enum values to lower case")
outputSuffix = flag.String("suffix", "_jsonenums", "suffix to be added to the output file") outputUpper = flag.Bool("upper", false, "set the json enum values to upper case")
outputNoStringer = flag.Bool("no-stringer", false, "disable the usage of stringer if exists")
outputPrefix = flag.String("prefix", "", "prefix to be added to the output file")
outputSuffix = flag.String("suffix", "_jsonenums", "suffix to be added to the output file")
) )
func main() { func main() {
@ -100,6 +103,10 @@ func main() {
} }
types := strings.Split(*typeNames, ",") types := strings.Split(*typeNames, ",")
if *outputLower && *outputUpper {
log.Fatal("cannot -upper and -lower in the same time")
}
// Only one directory at a time can be processed, and the default is ".". // Only one directory at a time can be processed, and the default is ".".
dir := "." dir := "."
if args := flag.Args(); len(args) == 1 { if args := flag.Args(); len(args) == 1 {
@ -122,10 +129,16 @@ func main() {
Command string Command string
PackageName string PackageName string
TypesAndValues map[string][]string TypesAndValues map[string][]string
Lower bool
Upper bool
NoStringer bool
}{ }{
Command: strings.Join(os.Args[1:], " "), Command: strings.Join(os.Args[1:], " "),
PackageName: pkg.Name, PackageName: pkg.Name,
TypesAndValues: make(map[string][]string), TypesAndValues: make(map[string][]string),
Lower: *outputLower,
Upper: *outputUpper,
NoStringer: *outputNoStringer,
} }
// Run generate for each type. // Run generate for each type.

View File

@ -15,9 +15,15 @@
package main package main
import "text/template" import (
"strings"
"text/template"
)
var generatedTmpl = template.Must(template.New("generated").Parse(` var generatedTmpl = template.Must(template.New("generated").Funcs(template.FuncMap{
"toLower": strings.ToLower,
"toUpper": strings.ToUpper,
}).Parse(`
// generated by jsonenums {{.Command}}; DO NOT EDIT // generated by jsonenums {{.Command}}; DO NOT EDIT
package {{.PackageName}} package {{.PackageName}}
@ -27,20 +33,24 @@ import (
"fmt" "fmt"
) )
{{ $upper := .Upper}}
{{ $lower := .Lower}}
{{ $noStringer := .NoStringer }}
{{range $typename, $values := .TypesAndValues}} {{range $typename, $values := .TypesAndValues}}
var ( var (
_{{$typename}}NameToValue = map[string]{{$typename}} { _{{$typename}}NameToValue = map[string]{{$typename}} {
{{range $values}}"{{.}}": {{.}}, {{range $values}}"{{ if $lower }}{{ toLower . }}{{ else if $upper }}{{ toUpper .}}{{ else }}{{.}}{{end}}": {{.}},
{{end}} {{end}}
} }
_{{$typename}}ValueToName = map[{{$typename}}]string { _{{$typename}}ValueToName = map[{{$typename}}]string {
{{range $values}}{{.}}: "{{.}}", {{range $values}}{{.}}: "{{ if $lower }}{{ toLower . }}{{ else if $upper }}{{ toUpper .}}{{ else }}{{.}}{{end}}",
{{end}} {{end}}
} }
) )
{{ if not $noStringer }}
func init() { func init() {
var v {{$typename}} var v {{$typename}}
if _, ok := interface{}(v).(fmt.Stringer); ok { if _, ok := interface{}(v).(fmt.Stringer); ok {
@ -50,13 +60,15 @@ func init() {
} }
} }
} }
{{ end }}
// MarshalJSON is generated so {{$typename}} satisfies json.Marshaler. // MarshalJSON is generated so {{$typename}} satisfies json.Marshaler.
func (r {{$typename}}) MarshalJSON() ([]byte, error) { func (r {{$typename}}) MarshalJSON() ([]byte, error) {
{{ if not $noStringer -}}
if s, ok := interface{}(r).(fmt.Stringer); ok { if s, ok := interface{}(r).(fmt.Stringer); ok {
return json.Marshal(s.String()) return json.Marshal(s.String())
} }
s, ok := _{{$typename}}ValueToName[r] {{ end }}s, ok := _{{$typename}}ValueToName[r]
if !ok { if !ok {
return nil, fmt.Errorf("invalid {{$typename}}: %d", r) return nil, fmt.Errorf("invalid {{$typename}}: %d", r)
} }