A small flexible merge library in go

conjungo

LICENSE Golang Godocs Go Report Card Travis Build Status codecov

A merge utility designed for flexibility and customizability. The library has a single simple point of entry that works out of the box for most basic use cases. From there, customizations can be made to the way two items are merged to fit your specific needs.

Merge any two things of the same type, including maps, slices, structs, and even basic types like string and int. By default, the target value will be overwritten by the source. If the overwrite option is turned off, only new values in source that do not already exist in target will be added.

If you would like to change the way two items of a particular type get merged, custom merge functions can be defined for any type or kind (see below).

Why Conjungo?

The definition of Conjungo:

I.v. a., to bind together, connect, join, unite (very freq. in all perr. and species of composition); constr. with cum, inter se, the dat., or the acc. only; trop. also with ad.

Reference: Latin Dictionary...

There are other merge libraries written in go, but none of them have the flexibility of this one. If you simply need to merge two things, a default set of merge functions are defined for merging maps, slices, and structs like most other libraries. But, if the way these default functions are defined does not meet your needs, Conjungo provides the ability to define your own merge functions. For instance, the default behavior when merging two integers is to replace the target with the source, but if you'd like to redefine that, you can write a custom merge function that is used when assessing integers. A custom function could add the two integers and return the result, or return the larger of the two integers. You could define a custom merge function for a specific struct type in your code, and define how that gets merged. The customizability of how things get merged is the focus of Conjungo.

The need for this library arose when we were merging large custom structs. We found that there was no single library that merged all the parts of the struct in the way that we needed. We had struct fields that were pointers to sub structs and maps that needed to be followed instead of simply replaced. We had slices that needed to be appended but also deduped. Conjungo solves these types of problems by allowing custom functions to be defined to handle each type.

Setup

To get conjungo:

go get github.com/InVisionApp/conjungo

We recommend that you vendor it within your project. We chose to use govendor.

govendor fetch github.com/InVisionApp/conjungo

Usage

Simple Merge

Merge two structs together:

type Foo struct {
	Name    string
	Size    int
	Special bool
	SubMap  map[string]string
}

targetStruct := Foo{
	Name:    "target",
	Size:    2,
	Special: false,
	SubMap:  map[string]string{"foo": "unchanged", "bar": "orig"},
}

sourceStruct := Foo{
	Name:    "source",
	Size:    4,
	Special: true,
	SubMap:  map[string]string{"bar": "newVal", "safe": "added"},
}

err := conjungo.Merge(&targetStruct, sourceStruct, nil)
if err != nil {
	log.Error(err)
}

results in:

{
  "Name": "source",
  "Size": 4,
  "Special": true,
  "SubMap": {
    "bar": "newVal",
    "foo": "unchanged",
    "safe": "added"
  }
}

Options

Overwrite bool
If true, overwrite a target value with source value even if it already exists

ErrorOnUnexported bool
Unexported fields on a struct can not be set. When a struct contains an unexported field, the default behavior is to treat the entire struct as a single entity and replace according to Overwrite settings.
If this is enabled, an error will be thrown instead.

Custom Merge Functions

Define a custom merge function for a type:

opts := conjungo.NewOptions()
opts.MergeFuncs.SetTypeMergeFunc(
	reflect.TypeOf(0),
	// merge two 'int' types by adding them together
	func(t, s reflect.Value, o *conjungo.Options) (reflect.Value, error) {
		iT, _ := t.Interface().(int)
		iS, _ := s.Interface().(int)
		return reflect.ValueOf(iT + iS), nil
	},
)

x := 1
y := 2

err := conjungo.Merge(&x, y, opts)
if err != nil {
	log.Error(err)
}

// x == 3

Define a custom merge function for a kind:

opts := conjungo.NewOptions()
opts.MergeFuncs.SetKindMergeFunc(
	reflect.TypeOf(struct{}{}).Kind(),
	// merge two 'struct' kinds by replacing the target with the source
	// provides a mechanism to set override = true for just structs
	func(t, s reflect.Value, o *conjungo.Options) (reflect.Value, error) {
		return s, nil
	},
)

