feat(Go-StudyExample):2021/02/09:新增merge源码阅读和单测代码

This commit is contained in:
Huangzj
2021-02-09 16:00:31 +08:00
parent 05f55b0eac
commit cf02f0bf10
51 changed files with 3712 additions and 1 deletions
+3 -1
View File
@@ -4,4 +4,6 @@ container源码分析文章:https://blog.csdn.net/qq_34326321/article/details/
copier源码分析文章:https://blog.csdn.net/qq_34326321/article/details/112177087 copier源码分析文章:https://blog.csdn.net/qq_34326321/article/details/112177087
mapstructure源码分析文章:https://blog.csdn.net/qq_34326321/article/details/113182689 mapstructure源码分析文章:https://blog.csdn.net/qq_34326321/article/details/113182689
merge源码分析文章:https://blog.csdn.net/qq_34326321/article/details/113182689
@@ -0,0 +1,4 @@
# These are supported funding model platforms
ko_fi: dariocc
custom: https://beerpay.io/imdario/mergo
@@ -0,0 +1,33 @@
#### joe made this: http://goel.io/joe
#### go ####
# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/
#### vim ####
# Swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]
# Session
Session.vim
# Temporary
.netrwhist
*~
# Auto-generated tag files
tags
@@ -0,0 +1,9 @@
language: go
install:
- go get -t
- go get golang.org/x/tools/cmd/cover
- go get github.com/mattn/goveralls
script:
- go test -race -v ./...
after_script:
- $HOME/gopath/bin/goveralls -service=travis-ci -repotoken $COVERALLS_TOKEN
@@ -0,0 +1,7 @@
{
"go.lintTool": "golangci-lint",
"go.lintFlags": [
"--enable-all",
"--disable=gomnd"
]
}
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at i@dario.im. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
@@ -0,0 +1,28 @@
Copyright (c) 2013 Dario Castañé. All rights reserved.
Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,247 @@
# Mergo
[![GoDoc][3]][4]
[![GitHub release][5]][6]
[![GoCard][7]][8]
[![Build Status][1]][2]
[![Coverage Status][9]][10]
[![Sourcegraph][11]][12]
[![FOSSA Status][13]][14]
[![GoCenter Kudos][15]][16]
[1]: https://travis-ci.org/imdario/mergo.png
[2]: https://travis-ci.org/imdario/mergo
[3]: https://godoc.org/github.com/imdario/mergo?status.svg
[4]: https://godoc.org/github.com/imdario/mergo
[5]: https://img.shields.io/github/release/imdario/mergo.svg
[6]: https://github.com/imdario/mergo/releases
[7]: https://goreportcard.com/badge/imdario/mergo
[8]: https://goreportcard.com/report/github.com/imdario/mergo
[9]: https://coveralls.io/repos/github/imdario/mergo/badge.svg?branch=master
[10]: https://coveralls.io/github/imdario/mergo?branch=master
[11]: https://sourcegraph.com/github.com/imdario/mergo/-/badge.svg
[12]: https://sourcegraph.com/github.com/imdario/mergo?badge
[13]: https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=shield
[14]: https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield
[15]: https://search.gocenter.io/api/ui/badge/github.com%2Fimdario%2Fmergo
[16]: https://search.gocenter.io/github.com/imdario/mergo
A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements.
Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection).
Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region of Marche.
## Status
It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc](https://github.com/imdario/mergo#mergo-in-the-wild).
### Important note
Please keep in mind that a problematic PR broke [0.3.9](//github.com/imdario/mergo/releases/tag/0.3.9). I reverted it in [0.3.10](//github.com/imdario/mergo/releases/tag/0.3.10), and I consider it stable but not bug-free. Also, this version adds suppot for go modules.
Keep in mind that in [0.3.2](//github.com/imdario/mergo/releases/tag/0.3.2), Mergo changed `Merge()`and `Map()` signatures to support [transformers](#transformers). I added an optional/variadic argument so that it won't break the existing code.
If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with ```go get -u github.com/imdario/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
### Donations
If Mergo is useful to you, consider buying me a coffee, a beer, or making a monthly donation to allow me to keep building great free software. :heart_eyes:
<a href='https://ko-fi.com/B0B58839' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://az743702.vo.msecnd.net/cdn/kofi1.png?v=0' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>
[![Beerpay](https://beerpay.io/imdario/mergo/badge.svg)](https://beerpay.io/imdario/mergo)
[![Beerpay](https://beerpay.io/imdario/mergo/make-wish.svg)](https://beerpay.io/imdario/mergo)
<a href="https://liberapay.com/dario/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a>
### Mergo in the wild
- [moby/moby](https://github.com/moby/moby)
- [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes)
- [vmware/dispatch](https://github.com/vmware/dispatch)
- [Shopify/themekit](https://github.com/Shopify/themekit)
- [imdario/zas](https://github.com/imdario/zas)
- [matcornic/hermes](https://github.com/matcornic/hermes)
- [OpenBazaar/openbazaar-go](https://github.com/OpenBazaar/openbazaar-go)
- [kataras/iris](https://github.com/kataras/iris)
- [michaelsauter/crane](https://github.com/michaelsauter/crane)
- [go-task/task](https://github.com/go-task/task)
- [sensu/uchiwa](https://github.com/sensu/uchiwa)
- [ory/hydra](https://github.com/ory/hydra)
- [sisatech/vcli](https://github.com/sisatech/vcli)
- [dairycart/dairycart](https://github.com/dairycart/dairycart)
- [projectcalico/felix](https://github.com/projectcalico/felix)
- [resin-os/balena](https://github.com/resin-os/balena)
- [go-kivik/kivik](https://github.com/go-kivik/kivik)
- [Telefonica/govice](https://github.com/Telefonica/govice)
- [supergiant/supergiant](supergiant/supergiant)
- [SergeyTsalkov/brooce](https://github.com/SergeyTsalkov/brooce)
- [soniah/dnsmadeeasy](https://github.com/soniah/dnsmadeeasy)
- [ohsu-comp-bio/funnel](https://github.com/ohsu-comp-bio/funnel)
- [EagerIO/Stout](https://github.com/EagerIO/Stout)
- [lynndylanhurley/defsynth-api](https://github.com/lynndylanhurley/defsynth-api)
- [russross/canvasassignments](https://github.com/russross/canvasassignments)
- [rdegges/cryptly-api](https://github.com/rdegges/cryptly-api)
- [casualjim/exeggutor](https://github.com/casualjim/exeggutor)
- [divshot/gitling](https://github.com/divshot/gitling)
- [RWJMurphy/gorl](https://github.com/RWJMurphy/gorl)
- [andrerocker/deploy42](https://github.com/andrerocker/deploy42)
- [elwinar/rambler](https://github.com/elwinar/rambler)
- [tmaiaroto/gopartman](https://github.com/tmaiaroto/gopartman)
- [jfbus/impressionist](https://github.com/jfbus/impressionist)
- [Jmeyering/zealot](https://github.com/Jmeyering/zealot)
- [godep-migrator/rigger-host](https://github.com/godep-migrator/rigger-host)
- [Dronevery/MultiwaySwitch-Go](https://github.com/Dronevery/MultiwaySwitch-Go)
- [thoas/picfit](https://github.com/thoas/picfit)
- [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server)
- [jnuthong/item_search](https://github.com/jnuthong/item_search)
- [bukalapak/snowboard](https://github.com/bukalapak/snowboard)
- [janoszen/containerssh](https://github.com/janoszen/containerssh)
## Install
go get github.com/imdario/mergo
// use in your .go code
import (
"github.com/imdario/mergo"
)
## Usage
You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as [they are zero values](https://golang.org/ref/spec#The_zero_value) too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection).
```go
if err := mergo.Merge(&dst, src); err != nil {
// ...
}
```
Also, you can merge overwriting values using the transformer `WithOverride`.
```go
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
// ...
}
```
Additionally, you can map a `map[string]interface{}` to a struct (and otherwise, from struct to map), following the same restrictions as in `Merge()`. Keys are capitalized to find each corresponding exported field.
```go
if err := mergo.Map(&dst, srcMap); err != nil {
// ...
}
```
Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as `map[string]interface{}`. They will be just assigned as values.
Here is a nice example:
```go
package main
import (
"fmt"
"github.com/imdario/mergo"
)
type Foo struct {
A string
B int64
}
func main() {
src := Foo{
A: "one",
B: 2,
}
dest := Foo{
A: "two",
}
mergo.Merge(&dest, src)
fmt.Println(dest)
// Will print
// {two 2}
}
```
Note: if test are failing due missing package, please execute:
go get gopkg.in/yaml.v2
### Transformers
Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, `time.Time` is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero `time.Time`?
```go
package main
import (
"fmt"
"github.com/imdario/mergo"
"reflect"
"time"
)
type timeTransformer struct {
}
func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
if typ == reflect.TypeOf(time.Time{}) {
return func(dst, src reflect.Value) error {
if dst.CanSet() {
isZero := dst.MethodByName("IsZero")
result := isZero.Call([]reflect.Value{})
if result[0].Bool() {
dst.Set(src)
}
}
return nil
}
}
return nil
}
type Snapshot struct {
Time time.Time
// ...
}
func main() {
src := Snapshot{time.Now()}
dest := Snapshot{}
mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{}))
fmt.Println(dest)
// Will print
// { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 }
}
```
## Contact me
If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): [@im_dario](https://twitter.com/im_dario)
## About
Written by [Dario Castañé](http://dario.im).
## Top Contributors
[![0](https://sourcerer.io/fame/imdario/imdario/mergo/images/0)](https://sourcerer.io/fame/imdario/imdario/mergo/links/0)
[![1](https://sourcerer.io/fame/imdario/imdario/mergo/images/1)](https://sourcerer.io/fame/imdario/imdario/mergo/links/1)
[![2](https://sourcerer.io/fame/imdario/imdario/mergo/images/2)](https://sourcerer.io/fame/imdario/imdario/mergo/links/2)
[![3](https://sourcerer.io/fame/imdario/imdario/mergo/images/3)](https://sourcerer.io/fame/imdario/imdario/mergo/links/3)
[![4](https://sourcerer.io/fame/imdario/imdario/mergo/images/4)](https://sourcerer.io/fame/imdario/imdario/mergo/links/4)
[![5](https://sourcerer.io/fame/imdario/imdario/mergo/images/5)](https://sourcerer.io/fame/imdario/imdario/mergo/links/5)
[![6](https://sourcerer.io/fame/imdario/imdario/mergo/images/6)](https://sourcerer.io/fame/imdario/imdario/mergo/links/6)
[![7](https://sourcerer.io/fame/imdario/imdario/mergo/images/7)](https://sourcerer.io/fame/imdario/imdario/mergo/links/7)
## License
[BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE).
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large)
+143
View File
@@ -0,0 +1,143 @@
// Copyright 2013 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements.
Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection).
Status
It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc.
Important note
Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules.
Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code.
If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u github.com/imdario/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
Install
Do your usual installation procedure:
go get github.com/imdario/mergo
// use in your .go code
import (
"github.com/imdario/mergo"
)
Usage
You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection).
if err := mergo.Merge(&dst, src); err != nil {
// ...
}
Also, you can merge overwriting values using the transformer WithOverride.
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
// ...
}
Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field.
if err := mergo.Map(&dst, srcMap); err != nil {
// ...
}
Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values.
Here is a nice example:
package main
import (
"fmt"
"github.com/imdario/mergo"
)
type Foo struct {
A string
B int64
}
func main() {
src := Foo{
A: "one",
B: 2,
}
dest := Foo{
A: "two",
}
mergo.Merge(&dest, src)
fmt.Println(dest)
// Will print
// {two 2}
}
Transformers
Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time?
package main
import (
"fmt"
"github.com/imdario/mergo"
"reflect"
"time"
)
type timeTransformer struct {
}
func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
if typ == reflect.TypeOf(time.Time{}) {
return func(dst, src reflect.Value) error {
if dst.CanSet() {
isZero := dst.MethodByName("IsZero")
result := isZero.Call([]reflect.Value{})
if result[0].Bool() {
dst.Set(src)
}
}
return nil
}
}
return nil
}
type Snapshot struct {
Time time.Time
// ...
}
func main() {
src := Snapshot{time.Now()}
dest := Snapshot{}
mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{}))
fmt.Println(dest)
// Will print
// { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 }
}
Contact me
If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario
About
Written by Dario Castañé: https://da.rio.hn
License
BSD 3-Clause license, as Go language.
*/
package mergo
@@ -0,0 +1,5 @@
module github.com/imdario/mergo
go 1.13
require gopkg.in/yaml.v2 v2.3.0
@@ -0,0 +1,4 @@
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
@@ -0,0 +1,21 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type issue100s struct {
Member interface{}
}
func TestIssue100(t *testing.T) {
m := make(map[string]interface{})
m["Member"] = "anything"
st := &issue100s{}
if err := mergo.Map(st, m); err != nil {
t.Error(err)
}
}
@@ -0,0 +1,48 @@
package mergo_test
import (
"reflect"
"testing"
"github.com/imdario/mergo"
)
type Record struct {
Data map[string]interface{}
Mapping map[string]string
}
func StructToRecord(in interface{}) *Record {
rec := Record{}
rec.Data = make(map[string]interface{})
rec.Mapping = make(map[string]string)
typ := reflect.TypeOf(in)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
dbFieldName := field.Tag.Get("db")
if dbFieldName != "" {
rec.Mapping[field.Name] = dbFieldName
}
}
if err := mergo.Map(&rec.Data, in); err != nil {
panic(err)
}
return &rec
}
func TestStructToRecord(t *testing.T) {
type A struct {
Name string `json:"name" db:"name"`
CIDR string `json:"cidr" db:"cidr"`
}
type Record struct {
Data map[string]interface{}
Mapping map[string]string
}
a := A{Name: "David", CIDR: "10.0.0.0/8"}
rec := StructToRecord(a)
if len(rec.Mapping) < 2 {
t.Fatalf("struct to record failed, no mapping, struct missing tags?, rec: %+v, a: %+v ", rec, a)
}
}
@@ -0,0 +1,35 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
func TestIssue121WithSliceDeepCopy(t *testing.T) {
dst := map[string]interface{}{
"inter": map[string]interface{}{
"a": "1",
"b": "2",
},
}
src := map[string]interface{}{
"inter": map[string]interface{}{
"a": "3",
"c": "4",
},
}
if err := mergo.Merge(&dst, src, mergo.WithSliceDeepCopy); err != nil {
t.Errorf("Error during the merge: %v", err)
}
if dst["inter"].(map[string]interface{})["a"].(string) != "3" {
t.Error("inter.a should equal '3'")
}
if dst["inter"].(map[string]interface{})["c"].(string) != "4" {
t.Error("inter.c should equal '4'")
}
}
@@ -0,0 +1,47 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
func TestIssue123(t *testing.T) {
src := map[string]interface{}{
"col1": nil,
"col2": 4,
"col3": nil,
}
dst := map[string]interface{}{
"col1": 2,
"col2": 3,
"col3": 3,
}
// Expected behavior
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
t.Fatal(err)
}
testCases := []struct {
key string
expected interface{}
}{
{
"col1",
nil,
},
{
"col2",
4,
},
{
"col3",
nil,
},
}
for _, tC := range testCases {
if dst[tC.key] != tC.expected {
t.Fatalf("expected %v in dst[%q], got %v", tC.expected, tC.key, dst[tC.key])
}
}
}
@@ -0,0 +1,40 @@
package mergo_test
import (
"encoding/json"
"testing"
"github.com/imdario/mergo"
)
type settings struct {
FirstSlice []string `json:"FirstSlice"`
SecondSlice []string `json:"SecondSlice"`
}
func TestIssue125MergeWithOverwrite(t *testing.T) {
var (
defaultSettings = settings{
FirstSlice: []string{},
SecondSlice: []string{},
}
something settings
data = `{"FirstSlice":[], "SecondSlice": null}`
)
if err := json.Unmarshal([]byte(data), &something); err != nil {
t.Errorf("Error while Unmarshalling maprequest: %s", err)
}
if err := mergo.Merge(&something, defaultSettings, mergo.WithOverrideEmptySlice); err != nil {
t.Errorf("Error while merging: %s", err)
}
if something.FirstSlice == nil {
t.Error("Invalid merging first slice")
}
if something.SecondSlice == nil {
t.Error("Invalid merging second slice")
}
}
@@ -0,0 +1,49 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
func TestIssue129Boolean(t *testing.T) {
type Foo struct {
A bool
B bool
}
src := Foo{
A: true,
B: false,
}
dst := Foo{
A: false,
B: true,
}
// Standard behavior
if err := mergo.Merge(&dst, src); err != nil {
t.Error(err)
}
if dst.A != true {
t.Errorf("expected true, got false")
}
if dst.B != true {
t.Errorf("expected true, got false")
}
// Expected behavior
dst = Foo{
A: false,
B: true,
}
if err := mergo.Merge(&dst, src, mergo.WithOverwriteWithEmptyValue); err != nil {
t.Error(err)
}
if dst.A != true {
t.Errorf("expected true, got false")
}
if dst.B != false {
t.Errorf("expected false, got true")
}
}
@@ -0,0 +1,32 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type foz struct {
A *bool
B string
}
func TestIssue131MergeWithOverwriteWithEmptyValue(t *testing.T) {
src := foz{
A: func(v bool) *bool { return &v }(false),
B: "src",
}
dest := foz{
A: func(v bool) *bool { return &v }(true),
B: "dest",
}
if err := mergo.Merge(&dest, src, mergo.WithOverwriteWithEmptyValue); err != nil {
t.Error(err)
}
if *src.A != *dest.A {
t.Errorf("dest.A not merged in properly: %v != %v", *src.A, *dest.A)
}
if src.B != dest.B {
t.Errorf("dest.B not merged in properly: %v != %v", src.B, dest.B)
}
}
@@ -0,0 +1,35 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type embeddedTestA struct {
Name string
Age uint8
}
type embeddedTestB struct {
embeddedTestA
Address string
}
func TestMergeEmbedded(t *testing.T) {
var (
err error
a = &embeddedTestA{
"Suwon", 16,
}
b = &embeddedTestB{}
)
if err := mergo.Merge(&b.embeddedTestA, *a); err != nil {
t.Error(err)
}
if b.Name != "Suwon" {
t.Errorf("%v %v", b.Name, err)
}
}
@@ -0,0 +1,42 @@
package mergo_test
import (
"encoding/json"
"testing"
"github.com/imdario/mergo"
)
const issue138configuration string = `
{
"Port": 80
}
`
func TestIssue138(t *testing.T) {
type config struct {
Port uint16
}
type compatibleConfig struct {
Port float64
}
foo := make(map[string]interface{})
// encoding/json unmarshals numbers as float64
// https://golang.org/pkg/encoding/json/#Unmarshal
json.Unmarshal([]byte(issue138configuration), &foo)
err := mergo.Map(&config{}, foo)
if err == nil {
t.Error("expected type mismatch error, got nil")
} else {
if err.Error() != "type mismatch on Port field: found float64, expected uint16" {
t.Errorf("expected type mismatch error, got %q", err)
}
}
c := compatibleConfig{}
if err := mergo.Map(&c, foo); err != nil {
t.Error(err)
}
}
@@ -0,0 +1,61 @@
package mergo_test
import (
"fmt"
"testing"
"github.com/imdario/mergo"
)
func TestIssue143(t *testing.T) {
testCases := []struct {
options []func(*mergo.Config)
expected func(map[string]interface{}) error
}{
{
options: []func(*mergo.Config){mergo.WithOverride},
expected: func(m map[string]interface{}) error {
properties := m["properties"].(map[string]interface{})
if properties["field1"] != "wrong" {
return fmt.Errorf("expected %q, got %v", "wrong", properties["field1"])
}
return nil
},
},
{
options: []func(*mergo.Config){},
expected: func(m map[string]interface{}) error {
properties := m["properties"].(map[string]interface{})
if properties["field1"] == "wrong" {
return fmt.Errorf("expected a map, got %v", "wrong")
}
return nil
},
},
}
for _, tC := range testCases {
base := map[string]interface{}{
"properties": map[string]interface{}{
"field1": map[string]interface{}{
"type": "text",
},
},
}
err := mergo.Map(
&base,
map[string]interface{}{
"properties": map[string]interface{}{
"field1": "wrong",
},
},
tC.options...,
)
if err != nil {
t.Error(err)
}
if err := tC.expected(base); err != nil {
t.Error(err)
}
}
}
@@ -0,0 +1,39 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type user struct {
Name string
}
type token struct {
User *user
Token *string
}
func TestIssue149(t *testing.T) {
dest := &token{
User: &user{
Name: "destination",
},
Token: nil,
}
tokenValue := "Issue149"
src := &token{
User: nil,
Token: &tokenValue,
}
if err := mergo.Merge(dest, src, mergo.WithOverwriteWithEmptyValue); err != nil {
t.Error(err)
}
if dest.User != nil {
t.Errorf("expected nil User, got %q", dest.User)
}
if dest.Token == nil {
t.Errorf("expected not nil Token, got %q", *dest.Token)
}
}
@@ -0,0 +1,28 @@
package mergo_test
import (
"encoding/json"
"testing"
"github.com/imdario/mergo"
)
func TestIssue17MergeWithOverwrite(t *testing.T) {
var (
request = `{"timestamp":null, "name": "foo"}`
maprequest = map[string]interface{}{
"timestamp": nil,
"name": "foo",
"newStuff": "foo",
}
)
var something map[string]interface{}
if err := json.Unmarshal([]byte(request), &something); err != nil {
t.Errorf("Error while Unmarshalling maprequest: %s", err)
}
if err := mergo.MergeWithOverwrite(&something, maprequest); err != nil {
t.Errorf("Error while merging: %s", err)
}
}
@@ -0,0 +1,31 @@
package mergo_test
import (
"testing"
"time"
"github.com/imdario/mergo"
)
type document struct {
Created *time.Time
}
func TestIssue23MergeWithOverwrite(t *testing.T) {
now := time.Now()
dst := document{
&now,
}
expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
src := document{
&expected,
}
if err := mergo.MergeWithOverwrite(&dst, src); err != nil {
t.Errorf("Error while merging %s", err)
}
if !dst.Created.Equal(*src.Created) { //--> https://golang.org/pkg/time/#pkg-overview
t.Errorf("Created not merged in properly: dst.Created(%v) != src.Created(%v)", dst.Created, src.Created)
}
}
@@ -0,0 +1,37 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type Foo struct {
Str string
Bslice []byte
}
func TestIssue33Merge(t *testing.T) {
dest := Foo{Str: "a"}
toMerge := Foo{
Str: "b",
Bslice: []byte{1, 2},
}
if err := mergo.Merge(&dest, toMerge); err != nil {
t.Errorf("Error while merging: %s", err)
}
// Merge doesn't overwrite an attribute if in destination it doesn't have a zero value.
// In this case, Str isn't a zero value string.
if dest.Str != "a" {
t.Errorf("dest.Str should have not been override as it has a non-zero value: dest.Str(%v) != 'a'", dest.Str)
}
// If we want to override, we must use MergeWithOverwrite or Merge using WithOverride.
if err := mergo.Merge(&dest, toMerge, mergo.WithOverride); err != nil {
t.Errorf("Error while merging: %s", err)
}
if dest.Str != toMerge.Str {
t.Errorf("dest.Str should have been override: dest.Str(%v) != toMerge.Str(%v)", dest.Str, toMerge.Str)
}
}
@@ -0,0 +1,67 @@
package mergo_test
import (
"testing"
"time"
"github.com/imdario/mergo"
)
type structWithoutTimePointer struct {
Created time.Time
}
func TestIssue38Merge(t *testing.T) {
dst := structWithoutTimePointer{
time.Now(),
}
expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
src := structWithoutTimePointer{
expected,
}
if err := mergo.Merge(&dst, src); err != nil {
t.Errorf("Error while merging %s", err)
}
if dst.Created == src.Created {
t.Errorf("Created merged unexpectedly: dst.Created(%v) == src.Created(%v)", dst.Created, src.Created)
}
}
func TestIssue38MergeEmptyStruct(t *testing.T) {
dst := structWithoutTimePointer{}
expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
src := structWithoutTimePointer{
expected,
}
if err := mergo.Merge(&dst, src); err != nil {
t.Errorf("Error while merging %s", err)
}
if dst.Created == src.Created {
t.Errorf("Created merged unexpectedly: dst.Created(%v) == src.Created(%v)", dst.Created, src.Created)
}
}
func TestIssue38MergeWithOverwrite(t *testing.T) {
dst := structWithoutTimePointer{
time.Now(),
}
expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
src := structWithoutTimePointer{
expected,
}
if err := mergo.MergeWithOverwrite(&dst, src); err != nil {
t.Errorf("Error while merging %s", err)
}
if dst.Created != src.Created {
t.Errorf("Created not merged in properly: dst.Created(%v) != src.Created(%v)", dst.Created, src.Created)
}
}
@@ -0,0 +1,21 @@
package mergo_test
import (
"testing"
"time"
"github.com/imdario/mergo"
)
type testStruct struct {
time.Duration
}
func TestIssue50Merge(t *testing.T) {
to := testStruct{}
from := testStruct{}
if err := mergo.Merge(&to, from); err != nil {
t.Fail()
}
}
@@ -0,0 +1,113 @@
package mergo_test
import (
"reflect"
"testing"
"time"
"github.com/imdario/mergo"
)
type structWithTime struct {
Birth time.Time
}
type timeTransfomer struct {
overwrite bool
}
func (t timeTransfomer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
if typ == reflect.TypeOf(time.Time{}) {
return func(dst, src reflect.Value) error {
if dst.CanSet() {
if t.overwrite {
isZero := src.MethodByName("IsZero")
result := isZero.Call([]reflect.Value{})
if !result[0].Bool() {
dst.Set(src)
}
} else {
isZero := dst.MethodByName("IsZero")
result := isZero.Call([]reflect.Value{})
if result[0].Bool() {
dst.Set(src)
}
}
}
return nil
}
}
return nil
}
func TestOverwriteZeroSrcTime(t *testing.T) {
now := time.Now()
dst := structWithTime{now}
src := structWithTime{}
if err := mergo.MergeWithOverwrite(&dst, src); err != nil {
t.FailNow()
}
if !dst.Birth.IsZero() {
t.Errorf("dst should have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
}
}
func TestOverwriteZeroSrcTimeWithTransformer(t *testing.T) {
now := time.Now()
dst := structWithTime{now}
src := structWithTime{}
if err := mergo.MergeWithOverwrite(&dst, src, mergo.WithTransformers(timeTransfomer{true})); err != nil {
t.FailNow()
}
if dst.Birth.IsZero() {
t.Errorf("dst should not have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
}
}
func TestOverwriteZeroDstTime(t *testing.T) {
now := time.Now()
dst := structWithTime{}
src := structWithTime{now}
if err := mergo.MergeWithOverwrite(&dst, src); err != nil {
t.FailNow()
}
if dst.Birth.IsZero() {
t.Errorf("dst should have been overwritten: dst.Birth(%v) != zero(%v)", dst.Birth, time.Time{})
}
}
func TestZeroDstTime(t *testing.T) {
now := time.Now()
dst := structWithTime{}
src := structWithTime{now}
if err := mergo.Merge(&dst, src); err != nil {
t.FailNow()
}
if !dst.Birth.IsZero() {
t.Errorf("dst should not have been overwritten: dst.Birth(%v) != zero(%v)", dst.Birth, time.Time{})
}
}
func TestZeroDstTimeWithTransformer(t *testing.T) {
now := time.Now()
dst := structWithTime{}
src := structWithTime{now}
if err := mergo.Merge(&dst, src, mergo.WithTransformers(timeTransfomer{})); err != nil {
t.FailNow()
}
if dst.Birth.IsZero() {
t.Errorf("dst should have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
}
}
@@ -0,0 +1,24 @@
package mergo_test
import (
"reflect"
"testing"
"github.com/imdario/mergo"
)
func TestIssue61MergeNilMap(t *testing.T) {
type T struct {
I map[string][]string
}
t1 := T{}
t2 := T{I: map[string][]string{"hi": {"there"}}}
if err := mergo.Merge(&t1, t2); err != nil {
t.Fail()
}
if !reflect.DeepEqual(t2, T{I: map[string][]string{"hi": {"there"}}}) {
t.FailNow()
}
}
@@ -0,0 +1,46 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type Student struct {
Name string
Books []string
}
type issue64TestData struct {
S1 Student
S2 Student
ExpectedSlice []string
}
func issue64Data() []issue64TestData {
return []issue64TestData{
{Student{"Jack", []string{"a", "B"}}, Student{"Tom", []string{"1"}}, []string{"a", "B"}},
{Student{"Jack", []string{"a", "B"}}, Student{"Tom", []string{}}, []string{"a", "B"}},
{Student{"Jack", []string{}}, Student{"Tom", []string{"1"}}, []string{"1"}},
{Student{"Jack", []string{}}, Student{"Tom", []string{}}, []string{}},
}
}
func TestIssue64MergeSliceWithOverride(t *testing.T) {
for _, data := range issue64Data() {
err := mergo.Merge(&data.S2, data.S1, mergo.WithOverride)
if err != nil {
t.Errorf("Error while merging %s", err)
}
if len(data.S2.Books) != len(data.ExpectedSlice) {
t.Errorf("Got %d elements in slice, but expected %d", len(data.S2.Books), len(data.ExpectedSlice))
}
for i, val := range data.S2.Books {
if val != data.ExpectedSlice[i] {
t.Errorf("Expected %s, but got %s while merging slice with override", data.ExpectedSlice[i], val)
}
}
}
}
@@ -0,0 +1,56 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type PrivateSliceTest66 struct {
PublicStrings []string
privateStrings []string
}
func TestPrivateSlice(t *testing.T) {
p1 := PrivateSliceTest66{
PublicStrings: []string{"one", "two", "three"},
privateStrings: []string{"four", "five"},
}
p2 := PrivateSliceTest66{
PublicStrings: []string{"six", "seven"},
}
if err := mergo.Merge(&p1, p2); err != nil {
t.Errorf("Error during the merge: %v", err)
}
if len(p1.PublicStrings) != 3 {
t.Error("3 elements should be in 'PublicStrings' field, when no append")
}
if len(p1.privateStrings) != 2 {
t.Error("2 elements should be in 'privateStrings' field")
}
}
func TestPrivateSliceWithAppendSlice(t *testing.T) {
p1 := PrivateSliceTest66{
PublicStrings: []string{"one", "two", "three"},
privateStrings: []string{"four", "five"},
}
p2 := PrivateSliceTest66{
PublicStrings: []string{"six", "seven"},
}
if err := mergo.Merge(&p1, p2, mergo.WithAppendSlice); err != nil {
t.Errorf("Error during the merge: %v", err)
}
if len(p1.PublicStrings) != 5 {
t.Error("5 elements should be in 'PublicStrings' field")
}
if len(p1.privateStrings) != 2 {
t.Error("2 elements should be in 'privateStrings' field")
}
}
@@ -0,0 +1,22 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type issue83My struct {
Data []int
}
func TestIssue83(t *testing.T) {
dst := issue83My{Data: []int{1, 2, 3}}
new := issue83My{}
if err := mergo.Merge(&dst, new, mergo.WithOverwriteWithEmptyValue); err != nil {
t.Error(err)
}
if len(dst.Data) > 0 {
t.Errorf("expected empty slice, got %v", dst.Data)
}
}
@@ -0,0 +1,90 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type DstStructIssue84 struct {
A int
B int
C int
}
type DstNestedStructIssue84 struct {
A struct {
A int
B int
C int
}
B int
C int
}
func TestIssue84MergeMapWithNilValueToStructWithOverride(t *testing.T) {
p1 := DstStructIssue84{
A: 0, B: 1, C: 2,
}
p2 := map[string]interface{}{
"A": 3, "B": 4, "C": 0,
}
if err := mergo.Map(&p1, p2, mergo.WithOverride); err != nil {
t.Errorf("Error during the merge: %v", err)
}
if p1.C != 0 {
t.Error("C field should become '0'")
}
}
func TestIssue84MergeMapWithoutKeyExistsToStructWithOverride(t *testing.T) {
p1 := DstStructIssue84{
A: 0, B: 1, C: 2,
}
p2 := map[string]interface{}{
"A": 3, "B": 4,
}
if err := mergo.Map(&p1, p2, mergo.WithOverride); err != nil {
t.Errorf("Error during the merge: %v", err)
}
if p1.C != 2 {
t.Error("C field should be '2'")
}
}
func TestIssue84MergeNestedMapWithNilValueToStructWithOverride(t *testing.T) {
p1 := DstNestedStructIssue84{
A: struct {
A int
B int
C int
}{A: 1, B: 2, C: 0},
B: 0,
C: 2,
}
p2 := map[string]interface{}{
"A": map[string]interface{}{
"A": 0, "B": 0, "C": 5,
}, "B": 4, "C": 0,
}
if err := mergo.Map(&p1, p2, mergo.WithOverride); err != nil {
t.Errorf("Error during the merge: %v", err)
}
if p1.B != 4 {
t.Error("A.C field should become '4'")
}
if p1.A.C != 5 {
t.Error("A.C field should become '5'")
}
if p1.A.B != 0 || p1.A.A != 0 {
t.Error("A.A and A.B field should become '0'")
}
}
@@ -0,0 +1,57 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
func TestIssue89Boolean(t *testing.T) {
type Foo struct {
Bar bool `json:"bar"`
}
src := Foo{Bar: true}
dst := Foo{Bar: false}
if err := mergo.Merge(&dst, src); err != nil {
t.Error(err)
}
if dst.Bar == false {
t.Errorf("expected true, got false")
}
}
func TestIssue89MergeWithEmptyValue(t *testing.T) {
p1 := map[string]interface{}{
"A": 3, "B": "note", "C": true,
}
p2 := map[string]interface{}{
"B": "", "C": false,
}
if err := mergo.Merge(&p1, p2, mergo.WithOverwriteWithEmptyValue); err != nil {
t.Error(err)
}
testCases := []struct {
key string
expected interface{}
}{
{
"A",
3,
},
{
"B",
"",
},
{
"C",
false,
},
}
for _, tC := range testCases {
if p1[tC.key] != tC.expected {
t.Errorf("expected %v in p1[%q], got %v", tC.expected, tC.key, p1[tC.key])
}
}
}
@@ -0,0 +1,37 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
var testDataS = []struct {
S1 Student
S2 Student
ExpectedSlice []string
}{
{Student{"Jack", []string{"a", "B"}}, Student{"Tom", []string{"1"}}, []string{"1", "a", "B"}},
{Student{"Jack", []string{"a", "B"}}, Student{"Tom", []string{}}, []string{"a", "B"}},
{Student{"Jack", []string{}}, Student{"Tom", []string{"1"}}, []string{"1"}},
{Student{"Jack", []string{}}, Student{"Tom", []string{}}, []string{}},
}
func TestMergeSliceWithOverrideWithAppendSlice(t *testing.T) {
for _, data := range testDataS {
err := mergo.Merge(&data.S2, data.S1, mergo.WithOverride, mergo.WithAppendSlice)
if err != nil {
t.Errorf("Error while merging %s", err)
}
if len(data.S2.Books) != len(data.ExpectedSlice) {
t.Errorf("Got %d elements in slice, but expected %d", len(data.S2.Books), len(data.ExpectedSlice))
}
for i, val := range data.S2.Books {
if val != data.ExpectedSlice[i] {
t.Errorf("Expected %s, but got %s while merging slice with override", data.ExpectedSlice[i], val)
}
}
}
}
+196
View File
@@ -0,0 +1,196 @@
// Copyright 2014 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on src/pkg/reflect/deepequal.go from official
// golang's stdlib.
package mergo
import (
"fmt"
"reflect"
"unicode"
"unicode/utf8"
)
func changeInitialCase(s string, mapper func(rune) rune) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(mapper(r)) + s[n:]
}
func isExported(field reflect.StructField) bool {
r, _ := utf8.DecodeRuneInString(field.Name)
return r >= 'A' && r <= 'Z'
}
// Traverses recursively both values, assigning src's fields values to dst.
// The map argument tracks comparisons that have already been seen, which allows
// short circuiting on recursive types.
func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) {
overwrite := config.Overwrite
//read note 同样是防止循环包含的处理
if dst.CanAddr() {
addr := dst.UnsafeAddr()
h := 17 * addr
seen := visited[h]
typ := dst.Type()
for p := seen; p != nil; p = p.next {
if p.ptr == addr && p.typ == typ {
return nil
}
}
// Remember, remember...
visited[h] = &visit{addr, typ, seen}
}
//read note 这边只会处理 map 、struct 、ptr
zeroValue := reflect.Value{}
switch dst.Kind() {
case reflect.Map:
dstMap := dst.Interface().(map[string]interface{})
//read note 遍历被merge的结构体的所有Field
for i, n := 0, src.NumField(); i < n; i++ {
srcType := src.Type()
field := srcType.Field(i)
if !isExported(field) {
continue
}
//read note map的key设置成小写开头
fieldName := field.Name
fieldName = changeInitialCase(fieldName, unicode.ToLower)
if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v)) || overwrite) {
dstMap[fieldName] = src.Field(i).Interface()
}
}
//read note ptr的处理和struct类似,不过这边要转换一个Value值
case reflect.Ptr:
if dst.IsNil() {
v := reflect.New(dst.Type().Elem())
dst.Set(v)
}
dst = dst.Elem()
fallthrough
case reflect.Struct:
srcMap := src.Interface().(map[string]interface{})
//read note 遍历被merge的map
for key := range srcMap {
config.overwriteWithEmptyValue = true
srcValue := srcMap[key]
//read note map key的首字母要大写
fieldName := changeInitialCase(key, unicode.ToUpper)
dstElement := dst.FieldByName(fieldName)
//read note Field不存在的处理
if dstElement == zeroValue {
// We discard it because the field doesn't exist.
continue
}
//read note dst和src结构体Value、kind的处理
srcElement := reflect.ValueOf(srcValue)
dstKind := dstElement.Kind()
srcKind := srcElement.Kind()
if srcKind == reflect.Ptr && dstKind != reflect.Ptr {
srcElement = srcElement.Elem()
srcKind = reflect.TypeOf(srcElement.Interface()).Kind()
} else if dstKind == reflect.Ptr {
// Can this work? I guess it can't.
if srcKind != reflect.Ptr && srcElement.CanAddr() {
srcPtr := srcElement.Addr()
srcElement = reflect.ValueOf(srcPtr)
srcKind = reflect.Ptr
}
}
if !srcElement.IsValid() {
continue
}
if srcKind == dstKind {
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface {
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else if srcKind == reflect.Map {
if err = deepMap(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else {
return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind)
}
}
}
return
}
// Map sets fields' values in dst from src.
// src can be a map with string keys or a struct. dst must be the opposite:
// if src is a map, dst must be a valid pointer to struct. If src is a struct,
// dst must be map[string]interface{}.
// It won't merge unexported (private) fields and will do recursively
// any exported field.
// If dst is a map, keys will be src fields' names in lower camel case.
// Missing key in src that doesn't match a field in dst will be skipped. This
// doesn't apply if dst is a map.
// This is separated method from Merge because it is cleaner and it keeps sane
// semantics: merging equal types, mapping different (restricted) types.
func Map(dst, src interface{}, opts ...func(*Config)) error {
return _map(dst, src, opts...)
}
// MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overridden by
// non-empty src attribute values.
// Deprecated: Use Map(…) with WithOverride
func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error {
return _map(dst, src, append(opts, WithOverride)...)
}
func _map(dst, src interface{}, opts ...func(*Config)) error {
//read note dst和src的类型判断
if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr {
return ErrNonPointerAgument
}
var (
vDst, vSrc reflect.Value
err error
)
config := &Config{}
for _, opt := range opts {
opt(config)
}
//read note 处理获取对应值
if vDst, vSrc, err = resolveValues(dst, src); err != nil {
return err
}
// To be friction-less, we redirect equal-type arguments
// to deepMerge. Only because arguments can be anything.
//read note 如果类型相同则直接调用deepMerge即可
if vSrc.Kind() == vDst.Kind() {
return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config)
}
//read note map转struct 或者 struct转map,其他情况都是错误的.
switch vSrc.Kind() {
case reflect.Struct:
if vDst.Kind() != reflect.Map {
return ErrExpectedMapAsDestination
}
case reflect.Map:
if vDst.Kind() != reflect.Struct {
return ErrExpectedStructAsDestination
}
default:
return ErrNotSupported
}
//read note 对struct转map和map转struct的处理
return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, config)
}
@@ -0,0 +1,420 @@
// Copyright 2013 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on src/pkg/reflect/deepequal.go from official
// golang's stdlib.
package mergo
import (
"fmt"
"reflect"
)
//read note 判断结构体是否有可导出字段
func hasMergeableFields(dst reflect.Value) (exported bool) {
for i, n := 0, dst.NumField(); i < n; i++ {
field := dst.Type().Field(i)
//read note 匿名字段如果是结构体需要判断该结构体中是否有可导出字段
if field.Anonymous && dst.Field(i).Kind() == reflect.Struct {
exported = exported || hasMergeableFields(dst.Field(i))
} else if isExportedComponent(&field) {
exported = exported || len(field.PkgPath) == 0
}
}
return
}
//read note 判断字段是否可导出,这边通过pkgPath和字段名首字母大小写确定
func isExportedComponent(field *reflect.StructField) bool {
pkgPath := field.PkgPath
//read note 查看一下pkgPath的注释,如果为空字符串表示可导出,否则不可导出
if len(pkgPath) > 0 {
return false
}
//read note 这边也是判断字段是否可导出
c := field.Name[0]
if 'a' <= c && c <= 'z' || c == '_' {
return false
}
return true
}
//read note 配置,这边采用Option的方式进行传参设置,通过Option修改配置的字段
type Config struct {
Overwrite bool //read note 是否覆盖
AppendSlice bool //read note 是否添加到对应数组中
TypeCheck bool //read note 是否进行类型检查
Transformers Transformers //read note 自定义类型转换
overwriteWithEmptyValue bool //read note 是否覆盖空值
overwriteSliceWithEmptyValue bool //read note 是否覆盖空数组
sliceDeepCopy bool //read note 数组中的元素是否进行深度克隆
debug bool
}
type Transformers interface {
Transformer(reflect.Type) func(dst, src reflect.Value) error
}
// Traverses recursively both values, assigning src's fields values to dst.
// The map argument tracks comparisons that have already been seen, which allows
// short circuiting on recursive types.
func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) {
overwrite := config.Overwrite
typeCheck := config.TypeCheck
overwriteWithEmptySrc := config.overwriteWithEmptyValue
overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue
sliceDeepCopy := config.sliceDeepCopy
//read note 零值返回
if !src.IsValid() {
return
}
//read note 这个地方应该是根据visited判断字段是否被deepMerge
if dst.CanAddr() {
addr := dst.UnsafeAddr()
h := 17 * addr
seen := visited[h]
typ := dst.Type()
//read note 这边是为了避免结构体中和结构体同类型的字段赋值同样的值。如果遇到这种情况会跳过赋值,因为已经赋值过了
for p := seen; p != nil; p = p.next {
if p.ptr == addr && p.typ == typ {
return nil
}
}
// Remember, remember...
//read note 记录已经被merge的字段
visited[h] = &visit{addr, typ, seen}
}
//read note 这个转换方法只有在 结果结构体或结构体字段不为空的情况下才会处理
if config.Transformers != nil && !isEmptyValue(dst) {
if fn := config.Transformers.Transformer(dst.Type()); fn != nil {
err = fn(dst, src)
return
}
}
switch dst.Kind() {
case reflect.Struct:
//read note 这边会遍历结构体的字段,判断是否有可导出的字段,如果有,才会进行Field遍历,实现deepMerge
if hasMergeableFields(dst) {
for i, n := 0, dst.NumField(); i < n; i++ {
//read note 对每一个字段进行deepMerge操作
if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil {
return
}
}
} else {
//read note 空值覆盖或者是有值覆盖,这个条件需要仔细阅读一下
if (isReflectNil(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) {
dst.Set(src)
}
}
case reflect.Map:
//read note 初始化map
if dst.IsNil() && !src.IsNil() {
dst.Set(reflect.MakeMap(dst.Type()))
}
//read note 这个地方按道理如果是两个相同的结构体,字段或者结构体的类型不可能不一样,所以这边有可能进去吗?
if src.Kind() != reflect.Map {
if overwrite {
dst.Set(src)
}
return
}
//read note 遍历map的key
for _, key := range src.MapKeys() {
//read note 获取被merge的map的value
srcElement := src.MapIndex(key)
if !srcElement.IsValid() {
continue
}
//read note 获取merge结果的map的value
dstElement := dst.MapIndex(key)
//read note fallthrough表示当前的case处理完之后还会继续往下执行一个case.
switch srcElement.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice:
if srcElement.IsNil() {
//read note 零值覆盖
if overwrite {
dst.SetMapIndex(key, srcElement)
}
continue
}
fallthrough
default:
if !srcElement.CanInterface() {
continue
}
switch reflect.TypeOf(srcElement.Interface()).Kind() {
case reflect.Struct:
fallthrough
case reflect.Ptr:
fallthrough
case reflect.Map:
//read note map、struct、ptr的处理类似,都需要获取value对应值,然后往下进行deepMerge操作
srcMapElm := srcElement
dstMapElm := dstElement
if srcMapElm.CanInterface() {
srcMapElm = reflect.ValueOf(srcMapElm.Interface())
if dstMapElm.IsValid() {
dstMapElm = reflect.ValueOf(dstMapElm.Interface())
}
}
if err = deepMerge(dstMapElm, srcMapElm, visited, depth+1, config); err != nil {
return
}
case reflect.Slice:
srcSlice := reflect.ValueOf(srcElement.Interface())
var dstSlice reflect.Value
//read note 如果结果字段是数组,判断是否空值进行初始化或者获取值
if !dstElement.IsValid() || dstElement.IsNil() {
dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len())
} else {
dstSlice = reflect.ValueOf(dstElement.Interface())
}
//read note 判断直接覆盖的条件,如果满足,会把被merge的数组覆盖到原数组上
if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice && !sliceDeepCopy {
if typeCheck && srcSlice.Type() != dstSlice.Type() {
return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type())
}
dstSlice = srcSlice
} else if config.AppendSlice {
//read note 如果标识数组append,则会对数组值进行append操作
if srcSlice.Type() != dstSlice.Type() {
return fmt.Errorf("cannot append two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type())
}
dstSlice = reflect.AppendSlice(dstSlice, srcSlice)
} else if sliceDeepCopy {
//read note 如果数组需要深度克隆,则会遍历数组的所有元素,对每个元素进行deepMerge
i := 0
for ; i < srcSlice.Len() && i < dstSlice.Len(); i++ {
srcElement := srcSlice.Index(i)
dstElement := dstSlice.Index(i)
if srcElement.CanInterface() {
srcElement = reflect.ValueOf(srcElement.Interface())
}
if dstElement.CanInterface() {
dstElement = reflect.ValueOf(dstElement.Interface())
}
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
}
}
//read note 设置map的值
dst.SetMapIndex(key, dstSlice)
}
}
//read note 这边的判断是如果上面的处理进行了赋值,则跳过这个key的处理,否则再往下就是默认设值的处理了
if dstElement.IsValid() && !isEmptyValue(dstElement) && (reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map || reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice) {
continue
}
//read note 设置转换结果为被转换的字段值,如果声明了覆盖标识(override)
if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement)) {
if dst.IsNil() {
dst.Set(reflect.MakeMap(dst.Type()))
}
dst.SetMapIndex(key, srcElement)
}
}
case reflect.Slice:
//read note 这边的slice的处理和map中对slice的处理类似,就不多赘述
if !dst.CanSet() {
break
}
if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice && !sliceDeepCopy {
dst.Set(src)
} else if config.AppendSlice {
if src.Type() != dst.Type() {
return fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type())
}
dst.Set(reflect.AppendSlice(dst, src))
} else if sliceDeepCopy {
for i := 0; i < src.Len() && i < dst.Len(); i++ {
srcElement := src.Index(i)
dstElement := dst.Index(i)
if srcElement.CanInterface() {
srcElement = reflect.ValueOf(srcElement.Interface())
}
if dstElement.CanInterface() {
dstElement = reflect.ValueOf(dstElement.Interface())
}
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
}
}
case reflect.Ptr:
fallthrough
case reflect.Interface:
//read note ptr和Interface的处理是一样的
//read note 空值的处理,判断是否覆盖.
if isReflectNil(src) {
if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) {
dst.Set(src)
}
break
}
//read note 不是Interface类型,这边dst控制、ptr和结构体类型进行处理
if src.Kind() != reflect.Interface {
if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) {
if dst.CanSet() && (overwrite || isEmptyValue(dst)) {
dst.Set(src)
}
} else if src.Kind() == reflect.Ptr {
if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil {
return
}
} else if dst.Elem().Type() == src.Type() {
if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil {
return
}
} else {
return ErrDifferentArgumentsTypes
}
break
}
//read note 空值处理
if dst.IsNil() || overwrite {
if dst.CanSet() && (overwrite || isEmptyValue(dst)) {
dst.Set(src)
}
break
}
//read note 类型相同,进行deepMerge处理
if dst.Elem().Kind() == src.Elem().Kind() {
if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil {
return
}
break
}
default:
//read note 默认情况下的处理,set值或者是直接赋值
mustSet := (isEmptyValue(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc)
if mustSet {
if dst.CanSet() {
dst.Set(src)
} else {
dst = src
}
}
}
return
}
// Merge will fill any empty for value type attributes on the dst struct using corresponding
// src attributes if they themselves are not empty. dst and src must be valid same-type structs
// and dst must be a pointer to struct.
// It won't merge unexported (private) fields and will do recursively any exported field.
func Merge(dst, src interface{}, opts ...func(*Config)) error {
//read note 这边的入参是被复制的结果结构体在前
return merge(dst, src, opts...)
}
// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by
// non-empty src attribute values.
// Deprecated: use Merge(…) with WithOverride
func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error {
return merge(dst, src, append(opts, WithOverride)...)
}
//read note ------------------------------------
// 下面这几个就是Option进行设置Config的函数处理
// WithTransformers adds transformers to merge, allowing to customize the merging of some types.
func WithTransformers(transformers Transformers) func(*Config) {
return func(config *Config) {
config.Transformers = transformers
}
}
// WithOverride will make merge override non-empty dst attributes with non-empty src attributes values.
func WithOverride(config *Config) {
config.Overwrite = true
}
// WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values.
func WithOverwriteWithEmptyValue(config *Config) {
config.Overwrite = true
config.overwriteWithEmptyValue = true
}
// WithOverrideEmptySlice will make merge override empty dst slice with empty src slice.
func WithOverrideEmptySlice(config *Config) {
config.overwriteSliceWithEmptyValue = true
}
// WithAppendSlice will make merge append slices instead of overwriting it.
func WithAppendSlice(config *Config) {
config.AppendSlice = true
}
// WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride).
func WithTypeCheck(config *Config) {
config.TypeCheck = true
}
// WithSliceDeepCopy will merge slice element one by one with Overwrite flag.
func WithSliceDeepCopy(config *Config) {
config.sliceDeepCopy = true
config.Overwrite = true
}
//read note ------------------------------------
func merge(dst, src interface{}, opts ...func(*Config)) error {
//read note 判断指针类型和结构体类型是否正确
if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr {
return ErrNonPointerAgument
}
var (
vDst, vSrc reflect.Value
err error
)
config := &Config{}
//read note optional设置config
for _, opt := range opts {
opt(config)
}
if vDst, vSrc, err = resolveValues(dst, src); err != nil {
return err
}
//read note 被merge的两个结构体类型必须一样,否则不能进行merge
if vDst.Type() != vSrc.Type() {
return ErrDifferentArgumentsTypes
}
//read note 进行deepMerge
return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config)
}
// IsReflectNil is the reflect value provided nil
func isReflectNil(v reflect.Value) bool {
k := v.Kind()
switch k {
case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr:
// Both interface and slice are nil if first word is 0.
// Both are always bigger than a word; assume flagIndir.
return v.IsNil()
default:
return false
}
}
@@ -0,0 +1,88 @@
package mergo_test
import (
"reflect"
"testing"
"github.com/imdario/mergo"
)
type transformer struct {
m map[reflect.Type]func(dst, src reflect.Value) error
}
func (s *transformer) Transformer(t reflect.Type) func(dst, src reflect.Value) error {
if fn, ok := s.m[t]; ok {
return fn
}
return nil
}
type foo struct {
s string
Bar *bar
}
type bar struct {
i int
s map[string]string
}
func TestMergeWithTransformerNilStruct(t *testing.T) {
a := foo{s: "foo"}
b := foo{Bar: &bar{i: 2, s: map[string]string{"foo": "bar"}}}
if err := mergo.Merge(&a, &b, mergo.WithOverride, mergo.WithTransformers(&transformer{
m: map[reflect.Type]func(dst, src reflect.Value) error{
reflect.TypeOf(&bar{}): func(dst, src reflect.Value) error {
// Do sthg with Elem
t.Log(dst.Elem().FieldByName("i"))
t.Log(src.Elem())
return nil
},
},
})); err != nil {
t.Error(err)
}
if a.s != "foo" {
t.Errorf("b not merged in properly: a.s.Value(%s) != expected(%s)", a.s, "foo")
}
if a.Bar == nil {
t.Errorf("b not merged in properly: a.Bar shouldn't be nil")
}
}
func TestMergeNonPointer(t *testing.T) {
dst := bar{
i: 1,
}
src := bar{
i: 2,
s: map[string]string{
"a": "1",
},
}
want := mergo.ErrNonPointerAgument
if got := mergo.Merge(dst, src); got != want {
t.Errorf("want: %s, got: %s", want, got)
}
}
func TestMapNonPointer(t *testing.T) {
dst := make(map[string]bar)
src := map[string]bar{
"a": {
i: 2,
s: map[string]string{
"a": "1",
},
},
}
want := mergo.ErrNonPointerAgument
if got := mergo.Merge(dst, src); got != want {
t.Errorf("want: %s, got: %s", want, got)
}
}
@@ -0,0 +1,79 @@
// Copyright 2013 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on src/pkg/reflect/deepequal.go from official
// golang's stdlib.
package mergo
import (
"errors"
"reflect"
)
// Errors reported by Mergo when it finds invalid arguments.
var (
ErrNilArguments = errors.New("src and dst must not be nil")
ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type")
ErrNotSupported = errors.New("only structs and maps are supported")
ErrExpectedMapAsDestination = errors.New("dst was expected to be a map")
ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct")
ErrNonPointerAgument = errors.New("dst must be a pointer")
)
// During deepMerge, must keep track of checks that are
// in progress. The comparison algorithm assumes that all
// checks in progress are true when it reencounters them.
// Visited are stored in a map indexed by 17 * a1 + a2;
type visit struct {
ptr uintptr
typ reflect.Type
next *visit
}
// From src/pkg/encoding/json/encode.go.
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
if v.IsNil() {
return true
}
return isEmptyValue(v.Elem())
case reflect.Func:
return v.IsNil()
case reflect.Invalid:
return true
}
return false
}
//read note 处理返回dst和src的对应值
func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) {
if dst == nil || src == nil {
err = ErrNilArguments
return
}
vDst = reflect.ValueOf(dst).Elem()
if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map {
err = ErrNotSupported
return
}
vSrc = reflect.ValueOf(src)
// We check if vSrc is a pointer to dereference it.
if vSrc.Kind() == reflect.Ptr {
vSrc = vSrc.Elem()
}
return
}
@@ -0,0 +1,940 @@
// Copyright 2013 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mergo_test
import (
"io/ioutil"
"reflect"
"strings"
"testing"
"time"
"github.com/imdario/mergo"
"gopkg.in/yaml.v2"
)
type simpleTest struct {
Value int
}
type complexTest struct {
St simpleTest
sz int
ID string
}
type mapTest struct {
M map[int]int
}
type ifcTest struct {
I interface{}
}
type moreComplextText struct {
Ct complexTest
St simpleTest
Nt simpleTest
}
type pointerTest struct {
C *simpleTest
}
type sliceTest struct {
S []int
}
func TestKb(t *testing.T) {
type testStruct struct {
Name string
KeyValue map[string]interface{}
}
akv := make(map[string]interface{})
akv["Key1"] = "not value 1"
akv["Key2"] = "value2"
a := testStruct{}
a.Name = "A"
a.KeyValue = akv
bkv := make(map[string]interface{})
bkv["Key1"] = "value1"
bkv["Key3"] = "value3"
b := testStruct{}
b.Name = "B"
b.KeyValue = bkv
ekv := make(map[string]interface{})
ekv["Key1"] = "value1"
ekv["Key2"] = "value2"
ekv["Key3"] = "value3"
expected := testStruct{}
expected.Name = "B"
expected.KeyValue = ekv
if err := mergo.Merge(&b, a); err != nil {
t.Error(err)
}
if !reflect.DeepEqual(b, expected) {
t.Errorf("Actual: %#v did not match \nExpected: %#v", b, expected)
}
}
func TestNil(t *testing.T) {
if err := mergo.Merge(nil, nil); err != mergo.ErrNilArguments {
t.Fail()
}
}
func TestDifferentTypes(t *testing.T) {
a := simpleTest{42}
b := 42
if err := mergo.Merge(&a, b); err != mergo.ErrDifferentArgumentsTypes {
t.Fail()
}
}
func TestSimpleStruct(t *testing.T) {
a := simpleTest{}
b := simpleTest{42}
if err := mergo.Merge(&a, b); err != nil {
t.FailNow()
}
if a.Value != 42 {
t.Errorf("b not merged in properly: a.Value(%d) != b.Value(%d)", a.Value, b.Value)
}
if !reflect.DeepEqual(a, b) {
t.FailNow()
}
}
func TestComplexStruct(t *testing.T) {
a := complexTest{}
a.ID = "athing"
b := complexTest{simpleTest{42}, 1, "bthing"}
if err := mergo.Merge(&a, b); err != nil {
t.FailNow()
}
if a.St.Value != 42 {
t.Errorf("b not merged in properly: a.St.Value(%d) != b.St.Value(%d)", a.St.Value, b.St.Value)
}
if a.sz == 1 {
t.Errorf("a's private field sz not preserved from merge: a.sz(%d) == b.sz(%d)", a.sz, b.sz)
}
if a.ID == b.ID {
t.Errorf("a's field ID merged unexpectedly: a.ID(%s) == b.ID(%s)", a.ID, b.ID)
}
}
func TestComplexStructWithOverwrite(t *testing.T) {
a := complexTest{simpleTest{1}, 1, "do-not-overwrite-with-empty-value"}
b := complexTest{simpleTest{42}, 2, ""}
expect := complexTest{simpleTest{42}, 1, "do-not-overwrite-with-empty-value"}
if err := mergo.MergeWithOverwrite(&a, b); err != nil {
t.FailNow()
}
if !reflect.DeepEqual(a, expect) {
t.Errorf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", a, expect)
}
}
func TestPointerStruct(t *testing.T) {
s1 := simpleTest{}
s2 := simpleTest{19}
a := pointerTest{&s1}
b := pointerTest{&s2}
if err := mergo.Merge(&a, b); err != nil {
t.FailNow()
}
if a.C.Value != b.C.Value {
t.Errorf("b not merged in properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value)
}
}
type embeddingStruct struct {
embeddedStruct
}
type embeddedStruct struct {
A string
}
func TestEmbeddedStruct(t *testing.T) {
tests := []struct {
src embeddingStruct
dst embeddingStruct
expected embeddingStruct
}{
{
src: embeddingStruct{
embeddedStruct{"foo"},
},
dst: embeddingStruct{
embeddedStruct{""},
},
expected: embeddingStruct{
embeddedStruct{"foo"},
},
},
{
src: embeddingStruct{
embeddedStruct{""},
},
dst: embeddingStruct{
embeddedStruct{"bar"},
},
expected: embeddingStruct{
embeddedStruct{"bar"},
},
},
{
src: embeddingStruct{
embeddedStruct{"foo"},
},
dst: embeddingStruct{
embeddedStruct{"bar"},
},
expected: embeddingStruct{
embeddedStruct{"bar"},
},
},
}
for _, test := range tests {
err := mergo.Merge(&test.dst, test.src)
if err != nil {
t.Errorf("unexpected error: %v", err)
continue
}
if !reflect.DeepEqual(test.dst, test.expected) {
t.Errorf("unexpected output\nexpected:\n%+v\nsaw:\n%+v\n", test.expected, test.dst)
}
}
}
func TestPointerStructNil(t *testing.T) {
a := pointerTest{nil}
b := pointerTest{&simpleTest{19}}
if err := mergo.Merge(&a, b); err != nil {
t.FailNow()
}
if a.C.Value != b.C.Value {
t.Errorf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value)
}
}
func testSlice(t *testing.T, a []int, b []int, e []int, opts ...func(*mergo.Config)) {
t.Helper()
bc := b
sa := sliceTest{a}
sb := sliceTest{b}
if err := mergo.Merge(&sa, sb, opts...); err != nil {
t.FailNow()
}
if !reflect.DeepEqual(sb.S, bc) {
t.Errorf("Source slice was modified %d != %d", sb.S, bc)
}
if !reflect.DeepEqual(sa.S, e) {
t.Errorf("b not merged in a proper way %d != %d", sa.S, e)
}
ma := map[string][]int{"S": a}
mb := map[string][]int{"S": b}
if err := mergo.Merge(&ma, mb, opts...); err != nil {
t.FailNow()
}
if !reflect.DeepEqual(mb["S"], bc) {
t.Errorf("map value: Source slice was modified %d != %d", mb["S"], bc)
}
if !reflect.DeepEqual(ma["S"], e) {
t.Errorf("map value: b not merged in a proper way %d != %d", ma["S"], e)
}
if a == nil {
// test case with missing dst key
ma := map[string][]int{}
mb := map[string][]int{"S": b}
if err := mergo.Merge(&ma, mb); err != nil {
t.FailNow()
}
if !reflect.DeepEqual(mb["S"], bc) {
t.Errorf("missing dst key: Source slice was modified %d != %d", mb["S"], bc)
}
if !reflect.DeepEqual(ma["S"], e) {
t.Errorf("missing dst key: b not merged in a proper way %d != %d", ma["S"], e)
}
}
if b == nil {
// test case with missing src key
ma := map[string][]int{"S": a}
mb := map[string][]int{}
if err := mergo.Merge(&ma, mb); err != nil {
t.FailNow()
}
if !reflect.DeepEqual(mb["S"], bc) {
t.Errorf("missing src key: Source slice was modified %d != %d", mb["S"], bc)
}
if !reflect.DeepEqual(ma["S"], e) {
t.Errorf("missing src key: b not merged in a proper way %d != %d", ma["S"], e)
}
}
}
func TestSlice(t *testing.T) {
testSlice(t, nil, []int{1, 2, 3}, []int{1, 2, 3})
testSlice(t, []int{}, []int{1, 2, 3}, []int{1, 2, 3})
testSlice(t, []int{1}, []int{2, 3}, []int{1})
testSlice(t, []int{1}, []int{}, []int{1})
testSlice(t, []int{1}, nil, []int{1})
testSlice(t, nil, []int{1, 2, 3}, []int{1, 2, 3}, mergo.WithAppendSlice)
testSlice(t, []int{}, []int{1, 2, 3}, []int{1, 2, 3}, mergo.WithAppendSlice)
testSlice(t, []int{1}, []int{2, 3}, []int{1, 2, 3}, mergo.WithAppendSlice)
testSlice(t, []int{1}, []int{2, 3}, []int{1, 2, 3}, mergo.WithAppendSlice, mergo.WithOverride)
testSlice(t, []int{1}, []int{}, []int{1}, mergo.WithAppendSlice)
testSlice(t, []int{1}, nil, []int{1}, mergo.WithAppendSlice)
}
func TestEmptyMaps(t *testing.T) {
a := mapTest{}
b := mapTest{
map[int]int{},
}
if err := mergo.Merge(&a, b); err != nil {
t.Fail()
}
if !reflect.DeepEqual(a, b) {
t.FailNow()
}
}
func TestEmptyToEmptyMaps(t *testing.T) {
a := mapTest{}
b := mapTest{}
if err := mergo.Merge(&a, b); err != nil {
t.Fail()
}
if !reflect.DeepEqual(a, b) {
t.FailNow()
}
}
func TestEmptyToNotEmptyMaps(t *testing.T) {
a := mapTest{map[int]int{
1: 2,
3: 4,
}}
aa := mapTest{map[int]int{
1: 2,
3: 4,
}}
b := mapTest{
map[int]int{},
}
if err := mergo.Merge(&a, b); err != nil {
t.Fail()
}
if !reflect.DeepEqual(a, aa) {
t.FailNow()
}
}
func TestMapsWithOverwrite(t *testing.T) {
m := map[string]simpleTest{
"a": {}, // overwritten by 16
"b": {42}, // overwritten by 0, as map Value is not addressable and it doesn't check for b is set or not set in `n`
"c": {13}, // overwritten by 12
"d": {61},
}
n := map[string]simpleTest{
"a": {16},
"b": {},
"c": {12},
"e": {14},
}
expect := map[string]simpleTest{
"a": {16},
"b": {},
"c": {12},
"d": {61},
"e": {14},
}
if err := mergo.MergeWithOverwrite(&m, n); err != nil {
t.Errorf(err.Error())
}
if !reflect.DeepEqual(m, expect) {
t.Errorf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", m, expect)
}
}
func TestMapWithEmbeddedStructPointer(t *testing.T) {
m := map[string]*simpleTest{
"a": {}, // overwritten by 16
"b": {42}, // not overwritten by empty value
"c": {13}, // overwritten by 12
"d": {61},
}
n := map[string]*simpleTest{
"a": {16},
"b": {},
"c": {12},
"e": {14},
}
expect := map[string]*simpleTest{
"a": {16},
"b": {42},
"c": {12},
"d": {61},
"e": {14},
}
if err := mergo.Merge(&m, n, mergo.WithOverride); err != nil {
t.Errorf(err.Error())
}
if !reflect.DeepEqual(m, expect) {
t.Errorf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", m, expect)
}
}
func TestMergeUsingStructAndMap(t *testing.T) {
type multiPtr struct {
Text string
Number int
}
type final struct {
Msg1 string
Msg2 string
}
type params struct {
Name string
Multi *multiPtr
Final *final
}
type config struct {
Foo string
Bar string
Params *params
}
cases := []struct {
name string
overwrite bool
changes *config
target *config
output *config
}{
{
name: "Should overwrite values in target for non-nil values in source",
overwrite: true,
changes: &config{
Bar: "from changes",
Params: &params{
Final: &final{
Msg1: "from changes",
Msg2: "from changes",
},
},
},
target: &config{
Foo: "from target",
Params: &params{
Name: "from target",
Multi: &multiPtr{
Text: "from target",
Number: 5,
},
Final: &final{
Msg1: "from target",
Msg2: "",
},
},
},
output: &config{
Foo: "from target",
Bar: "from changes",
Params: &params{
Name: "from target",
Multi: &multiPtr{
Text: "from target",
Number: 5,
},
Final: &final{
Msg1: "from changes",
Msg2: "from changes",
},
},
},
},
{
name: "Should not overwrite values in target for non-nil values in source",
overwrite: false,
changes: &config{
Bar: "from changes",
Params: &params{
Final: &final{
Msg1: "from changes",
Msg2: "from changes",
},
},
},
target: &config{
Foo: "from target",
Params: &params{
Name: "from target",
Multi: &multiPtr{
Text: "from target",
Number: 5,
},
Final: &final{
Msg1: "from target",
Msg2: "",
},
},
},
output: &config{
Foo: "from target",
Bar: "from changes",
Params: &params{
Name: "from target",
Multi: &multiPtr{
Text: "from target",
Number: 5,
},
Final: &final{
Msg1: "from target",
Msg2: "from changes",
},
},
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var err error
if tc.overwrite {
err = mergo.Merge(tc.target, *tc.changes, mergo.WithOverride)
} else {
err = mergo.Merge(tc.target, *tc.changes)
}
if err != nil {
t.Error(err)
}
if !reflect.DeepEqual(tc.target, tc.output) {
t.Errorf("Test failed:\ngot :\n%+v\n\nwant :\n%+v\n\n", tc.target.Params, tc.output.Params)
}
})
}
}
func TestMaps(t *testing.T) {
m := map[string]simpleTest{
"a": {},
"b": {42},
"c": {13},
"d": {61},
}
n := map[string]simpleTest{
"a": {16},
"b": {},
"c": {12},
"e": {14},
}
expect := map[string]simpleTest{
"a": {0},
"b": {42},
"c": {13},
"d": {61},
"e": {14},
}
if err := mergo.Merge(&m, n); err != nil {
t.Errorf(err.Error())
}
if !reflect.DeepEqual(m, expect) {
t.Errorf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", m, expect)
}
if m["a"].Value != 0 {
t.Errorf(`n merged in m because I solved non-addressable map values TODO: m["a"].Value(%d) != n["a"].Value(%d)`, m["a"].Value, n["a"].Value)
}
if m["b"].Value != 42 {
t.Errorf(`n wrongly merged in m: m["b"].Value(%d) != n["b"].Value(%d)`, m["b"].Value, n["b"].Value)
}
if m["c"].Value != 13 {
t.Errorf(`n overwritten in m: m["c"].Value(%d) != n["c"].Value(%d)`, m["c"].Value, n["c"].Value)
}
}
func TestMapsWithNilPointer(t *testing.T) {
m := map[string]*simpleTest{
"a": nil,
"b": nil,
}
n := map[string]*simpleTest{
"b": nil,
"c": nil,
}
expect := map[string]*simpleTest{
"a": nil,
"b": nil,
"c": nil,
}
if err := mergo.Merge(&m, n, mergo.WithOverride); err != nil {
t.Errorf(err.Error())
}
if !reflect.DeepEqual(m, expect) {
t.Errorf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", m, expect)
}
}
func TestYAMLMaps(t *testing.T) {
thing := loadYAML("testdata/thing.yml")
license := loadYAML("testdata/license.yml")
ft := thing["fields"].(map[interface{}]interface{})
fl := license["fields"].(map[interface{}]interface{})
// license has one extra field (site) and another already existing in thing (author) that Mergo won't override.
expectedLength := len(ft) + len(fl) - 1
if err := mergo.Merge(&license, thing); err != nil {
t.Error(err.Error())
}
currentLength := len(license["fields"].(map[interface{}]interface{}))
if currentLength != expectedLength {
t.Errorf(`thing not merged in license properly, license must have %d elements instead of %d`, expectedLength, currentLength)
}
fields := license["fields"].(map[interface{}]interface{})
if _, ok := fields["id"]; !ok {
t.Errorf(`thing not merged in license properly, license must have a new id field from thing`)
}
}
func TestTwoPointerValues(t *testing.T) {
a := &simpleTest{}
b := &simpleTest{42}
if err := mergo.Merge(a, b); err != nil {
t.Errorf(`Boom. You crossed the streams: %s`, err)
}
}
func TestMap(t *testing.T) {
a := complexTest{}
a.ID = "athing"
c := moreComplextText{a, simpleTest{}, simpleTest{}}
b := map[string]interface{}{
"ct": map[string]interface{}{
"st": map[string]interface{}{
"value": 42,
},
"sz": 1,
"id": "bthing",
},
"st": &simpleTest{144}, // Mapping a reference
"zt": simpleTest{299}, // Mapping a missing field (zt doesn't exist)
"nt": simpleTest{3},
}
if err := mergo.Map(&c, b); err != nil {
t.FailNow()
}
m := b["ct"].(map[string]interface{})
n := m["st"].(map[string]interface{})
o := b["st"].(*simpleTest)
p := b["nt"].(simpleTest)
if c.Ct.St.Value != 42 {
t.Errorf("b not merged in properly: c.Ct.St.Value(%d) != b.Ct.St.Value(%d)", c.Ct.St.Value, n["value"])
}
if c.St.Value != 144 {
t.Errorf("b not merged in properly: c.St.Value(%d) != b.St.Value(%d)", c.St.Value, o.Value)
}
if c.Nt.Value != 3 {
t.Errorf("b not merged in properly: c.Nt.Value(%d) != b.Nt.Value(%d)", c.St.Value, p.Value)
}
if c.Ct.sz == 1 {
t.Errorf("a's private field sz not preserved from merge: c.Ct.sz(%d) == b.Ct.sz(%d)", c.Ct.sz, m["sz"])
}
if c.Ct.ID == m["id"] {
t.Errorf("a's field ID merged unexpectedly: c.Ct.ID(%s) == b.Ct.ID(%s)", c.Ct.ID, m["id"])
}
}
func TestSimpleMap(t *testing.T) {
a := simpleTest{}
b := map[string]interface{}{
"value": 42,
}
if err := mergo.Map(&a, b); err != nil {
t.FailNow()
}
if a.Value != 42 {
t.Errorf("b not merged in properly: a.Value(%d) != b.Value(%v)", a.Value, b["value"])
}
}
func TestIfcMap(t *testing.T) {
a := ifcTest{}
b := ifcTest{42}
if err := mergo.Map(&a, b); err != nil {
t.FailNow()
}
if a.I != 42 {
t.Errorf("b not merged in properly: a.I(%d) != b.I(%d)", a.I, b.I)
}
if !reflect.DeepEqual(a, b) {
t.FailNow()
}
}
func TestIfcMapNoOverwrite(t *testing.T) {
a := ifcTest{13}
b := ifcTest{42}
if err := mergo.Map(&a, b); err != nil {
t.FailNow()
}
if a.I != 13 {
t.Errorf("a not left alone: a.I(%d) == b.I(%d)", a.I, b.I)
}
}
func TestIfcMapWithOverwrite(t *testing.T) {
a := ifcTest{13}
b := ifcTest{42}
if err := mergo.MapWithOverwrite(&a, b); err != nil {
t.FailNow()
}
if a.I != 42 {
t.Errorf("b not merged in properly: a.I(%d) != b.I(%d)", a.I, b.I)
}
if !reflect.DeepEqual(a, b) {
t.FailNow()
}
}
type pointerMapTest struct {
A int
hidden int
B *simpleTest
}
func TestBackAndForth(t *testing.T) {
pt := pointerMapTest{42, 1, &simpleTest{66}}
m := make(map[string]interface{})
if err := mergo.Map(&m, pt); err != nil {
t.FailNow()
}
var (
v interface{}
ok bool
)
if v, ok = m["a"]; v.(int) != pt.A || !ok {
t.Errorf("pt not merged in properly: m[`a`](%d) != pt.A(%d)", v, pt.A)
}
if v, ok = m["b"]; !ok {
t.Errorf("pt not merged in properly: B is missing in m")
}
var st *simpleTest
if st = v.(*simpleTest); st.Value != 66 {
t.Errorf("something went wrong while mapping pt on m, B wasn't copied")
}
bpt := pointerMapTest{}
if err := mergo.Map(&bpt, m); err != nil {
t.Error(err)
}
if bpt.A != pt.A {
t.Errorf("pt not merged in properly: bpt.A(%d) != pt.A(%d)", bpt.A, pt.A)
}
if bpt.hidden == pt.hidden {
t.Errorf("pt unexpectedly merged: bpt.hidden(%d) == pt.hidden(%d)", bpt.hidden, pt.hidden)
}
if bpt.B.Value != pt.B.Value {
t.Errorf("pt not merged in properly: bpt.B.Value(%d) != pt.B.Value(%d)", bpt.B.Value, pt.B.Value)
}
}
func TestEmbeddedPointerUnpacking(t *testing.T) {
tests := []struct{ input pointerMapTest }{
{pointerMapTest{42, 1, nil}},
{pointerMapTest{42, 1, &simpleTest{66}}},
}
newValue := 77
m := map[string]interface{}{
"b": map[string]interface{}{
"value": newValue,
},
}
for _, test := range tests {
pt := test.input
if err := mergo.MapWithOverwrite(&pt, m); err != nil {
t.FailNow()
}
if pt.B.Value != newValue {
t.Errorf("pt not mapped properly: pt.A.Value(%d) != m[`b`][`value`](%d)", pt.B.Value, newValue)
}
}
}
type structWithTimePointer struct {
Birth *time.Time
}
func TestTime(t *testing.T) {
now := time.Now()
dataStruct := structWithTimePointer{
Birth: &now,
}
dataMap := map[string]interface{}{
"Birth": &now,
}
b := structWithTimePointer{}
if err := mergo.Merge(&b, dataStruct); err != nil {
t.FailNow()
}
if b.Birth.IsZero() {
t.Errorf("time.Time not merged in properly: b.Birth(%v) != dataStruct['Birth'](%v)", b.Birth, dataStruct.Birth)
}
if b.Birth != dataStruct.Birth {
t.Errorf("time.Time not merged in properly: b.Birth(%v) != dataStruct['Birth'](%v)", b.Birth, dataStruct.Birth)
}
b = structWithTimePointer{}
if err := mergo.Map(&b, dataMap); err != nil {
t.FailNow()
}
if b.Birth.IsZero() {
t.Errorf("time.Time not merged in properly: b.Birth(%v) != dataMap['Birth'](%v)", b.Birth, dataMap["Birth"])
}
}
type simpleNested struct {
A int
}
type structWithNestedPtrValueMap struct {
NestedPtrValue map[string]*simpleNested
}
func TestNestedPtrValueInMap(t *testing.T) {
src := &structWithNestedPtrValueMap{
NestedPtrValue: map[string]*simpleNested{
"x": {
A: 1,
},
},
}
dst := &structWithNestedPtrValueMap{
NestedPtrValue: map[string]*simpleNested{
"x": {},
},
}
if err := mergo.Map(dst, src); err != nil {
t.FailNow()
}
if dst.NestedPtrValue["x"].A == 0 {
t.Errorf("Nested Ptr value not merged in properly: dst.NestedPtrValue[\"x\"].A(%v) != src.NestedPtrValue[\"x\"].A(%v)", dst.NestedPtrValue["x"].A, src.NestedPtrValue["x"].A)
}
}
func loadYAML(path string) (m map[string]interface{}) {
m = make(map[string]interface{})
raw, _ := ioutil.ReadFile(path)
_ = yaml.Unmarshal(raw, &m)
return
}
type structWithMap struct {
m map[string]structWithUnexportedProperty
}
type structWithUnexportedProperty struct {
s string
}
func TestUnexportedProperty(t *testing.T) {
a := structWithMap{map[string]structWithUnexportedProperty{
"key": {"hello"},
}}
b := structWithMap{map[string]structWithUnexportedProperty{
"key": {"hi"},
}}
defer func() {
if r := recover(); r != nil {
t.Errorf("Should not have panicked")
}
}()
mergo.Merge(&a, b)
}
type structWithBoolPointer struct {
C *bool
}
func TestBooleanPointer(t *testing.T) {
bt, bf := true, false
src := structWithBoolPointer{
&bt,
}
dst := structWithBoolPointer{
&bf,
}
if err := mergo.Merge(&dst, src); err != nil {
t.FailNow()
}
if dst.C == src.C {
t.Errorf("dst.C should be a different pointer than src.C")
}
if *dst.C != *src.C {
t.Errorf("dst.C should be true")
}
}
func TestMergeMapWithInnerSliceOfDifferentType(t *testing.T) {
testCases := []struct {
name string
options []func(*mergo.Config)
err string
}{
{
"With override and append slice",
[]func(*mergo.Config){mergo.WithOverride, mergo.WithAppendSlice},
"cannot append two slices with different type",
},
{
"With override and type check",
[]func(*mergo.Config){mergo.WithOverride, mergo.WithTypeCheck},
"cannot override two slices with different type",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
src := map[string]interface{}{
"foo": []string{"a", "b"},
}
dst := map[string]interface{}{
"foo": []int{1, 2},
}
if err := mergo.Merge(&src, &dst, tc.options...); err == nil || !strings.Contains(err.Error(), tc.err) {
t.Errorf("expected %q, got %q", tc.err, err)
}
})
}
}
func TestMergeSlicesIsNotSupported(t *testing.T) {
src := []string{"a", "b"}
dst := []int{1, 2}
if err := mergo.Merge(&src, &dst, mergo.WithOverride, mergo.WithAppendSlice); err != mergo.ErrNotSupported {
t.Errorf("expected %q, got %q", mergo.ErrNotSupported, err)
}
}
@@ -0,0 +1,20 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type mapInterface map[string]interface{}
func TestMergeMapsEmptyString(t *testing.T) {
a := mapInterface{"s": ""}
b := mapInterface{"s": "foo"}
if err := mergo.Merge(&a, b); err != nil {
t.Error(err)
}
if a["s"] != "foo" {
t.Errorf("b not merged in properly: a.s.Value(%s) != expected(%s)", a["s"], "foo")
}
}
@@ -0,0 +1,44 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
func TestMapInterfaceWithMultipleLayer(t *testing.T) {
m1 := map[string]interface{}{
"k1": map[string]interface{}{
"k1.1": "v1",
},
}
m2 := map[string]interface{}{
"k1": map[string]interface{}{
"k1.1": "v2",
"k1.2": "v3",
},
}
if err := mergo.Map(&m1, m2, mergo.WithOverride); err != nil {
t.Errorf("Error merging: %v", err)
}
// Check overwrite of sub map works
expected := "v2"
actual := m1["k1"].(map[string]interface{})["k1.1"].(string)
if actual != expected {
t.Errorf("Expected %v but got %v",
expected,
actual)
}
// Check new key is merged
expected = "v3"
actual = m1["k1"].(map[string]interface{})["k1.2"].(string)
if actual != expected {
t.Errorf("Expected %v but got %v",
expected,
actual)
}
}
@@ -0,0 +1,4 @@
import: ../../../../fossene/db/schema/thing.yml
fields:
site: string
author: root
@@ -0,0 +1,6 @@
fields:
id: int
name: string
parent: ref "datu:thing"
status: enum(draft, public, private)
author: updater
@@ -0,0 +1,92 @@
package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type inner struct {
A int
}
type outer struct {
inner
B int
}
func TestV039Issue139(t *testing.T) {
dst := outer{
inner: inner{A: 1},
B: 2,
}
src := outer{
inner: inner{A: 10},
B: 20,
}
err := mergo.MergeWithOverwrite(&dst, src)
if err != nil {
panic(err.Error())
}
if dst.inner.A == 1 {
t.Errorf("expected %d, got %d", src.inner.A, dst.inner.A)
}
}
func TestV039Issue152(t *testing.T) {
dst := map[string]interface{}{
"properties": map[string]interface{}{
"field1": map[string]interface{}{
"type": "text",
},
"field2": "ohai",
},
}
src := map[string]interface{}{
"properties": map[string]interface{}{
"field1": "wrong",
},
}
if err := mergo.Map(&dst, src, mergo.WithOverride); err != nil {
t.Error(err)
}
}
type issue146Foo struct {
A string
B map[string]issue146Bar
}
type issue146Bar struct {
C *string
D *string
}
func TestV039Issue146(t *testing.T) {
var (
s1 = "asd"
s2 = "sdf"
)
dst := issue146Foo{
A: "two",
B: map[string]issue146Bar{
"foo": {
C: &s1,
},
},
}
src := issue146Foo{
A: "one",
B: map[string]issue146Bar{
"foo": {
D: &s2,
},
},
}
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
t.Error(err)
}
if dst.B["foo"].D == nil {
t.Errorf("expected %v, got nil", &s2)
}
}
+66
View File
@@ -0,0 +1,66 @@
/*
* @Author : huangzj
* @Time : 2021/2/2 11:37
* @Description
*/
package merge
import (
"fmt"
"log"
"testing"
"github.com/imdario/mergo"
)
type redisConfig struct {
Address string
Port int
DB int
}
var defaultConfig = redisConfig{
Address: "127.0.0.1",
Port: 6381,
DB: 1,
}
//基础使用,如果被merge的对象字段有值则不覆盖
func TestBaseUse(t *testing.T) {
var config redisConfig
if err := mergo.Merge(&config, defaultConfig); err != nil {
log.Fatal(err)
}
fmt.Println("redis address: ", config.Address)
fmt.Println("redis port: ", config.Port)
fmt.Println("redis db: ", config.DB)
var m = make(map[string]interface{})
if err := mergo.Map(&m, defaultConfig); err != nil {
log.Fatal(err)
}
fmt.Println(m)
}
//测试字段覆盖
func TestOverride(t *testing.T) {
var config redisConfig
if err := mergo.Merge(&config, defaultConfig); err != nil {
log.Fatal(err)
}
fmt.Println("redis address: ", config.Address)
fmt.Println("redis port: ", config.Port)
fmt.Println("redis db: ", config.DB)
var m = make(map[string]interface{})
if err := mergo.Merge(&config, defaultConfig, mergo.WithOverride); err != nil {
log.Fatal(err)
}
fmt.Println(m)
}
+41
View File
@@ -0,0 +1,41 @@
/*
* @Author : huangzj
* @Time : 2021/2/3 9:50
* @Description
*/
package merge
import (
"fmt"
"github.com/imdario/mergo"
"log"
"testing"
)
type redisConfig2 struct {
Address string
Port int
DBs []int
}
var defaultConfig2 = redisConfig2{
Address: "127.0.0.1",
Port: 6381,
}
// 前提:需要配置 WithOverride 一起使用
// WithOverrideEmptySlice 空数组覆盖
// WithOverwriteWithEmptyValue 空字段、空数组覆盖
func TestNilOverride(t *testing.T) {
var config redisConfig2
config.DBs = []int{2, 3}
if err := mergo.Merge(&config, defaultConfig2, mergo.WithOverride, mergo.WithOverrideEmptySlice); err != nil {
log.Fatal(err)
}
fmt.Println("redis address: ", config.Address)
fmt.Println("redis port: ", config.Port)
fmt.Println("redis dbs: ", config.DBs)
}
+11
View File
@@ -0,0 +1,11 @@
参考地址:[https://segmentfault.com/a/1190000021997004](https://segmentfault.com/a/1190000021997004)
工程地址:[https://github.com/imdario/mergo](https://github.com/imdario/mergo)
获取方式:go get github.com/imdario/mergo
注意事项
mergo不会赋值非导出字段;
map中对应的键名首字母会转为小写;
mergo可嵌套赋值,我们演示的只有一层结构。
+54
View File
@@ -0,0 +1,54 @@
/*
* @Author : huangzj
* @Time : 2021/2/2 11:49
* @Description
*/
package merge
import "testing"
import (
"fmt"
"log"
"github.com/imdario/mergo"
)
type redisConfig1 struct {
Address string
Port int
DBs []int
}
var defaultConfig1 = redisConfig1{
Address: "127.0.0.1",
Port: 6381,
DBs: []int{1},
}
func TestAppend(t *testing.T) {
var config redisConfig1
config.DBs = []int{2, 3}
if err := mergo.Merge(&config, defaultConfig1, mergo.WithAppendSlice); err != nil {
log.Fatal(err)
}
fmt.Println("redis address: ", config.Address)
fmt.Println("redis port: ", config.Port)
fmt.Println("redis dbs: ", config.DBs)
}
func TestNotAppend(t *testing.T) {
var config redisConfig1
config.DBs = []int{2, 3}
if err := mergo.Merge(&config, defaultConfig1); err != nil {
log.Fatal(err)
}
fmt.Println("redis address: ", config.Address)
fmt.Println("redis port: ", config.Port)
fmt.Println("redis dbs: ", config.DBs)
}
+42
View File
@@ -0,0 +1,42 @@
/*
* @Author : huangzj
* @Time : 2021/2/3 9:59
* @Description
*/
package merge
import (
"fmt"
"github.com/imdario/mergo"
"log"
"testing"
)
func TestWithoutTypeCheck(t *testing.T) {
m1 := make(map[string]interface{})
m1["dbs"] = []uint32{2, 3}
m2 := make(map[string]interface{})
m2["dbs"] = []int{1}
if err := mergo.Map(&m1, &m2, mergo.WithOverride); err != nil {
log.Fatal(err)
}
fmt.Println(m1)
}
func TestWithTypeCheck(t *testing.T) {
m1 := make(map[string]interface{})
m1["dbs"] = []uint32{2, 3}
m2 := make(map[string]interface{})
m2["dbs"] = []int{1}
if err := mergo.Map(&m1, &m2, mergo.WithOverride, mergo.WithTypeCheck); err != nil {
log.Fatal(err)
}
fmt.Println(m1)
}
+2
View File
@@ -53,6 +53,8 @@ json与struct之间转换处理工具使用示例
2021/01/27:新增mapstructure源码阅读和单测代码 2021/01/27:新增mapstructure源码阅读和单测代码
2021/02/09:新增merge源码阅读和单测代码
# mod vendor模式加载包 # mod vendor模式加载包
通过go mod的方式加载的github上面的包会有报红的问题,但是包本身是可以运行的,这样就是会有一个问题,如果你想要点击去看方法的内容,没办法做到 通过go mod的方式加载的github上面的包会有报红的问题,但是包本身是可以运行的,这样就是会有一个问题,如果你想要点击去看方法的内容,没办法做到