summaryrefslogtreecommitdiff
path: root/vendor/gomodules.xyz/jsonpatch/v2/jsonpatch.go
blob: a411d542c68cafe426379a72caaa5c5cb59158e2 (about) (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package jsonpatch

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strings"
)

var errBadJSONDoc = fmt.Errorf("invalid JSON Document")

type JsonPatchOperation = Operation

type Operation struct {
	Operation string      `json:"op"`
	Path      string      `json:"path"`
	Value     interface{} `json:"value,omitempty"`
}

func (j *Operation) Json() string {
	b, _ := json.Marshal(j)
	return string(b)
}

func (j *Operation) MarshalJSON() ([]byte, error) {
	// Ensure for add and replace we emit `value: null`
	if j.Value == nil && (j.Operation == "replace" || j.Operation == "add") {
		return json.Marshal(struct {
			Operation string      `json:"op"`
			Path      string      `json:"path"`
			Value     interface{} `json:"value"`
		}{
			Operation: j.Operation,
			Path:      j.Path,
		})
	}
	// otherwise just marshal normally. We cannot literally do json.Marshal(j) as it would be recursively
	// calling this function.
	return json.Marshal(struct {
		Operation string      `json:"op"`
		Path      string      `json:"path"`
		Value     interface{} `json:"value,omitempty"`
	}{
		Operation: j.Operation,
		Path:      j.Path,
		Value:     j.Value,
	})
}

type ByPath []Operation

func (a ByPath) Len() int           { return len(a) }
func (a ByPath) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByPath) Less(i, j int) bool { return a[i].Path < a[j].Path }

func NewOperation(op, path string, value interface{}) Operation {
	return Operation{Operation: op, Path: path, Value: value}
}

// CreatePatch creates a patch as specified in http://jsonpatch.com/
//
// 'a' is original, 'b' is the modified document. Both are to be given as json encoded content.
// The function will return an array of JsonPatchOperations
//
// An error will be returned if any of the two documents are invalid.
func CreatePatch(a, b []byte) ([]Operation, error) {
	var aI interface{}
	var bI interface{}
	err := json.Unmarshal(a, &aI)
	if err != nil {
		return nil, errBadJSONDoc
	}
	err = json.Unmarshal(b, &bI)
	if err != nil {
		return nil, errBadJSONDoc
	}
	return handleValues(aI, bI, "", []Operation{})
}

// Returns true if the values matches (must be json types)
// The types of the values must match, otherwise it will always return false
// If two map[string]interface{} are given, all elements must match.
func matchesValue(av, bv interface{}) bool {
	if reflect.TypeOf(av) != reflect.TypeOf(bv) {
		return false
	}
	switch at := av.(type) {
	case string:
		bt, ok := bv.(string)
		if ok && bt == at {
			return true
		}
	case float64:
		bt, ok := bv.(float64)
		if ok && bt == at {
			return true
		}
	case bool:
		bt, ok := bv.(bool)
		if ok && bt == at {
			return true
		}
	case map[string]interface{}:
		bt, ok := bv.(map[string]interface{})
		if !ok {
			return false
		}
		for key := range at {
			if !matchesValue(at[key], bt[key]) {
				return false
			}
		}
		for key := range bt {
			if !matchesValue(at[key], bt[key]) {
				return false
			}
		}
		return true
	case []interface{}:
		bt, ok := bv.([]interface{})
		if !ok {
			return false
		}
		if len(bt) != len(at) {
			return false
		}
		for key := range at {
			if !matchesValue(at[key], bt[key]) {
				return false
			}
		}
		for key := range bt {
			if !matchesValue(at[key], bt[key]) {
				return false
			}
		}
		return true
	}
	return false
}

// From http://tools.ietf.org/html/rfc6901#section-4 :
//
// Evaluation of each reference token begins by decoding any escaped
// character sequence.  This is performed by first transforming any
// occurrence of the sequence '~1' to '/', and then transforming any
// occurrence of the sequence '~0' to '~'.
//   TODO decode support:
//   var rfc6901Decoder = strings.NewReplacer("~1", "/", "~0", "~")

var rfc6901Encoder = strings.NewReplacer("~", "~0", "/", "~1")

func makePath(path string, newPart interface{}) string {
	key := rfc6901Encoder.Replace(fmt.Sprintf("%v", newPart))
	if path == "" {
		return "/" + key
	}
	return path + "/" + key
}

// diff returns the (recursive) difference between a and b as an array of JsonPatchOperations.
func diff(a, b map[string]interface{}, path string, patch []Operation) ([]Operation, error) {
	for key, bv := range b {
		p := makePath(path, key)
		av, ok := a[key]
		// value was added
		if !ok {
			patch = append(patch, NewOperation("add", p, bv))
			continue
		}
		// Types are the same, compare values
		var err error
		patch, err = handleValues(av, bv, p, patch)
		if err != nil {
			return nil, err
		}
	}
	// Now add all deleted values as nil
	for key := range a {
		_, found := b[key]
		if !found {
			p := makePath(path, key)

			patch = append(patch, NewOperation("remove", p, nil))
		}
	}
	return patch, nil
}

func handleValues(av, bv interface{}, p string, patch []Operation) ([]Operation, error) {
	{
		at := reflect.TypeOf(av)
		bt := reflect.TypeOf(bv)
		if at == nil && bt == nil {
			// do nothing
			return patch, nil
		} else if at != bt {
			// If types have changed, replace completely (preserves null in destination)
			return append(patch, NewOperation("replace", p, bv)), nil
		}
	}

	var err error
	switch at := av.(type) {
	case map[string]interface{}:
		bt := bv.(map[string]interface{})
		patch, err = diff(at, bt, p, patch)
		if err != nil {
			return nil, err
		}
	case string, float64, bool:
		if !matchesValue(av, bv) {
			patch = append(patch, NewOperation("replace", p, bv))
		}
	case []interface{}:
		bt := bv.([]interface{})
		n := min(len(at), len(bt))
		for i := len(at) - 1; i >= n; i-- {
			patch = append(patch, NewOperation("remove", makePath(p, i), nil))
		}
		for i := n; i < len(bt); i++ {
			patch = append(patch, NewOperation("add", makePath(p, i), bt[i]))
		}
		for i := 0; i < n; i++ {
			var err error
			patch, err = handleValues(at[i], bt[i], makePath(p, i), patch)
			if err != nil {
				return nil, err
			}
		}
	default:
		panic(fmt.Sprintf("Unknown type:%T ", av))
	}
	return patch, nil
}

func min(x int, y int) int {
	if y < x {
		return y
	}
	return x
}