Define a custom merge function for a struct type:

	type Foo struct {
		Name string
		Size int
	}

	target := Foo{
		Name: "bar",
		Size: 25,
	}

	source := Foo{
		Name: "baz",
		Size: 35,
	}

	opts := conjungo.NewOptions()
	opts.MergeFuncs.SetTypeMergeFunc(
		reflect.TypeOf(Foo{}),
		// merge two 'int' types by adding them together
		func(t, s reflect.Value, o *conjungo.Options) (reflect.Value, error) {
			tFoo := t.Interface().(Foo)
			sFoo := s.Interface().(Foo)

			// names are merged by concatenating them
			tFoo.Name = tFoo.Name + "." + sFoo.Name
			// sizes are merged by averaging them
			tFoo.Size = (tFoo.Size + sFoo.Size) / 2

			return reflect.ValueOf(tFoo), nil
		},
	)

Define a custom type and a function to merge it:

type jsonString string

var targetJSON jsonString = `
{
  "a": "wrong",
  "b": 1,
  "c": {"bar": "orig", "foo": "unchanged"},
}`

var sourceJSON jsonString = `
{
  "a": "correct",
  "b": 2,
  "c": {"bar": "newVal", "safe": "added"},
}`

opts := conjungo.NewOptions()
opts.MergeFuncs.SetTypeMergeFunc(
	reflect.TypeOf(jsonString("")),
	// merge two json strings by unmarshalling them to maps
	func(t, s reflect.Value, o *conjungo.Options) (reflect.Value, error) {
		targetStr, _ := t.Interface().(jsonString)
		sourceStr, _ := s.Interface().(jsonString)

		targetMap := map[string]interface{}{}
		if err := json.Unmarshal([]byte(targetStr), &targetMap); err != nil {
			return reflect.Value{}, err
		}

		sourceMap := map[string]interface{}{}
		if err := json.Unmarshal([]byte(sourceStr), &sourceMap); err != nil {
			return reflect.Value{}, err
		}

		err := conjungo.Merge(&targetMap, sourceMap, o)
		if err != nil {
			return reflect.Value{}, err
		}

		mergedJSON, err := json.Marshal(targetMap)
		if err != nil {
			return reflect.Value{}, err
		}

		return reflect.ValueOf(jsonString(mergedJSON)), nil
	},
)

See working examples for more details.

