Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parsetag #2

Merged
merged 2 commits into from Nov 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 36 additions & 0 deletions parsetag.go
@@ -0,0 +1,36 @@
package reflectutils

import (
"reflect"
"regexp"
)

var aTagRE = regexp.MustCompile(`(\S+):"((?:[^"\\]|\\.)*)"(?:\s+|$)`)

type Tag struct {
Tag string
Value string
}

// SplitTag breaks apart a reflect.StructTag into an array of key/value pairs.
func SplitTag(tag reflect.StructTag) []Tag {
found := make([]Tag, 0, 5)
s := string(tag)
for len(s) > 0 {
f := aTagRE.FindStringSubmatchIndex(s)
if len(f) != 6 {
break
}
tag := s[f[2]:f[3]]
value := s[f[4]:f[5]]
found = append(found, Tag{
Tag: tag,
Value: value,
})
s = s[f[1]:]
}
if len(found) == 0 {
return nil
}
return found
}
31 changes: 31 additions & 0 deletions parsetag_test.go
@@ -0,0 +1,31 @@
package reflectutils_test

import (
"reflect"
"testing"

"github.com/muir/reflectutils"

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

func TestSplitTag(t *testing.T) {
ts(t, `env:"foo"`, "env", "foo")
ts(t, `env:"YO" flag:"foo,bar"`, "env", "YO", "flag", "foo,bar")
ts(t, ``)
ts(t, `env:"YO" flag:"foo\",bar"`, "env", "YO", "flag", `foo\",bar`)
ts(t, `env:"YO" flag:"foo,bar" `, "env", "YO", "flag", "foo,bar")
}

func ts(t *testing.T, tag reflect.StructTag, want ...string) {
t.Log(tag)
tags := reflectutils.SplitTag(tag)
s := make([]string, 0, len(tags)*2)
if len(tags) == 0 {
s = nil
}
for _, tag := range tags {
s = append(s, tag.Tag, tag.Value)
}
assert.Equal(t, want, s, tag)
}