Skip to content

Commit

Permalink
Merge pull request #2 from muir/parsetag
Browse files Browse the repository at this point in the history
Parsetag
  • Loading branch information
muir committed Nov 3, 2021
2 parents a2ec61a + 7e33b26 commit 7f2142f
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
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)
}

0 comments on commit 7f2142f

Please sign in to comment.