Skip to content

Commit

Permalink
patch,tests: logic extract and unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
liov committed Sep 18, 2020
1 parent 50cb961 commit a1b3afb
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 13 deletions.
30 changes: 17 additions & 13 deletions patch/patcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,24 +533,28 @@ func (p *Patcher) patchIdent(id *ast.Ident, obj types.Object) {
v.Tag = &ast.BasicLit{}
}

//tag override
oldTags := strings.Split(strings.TrimSpace(strings.Trim(v.Tag.Value, "` ")), " ")
var newTags []string
for _, tag := range oldTags {
var key string
if kv := strings.Split(tag, ":"); len(kv) > 0 {
key = kv[0]
}
if _, exist := reflect.StructTag(tags).Lookup(key); !exist {
newTags = append(newTags, tag)
}
}
v.Tag.Value = "`" + strings.Join(append(oldTags[:len(oldTags)-1], tags), " ") + "`"
v.Tag.Value = "`" + mergeTags(v.Tag.Value, tags) + "`"
log.Printf("Add tags:\t%q.%s %s", obj.Pkg().Path(), id.Name, v.Tag.Value)
}
}
}

// Override tags
func mergeTags(oldTag, newTag string) string {
oldTags := strings.Split(strings.TrimSpace(strings.Trim(oldTag, "` ")), " ")
var newTags []string
for _, tag := range oldTags {
var key string
if kv := strings.Split(tag, ":"); len(kv) > 0 {
key = kv[0]
}
if value, exist := reflect.StructTag(newTag).Lookup(key); !exist || value == "" {
newTags = append(newTags, tag)
}
}
return strings.Join(append(newTags, newTag), " ")
}

func (p *Patcher) patchComments(id *ast.Ident, repl string) {
doc, comment := p.findCommentGroups(id)
if doc == nil && comment == nil {
Expand Down
43 changes: 43 additions & 0 deletions patch/patcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package patch

import (
"testing"
)

func TestMergeTags(t *testing.T) {
tests := []struct {
name string
in [2]string
want string
}{
{ name:"NotOverrideTag",
in: [2]string{
`json:"code;omitempty"`,
`test:"test"`,
},
want: `json:"code;omitempty" test:"test"`,
},
{ name:"OverrideSingleTag",
in: [2]string{
`json:"code;omitempty"`,
`json:"-" test:"test"`,
},
want: `json:"-" test:"test"`,
},
{ name:"OverrideMultiTag",
in: [2]string{
`json:"code;omitempty" test1:"test""`,
`test1:"test1" test2:"test2"`,
},
want: `json:"code;omitempty" test1:"test1" test2:"test2"`,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := mergeTags(test.in[0], test.in[1]); got != test.want {
t.Fatalf(" got: %s\nwant: %s\n", got, test.want)
}
})
}
}

0 comments on commit a1b3afb

Please sign in to comment.