Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
cardinalby committed Feb 10, 2024
0 parents commit ef338c3
Show file tree
Hide file tree
Showing 25 changed files with 1,453 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/list.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: list

on:
push:
tags:
- "v*.*.*"
workflow_dispatch:
jobs:
list:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3

- uses: actions/setup-go@v4
with:
go-version-file: 'go.mod'

- run: go mod download
- run: go test ./...

- env:
GOPROXY: "proxy.golang.org"
run: go list -m github.com/cardinalby/go-dto-merge@${{ github.ref_name }}
20 changes: 20 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: test

on:
push:
branches:
- "**"
workflow_dispatch:
pull_request:
jobs:
test:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3

- uses: actions/setup-go@v4
with:
go-version-file: 'go.mod'

- run: go mod download
- run: go test ./...
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.idea
vendor
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Cardinal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
128 changes: 128 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
[![test](https://github.com/cardinalby/go-dto-merge/actions/workflows/test.yml/badge.svg)](https://github.com/cardinalby/go-dto-merge/actions/workflows/test.yml)
[![list](https://github.com/cardinalby/go-dto-merge/actions/workflows/list.yml/badge.svg)](https://github.com/cardinalby/go-dto-merge/actions/workflows/list.yml)
[![Go Reference](https://pkg.go.dev/badge/github.com/cardinalby/go-dto-merge.svg)](https://pkg.go.dev/github.com/cardinalby/go-dto-merge)

# dtomerge package

This package provides a way to deep merge two structs of the same type.

It's useful for merging **default** values with **user-provided** values (e.g. configs).
Values that are not present in the user-provided struct will be taken from the default struct.

**Only exported** fields are merged.

## Example
```
go get github.com/cardinalby/go-dto-merge
```

Example `Config` struct has a nested `UserConfig` struct.
```go

import "github.com/cardinalby/go-dto-merge"

type UserConfig struct {
Role string // for non-pointer fields zero value indicates it's not specified
Name string
}

type Config struct {
Verbose *bool // it is a pointer to distinguish between "not specified" and false
User UserConfig
}
```

Given defaults, we can merge them with user-provided values:
```go
// ptr is some helper function to create a pointer to a value
defaults := Config{ // it's called "src"
Verbose: ptr(true),
User: UserConfig{
Role: "admin",
Name: "John",
},
}
userProvided := Config{ // it's called "patch"
User: UserConfig{
Name: "Jane",
},
}
res, err := dtomerge.Merge(defaults, userProvided) // (src, patch)

// res == Config{
// Verbose: (*bool) true,
// User: UserConfig{
// Role: "admin",
// Name: "Jane",
// },
// }
```

## Pointers
Pointers can be used to distinguish between "not specified" and "explicit zero value" fields.
- If `patch` field contains a nil pointer, it will not override `defaults.Verbose`
- If `patch` field contains a pointer to zero value, it will override `src` field
only in case `src` pointer field is nil (value will be copied)
- If `patch` field contains a pointer tp **non**-zero value, it will override `src` field (value will be copied)

Use `dtomerge.OptDeRefPointers(false)` option to handle pointers as regular fields.

## Slices and maps
Setting additional option you can merge slices and maps as well.

```go

import (
"github.com/cardinalby/go-dto-merge"
"github.com/cardinalby/go-dto-merge/opt"
)

type Config struct {
Roles []string
Permissions map[string]bool
}

defaults := Config{
Roles: []string{"admin", "user"},
Permissions: map[string]bool{
"read": true,
"write": false,
},
}

userProvided := Config{
Roles: []string{"user", "guest"},
Permissions: map[string]bool{
"write": true,
},
}

res, err := dtomerge.Merge(defaults, userProvided,
// merge map keys
dtomerge.OptIterateMaps(true),
// merge slices as unique sets
dtomerge.OptMergeSlices(dtomerge.SlicesMergeStrategyUnique),
)

// res == Config{
// Roles: []string{"admin", "user", "guest"},
// Permissions: map[string]bool{
// "read": true,
// "write": true,
// },
// }
```

Possible `MergeSlices` strategies:
- `dtomerge.SlicesMergeStrategyUnique`: `[1, 2, 3] + [4, 2, 1] → [1, 2, 3, 4]`
- `dtomerge.SlicesMergeStrategyByIndex`: `[1, 2, 3] + [11, 12] → [11, 12, 3]`
- `dtomerge.SlicesMergeStrategyAtomic`: merge as a whole, default

## Other options
You can:
- specify a custom merge function for a specific type.
- specify a custom merge options for a specific type.

See [options godoc](https://pkg.go.dev/github.com/cardinalby/go-dto-merge#Options) for more details.


65 changes: 65 additions & 0 deletions any.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package dtomerge

import (
"fmt"
"reflect"

"github.com/cardinalby/go-dto-merge/types"
)

func mergeAny(src reflect.Value, patch reflect.Value, opts Options) (reflect.Value, error) {
srcType := src.Type()
patchType := patch.Type()
if srcType != patchType {
return reflect.Value{},
fmt.Errorf("%w: src type '%s' != patch type '%s'",
types.ErrInvalidTypes, srcType.Name(), patchType.Name())
}

customMergeFuncs, err := opts.getCustomReflectMergeFuncs()
if err != nil {
return reflect.Value{}, err
}

if mergeFn, has := customMergeFuncs[srcType]; has {
return mergeFn(src, patch)
}
if opts.RespectMergers {
mergeFn, isMerger := AsMerger(src)
if isMerger {
return mergeFn(patch)
}
}
if customOptions, ok := opts.CustomMergeOptions[srcType]; ok {
opts = customOptions
} else if opts.RespectMergeOptionsProviders {
if optionsProvider, ok := src.Interface().(MergeOptionsProvider); ok {
opts = optionsProvider.GetMergeOptions()
}
}

if opts.DeRefPointers && srcType.Kind() == reflect.Ptr {
return mergePointers(src, patch, opts)
}

if srcType.Kind() == reflect.Struct {
if _, isAtomic := opts.getAtomicTypesMap()[srcType]; !isAtomic {
return mergeStructs(src, patch, opts)
}
}

if opts.IterateMaps && srcType.Kind() == reflect.Map {
return mergeMaps(src, patch, opts)
}

if srcType.Kind() == reflect.Slice {
if srcType.Elem().Comparable() && opts.SlicesMerge == SlicesMergeStrategyUnique {
return mergeComparableSlicesUnique(src, patch, opts)
}
if opts.SlicesMerge == SlicesMergeStrategyByIndex {
return mergeSlicesByIndex(src, patch, opts)
}
}

return mergeSimpleValue(src, patch, opts)
}
45 changes: 45 additions & 0 deletions examples/1_simple_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package examples

import (
"testing"

dtomerge "github.com/cardinalby/go-dto-merge"
"github.com/stretchr/testify/require"
)

func ptr[T any](v T) *T {
return &v
}

func TestSimpleExample(t *testing.T) {
t.Parallel()

type UserConfig struct {
Role string // for non-pointer fields zero value indicates it's not specified
Name string
}

type Config struct {
Verbose *bool // it is a pointer to distinguish between "not specified" and false
User UserConfig
}

defaults := Config{
Verbose: ptr(true),
User: UserConfig{
Role: "admin",
Name: "John",
},
}
userProvided := Config{
User: UserConfig{
Name: "Jane",
},
}
res, err := dtomerge.Merge(defaults, userProvided)
require.NoError(t, err)

require.Equal(t, true, *res.Verbose)
require.Equal(t, "admin", res.User.Role)
require.Equal(t, "Jane", res.User.Name)
}
44 changes: 44 additions & 0 deletions examples/2_maps_slices_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package examples

import (
"testing"

dtomerge "github.com/cardinalby/go-dto-merge"
"github.com/stretchr/testify/require"
)

func TestSlicesMapsExample(t *testing.T) {
t.Parallel()

type Config struct {
Roles []string
Permissions map[string]bool
}

defaults := Config{
Roles: []string{"admin", "user"},
Permissions: map[string]bool{
"read": true,
"write": false,
},
}

userProvided := Config{
Roles: []string{"user", "guest"},
Permissions: map[string]bool{
"write": true,
},
}

res, err := dtomerge.Merge(defaults, userProvided,
dtomerge.OptIterateMaps(true),
dtomerge.OptMergeSlices(dtomerge.SlicesMergeStrategyUnique),
)
require.NoError(t, err)

require.Equal(t, []string{"admin", "user", "guest"}, res.Roles)
require.Equal(t, map[string]bool{
"read": true,
"write": true,
}, res.Permissions)
}
10 changes: 10 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module github.com/cardinalby/go-dto-merge

go 1.19

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.8.4 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
9 changes: 9 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
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=
Loading

0 comments on commit ef338c3

Please sign in to comment.