pax_global_header 0000666 0000000 0000000 00000000064 14020004554 0014504 g ustar 00root root 0000000 0000000 52 comment=29fb3d3bdc5512887f1dc9aedde6a0fed407fa8f
mergo-0.3.12/ 0000775 0000000 0000000 00000000000 14020004554 0012700 5 ustar 00root root 0000000 0000000 mergo-0.3.12/.deepsource.toml 0000664 0000000 0000000 00000000227 14020004554 0016012 0 ustar 00root root 0000000 0000000 version = 1
test_patterns = [
"*_test.go"
]
[[analyzers]]
name = "go"
enabled = true
[analyzers.meta]
import_path = "github.com/imdario/mergo" mergo-0.3.12/.github/ 0000775 0000000 0000000 00000000000 14020004554 0014240 5 ustar 00root root 0000000 0000000 mergo-0.3.12/.github/FUNDING.yml 0000664 0000000 0000000 00000000167 14020004554 0016061 0 ustar 00root root 0000000 0000000 # These are supported funding model platforms
github: imdario
ko_fi: dariocc
custom: https://beerpay.io/imdario/mergo
mergo-0.3.12/.gitignore 0000664 0000000 0000000 00000000754 14020004554 0014676 0 ustar 00root root 0000000 0000000 #### 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
mergo-0.3.12/.travis.yml 0000664 0000000 0000000 00000000421 14020004554 0015006 0 ustar 00root root 0000000 0000000 language: go
arch:
- amd64
- ppc64le
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
mergo-0.3.12/.vscode/ 0000775 0000000 0000000 00000000000 14020004554 0014241 5 ustar 00root root 0000000 0000000 mergo-0.3.12/.vscode/settings.json 0000664 0000000 0000000 00000000165 14020004554 0016776 0 ustar 00root root 0000000 0000000 {
"go.lintTool": "golangci-lint",
"go.lintFlags": [
"--enable-all",
"--disable=gomnd"
]
} mergo-0.3.12/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000006207 14020004554 0015504 0 ustar 00root root 0000000 0000000 # 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/
mergo-0.3.12/LICENSE 0000664 0000000 0000000 00000003000 14020004554 0013676 0 ustar 00root root 0000000 0000000 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.
mergo-0.3.12/README.md 0000664 0000000 0000000 00000024230 14020004554 0014160 0 ustar 00root root 0000000 0000000 # 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:
[](https://beerpay.io/imdario/mergo)
[](https://beerpay.io/imdario/mergo)
### 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)
- [containerssh/containerssh](https://github.com/containerssh/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
[](https://sourcerer.io/fame/imdario/imdario/mergo/links/0)
[](https://sourcerer.io/fame/imdario/imdario/mergo/links/1)
[](https://sourcerer.io/fame/imdario/imdario/mergo/links/2)
[](https://sourcerer.io/fame/imdario/imdario/mergo/links/3)
[](https://sourcerer.io/fame/imdario/imdario/mergo/links/4)
[](https://sourcerer.io/fame/imdario/imdario/mergo/links/5)
[](https://sourcerer.io/fame/imdario/imdario/mergo/links/6)
[](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).
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large)
mergo-0.3.12/doc.go 0000664 0000000 0000000 00000010475 14020004554 0014003 0 ustar 00root root 0000000 0000000 // 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
mergo-0.3.12/go.mod 0000664 0000000 0000000 00000000112 14020004554 0014000 0 ustar 00root root 0000000 0000000 module github.com/imdario/mergo
go 1.13
require gopkg.in/yaml.v2 v2.3.0
mergo-0.3.12/go.sum 0000664 0000000 0000000 00000000550 14020004554 0014033 0 ustar 00root root 0000000 0000000 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=
mergo-0.3.12/issue100_test.go 0000664 0000000 0000000 00000000451 14020004554 0015637 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue104_test.go 0000664 0000000 0000000 00000001766 14020004554 0015655 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue121_test.go 0000664 0000000 0000000 00000001231 14020004554 0015637 0 ustar 00root root 0000000 0000000 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'")
}
}
mergo-0.3.12/issue123_test.go 0000664 0000000 0000000 00000001245 14020004554 0015646 0 ustar 00root root 0000000 0000000 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])
}
}
}
mergo-0.3.12/issue125_test.go 0000664 0000000 0000000 00000001537 14020004554 0015654 0 ustar 00root root 0000000 0000000 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")
}
}
mergo-0.3.12/issue129_test.go 0000664 0000000 0000000 00000001336 14020004554 0015655 0 ustar 00root root 0000000 0000000 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")
}
}
mergo-0.3.12/issue131_test.go 0000664 0000000 0000000 00000001157 14020004554 0015647 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue136_test.go 0000664 0000000 0000000 00000000713 14020004554 0015651 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue138_test.go 0000664 0000000 0000000 00000001454 14020004554 0015656 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue143_test.go 0000664 0000000 0000000 00000002374 14020004554 0015654 0 ustar 00root root 0000000 0000000 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)
}
}
}
mergo-0.3.12/issue149_test.go 0000664 0000000 0000000 00000001150 14020004554 0015651 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue174_test.go 0000664 0000000 0000000 00000000477 14020004554 0015662 0 ustar 00root root 0000000 0000000 package mergo_test
import (
"testing"
"github.com/imdario/mergo"
)
type structWithBlankField struct {
_ struct{}
A struct{}
}
func TestIssue174(t *testing.T) {
dst := structWithBlankField{}
src := structWithBlankField{}
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
t.Error(err)
}
}
mergo-0.3.12/issue17_test.go 0000664 0000000 0000000 00000001135 14020004554 0015566 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue23_test.go 0000664 0000000 0000000 00000001175 14020004554 0015567 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue33_test.go 0000664 0000000 0000000 00000001705 14020004554 0015567 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue38_test.go 0000664 0000000 0000000 00000002744 14020004554 0015600 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue50_test.go 0000664 0000000 0000000 00000000414 14020004554 0015562 0 ustar 00root root 0000000 0000000 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()
}
}
mergo-0.3.12/issue52_test.go 0000664 0000000 0000000 00000004614 14020004554 0015572 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue61_test.go 0000664 0000000 0000000 00000000602 14020004554 0015563 0 ustar 00root root 0000000 0000000 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()
}
}
mergo-0.3.12/issue64_test.go 0000664 0000000 0000000 00000002265 14020004554 0015575 0 ustar 00root root 0000000 0000000 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)
}
}
}
}
mergo-0.3.12/issue66_test.go 0000664 0000000 0000000 00000002365 14020004554 0015600 0 ustar 00root root 0000000 0000000 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")
}
}
mergo-0.3.12/issue83_test.go 0000664 0000000 0000000 00000000603 14020004554 0015570 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/issue84_test.go 0000664 0000000 0000000 00000003026 14020004554 0015573 0 ustar 00root root 0000000 0000000 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'")
}
}
mergo-0.3.12/issue89_test.go 0000664 0000000 0000000 00000001624 14020004554 0015602 0 ustar 00root root 0000000 0000000 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])
}
}
}
mergo-0.3.12/issue90_test.go 0000664 0000000 0000000 00000001301 14020004554 0015562 0 ustar 00root root 0000000 0000000 package mergo_test
import (
"github.com/imdario/mergo"
"reflect"
"testing"
)
type structWithStringMap struct {
Data map[string]string
}
func TestIssue90(t *testing.T) {
dst := map[string]structWithStringMap{
"struct": {
Data: nil,
},
}
src := map[string]structWithStringMap{
"struct": {
Data: map[string]string{
"foo": "bar",
},
},
}
expected := map[string]structWithStringMap{
"struct": {
Data: map[string]string{
"foo": "bar",
},
},
}
err := mergo.Merge(&dst, src, mergo.WithOverride)
if err != nil {
t.Errorf("unexpected error %v", err)
}
if !reflect.DeepEqual(dst, expected) {
t.Errorf("expected: %#v\ngot: %#v", expected, dst)
}
}
mergo-0.3.12/issueXXX_test.go 0000664 0000000 0000000 00000002122 14020004554 0016023 0 ustar 00root root 0000000 0000000 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)
}
}
}
}
mergo-0.3.12/map.go 0000664 0000000 0000000 00000012452 14020004554 0014010 0 ustar 00root root 0000000 0000000 // 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
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}
}
zeroValue := reflect.Value{}
switch dst.Kind() {
case reflect.Map:
dstMap := dst.Interface().(map[string]interface{})
for i, n := 0, src.NumField(); i < n; i++ {
srcType := src.Type()
field := srcType.Field(i)
if !isExported(field) {
continue
}
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()
}
}
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{})
for key := range srcMap {
config.overwriteWithEmptyValue = true
srcValue := srcMap[key]
fieldName := changeInitialCase(key, unicode.ToUpper)
dstElement := dst.FieldByName(fieldName)
if dstElement == zeroValue {
// We discard it because the field doesn't exist.
continue
}
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 {
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)
}
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.
if vSrc.Kind() == vDst.Kind() {
return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config)
}
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
}
return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, config)
}
mergo-0.3.12/merge.go 0000664 0000000 0000000 00000025417 14020004554 0014337 0 ustar 00root root 0000000 0000000 // 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"
)
func hasMergeableFields(dst reflect.Value) (exported bool) {
for i, n := 0, dst.NumField(); i < n; i++ {
field := dst.Type().Field(i)
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
}
func isExportedComponent(field *reflect.StructField) bool {
pkgPath := field.PkgPath
if len(pkgPath) > 0 {
return false
}
c := field.Name[0]
if 'a' <= c && c <= 'z' || c == '_' {
return false
}
return true
}
type Config struct {
Overwrite bool
AppendSlice bool
TypeCheck bool
Transformers Transformers
overwriteWithEmptyValue bool
overwriteSliceWithEmptyValue bool
sliceDeepCopy bool
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
if !src.IsValid() {
return
}
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}
}
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:
if hasMergeableFields(dst) {
for i, n := 0, dst.NumField(); i < n; i++ {
if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil {
return
}
}
} else {
if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) {
dst.Set(src)
}
}
case reflect.Map:
if dst.IsNil() && !src.IsNil() {
if dst.CanSet() {
dst.Set(reflect.MakeMap(dst.Type()))
} else {
dst = src
return
}
}
if src.Kind() != reflect.Map {
if overwrite {
dst.Set(src)
}
return
}
for _, key := range src.MapKeys() {
srcElement := src.MapIndex(key)
if !srcElement.IsValid() {
continue
}
dstElement := dst.MapIndex(key)
switch srcElement.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice:
if srcElement.IsNil() {
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:
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
if !dstElement.IsValid() || dstElement.IsNil() {
dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len())
} else {
dstSlice = reflect.ValueOf(dstElement.Interface())
}
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 {
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 {
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
}
}
}
dst.SetMapIndex(key, dstSlice)
}
}
if dstElement.IsValid() && !isEmptyValue(dstElement) && (reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map || reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice) {
continue
}
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:
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:
if isReflectNil(src) {
if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) {
dst.Set(src)
}
break
}
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
}
if dst.IsNil() || overwrite {
if dst.CanSet() && (overwrite || isEmptyValue(dst)) {
dst.Set(src)
}
break
}
if dst.Elem().Kind() == src.Elem().Kind() {
if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil {
return
}
break
}
default:
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 {
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)...)
}
// 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
}
func merge(dst, src interface{}, opts ...func(*Config)) error {
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)
}
if vDst, vSrc, err = resolveValues(dst, src); err != nil {
return err
}
if vDst.Type() != vSrc.Type() {
return ErrDifferentArgumentsTypes
}
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
}
}
mergo-0.3.12/merge_test.go 0000664 0000000 0000000 00000003167 14020004554 0015374 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/mergo.go 0000664 0000000 0000000 00000004430 14020004554 0014341 0 ustar 00root root 0000000 0000000 // 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
}
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
}
mergo-0.3.12/mergo_test.go 0000664 0000000 0000000 00000051763 14020004554 0015413 0 ustar 00root root 0000000 0000000 // 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: ¶ms{
Final: &final{
Msg1: "from changes",
Msg2: "from changes",
},
},
},
target: &config{
Foo: "from target",
Params: ¶ms{
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: ¶ms{
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: ¶ms{
Final: &final{
Msg1: "from changes",
Msg2: "from changes",
},
},
},
target: &config{
Foo: "from target",
Params: ¶ms{
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: ¶ms{
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)
}
}
mergo-0.3.12/pr80_test.go 0000664 0000000 0000000 00000000611 14020004554 0015055 0 ustar 00root root 0000000 0000000 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")
}
}
mergo-0.3.12/pr81_test.go 0000664 0000000 0000000 00000001477 14020004554 0015071 0 ustar 00root root 0000000 0000000 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)
}
}
mergo-0.3.12/testdata/ 0000775 0000000 0000000 00000000000 14020004554 0014511 5 ustar 00root root 0000000 0000000 mergo-0.3.12/testdata/license.yml 0000664 0000000 0000000 00000000132 14020004554 0016652 0 ustar 00root root 0000000 0000000 import: ../../../../fossene/db/schema/thing.yml
fields:
site: string
author: root
mergo-0.3.12/testdata/thing.yml 0000664 0000000 0000000 00000000177 14020004554 0016352 0 ustar 00root root 0000000 0000000 fields:
id: int
name: string
parent: ref "datu:thing"
status: enum(draft, public, private)
author: updater
mergo-0.3.12/v039_bugs_test.go 0000664 0000000 0000000 00000002565 14020004554 0016017 0 ustar 00root root 0000000 0000000 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)
}
}