From d27823de5381e6fe3a1fa21f294890735b25f704 Mon Sep 17 00:00:00 2001 From: Aaron L Date: Wed, 9 Nov 2016 23:45:11 -0800 Subject: [PATCH] Add enum string parsing --- strmangle/strmangle.go | 15 +++++++++++++++ strmangle/strmangle_test.go | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/strmangle/strmangle.go b/strmangle/strmangle.go index 481318b..911ffdc 100644 --- a/strmangle/strmangle.go +++ b/strmangle/strmangle.go @@ -16,6 +16,8 @@ import ( var ( idAlphabet = []byte("abcdefghijklmnopqrstuvwxyz") smartQuoteRgx = regexp.MustCompile(`^(?i)"?[a-z_][_a-z0-9]*"?(\."?[_a-z][_a-z0-9]*"?)*(\.\*)?$`) + + rgxEnum = regexp.MustCompile(`^enum\((,?'[^']+')+\)$`) ) var uppercaseWords = map[string]struct{}{ @@ -574,3 +576,16 @@ func GenerateIgnoreTags(tags []string) string { return buf.String() } + +// ParseEnum takes a string that looks like: +// enum('one','two') and returns the strings one, two +func ParseEnum(s string) []string { + if !rgxEnum.MatchString(s) { + return nil + } + + s = strings.TrimPrefix(s, "enum('") + s = strings.TrimSuffix(s, "')") + + return strings.Split(s, "','") +} diff --git a/strmangle/strmangle_test.go b/strmangle/strmangle_test.go index 6d802d4..b9efe1e 100644 --- a/strmangle/strmangle_test.go +++ b/strmangle/strmangle_test.go @@ -1,6 +1,7 @@ package strmangle import ( + "fmt" "strings" "testing" ) @@ -513,3 +514,17 @@ func TestGenerateIgnoreTags(t *testing.T) { t.Errorf("expected %s, got %s", exp, tags) } } + +func TestParseEnum(t *testing.T) { + t.Parallel() + + vals := []string{"one", "two", "three"} + toParse := fmt.Sprintf("enum('%s')", strings.Join(vals, "','")) + + gotVals := ParseEnum(toParse) + for i, v := range vals { + if gotVals[i] != v { + t.Errorf("%d) want: %s, got %s", i, v, gotVals[i]) + } + } +}