aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/config/merge.go
blob: ae432094627e205c0eb6e39fc1146f5424f97836 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2021 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package config

import (
	"encoding/json"
)

// Unfortunately, if we want to apply a JSON patch to some configuration, we cannot just unmarshal
// it twice - in that case json.RawMessage objects will be completely replaced, but not merged.
func MergeJSONs(left, right []byte) ([]byte, error) {
	vLeft, err := parseFragment(left)
	if err != nil {
		return nil, err
	}
	vRight, err := parseFragment(right)
	if err != nil {
		return nil, err
	}
	return json.Marshal(mergeRecursive(vLeft, vRight))
}

// Recursively apply a patch to a raw JSON data.
// Patch is supposed to be a map, which possibly nests other map objects.
func PatchJSON(left []byte, patch map[string]any) ([]byte, error) {
	vLeft, err := parseFragment(left)
	if err != nil {
		return nil, err
	}
	return json.Marshal(mergeRecursive(vLeft, patch))
}

func parseFragment(input []byte) (parsed any, err error) {
	if len(input) == 0 {
		// For convenience, we allow empty strings to be passed to the function that merges JSONs.
		return
	}
	err = json.Unmarshal(json.RawMessage(input), &parsed)
	return
}

// If one of the elements is not a map, use the new one.
// Otherwise, recursively merge map elements.
func mergeRecursive(left, right any) any {
	if left == nil {
		return right
	}
	if right == nil {
		return left
	}
	mLeft, okLeft := left.(map[string]any)
	mRight, okRight := right.(map[string]any)
	if !okLeft || !okRight {
		return right
	}
	for key, val := range mRight {
		valLeft, ok := mLeft[key]
		if ok {
			mLeft[key] = mergeRecursive(valLeft, val)
		} else {
			mLeft[key] = val
		}
	}
	return mLeft
}