Comments
  • Convert to using reflect.Value instead of Interface{}

    Convert to using reflect.Value instead of Interface{}

    reflect.Value has more flexibility than an interface. Change how things work internally, so that is what gets passed around. This also allows for generic merge functions of maps of any types. Also switch to requiring the target passed as a pointer and setting its value instead of returning the merged item.

  • Creates duplicates in nested struct slices

    Creates duplicates in nested struct slices

    Behavior

    When merging a struct with slices of structs, Conjungo will create duplicate items in the slice.

    Expected Behavior

    When merging a slice of structs in a struct I expect it to not create duplicates in the array, but skip the structs that are equal.

    Test Case

    package main
    
    import (
    	"testing"
    
    	"github.com/InVisionApp/conjungo"
    	"github.com/stretchr/testify/assert"
    )
    
    type TestStruct struct {
    	Val       string
    	Resources []NestedStruct
    }
    
    type NestedStruct struct {
    	Key string
    	Val string
    }
    
    func TestNestedStructMerge(t *testing.T) {
    	s1 := TestStruct{
    		Val: "a struct",
    		Resources: []NestedStruct{
    			NestedStruct{
    				Key: "k1",
    				Val: "v1",
    			},
    		},
    	}
    
    	s2 := TestStruct{
    		Val: "a struct",
    		Resources: []NestedStruct{
    			NestedStruct{
    				Key: "k1",
    				Val: "v1",
    			},
    		},
    	}
    
    	// Confirming that the Resources are equal according to the == operator
    	assert.Equal(t, s2.Resources, s1.Resources)
    
    	// Confirming that the main structs themselves are equal according to the == operator
    	assert.Equal(t, s2, s1)
    
    	// Asserting no errors
    	assert.Nil(t, conjungo.Merge(&s2, s1, conjungo.NewOptions()))
    
    	// I expect there to be only 1 item in the target struct's array
    	assert.Len(t, s2.Resources, 1)
    }
    
  • accept values

    accept values

    Overall robustness:

    • Accept reflect.Value of the target and source to merge.
    • Accept a pointer to source
    • Accept uninitialized targets
    • Robust panic recovery
  • Prep oss

    Prep oss

    • Added LICENSE
    • Added Badges for GoDoc, Go Report Card, Code Coverage, Travis
    • Renamed project to conjungo
    • Fixed references
    • Added Code Coverage webhooks
  • Proposal: Introduce go modules and reduce dependency footprint

    Proposal: Introduce go modules and reduce dependency footprint

    Go modules is kinda self explanatory. Removed logrus to reduce the dependency footprint. If we really want a logger for those kind of warnings, we should accept a logger interface in opts.

  • Proposal: Treat byte slices `[]byte` as single entity

    Proposal: Treat byte slices `[]byte` as single entity

    Currently byte slices are treated like normal slices and the default behaviour of mergeSlice would append those together. This PR provides a predefined merge func for byte slices to treat them as a single entity.

  • Deep merge should continue on Ptr, fixes #23

    Deep merge should continue on Ptr, fixes #23

    Test case for #23. As stated there, the deep merge stops once a target is a pointer. The pointer should be dereferenced and the deep merge should continue.

  • Proposal: Add merge type 'interface' for types which implement an interface

    Proposal: Add merge type 'interface' for types which implement an interface

    Adds a merge type Implements which sits between Type and Kind merge. Useful for cases where you have many types needed to merge in a specific way without the need to change the merge for a kind, since you don't want all of those kinds to be merged that way.

    Personal real world example: Merge slices of pointers of some types in a specific way, but not all types of kind slice. E.g. Merge the elements of that slice by a specific Key (exposed by MergeKey() string or similiar), instead of just appending them.

  • Proposal: Add option IgnoreEmpty to always ignore source value when it is zero

    Proposal: Add option IgnoreEmpty to always ignore source value when it is zero

    Useful in combination with overwrite to only overwrite if the source is actually set. One can also make that possible by providing his own default func, but I thought this feature is worth to be available directly. Backwards compatible, does not change the current behaviour (see tests).

    reflect.Value{}.IsZero() is available since golang 1.13 and the issue leading to this function and the reasoning behind it: https://github.com/golang/go/issues/7501

    My gut proposed to change how isEmpty() works, but that broke a lot of things as it is used in a lot of places. So I kept adding this feature with as minimal changes as possible

  • Yields different results if a structs field is a pointer vs. value

    Yields different results if a structs field is a pointer vs. value

    https://play.golang.org/p/mgcKU7YcxX1

    That also results to the custom type merge function not beeing called.

    I debugged it until https://github.com/InVisionApp/conjungo/blob/master/mfunc.go#L60. Where v.Type() is Ptr, and it can't find a default merge function for that kind, since there's none.

    So it continues and uses https://github.com/InVisionApp/conjungo/blob/master/mfunc.go#L80 which just replaces the whole tree without deep merging further

Distributed merge sort for large sets across nodes in a network

distMergeSort An implementation of mergesort distributed across nodes used to sort large sets. Introduction Merge sort partitions sets so that they ca

Jul 8, 2022
flexible data type for Go
flexible data type for Go

Generic flexible data type for Go support: Go 1.12+ Install standard go get: go get -u github.com/usk81/generic/v2 Usage encode/decode: package main

Dec 31, 2022
A threadsafe single-value cache for Go with a simple but flexible API

