Skip to content

Commit

Permalink
kmsg: add EnumStrings(), ParseEnum() functions
Browse files Browse the repository at this point in the history
This should make it easier to list valid options for the string value of
an enum, as well as easier to parse a string into an enum.

The parsing is aggressive in what we accept by lowercasing and stripping
all dots and underscores. I expect most input to just match based off
lowercasing, but a stray _ shouldn't affect anything.
  • Loading branch information
twmb committed Sep 15, 2021
1 parent 2f676c0 commit 8216b7c
Show file tree
Hide file tree
Showing 3 changed files with 409 additions and 0 deletions.
46 changes: 46 additions & 0 deletions generate/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,52 @@ func (e Enum) WriteStringFunc(l *LineWriter) {
l.Write("}")
}

func (e Enum) WriteStringsFunc(l *LineWriter) {
l.Write("func %sStrings() []string {", e.Name)
l.Write("return []string{")
for _, v := range e.Values {
l.Write(`"%s",`, v.Word)
}
l.Write("}")
l.Write("}")
}

func (e Enum) WriteParseFunc(l *LineWriter) {
l.Write("// Parse%s normalizes the input s and returns", e.Name)
l.Write("// the value represented by the string.")
l.Write("//")
l.Write("// Normalizing works by stripping all dots and underscores,")
l.Write("// trimming spaces, and lowercasing.")
l.Write("func Parse%[1]s(s string) (%[1]s, error) {", e.Name)
l.Write("switch strnorm(s) {")
for _, v := range e.Values {
l.Write(`case "%s":`, strnorm(v.Word))
l.Write("return %d, nil", v.Value)
}
l.Write("default:")
l.Write(`return 0, fmt.Errorf("%s: unable to parse %%q", s)`, e.Name)
l.Write("}")
l.Write("}")
}

func strnorm(s string) string {
s = strings.ReplaceAll(s, ".", "")
s = strings.ReplaceAll(s, "_", "")
s = strings.TrimSpace(s)
s = strings.ToLower(s)
return s
}

func writeStrnorm(l *LineWriter) {
l.Write(`func strnorm(s string) string {`)
l.Write(`s = strings.ReplaceAll(s, ".", "")`)
l.Write(`s = strings.ReplaceAll(s, "_", "")`)
l.Write(`s = strings.TrimSpace(s)`)
l.Write(`s = strings.ToLower(s)`)
l.Write(`return s`)
l.Write(`}`)
}

func (e Enum) WriteConsts(l *LineWriter) {
l.Write("const (")
if !e.HasZero {
Expand Down
6 changes: 6 additions & 0 deletions generate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,8 @@ func main() {
l.Write("package kmsg")
l.Write("import (")
l.Write(`"context"`)
l.Write(`"fmt"`)
l.Write(`"strings"`)
l.Write(`"reflect"`)
l.Write("")
l.Write(`"github.com/twmb/franz-go/pkg/kmsg/internal/kbin"`)
Expand Down Expand Up @@ -507,8 +509,12 @@ func main() {
for _, e := range newEnums {
e.WriteDefn(l)
e.WriteStringFunc(l)
e.WriteStringsFunc(l)
e.WriteParseFunc(l)
e.WriteConsts(l)
}

writeStrnorm(l)

fmt.Println(l.buf.String())
}
Loading

0 comments on commit 8216b7c

Please sign in to comment.