diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index 2aea4d6..0000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1,5 +0,0 @@ -# These are supported funding model platforms - -github: imdario -ko_fi: dariocc -custom: https://beerpay.io/imdario/mergo diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 529c341..0000000 --- a/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -#### 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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0a1ff9f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,112 @@ + +# Contributing to mergo + +First off, thanks for taking the time to contribute! ❤️ + +All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 + +> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: +> - Star the project +> - Tweet about it +> - Refer this project in your project's readme +> - Mention the project at local meetups and tell your friends/colleagues + + +## Table of Contents + +- [Code of Conduct](#code-of-conduct) +- [I Have a Question](#i-have-a-question) +- [I Want To Contribute](#i-want-to-contribute) +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) + +## Code of Conduct + +This project and everyone participating in it is governed by the +[mergo Code of Conduct](https://github.com/imdario/mergoblob/master/CODE_OF_CONDUCT.md). +By participating, you are expected to uphold this code. Please report unacceptable behavior +to <>. + + +## I Have a Question + +> If you want to ask a question, we assume that you have read the available [Documentation](https://pkg.go.dev/github.com/imdario/mergo). + +Before you ask a question, it is best to search for existing [Issues](https://github.com/imdario/mergo/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. + +If you then still feel the need to ask a question and need clarification, we recommend the following: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). +- Provide as much context as you can about what you're running into. +- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. + +We will then take care of the issue as soon as possible. + +## I Want To Contribute + +> ### Legal Notice +> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. + +### Reporting Bugs + + +#### Before Submitting a Bug Report + +A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. + +- Make sure that you are using the latest version. +- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)). +- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/imdario/mergoissues?q=label%3Abug). +- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. +- Collect information about the bug: +- Stack trace (Traceback) +- OS, Platform and Version (Windows, Linux, macOS, x86, ARM) +- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. +- Possibly your input and the output +- Can you reliably reproduce the issue? And can you also reproduce it with older versions? + + +#### How Do I Submit a Good Bug Report? + +> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . + + +We use GitHub issues to track bugs and errors. If you run into an issue with the project: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) +- Explain the behavior you would expect and the actual behavior. +- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. +- Provide the information you collected in the previous section. + +Once it's filed: + +- The project team will label the issue accordingly. +- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. +- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be implemented by someone. + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion for mergo, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. + + +#### Before Submitting an Enhancement + +- Make sure that you are using the latest version. +- Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration. +- Perform a [search](https://github.com/imdario/mergo/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. +- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. + + +#### How Do I Submit a Good Enhancement Suggestion? + +Enhancement suggestions are tracked as [GitHub issues](https://github.com/imdario/mergo/issues). + +- Use a **clear and descriptive title** for the issue to identify the suggestion. +- Provide a **step-by-step description of the suggested enhancement** in as many details as possible. +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. +- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. +- **Explain why this enhancement would be useful** to most mergo users. You may also want to point out the other projects that solved it better and which could serve as inspiration. + + +## Attribution +This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)! diff --git a/README.md b/README.md index aa8cbd7..7e6f7ae 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,7 @@ [![Coverage Status][9]][10] [![Sourcegraph][11]][12] [![FOSSA Status][13]][14] - -[![GoCenter Kudos][15]][16] +[![Become my sponsor][15]][16] [1]: https://travis-ci.org/imdario/mergo.png [2]: https://travis-ci.org/imdario/mergo @@ -25,8 +24,8 @@ [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 +[15]: https://img.shields.io/github/sponsors/imdario +[16]: https://github.com/sponsors/imdario A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. @@ -36,11 +35,11 @@ ## 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). +It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, Microsoft, 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. +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 support 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. @@ -51,12 +50,12 @@ 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: Buy Me a Coffee at ko-fi.com -[![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) Donate using Liberapay +Become my sponsor ### Mergo in the wild +- [cli/cli](https://github.com/cli/cli) - [moby/moby](https://github.com/moby/moby) - [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) - [vmware/dispatch](https://github.com/vmware/dispatch) @@ -98,6 +97,8 @@ - [jnuthong/item_search](https://github.com/jnuthong/item_search) - [bukalapak/snowboard](https://github.com/bukalapak/snowboard) - [containerssh/containerssh](https://github.com/containerssh/containerssh) +- [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser) +- [tjpnz/structbot](https://github.com/tjpnz/structbot) ## Install @@ -168,7 +169,7 @@ Note: if test are failing due missing package, please execute: - go get gopkg.in/yaml.v2 + go get gopkg.in/yaml.v3 ### Transformers @@ -218,7 +219,6 @@ } ``` - ## 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) @@ -227,18 +227,6 @@ 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). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..abc8759 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,12 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.3.x | :white_check_mark: | +| < 0.3 | :x: | + +## Reporting a Vulnerability + +Report any vulnerability to d@rio.hn. diff --git a/debian/changelog b/debian/changelog index 53a0074..f87a7ea 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +golang-github-imdario-mergo (0.3.13+git20220917.1.c42713b-1) UNRELEASED; urgency=low + + * New upstream snapshot. + + -- Debian Janitor Thu, 03 Nov 2022 09:08:56 -0000 + golang-github-imdario-mergo (0.3.12-1) unstable; urgency=medium * Team upload. diff --git a/go.mod b/go.mod index 3d689d9..4cc3d51 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,4 @@ go 1.13 -require gopkg.in/yaml.v2 v2.3.0 +require gopkg.in/yaml.v3 v3.0.1 diff --git a/go.sum b/go.sum index 168980d..a62c313 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +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= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/issue123_test.go b/issue123_test.go index ae62d7b..9a9e4d8 100644 --- a/issue123_test.go +++ b/issue123_test.go @@ -23,20 +23,20 @@ t.Fatal(err) } testCases := []struct { + expected interface{} key string - expected interface{} }{ { + nil, "col1", - nil, }, { + 4, "col2", - 4, }, { + nil, "col3", - nil, }, } for _, tC := range testCases { diff --git a/issue136_test.go b/issue136_test.go index 4fe81c7..0246ec9 100644 --- a/issue136_test.go +++ b/issue136_test.go @@ -12,8 +12,8 @@ } type embeddedTestB struct { + Address string embeddedTestA - Address string } func TestMergeEmbedded(t *testing.T) { diff --git a/issue143_test.go b/issue143_test.go index 8cca4d8..0ea9306 100644 --- a/issue143_test.go +++ b/issue143_test.go @@ -9,8 +9,8 @@ func TestIssue143(t *testing.T) { testCases := []struct { + expected func(map[string]interface{}) error options []func(*mergo.Config) - expected func(map[string]interface{}) error }{ { options: []func(*mergo.Config){mergo.WithOverride}, diff --git a/issue209_test.go b/issue209_test.go new file mode 100644 index 0000000..00de234 --- /dev/null +++ b/issue209_test.go @@ -0,0 +1,26 @@ +package mergo_test + +import ( + "testing" + + "github.com/imdario/mergo" +) + +func TestIssue209(t *testing.T) { + dst := []string{"a", "b"} + src := []string{"c", "d"} + + if err := mergo.Merge(&dst, src, mergo.WithAppendSlice); err != nil { + t.Error(err) + } + + expected := []string{"a", "b", "c", "d"} + if len(dst) != len(expected) { + t.Errorf("arrays not equal length") + } + for i := range expected { + if dst[i] != expected[i] { + t.Errorf("array elements at %d are not equal", i) + } + } +} diff --git a/issue89_test.go b/issue89_test.go index 0a38994..e47a0df 100644 --- a/issue89_test.go +++ b/issue89_test.go @@ -33,20 +33,20 @@ t.Error(err) } testCases := []struct { + expected interface{} key string - expected interface{} }{ { + 3, "A", - 3, }, { + "", "B", - "", }, { + false, "C", - false, }, } for _, tC := range testCases { diff --git a/issue90_test.go b/issue90_test.go index 872a327..cb97537 100644 --- a/issue90_test.go +++ b/issue90_test.go @@ -10,11 +10,10 @@ Data map[string]string } - func TestIssue90(t *testing.T) { - dst := map[string]structWithStringMap{ - "struct": { - Data: nil, + dst := map[string]structWithStringMap{ + "struct": { + Data: nil, }, } src := map[string]structWithStringMap{ diff --git a/map.go b/map.go index a13a7ee..f739255 100644 --- a/map.go +++ b/map.go @@ -44,7 +44,7 @@ } } // Remember, remember... - visited[h] = &visit{addr, typ, seen} + visited[h] = &visit{typ, seen, addr} } zeroValue := reflect.Value{} switch dst.Kind() { diff --git a/merge.go b/merge.go index 8c2a8fc..4b47d0b 100644 --- a/merge.go +++ b/merge.go @@ -38,10 +38,10 @@ } type Config struct { + Transformers Transformers Overwrite bool AppendSlice bool TypeCheck bool - Transformers Transformers overwriteWithEmptyValue bool overwriteSliceWithEmptyValue bool sliceDeepCopy bool @@ -76,10 +76,10 @@ } } // Remember, remember... - visited[h] = &visit{addr, typ, seen} - } - - if config.Transformers != nil && !isEmptyValue(dst) { + visited[h] = &visit{typ, seen, addr} + } + + if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { if fn := config.Transformers.Transformer(dst.Type()); fn != nil { err = fn(dst, src) return diff --git a/merge_test.go b/merge_test.go index dd51dab..b87e23a 100644 --- a/merge_test.go +++ b/merge_test.go @@ -19,13 +19,13 @@ } type foo struct { + Bar *bar s string - Bar *bar } type bar struct { + s map[string]string i int - s map[string]string } func TestMergeWithTransformerNilStruct(t *testing.T) { diff --git a/mergo.go b/mergo.go index 3cc926c..d2af2a9 100644 --- a/mergo.go +++ b/mergo.go @@ -17,7 +17,7 @@ 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") + ErrNotSupported = errors.New("only structs, maps, and slices 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") @@ -28,9 +28,9 @@ // 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 + ptr uintptr } // From src/pkg/encoding/json/encode.go. @@ -65,7 +65,7 @@ return } vDst = reflect.ValueOf(dst).Elem() - if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map { + if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map && vDst.Kind() != reflect.Slice { err = ErrNotSupported return } diff --git a/mergo_test.go b/mergo_test.go index d69714c..5e37d04 100644 --- a/mergo_test.go +++ b/mergo_test.go @@ -13,7 +13,7 @@ "time" "github.com/imdario/mergo" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) type simpleTest struct { @@ -21,9 +21,9 @@ } type complexTest struct { + ID string St simpleTest sz int - ID string } type mapTest struct { @@ -50,8 +50,8 @@ func TestKb(t *testing.T) { type testStruct struct { + KeyValue map[string]interface{} Name string - KeyValue map[string]interface{} } akv := make(map[string]interface{}) @@ -116,7 +116,7 @@ func TestComplexStruct(t *testing.T) { a := complexTest{} a.ID = "athing" - b := complexTest{simpleTest{42}, 1, "bthing"} + b := complexTest{"bthing", simpleTest{42}, 1} if err := mergo.Merge(&a, b); err != nil { t.FailNow() } @@ -132,10 +132,10 @@ } 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"} + a := complexTest{"do-not-overwrite-with-empty-value", simpleTest{1}, 1} + b := complexTest{"", simpleTest{42}, 2} + + expect := complexTest{"do-not-overwrite-with-empty-value", simpleTest{42}, 1} if err := mergo.MergeWithOverwrite(&a, b); err != nil { t.FailNow() } @@ -417,22 +417,22 @@ Msg2 string } type params struct { - Name string Multi *multiPtr Final *final + Name string } type config struct { + Params *params Foo string Bar string - Params *params } cases := []struct { - name string - overwrite bool changes *config target *config output *config + name string + overwrite bool }{ { name: "Should overwrite values in target for non-nil values in source", @@ -603,18 +603,18 @@ 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{}) + ft := thing["fields"].(map[string]interface{}) + fl := license["fields"].(map[string]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{})) + currentLength := len(license["fields"].(map[string]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{}) + fields := license["fields"].(map[string]interface{}) if _, ok := fields["id"]; !ok { t.Errorf(`thing not merged in license properly, license must have a new id field from thing`) } @@ -721,13 +721,13 @@ } type pointerMapTest struct { + B *simpleTest A int hidden int - B *simpleTest } func TestBackAndForth(t *testing.T) { - pt := pointerMapTest{42, 1, &simpleTest{66}} + pt := pointerMapTest{&simpleTest{66}, 42, 1} m := make(map[string]interface{}) if err := mergo.Map(&m, pt); err != nil { t.FailNow() @@ -763,8 +763,8 @@ func TestEmbeddedPointerUnpacking(t *testing.T) { tests := []struct{ input pointerMapTest }{ - {pointerMapTest{42, 1, nil}}, - {pointerMapTest{42, 1, &simpleTest{66}}}, + {pointerMapTest{nil, 42, 1}}, + {pointerMapTest{&simpleTest{66}, 42, 1}}, } newValue := 77 m := map[string]interface{}{ @@ -900,18 +900,18 @@ func TestMergeMapWithInnerSliceOfDifferentType(t *testing.T) { testCases := []struct { name string + err string options []func(*mergo.Config) - err string }{ { "With override and append slice", + "cannot append two slices with different type", []func(*mergo.Config){mergo.WithOverride, mergo.WithAppendSlice}, - "cannot append two slices with different type", }, { "With override and type check", + "cannot override two slices with different type", []func(*mergo.Config){mergo.WithOverride, mergo.WithTypeCheck}, - "cannot override two slices with different type", }, } for _, tc := range testCases { @@ -930,11 +930,11 @@ } } -func TestMergeSlicesIsNotSupported(t *testing.T) { +func TestMergeDifferentSlicesIsNotSupported(t *testing.T) { src := []string{"a", "b"} dst := []int{1, 2} - if err := mergo.Merge(&src, &dst, mergo.WithOverride, mergo.WithAppendSlice); err != mergo.ErrNotSupported { + if err := mergo.Merge(&src, &dst, mergo.WithOverride, mergo.WithAppendSlice); err != mergo.ErrDifferentArgumentsTypes { t.Errorf("expected %q, got %q", mergo.ErrNotSupported, err) } } diff --git a/pr211_2_test.go b/pr211_2_test.go new file mode 100644 index 0000000..df4c575 --- /dev/null +++ b/pr211_2_test.go @@ -0,0 +1,25 @@ +package mergo + +import ( + "reflect" + "testing" + "time" +) + +type transformer struct { +} + +func (s *transformer) Transformer(t reflect.Type) func(dst, src reflect.Value) error { + return nil +} + +func Test_deepMergeTransformerInvalidDestination(t *testing.T) { + foo := time.Time{} + src := reflect.ValueOf(foo) + deepMerge(reflect.Value{}, src, make(map[uintptr]*visit), 0, &Config{ + Transformers: &transformer{}, + }) + // this test is intentionally not asserting on anything, it's sole + // purpose to verify deepMerge doesn't panic when a transformer is + // passed and the destination is invalid. +} diff --git a/pr211_test.go b/pr211_test.go new file mode 100644 index 0000000..09b87e9 --- /dev/null +++ b/pr211_test.go @@ -0,0 +1,36 @@ +package mergo_test + +import ( + "reflect" + "testing" + + "github.com/imdario/mergo" +) + +func TestMergeWithTransformerZeroValue(t *testing.T) { + // This test specifically tests that a transformer can be used to + // prevent overwriting a zero value (in this case a bool). This would fail prior to #211 + type fooWithBoolPtr struct { + b *bool + } + var Bool = func(b bool) *bool { return &b } + a := fooWithBoolPtr{b: Bool(false)} + b := fooWithBoolPtr{b: Bool(true)} + + if err := mergo.Merge(&a, &b, mergo.WithTransformers(&transformer{ + m: map[reflect.Type]func(dst, src reflect.Value) error{ + reflect.TypeOf(Bool(false)): func(dst, src reflect.Value) error { + if dst.CanSet() && dst.IsNil() { + dst.Set(src) + } + return nil + }, + }, + })); err != nil { + t.Error(err) + } + + if *a.b != false { + t.Errorf("b not merged in properly: a.b(%v) != expected(%v)", a.b, false) + } +} diff --git a/v039_bugs_test.go b/v039_bugs_test.go index c470ed0..16a8cc0 100644 --- a/v039_bugs_test.go +++ b/v039_bugs_test.go @@ -53,8 +53,8 @@ } type issue146Foo struct { + B map[string]issue146Bar A string - B map[string]issue146Bar } type issue146Bar struct {