Skip to content

Commit

Permalink
Add support for changing default tag name
Browse files Browse the repository at this point in the history
  • Loading branch information
tiendc committed Sep 22, 2024
1 parent 7adf730 commit 10ace32
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
18 changes: 16 additions & 2 deletions deepcopy.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@ package deepcopy
import (
"fmt"
"reflect"
"strings"
"sync"
)

const (
// DefaultTagName default tag name for the program to parse input struct tags
// to build copier configuration.
DefaultTagName = "copy"
)

var (
// defaultTagName default tag name for the program to parse input struct tags
// to build copier configuration.
defaultTagName = DefaultTagName
)

// Context copier context
type Context struct {
// CopyBetweenPtrAndValue allow or not copying between pointers and values (default is `true`)
Expand Down Expand Up @@ -116,3 +121,12 @@ func ClearCache() {
copierCacheMap = map[cacheKey]copier{}
mu.Unlock()
}

// SetDefaultTagName overwrites the default tag name.
// This function should only be called once at program startup.
func SetDefaultTagName(tag string) {
tagName := strings.TrimSpace(tag)
if tagName != "" && tagName == tag {
defaultTagName = tagName
}
}
10 changes: 10 additions & 0 deletions deepcopy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,13 @@ func Test_ConfigOption(t *testing.T) {
UseGlobalCache(true)(ctx)
assert.Equal(t, true, ctx.UseGlobalCache)
}

func Test_SetDefaultTagName(t *testing.T) {
assert.Equal(t, DefaultTagName, defaultTagName)
// Invalid one
SetDefaultTagName(" abc")
assert.Equal(t, DefaultTagName, defaultTagName)
// Valid one
SetDefaultTagName("abc")
assert.Equal(t, "abc", defaultTagName)
}
2 changes: 1 addition & 1 deletion struct_tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (detail *fieldDetail) markDone() {

// parseTag parses struct tag for getting copying detail and configuration
func parseTag(detail *fieldDetail) {
tagValue, ok := detail.field.Tag.Lookup(DefaultTagName)
tagValue, ok := detail.field.Tag.Lookup(defaultTagName)
detail.key = detail.field.Name
if !ok {
return
Expand Down

0 comments on commit 10ace32

Please sign in to comment.