pax_global_header00006660000000000000000000000064146602024120014507gustar00rootroot0000000000000052 comment=59ea6a9cd9f9c60cb6b1c58476f76cd3172ccebf mergo-1.0.1/000077500000000000000000000000001466020241200126175ustar00rootroot00000000000000mergo-1.0.1/.deepsource.toml000066400000000000000000000002161466020241200157270ustar00rootroot00000000000000version = 1 test_patterns = [ "*_test.go" ] [[analyzers]] name = "go" enabled = true [analyzers.meta] import_path = "dario.cat/mergo"mergo-1.0.1/.github/000077500000000000000000000000001466020241200141575ustar00rootroot00000000000000mergo-1.0.1/.github/FUNDING.yml000066400000000000000000000000771466020241200160000ustar00rootroot00000000000000# These are supported funding model platforms github: darccio mergo-1.0.1/.github/dependabot.yml000066400000000000000000000007701466020241200170130ustar00rootroot00000000000000# To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "gomod" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "weekly" mergo-1.0.1/.github/workflows/000077500000000000000000000000001466020241200162145ustar00rootroot00000000000000mergo-1.0.1/.github/workflows/codeql-analysis.yml000066400000000000000000000052441466020241200220340ustar00rootroot00000000000000# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: [ master ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] schedule: - cron: '43 19 * * 2' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'go' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support steps: - name: Checkout repository uses: actions/checkout@v3 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs # queries: security-extended,security-and-quality # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v2 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # If the Autobuild fails above, remove it and uncomment the following three lines. # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # - run: | # echo "Run, Build Application using script" # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 mergo-1.0.1/.github/workflows/openssf.yml000066400000000000000000000014601466020241200204150ustar00rootroot00000000000000name: 'openssf' on: push: branches: - master jobs: scorecard: name: OpenSSF runs-on: ubuntu-latest permissions: # Needed to upload the results to code-scanning dashboard. security-events: write actions: read contents: read # Needed to access OIDC token. id-token: write steps: - name: Checkout repository uses: actions/checkout@v3 with: persist-credentials: false - name: OSSF Scorecard action uses: ossf/scorecard-action@v2.1.3 with: results_file: results.sarif results_format: sarif publish_results: true - name: "Upload SARIF results to code scanning" uses: github/codeql-action/upload-sarif@v2.3.6 with: sarif_file: results.sarif mergo-1.0.1/.github/workflows/tests.yml000066400000000000000000000005321466020241200201010ustar00rootroot00000000000000name: 'tests' on: push: branches: - master jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Go uses: actions/setup-go@v4 with: go-version: '>=1.17.0' - name: Build run: go build -v ./... - name: Test run: go test -v ./...mergo-1.0.1/.gitignore000066400000000000000000000010051466020241200146030ustar00rootroot00000000000000#### 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 # Golang/Intellij .idea # 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-1.0.1/.travis.yml000066400000000000000000000004211466020241200147250ustar00rootroot00000000000000language: 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-1.0.1/.vscode/000077500000000000000000000000001466020241200141605ustar00rootroot00000000000000mergo-1.0.1/.vscode/settings.json000066400000000000000000000001651466020241200167150ustar00rootroot00000000000000{ "go.lintTool": "golangci-lint", "go.lintFlags": [ "--enable-all", "--disable=gomnd" ] }mergo-1.0.1/CODE_OF_CONDUCT.md000066400000000000000000000062071466020241200154230ustar00rootroot00000000000000# 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-1.0.1/CONTRIBUTING.md000066400000000000000000000176101466020241200150550ustar00rootroot00000000000000 # 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)! mergo-1.0.1/LICENSE000066400000000000000000000030001466020241200136150ustar00rootroot00000000000000Copyright (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-1.0.1/README.md000066400000000000000000000217201466020241200141000ustar00rootroot00000000000000# Mergo [![GitHub release][5]][6] [![GoCard][7]][8] [![Test status][1]][2] [![OpenSSF Scorecard][21]][22] [![OpenSSF Best Practices][19]][20] [![Coverage status][9]][10] [![Sourcegraph][11]][12] [![FOSSA status][13]][14] [![GoDoc][3]][4] [![Become my sponsor][15]][16] [![Tidelift][17]][18] [1]: https://github.com/imdario/mergo/workflows/tests/badge.svg?branch=master [2]: https://github.com/imdario/mergo/actions/workflows/tests.yml [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://img.shields.io/github/sponsors/imdario [16]: https://github.com/sponsors/imdario [17]: https://tidelift.com/badges/package/go/github.com%2Fimdario%2Fmergo [18]: https://tidelift.com/subscription/pkg/go-github.com-imdario-mergo [19]: https://bestpractices.coreinfrastructure.org/projects/7177/badge [20]: https://bestpractices.coreinfrastructure.org/projects/7177 [21]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo/badge [22]: https://api.securityscorecards.dev/projects/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 Mergo is stable and frozen, ready for production. Check a short list of the projects using at large scale it [here](https://github.com/imdario/mergo#mergo-in-the-wild). No new features are accepted. They will be considered for a future v2 that improves the implementation and fixes bugs for corner cases. ### Important notes #### 1.0.0 In [1.0.0](//github.com/imdario/mergo/releases/tag/1.0.0) Mergo moves to a vanity URL `dario.cat/mergo`. No more v1 versions will be released. If the vanity URL is causing issues in your project due to a dependency pulling Mergo - it isn't a direct dependency in your project - it is recommended to use [replace](https://github.com/golang/go/wiki/Modules#when-should-i-use-the-replace-directive) to pin the version to the last one with the old import URL: ``` replace github.com/imdario/mergo => github.com/imdario/mergo v0.3.16 ``` #### 0.3.9 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. 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 dario.cat/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: Donate using Liberapay Become my sponsor ### Mergo in the wild Mergo is used by [thousands](https://deps.dev/go/dario.cat%2Fmergo/v1.0.0/dependents) [of](https://deps.dev/go/github.com%2Fimdario%2Fmergo/v0.3.16/dependents) [projects](https://deps.dev/go/github.com%2Fimdario%2Fmergo/v0.3.12), including: * [containerd/containerd](https://github.com/containerd/containerd) * [datadog/datadog-agent](https://github.com/datadog/datadog-agent) * [docker/cli/](https://github.com/docker/cli/) * [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser) * [go-micro/go-micro](https://github.com/go-micro/go-micro) * [grafana/loki](https://github.com/grafana/loki) * [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) * [masterminds/sprig](github.com/Masterminds/sprig) * [moby/moby](https://github.com/moby/moby) * [slackhq/nebula](https://github.com/slackhq/nebula) * [volcano-sh/volcano](https://github.com/volcano-sh/volcano) ## Install go get dario.cat/mergo // use in your .go code import ( "dario.cat/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 { // ... } ``` If you need to override pointers, so the source pointer's value is assigned to the destination's pointer, you must use `WithoutDereference`: ```go package main import ( "fmt" "dario.cat/mergo" ) type Foo struct { A *string B int64 } func main() { first := "first" second := "second" src := Foo{ A: &first, B: 2, } dest := Foo{ A: &second, B: 1, } mergo.Merge(&dest, src, mergo.WithOverride, mergo.WithoutDereference) } ``` 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" "dario.cat/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.v3 ### 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" "dario.cat/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). ## License [BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE). [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large) mergo-1.0.1/SECURITY.md000066400000000000000000000005601466020241200144110ustar00rootroot00000000000000# Security Policy ## Supported Versions | Version | Supported | | ------- | ------------------ | | 0.3.x | :white_check_mark: | | < 0.3 | :x: | ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. mergo-1.0.1/doc.go000066400000000000000000000105261466020241200137170ustar00rootroot00000000000000// 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 notes 1.0.0 In 1.0.0 Mergo moves to a vanity URL `dario.cat/mergo`. 0.3.9 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 dario.cat/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 dario.cat/mergo // use in your .go code import ( "dario.cat/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" "dario.cat/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" "dario.cat/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-1.0.1/go.mod000066400000000000000000000001011466020241200137150ustar00rootroot00000000000000module dario.cat/mergo go 1.13 require gopkg.in/yaml.v3 v3.0.1 mergo-1.0.1/go.sum000066400000000000000000000005501466020241200137520ustar00rootroot00000000000000gopkg.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.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= mergo-1.0.1/issue100_test.go000066400000000000000000000004401466020241200155540ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue104_test.go000066400000000000000000000017551466020241200155720ustar00rootroot00000000000000package mergo_test import ( "reflect" "testing" "dario.cat/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-1.0.1/issue121_test.go000066400000000000000000000012201466020241200155540ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue123_test.go000066400000000000000000000012341466020241200155630ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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 { expected interface{} key string }{ { nil, "col1", }, { 4, "col2", }, { nil, "col3", }, } 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-1.0.1/issue125_test.go000066400000000000000000000015261466020241200155710ustar00rootroot00000000000000package mergo_test import ( "encoding/json" "testing" "dario.cat/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-1.0.1/issue129_test.go000066400000000000000000000013251466020241200155720ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue131_test.go000066400000000000000000000056501466020241200155700ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/mergo" ) type foz struct { A *bool B string C *bool D *bool E *bool F *baz } type baz struct { A *bool } 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) } } func TestIssue131MergeWithoutDereferenceWithOverride(t *testing.T) { src := foz{ A: func(v bool) *bool { return &v }(false), B: "src", C: nil, D: func(v bool) *bool { return &v }(false), E: func(v bool) *bool { return &v }(true), } dest := foz{ A: func(v bool) *bool { return &v }(true), B: "dest", C: func(v bool) *bool { return &v }(false), D: nil, E: func(v bool) *bool { return &v }(false), } if err := mergo.Merge(&dest, src, mergo.WithoutDereference, mergo.WithOverride); 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) } if *dest.C != false { t.Errorf("dest.C not merged in properly: %v != %v", *src.C, *dest.C) } if *dest.D != false { t.Errorf("dest.D not merged in properly: %v != %v", src.D, *dest.D) } if *dest.E != true { t.Errorf("dest.E not merged in properly: %v != %v", *src.E, *dest.E) } } func TestIssue131MergeWithoutDereference(t *testing.T) { src := foz{ A: func(v bool) *bool { return &v }(false), B: "src", C: nil, D: func(v bool) *bool { return &v }(false), E: func(v bool) *bool { return &v }(true), F: &baz{ A: func(v bool) *bool { return &v }(true), }, } dest := foz{ A: func(v bool) *bool { return &v }(true), B: "dest", C: func(v bool) *bool { return &v }(false), D: nil, E: func(v bool) *bool { return &v }(false), F: nil, } if err := mergo.Merge(&dest, src, mergo.WithoutDereference); err != nil { t.Error(err) } if *src.A == *dest.A { t.Errorf("dest.A should not have been merged: %v == %v", *src.A, *dest.A) } if src.B == dest.B { t.Errorf("dest.B should not have been merged: %v == %v", src.B, dest.B) } if *dest.C != false { t.Errorf("dest.C not merged in properly: %v != %v", *src.C, *dest.C) } if *dest.D != false { t.Errorf("dest.D not merged in properly: %v != %v", src.D, *dest.D) } if *dest.E == true { t.Errorf("dest.E should not have been merged: %v == %v", *src.E, *dest.E) } if dest.F == nil { t.Errorf("dest.F should not have be overriden with nil: %v == %v", src.F, dest.F) } if *dest.F.A == false { t.Errorf("dest.F.A not merged in properly: %v != %v", *src.F.A, *dest.F.A) } } mergo-1.0.1/issue136_test.go000066400000000000000000000007021466020241200155660ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/mergo" ) type embeddedTestA struct { Name string Age uint8 } type embeddedTestB struct { Address string embeddedTestA } 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-1.0.1/issue138_test.go000066400000000000000000000014431466020241200155730ustar00rootroot00000000000000package mergo_test import ( "encoding/json" "testing" "dario.cat/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-1.0.1/issue143_test.go000066400000000000000000000023631466020241200155710ustar00rootroot00000000000000package mergo_test import ( "fmt" "testing" "dario.cat/mergo" ) func TestIssue143(t *testing.T) { testCases := []struct { expected func(map[string]interface{}) error options []func(*mergo.Config) }{ { 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-1.0.1/issue149_test.go000066400000000000000000000011371466020241200155750ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue174_test.go000066400000000000000000000004661466020241200155770ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue17_test.go000066400000000000000000000011241466020241200155030ustar00rootroot00000000000000package mergo_test import ( "encoding/json" "testing" "dario.cat/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-1.0.1/issue187_test.go000066400000000000000000000032031466020241200155730ustar00rootroot00000000000000package mergo_test import ( "dario.cat/mergo" "testing" ) func TestIssue187MergeStructToMap(t *testing.T) { dst := map[string]interface{}{ "empty": "data", } src := struct { Foo string Bar int Empty string }{ Foo: "hello", Bar: 42, } if err := mergo.Map(&dst, src); err != nil { t.Error(err) } if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "data" { t.Errorf("expected dst to be {foo: hello, bar: 42, empty: data}, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"]) } } func TestIssue187MergeStructToMapWithOverwrite(t *testing.T) { dst := map[string]interface{}{ "foo": "initial", "bar": 1, "empty": "data", } src := struct { Foo string Bar int Empty string }{ Foo: "hello", Bar: 42, } if err := mergo.Map(&dst, src, mergo.WithOverride); err != nil { t.Error(err) } if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "data" { t.Errorf("expected dst to be {foo: hello, bar: 42, empty: data}, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"]) } } func TestIssue187MergeStructToMapWithOverwriteWithEmptyValue(t *testing.T) { dst := map[string]interface{}{ "foo": "initial", "bar": 1, "empty": "data", } src := struct { Foo string Bar int Empty string }{ Foo: "hello", Bar: 42, } if err := mergo.Map(&dst, src, mergo.WithOverwriteWithEmptyValue); err != nil { t.Error(err) } if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "" { t.Errorf("expected dst to be {foo: hello, bar: 42, empty: }, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"]) } } mergo-1.0.1/issue202_test.go000066400000000000000000000045631466020241200155710ustar00rootroot00000000000000package mergo_test import ( "reflect" "testing" "dario.cat/mergo" ) func TestIssue202(t *testing.T) { tests := []struct { name string dst, src, want map[string]interface{} }{ { name: "slice override string", dst: map[string]interface{}{ "x": 456, "y": "foo", }, src: map[string]interface{}{ "x": "123", "y": []int{1, 2, 3}, }, want: map[string]interface{}{ "x": "123", "y": []int{1, 2, 3}, }, }, { name: "string override slice", dst: map[string]interface{}{ "x": 456, "y": []int{1, 2, 3}, }, src: map[string]interface{}{ "x": "123", "y": "foo", }, want: map[string]interface{}{ "x": "123", "y": "foo", }, }, { name: "map override string", dst: map[string]interface{}{ "x": 456, "y": "foo", }, src: map[string]interface{}{ "x": "123", "y": map[string]interface{}{ "a": true, }, }, want: map[string]interface{}{ "x": "123", "y": map[string]interface{}{ "a": true, }, }, }, { name: "string override map", dst: map[string]interface{}{ "x": 456, "y": map[string]interface{}{ "a": true, }, }, src: map[string]interface{}{ "x": "123", "y": "foo", }, want: map[string]interface{}{ "x": "123", "y": "foo", }, }, { name: "map override map", dst: map[string]interface{}{ "x": 456, "y": map[string]interface{}{ "a": 10, }, }, src: map[string]interface{}{ "x": "123", "y": map[string]interface{}{ "a": true, }, }, want: map[string]interface{}{ "x": "123", "y": map[string]interface{}{ "a": true, }, }, }, { name: "map override map with merge", dst: map[string]interface{}{ "x": 456, "y": map[string]interface{}{ "a": 10, "b": 100, }, }, src: map[string]interface{}{ "x": "123", "y": map[string]interface{}{ "a": true, }, }, want: map[string]interface{}{ "x": "123", "y": map[string]interface{}{ "a": true, "b": 100, }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := mergo.Merge(&tt.dst, tt.src, mergo.WithOverride); err != nil { t.Error(err) } if !reflect.DeepEqual(tt.dst, tt.want) { t.Errorf("maps not equal.\nwant:\n%v\ngot:\n%v\n", tt.want, tt.dst) } }) } } mergo-1.0.1/issue209_test.go000066400000000000000000000007331466020241200155730ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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) } } } mergo-1.0.1/issue220_test.go000066400000000000000000000007431466020241200155650ustar00rootroot00000000000000package mergo_test import ( "reflect" "testing" "dario.cat/mergo" ) func TestIssue220(t *testing.T) { dst := []interface{}{ map[string]int{ "a": 1, }, } src := []interface{}{ "nil", } expected := []interface{}{ map[string]int{ "a": 1, }, } err := mergo.Merge(&dst, src, mergo.WithSliceDeepCopy) if err != nil { t.Errorf("unexpected error %v", err) } if !reflect.DeepEqual(dst, expected) { t.Errorf("expected: %#v\ngot: %#v", expected, dst) } } mergo-1.0.1/issue230_test.go000066400000000000000000000032541466020241200155660ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/mergo" ) var testDataM = []struct { M1 mapTest M2 mapTest WithOverrideEmptyValue bool ExpectedMap map[int]int }{ { M1: mapTest{ M: map[int]int{1: 1, 3: 3}, }, M2: mapTest{ M: map[int]int{1: 2, 2: 2}, }, WithOverrideEmptyValue: true, ExpectedMap: map[int]int{1: 1, 3: 3}, }, { M1: mapTest{ M: map[int]int{1: 1, 3: 3}, }, M2: mapTest{ M: map[int]int{1: 2, 2: 2}, }, WithOverrideEmptyValue: false, ExpectedMap: map[int]int{1: 1, 2: 2, 3: 3}, }, { M1: mapTest{ M: map[int]int{}, }, M2: mapTest{ M: map[int]int{1: 2, 2: 2}, }, WithOverrideEmptyValue: true, ExpectedMap: map[int]int{}, }, { M1: mapTest{ M: map[int]int{}, }, M2: mapTest{ M: map[int]int{1: 2, 2: 2}, }, WithOverrideEmptyValue: false, ExpectedMap: map[int]int{1: 2, 2: 2}, }, } func withOverrideEmptyValue(enable bool) func(*mergo.Config) { if enable { return mergo.WithOverwriteWithEmptyValue } return mergo.WithOverride } func TestMergeMapWithOverride(t *testing.T) { t.Parallel() for _, data := range testDataM { err := mergo.Merge(&data.M2, data.M1, withOverrideEmptyValue(data.WithOverrideEmptyValue)) if err != nil { t.Errorf("Error while merging %s", err) } if len(data.M2.M) != len(data.ExpectedMap) { t.Errorf("Got %d elements in map, but expected %d", len(data.M2.M), len(data.ExpectedMap)) return } for i, val := range data.M2.M { if val != data.ExpectedMap[i] { t.Errorf("Expected value: %d, but got %d while merging map", data.ExpectedMap[i], val) } } } } mergo-1.0.1/issue23_test.go000066400000000000000000000011641466020241200155040ustar00rootroot00000000000000package mergo_test import ( "testing" "time" "dario.cat/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-1.0.1/issue33_test.go000066400000000000000000000016741466020241200155130ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue38_test.go000066400000000000000000000027331466020241200155150ustar00rootroot00000000000000package mergo_test import ( "testing" "time" "dario.cat/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-1.0.1/issue50_test.go000066400000000000000000000004031466020241200154770ustar00rootroot00000000000000package mergo_test import ( "testing" "time" "dario.cat/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-1.0.1/issue52_test.go000066400000000000000000000046031466020241200155070ustar00rootroot00000000000000package mergo_test import ( "reflect" "testing" "time" "dario.cat/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-1.0.1/issue61_test.go000066400000000000000000000005711466020241200155070ustar00rootroot00000000000000package mergo_test import ( "reflect" "testing" "dario.cat/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-1.0.1/issue64_test.go000066400000000000000000000022541466020241200155120ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue66_test.go000066400000000000000000000023541466020241200155150ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue83_test.go000066400000000000000000000005721466020241200155140ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue84_test.go000066400000000000000000000030151466020241200155100ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/issue89_test.go000066400000000000000000000015641466020241200155240ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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 { expected interface{} key string }{ { "", "B", }, { false, "C", }, } 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-1.0.1/issue90_test.go000066400000000000000000000012571466020241200155130ustar00rootroot00000000000000package mergo_test import ( "reflect" "testing" "dario.cat/mergo" ) 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-1.0.1/issueXXX_test.go000066400000000000000000000021111466020241200157400ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/map.go000066400000000000000000000126031466020241200137250ustar00rootroot00000000000000// 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{typ, seen, addr} } 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 _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) || config.overwriteWithEmptyValue { 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 ErrNonPointerArgument } 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-1.0.1/merge.go000066400000000000000000000276731466020241200142640ustar00rootroot00000000000000// 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 { Transformers Transformers Overwrite bool ShouldNotDereference bool AppendSlice bool TypeCheck bool 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{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 } } 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, !config.ShouldNotDereference) || 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.CanSet() { 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, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !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, !config.ShouldNotDereference) { if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice { continue } if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map && reflect.TypeOf(dstElement.Interface()).Kind() == reflect.Map { continue } } if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement, !config.ShouldNotDereference)) { if dst.IsNil() { dst.Set(reflect.MakeMap(dst.Type())) } dst.SetMapIndex(key, srcElement) } } // Ensure that all keys in dst are deleted if they are not in src. if overwriteWithEmptySrc { for _, key := range dst.MapKeys() { srcElement := src.MapIndex(key) if !srcElement.IsValid() { dst.SetMapIndex(key, reflect.Value{}) } } } case reflect.Slice: if !dst.CanSet() { break } if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !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, !config.ShouldNotDereference)) { dst.Set(src) } } else if src.Kind() == reflect.Ptr { if !config.ShouldNotDereference { if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { return } } else if src.Elem().Kind() != reflect.Struct { if overwriteWithEmptySrc || (overwrite && !src.IsNil()) || dst.IsNil() { dst.Set(src) } } } 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, !config.ShouldNotDereference)) { 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, !config.ShouldNotDereference) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || 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 } // WithoutDereference prevents dereferencing pointers when evaluating whether they are empty // (i.e. a non-nil pointer is never considered empty). func WithoutDereference(config *Config) { config.ShouldNotDereference = 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 ErrNonPointerArgument } 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-1.0.1/merge_test.go000066400000000000000000000031601466020241200153040ustar00rootroot00000000000000package mergo_test import ( "reflect" "testing" "dario.cat/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 { Bar *bar s string } type bar struct { s map[string]string i int } 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.ErrNonPointerArgument 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.ErrNonPointerArgument if got := mergo.Merge(dst, src); got != want { t.Errorf("want: %s, got: %s", want, got) } } mergo-1.0.1/mergo.go000066400000000000000000000046311466020241200142630ustar00rootroot00000000000000// 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, 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") ErrNonPointerArgument = 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 { typ reflect.Type next *visit ptr uintptr } // From src/pkg/encoding/json/encode.go. func isEmptyValue(v reflect.Value, shouldDereference bool) 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 } if shouldDereference { return isEmptyValue(v.Elem(), shouldDereference) } return false 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 && vDst.Kind() != reflect.Slice { 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-1.0.1/mergo_test.go000066400000000000000000000517521466020241200153300ustar00rootroot00000000000000// 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" "dario.cat/mergo" "gopkg.in/yaml.v3" ) type simpleTest struct { Value int } type complexTest struct { ID string St simpleTest sz int } 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 { KeyValue map[string]interface{} Name string } 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{"bthing", simpleTest{42}, 1} 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{"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() } 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 { Multi *multiPtr Final *final Name string } type config struct { Params *params Foo string Bar string } cases := []struct { changes *config target *config output *config name string overwrite bool }{ { 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[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[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[string]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 { B *simpleTest A int hidden int } func TestBackAndForth(t *testing.T) { pt := pointerMapTest{&simpleTest{66}, 42, 1} 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{nil, 42, 1}}, {pointerMapTest{&simpleTest{66}, 42, 1}}, } 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 err string options []func(*mergo.Config) }{ { "With override and append slice", "cannot append two slices with different type", []func(*mergo.Config){mergo.WithOverride, mergo.WithAppendSlice}, }, { "With override and type check", "cannot override two slices with different type", []func(*mergo.Config){mergo.WithOverride, mergo.WithTypeCheck}, }, } 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 TestMergeDifferentSlicesIsNotSupported(t *testing.T) { src := []string{"a", "b"} dst := []int{1, 2} if err := mergo.Merge(&src, &dst, mergo.WithOverride, mergo.WithAppendSlice); err != mergo.ErrDifferentArgumentsTypes { t.Errorf("expected %q, got %q", mergo.ErrNotSupported, err) } } mergo-1.0.1/pr211_2_test.go000066400000000000000000000011161466020241200152720ustar00rootroot00000000000000package 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. } mergo-1.0.1/pr211_test.go000066400000000000000000000015451466020241200150570ustar00rootroot00000000000000package mergo_test import ( "reflect" "testing" "dario.cat/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) } } mergo-1.0.1/pr80_test.go000066400000000000000000000006001466020241200147720ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/pr81_test.go000066400000000000000000000014661466020241200150060ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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-1.0.1/testdata/000077500000000000000000000000001466020241200144305ustar00rootroot00000000000000mergo-1.0.1/testdata/license.yml000066400000000000000000000001321466020241200165710ustar00rootroot00000000000000import: ../../../../fossene/db/schema/thing.yml fields: site: string author: root mergo-1.0.1/testdata/thing.yml000066400000000000000000000001771466020241200162710ustar00rootroot00000000000000fields: id: int name: string parent: ref "datu:thing" status: enum(draft, public, private) author: updater mergo-1.0.1/v039_bugs_test.go000066400000000000000000000025541466020241200157340ustar00rootroot00000000000000package mergo_test import ( "testing" "dario.cat/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 { B map[string]issue146Bar A string } 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) } }