SVCache SVCache is a threadsafe, single-value cache with a simple but flexible API. When there is no fresh value in the cache, an attempt to retrieve

Jan 23, 2022
Package set is a small wrapper around the official reflect package that facilitates loose type conversion and assignment into native Go types.

Package set is a small wrapper around the official reflect package that facilitates loose type conversion and assignment into native Go types. Read th

Dec 27, 2022
A small SAT solver in Go

Saturday Saturday is a simple SAT solver in Go that implements the Davis-Putnam backtracking algorithm plus a few optimizations as described in the 20

Sep 24, 2021
A fast (5x) string keyed read-only map for Go - particularly good for keys using a small set of nearby runes.

faststringmap faststringmap is a fast read-only string keyed map for Go (golang). For our use case it is approximately 5 times faster than using Go's

Jan 8, 2023
Golang string comparison and edit distance algorithms library, featuring : Levenshtein, LCS, Hamming, Damerau levenshtein (OSA and Adjacent transpositions algorithms), Jaro-Winkler, Cosine, etc...

Go-edlib : Edit distance and string comparison library Golang string comparison and edit distance algorithms library featuring : Levenshtein, LCS, Ham

Dec 20, 2022
Go native library for fast point tracking and K-Nearest queries

Geo Index Geo Index library Overview Splits the earth surface in a grid. At each cell we can store data, such as list of points, count of points, etc.

Dec 3, 2022
Data structure and algorithm library for go, designed to provide functions similar to C++ STL

GoSTL English | 简体中文 Introduction GoSTL is a data structure and algorithm library for go, designed to provide functions similar to C++ STL, but more p

Dec 26, 2022
Zero allocation Nullable structures in one library with handy conversion functions, marshallers and unmarshallers

nan - No Allocations Nevermore Package nan - Zero allocation Nullable structures in one library with handy conversion functions, marshallers and unmar

Dec 20, 2022
A Go library for an efficient implementation of a skip list: https://godoc.org/github.com/MauriceGit/skiplist
A Go library for an efficient implementation of a skip list: https://godoc.org/github.com/MauriceGit/skiplist

Fast Skiplist Implementation This Go-library implements a very fast and efficient Skiplist that can be used as direct substitute for a balanced tree o

Dec 30, 2022
Go Library [DEPRECATED]

Tideland Go Library Description The Tideland Go Library contains a larger set of useful Google Go packages for different purposes. ATTENTION: The cell

Nov 15, 2022
an R-Tree library for Go

rtreego A library for efficiently storing and querying spatial data in the Go programming language. About The R-tree is a popular data structure for e

Jan 3, 2023
Golang library for reading and writing Microsoft Excel™ (XLSX) files.
Golang library for reading and writing Microsoft Excel™ (XLSX) files.

Excelize Introduction Excelize is a library written in pure Go providing a set of functions that allow you to write to and read from XLSX / XLSM / XLT

Jan 9, 2023
Golang library for querying and parsing OFX

OFXGo OFXGo is a library for querying OFX servers and/or parsing the responses. It also provides an example command-line client to demonstrate the use

Nov 25, 2022
Go (golang) library for reading and writing XLSX files.

XLSX Introduction xlsx is a library to simplify reading and writing the XML format used by recent version of Microsoft Excel in Go programs. Tutorial

Jan 5, 2023
indexing library for Go

Bluge modern text indexing in go - blugelabs.com Features Supported field types: Text, Numeric, Date, Geo Point Supported query types: Term, Phrase, M

Jan 3, 2023
A feature complete and high performance multi-group Raft library in Go.
A feature complete and high performance multi-group Raft library in Go.

Dragonboat - A Multi-Group Raft library in Go / 中文版 News 2021-01-20 Dragonboat v3.3 has been released, please check CHANGELOG for all changes. 2020-03

Jan 5, 2023
Go library implementing xor filters
Go library implementing xor filters

xorfilter: Go library implementing xor filters Bloom filters are used to quickly check whether an element is part of a set. Xor filters are a faster a

Dec 30, 2022