v1.0.1
This commit is contained in:
commit
b90e1881c2
61 changed files with 4330 additions and 0 deletions
12
.deepsource.toml
Normal file
12
.deepsource.toml
Normal file
|
@ -0,0 +1,12 @@
|
|||
version = 1
|
||||
|
||||
test_patterns = [
|
||||
"*_test.go"
|
||||
]
|
||||
|
||||
[[analyzers]]
|
||||
name = "go"
|
||||
enabled = true
|
||||
|
||||
[analyzers.meta]
|
||||
import_path = "git.ct129.com/VPN/mergo"
|
5
.github/FUNDING.yml
vendored
Normal file
5
.github/FUNDING.yml
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
# These are supported funding model platforms
|
||||
|
||||
github: darccio
|
||||
tidelift: go/git.ct129.com/VPN/mergo
|
||||
thanks_dev: gh/darccio
|
11
.github/dependabot.yml
vendored
Normal file
11
.github/dependabot.yml
vendored
Normal file
|
@ -0,0 +1,11 @@
|
|||
# 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"
|
72
.github/workflows/codeql-analysis.yml
vendored
Normal file
72
.github/workflows/codeql-analysis.yml
vendored
Normal file
|
@ -0,0 +1,72 @@
|
|||
# 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
|
31
.github/workflows/openssf.yml
vendored
Normal file
31
.github/workflows/openssf.yml
vendored
Normal file
|
@ -0,0 +1,31 @@
|
|||
name: '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
|
18
.github/workflows/tests.yml
vendored
Normal file
18
.github/workflows/tests.yml
vendored
Normal file
|
@ -0,0 +1,18 @@
|
|||
name: '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 ./...
|
36
.gitignore
vendored
Normal file
36
.gitignore
vendored
Normal file
|
@ -0,0 +1,36 @@
|
|||
#### 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
|
12
.travis.yml
Normal file
12
.travis.yml
Normal file
|
@ -0,0 +1,12 @@
|
|||
language: go
|
||||
arch:
|
||||
- amd64
|
||||
- ppc64le
|
||||
install:
|
||||
- go get -t
|
||||
- go get golang.org/x/tools/cmd/cover
|
||||
- go get github.com/mattn/goveralls
|
||||
script:
|
||||
- go test -race -v ./...
|
||||
after_script:
|
||||
- $HOME/gopath/bin/goveralls -service=travis-ci -repotoken $COVERALLS_TOKEN
|
7
.vscode/settings.json
vendored
Normal file
7
.vscode/settings.json
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"go.lintTool": "golangci-lint",
|
||||
"go.lintFlags": [
|
||||
"--enable-all",
|
||||
"--disable=gomnd"
|
||||
]
|
||||
}
|
46
CODE_OF_CONDUCT.md
Normal file
46
CODE_OF_CONDUCT.md
Normal file
|
@ -0,0 +1,46 @@
|
|||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at i@dario.im. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
112
CONTRIBUTING.md
Normal file
112
CONTRIBUTING.md
Normal file
|
@ -0,0 +1,112 @@
|
|||
<!-- omit in toc -->
|
||||
# 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
|
||||
|
||||
<!-- omit in toc -->
|
||||
## 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://git.ct129.com/VPN/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/git.ct129.com/VPN/mergo).
|
||||
|
||||
Before you ask a question, it is best to search for existing [Issues](https://git.ct129.com/VPN/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://git.ct129.com/VPN/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 <!-- omit in toc -->
|
||||
> 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
|
||||
|
||||
<!-- omit in toc -->
|
||||
#### 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://git.ct129.com/VPN/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?
|
||||
|
||||
<!-- omit in toc -->
|
||||
#### 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 .
|
||||
<!-- You may add a PGP key to allow the messages to be sent encrypted as well. -->
|
||||
|
||||
We use GitHub issues to track bugs and errors. If you run into an issue with the project:
|
||||
|
||||
- Open an [Issue](https://git.ct129.com/VPN/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.
|
||||
|
||||
<!-- omit in toc -->
|
||||
#### 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://git.ct129.com/VPN/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.
|
||||
|
||||
<!-- omit in toc -->
|
||||
#### How Do I Submit a Good Enhancement Suggestion?
|
||||
|
||||
Enhancement suggestions are tracked as [GitHub issues](https://git.ct129.com/VPN/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. <!-- this should only be included if the project has a GUI -->
|
||||
- **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.
|
||||
|
||||
<!-- omit in toc -->
|
||||
## Attribution
|
||||
This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)!
|
7
FUNDING.json
Normal file
7
FUNDING.json
Normal file
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"drips": {
|
||||
"ethereum": {
|
||||
"ownedBy": "0x6160020e7102237aC41bdb156e94401692D76930"
|
||||
}
|
||||
}
|
||||
}
|
28
LICENSE
Normal file
28
LICENSE
Normal file
|
@ -0,0 +1,28 @@
|
|||
Copyright (c) 2013 Dario Castañé. All rights reserved.
|
||||
Copyright (c) 2012 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
258
README.md
Normal file
258
README.md
Normal file
|
@ -0,0 +1,258 @@
|
|||
# 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://git.ct129.com/VPN/mergo/workflows/tests/badge.svg?branch=master
|
||||
[2]: https://git.ct129.com/VPN/mergo/actions/workflows/tests.yml
|
||||
[3]: https://godoc.org/git.ct129.com/VPN/mergo?status.svg
|
||||
[4]: https://godoc.org/git.ct129.com/VPN/mergo
|
||||
[5]: https://img.shields.io/github/release/imdario/mergo.svg
|
||||
[6]: https://git.ct129.com/VPN/mergo/releases
|
||||
[7]: https://goreportcard.com/badge/imdario/mergo
|
||||
[8]: https://goreportcard.com/report/git.ct129.com/VPN/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/git.ct129.com/VPN/mergo/-/badge.svg
|
||||
[12]: https://sourcegraph.com/git.ct129.com/VPN/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/git.ct129.com/VPN/mergo/badge
|
||||
[22]: https://api.securityscorecards.dev/projects/git.ct129.com/VPN/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://git.ct129.com/VPN/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](//git.ct129.com/VPN/mergo/releases/tag/1.0.0) Mergo moves to a vanity URL `git.ct129.com/VPN/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 git.ct129.com/VPN/mergo => git.ct129.com/VPN/mergo v0.3.16
|
||||
```
|
||||
|
||||
#### 0.3.9
|
||||
|
||||
Please keep in mind that a problematic PR broke [0.3.9](//git.ct129.com/VPN/mergo/releases/tag/0.3.9). I reverted it in [0.3.10](//git.ct129.com/VPN/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](//git.ct129.com/VPN/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 git.ct129.com/VPN/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
|
||||
|
||||
### Donations
|
||||
|
||||
If Mergo is useful to you, consider buying me a coffee, a beer, or making a monthly donation to allow me to keep building great free software. :heart_eyes:
|
||||
|
||||
<a href="https://liberapay.com/dario/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a>
|
||||
<a href='https://github.com/sponsors/imdario' target='_blank'><img alt="Become my sponsor" src="https://img.shields.io/github/sponsors/imdario?style=for-the-badge" /></a>
|
||||
|
||||
### 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 git.ct129.com/VPN/mergo
|
||||
|
||||
// use in your .go code
|
||||
import (
|
||||
"git.ct129.com/VPN/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"
|
||||
|
||||
"git.ct129.com/VPN/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"
|
||||
"git.ct129.com/VPN/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"
|
||||
"git.ct129.com/VPN/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).
|
||||
|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large)
|
14
SECURITY.md
Normal file
14
SECURITY.md
Normal file
|
@ -0,0 +1,14 @@
|
|||
# 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.
|
148
doc.go
Normal file
148
doc.go
Normal file
|
@ -0,0 +1,148 @@
|
|||
// 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 `git.ct129.com/VPN/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 git.ct129.com/VPN/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 git.ct129.com/VPN/mergo
|
||||
|
||||
// use in your .go code
|
||||
import (
|
||||
"git.ct129.com/VPN/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"
|
||||
"git.ct129.com/VPN/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"
|
||||
"git.ct129.com/VPN/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
|
5
go.mod
Normal file
5
go.mod
Normal file
|
@ -0,0 +1,5 @@
|
|||
module git.ct129.com/VPN/mergo
|
||||
|
||||
go 1.13
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1
|
4
go.sum
Normal file
4
go.sum
Normal file
|
@ -0,0 +1,4 @@
|
|||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
21
issue100_test.go
Normal file
21
issue100_test.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
48
issue104_test.go
Normal file
48
issue104_test.go
Normal file
|
@ -0,0 +1,48 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
35
issue121_test.go
Normal file
35
issue121_test.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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'")
|
||||
}
|
||||
}
|
47
issue123_test.go
Normal file
47
issue123_test.go
Normal file
|
@ -0,0 +1,47 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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])
|
||||
}
|
||||
}
|
||||
}
|
40
issue125_test.go
Normal file
40
issue125_test.go
Normal file
|
@ -0,0 +1,40 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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")
|
||||
}
|
||||
}
|
49
issue129_test.go
Normal file
49
issue129_test.go
Normal file
|
@ -0,0 +1,49 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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")
|
||||
}
|
||||
}
|
122
issue131_test.go
Normal file
122
issue131_test.go
Normal file
|
@ -0,0 +1,122 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
35
issue136_test.go
Normal file
35
issue136_test.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
42
issue138_test.go
Normal file
42
issue138_test.go
Normal file
|
@ -0,0 +1,42 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
61
issue143_test.go
Normal file
61
issue143_test.go
Normal file
|
@ -0,0 +1,61 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
||||
}
|
39
issue149_test.go
Normal file
39
issue149_test.go
Normal file
|
@ -0,0 +1,39 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
21
issue174_test.go
Normal file
21
issue174_test.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
28
issue17_test.go
Normal file
28
issue17_test.go
Normal file
|
@ -0,0 +1,28 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
71
issue187_test.go
Normal file
71
issue187_test.go
Normal file
|
@ -0,0 +1,71 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"git.ct129.com/VPN/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"])
|
||||
}
|
||||
}
|
138
issue202_test.go
Normal file
138
issue202_test.go
Normal file
|
@ -0,0 +1,138 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
26
issue209_test.go
Normal file
26
issue209_test.go
Normal file
|
@ -0,0 +1,26 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
||||
}
|
33
issue220_test.go
Normal file
33
issue220_test.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
85
issue230_test.go
Normal file
85
issue230_test.go
Normal file
|
@ -0,0 +1,85 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
31
issue23_test.go
Normal file
31
issue23_test.go
Normal file
|
@ -0,0 +1,31 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
37
issue33_test.go
Normal file
37
issue33_test.go
Normal file
|
@ -0,0 +1,37 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
67
issue38_test.go
Normal file
67
issue38_test.go
Normal file
|
@ -0,0 +1,67 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
21
issue50_test.go
Normal file
21
issue50_test.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.ct129.com/VPN/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()
|
||||
}
|
||||
}
|
113
issue52_test.go
Normal file
113
issue52_test.go
Normal file
|
@ -0,0 +1,113 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
24
issue61_test.go
Normal file
24
issue61_test.go
Normal file
|
@ -0,0 +1,24 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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()
|
||||
}
|
||||
}
|
46
issue64_test.go
Normal file
46
issue64_test.go
Normal file
|
@ -0,0 +1,46 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
56
issue66_test.go
Normal file
56
issue66_test.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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")
|
||||
}
|
||||
}
|
22
issue83_test.go
Normal file
22
issue83_test.go
Normal file
|
@ -0,0 +1,22 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
90
issue84_test.go
Normal file
90
issue84_test.go
Normal file
|
@ -0,0 +1,90 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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'")
|
||||
}
|
||||
}
|
53
issue89_test.go
Normal file
53
issue89_test.go
Normal file
|
@ -0,0 +1,53 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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])
|
||||
}
|
||||
}
|
||||
}
|
43
issue90_test.go
Normal file
43
issue90_test.go
Normal file
|
@ -0,0 +1,43 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
37
issueXXX_test.go
Normal file
37
issueXXX_test.go
Normal file
|
@ -0,0 +1,37 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
178
map.go
Normal file
178
map.go
Normal file
|
@ -0,0 +1,178 @@
|
|||
// 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)
|
||||
}
|
409
merge.go
Normal file
409
merge.go
Normal file
|
@ -0,0 +1,409 @@
|
|||
// 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
|
||||
}
|
||||
}
|
88
merge_test.go
Normal file
88
merge_test.go
Normal file
|
@ -0,0 +1,88 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
81
mergo.go
Normal file
81
mergo.go
Normal file
|
@ -0,0 +1,81 @@
|
|||
// 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
|
||||
}
|
940
mergo_test.go
Normal file
940
mergo_test.go
Normal file
|
@ -0,0 +1,940 @@
|
|||
// Copyright 2013 Dario Castañé. All rights reserved.
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mergo_test
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
25
pr211_2_test.go
Normal file
25
pr211_2_test.go
Normal file
|
@ -0,0 +1,25 @@
|
|||
package mergo
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type transformer struct {
|
||||
}
|
||||
|
||||
func (s *transformer) Transformer(t reflect.Type) func(dst, src reflect.Value) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func Test_deepMergeTransformerInvalidDestination(t *testing.T) {
|
||||
foo := time.Time{}
|
||||
src := reflect.ValueOf(foo)
|
||||
deepMerge(reflect.Value{}, src, make(map[uintptr]*visit), 0, &Config{
|
||||
Transformers: &transformer{},
|
||||
})
|
||||
// this test is intentionally not asserting on anything, it's sole
|
||||
// purpose to verify deepMerge doesn't panic when a transformer is
|
||||
// passed and the destination is invalid.
|
||||
}
|
36
pr211_test.go
Normal file
36
pr211_test.go
Normal file
|
@ -0,0 +1,36 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
20
pr80_test.go
Normal file
20
pr80_test.go
Normal file
|
@ -0,0 +1,20 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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")
|
||||
}
|
||||
}
|
44
pr81_test.go
Normal file
44
pr81_test.go
Normal file
|
@ -0,0 +1,44 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
4
testdata/license.yml
vendored
Normal file
4
testdata/license.yml
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
import: ../../../../fossene/db/schema/thing.yml
|
||||
fields:
|
||||
site: string
|
||||
author: root
|
6
testdata/thing.yml
vendored
Normal file
6
testdata/thing.yml
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
fields:
|
||||
id: int
|
||||
name: string
|
||||
parent: ref "datu:thing"
|
||||
status: enum(draft, public, private)
|
||||
author: updater
|
92
v039_bugs_test.go
Normal file
92
v039_bugs_test.go
Normal file
|
@ -0,0 +1,92 @@
|
|||
package mergo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ct129.com/VPN/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)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue