-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONPatchOperation.swift
418 lines (394 loc) · 15.5 KB
/
JSONPatchOperation.swift
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//
// JSONPatchOperation.swift
// DynamicJSON
//
// Created by Matthias Zenger on 02/04/2024.
// Copyright © 2024 Matthias Zenger. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
///
/// Enumeration of individual JSONPatch operations.
///
public enum JSONPatchOperation: Codable,
Hashable,
CustomStringConvertible,
CustomDebugStringConvertible {
/// *add(path, value)*: Add `value` to the JSON value at `path`
case add(JSONPointer, JSON)
/// *remove(path)*: Remove the value at location `path` in a JSON value.
case remove(JSONPointer)
/// *replace(path, value)*: Replace the value at location `path` with `value`.
case replace(JSONPointer, JSON)
/// *move(path, from)*: Move the value at `from` to `path`. This is equivalent
/// to first removing the value at `from` and then adding it to `path`.
case move(JSONPointer, JSONPointer)
/// *copy(path, from)*: Copy the value at `from` to `path`. This is equivalent
/// to looking up the value at `from` and then adding it to `path`.
case copy(JSONPointer, JSONPointer)
/// *test(path, value)*: Compares value at `path` with `value` and fails if the
/// two are different.
case test(JSONPointer, JSON)
/// Collection of errors raised by functionality provided by `JSONPatchOperation`.
public enum Error: LocalizedError, CustomStringConvertible {
case indexOutOfBounds(Int, Int)
case cannotRemoveRoot
case cannotAddValue(JSONReference)
case cannotReplaceValue(JSONReference)
case cannotRemoveValue(JSONReference)
case testFailed(JSONReference)
case valueNotFound(JSONReference)
case indexRequiredToMutateArray(JSONReference)
case memberRequiredToMutateObject(JSONReference)
public var description: String {
switch self {
case .indexOutOfBounds(let index, let max):
return "index \(index) out of array bounds [0..\(max)["
case .cannotRemoveRoot:
return "cannot remove root"
case .cannotAddValue(let ref):
return "cannot add value at \(ref)"
case .cannotRemoveValue(let ref):
return "cannot remove value at \(ref)"
case .cannotReplaceValue(let ref):
return "cannot replace value at \(ref)"
case .testFailed(let ref):
return "test for value at location \(ref) failed"
case .indexRequiredToMutateArray(let ref):
return "index required to access array at \(ref)"
case .memberRequiredToMutateObject(let ref):
return "member required to access object at \(ref)"
case .valueNotFound(let ref):
return "\(ref) does not refer to a value"
}
}
public var errorDescription: String? {
return self.description
}
public var failureReason: String? {
switch self {
case .indexOutOfBounds(_, _),
.cannotRemoveRoot,
.cannotAddValue(_),
.cannotRemoveValue(_),
.testFailed(_),
.indexRequiredToMutateArray(_),
.memberRequiredToMutateObject(_),
.cannotReplaceValue(_),
.valueNotFound(_):
return "application error"
}
}
}
/// Enumeration of JSON Patch operation types.
public enum OperationType: String {
case add
case remove
case replace
case move
case copy
case test
}
public enum CodingKeys: String, CodingKey {
case op
case path
case value
case from
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let op = try container.decode(String.self, forKey: .op)
switch op {
case OperationType.add.rawValue:
self = .add(try container.decode(JSONPointer.self, forKey: .path),
try container.decode(JSON.self, forKey: .value))
case OperationType.remove.rawValue:
self = .remove(try container.decode(JSONPointer.self, forKey: .path))
case OperationType.replace.rawValue:
self = .replace(try container.decode(JSONPointer.self, forKey: .path),
try container.decode(JSON.self, forKey: .value))
case OperationType.move.rawValue:
self = .move(try container.decode(JSONPointer.self, forKey: .path),
try container.decode(JSONPointer.self, forKey: .from))
case OperationType.copy.rawValue:
self = .copy(try container.decode(JSONPointer.self, forKey: .path),
try container.decode(JSONPointer.self, forKey: .from))
case OperationType.test.rawValue:
self = .test(try container.decode(JSONPointer.self, forKey: .path),
try container.decode(JSON.self, forKey: .value))
default:
throw DecodingError.dataCorrupted(
DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "invalid JSONPatchOperation encoding"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .add(path, value):
try container.encode(OperationType.add.rawValue, forKey: .op)
try container.encode(path, forKey: .path)
try container.encode(value, forKey: .value)
case let .remove(path):
try container.encode(OperationType.remove.rawValue, forKey: .op)
try container.encode(path, forKey: .path)
case let .replace(path, value):
try container.encode(OperationType.replace.rawValue, forKey: .op)
try container.encode(path, forKey: .path)
try container.encode(value, forKey: .value)
case let .move(path, from):
try container.encode(OperationType.move.rawValue, forKey: .op)
try container.encode(path, forKey: .path)
try container.encode(from, forKey: .from)
case let .copy(path, from):
try container.encode(OperationType.copy.rawValue, forKey: .op)
try container.encode(path, forKey: .path)
try container.encode(from, forKey: .from)
case let .test(path, value):
try container.encode(OperationType.test.rawValue, forKey: .op)
try container.encode(path, forKey: .path)
try container.encode(value, forKey: .value)
}
}
/// Returns the operation type of this JSON patch operation.
public var op: OperationType {
switch self {
case .add(_, _):
return OperationType.add
case .remove(_):
return OperationType.remove
case .replace(_, _):
return OperationType.replace
case .move(_, _):
return OperationType.move
case .copy(_, _):
return OperationType.copy
case .test(_, _):
return OperationType.test
}
}
/// Returns the `path` property of this JSON patch operation.
public var path: JSONPointer {
switch self {
case .add(let path, _):
return path
case .remove(let path):
return path
case .replace(let path, _):
return path
case .move(let path, _):
return path
case .copy(let path, _):
return path
case .test(let path, _):
return path
}
}
/// Encodes this JSONPatchOperation value using the provided encoding strategies and
/// returns it as a `Data` object.
public func data(formatting: JSONEncoder.OutputFormatting = .init(),
dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate,
floatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .throw,
userInfo: [CodingUserInfoKey : Any]? = nil) throws -> Data {
let encoder = JSONEncoder()
encoder.outputFormatting = formatting
encoder.keyEncodingStrategy = .useDefaultKeys
encoder.dateEncodingStrategy = dateEncodingStrategy
encoder.nonConformingFloatEncodingStrategy = floatEncodingStrategy
if let userInfo {
encoder.userInfo = userInfo
}
return try encoder.encode(self)
}
/// Encodes this JSONPatchOperation value using the provided encoding strategies and
/// returns it as a string.
public func string(formatting: JSONEncoder.OutputFormatting = .init(),
dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate,
floatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .throw,
userInfo: [CodingUserInfoKey : Any]? = nil) throws -> String? {
return String(data: try self.data(formatting: formatting,
dateEncodingStrategy: dateEncodingStrategy,
floatEncodingStrategy: floatEncodingStrategy,
userInfo: userInfo),
encoding: .utf8)
}
/// Applies this JSON patch operation to the given JSON document, mutating this JSON
/// document in place.
public func apply(to json: inout JSON) throws {
switch self {
case .add(let path, let value):
if let (parent, segment) = path.deselect {
try json.mutate(
parent,
array: { arr in
switch segment.index {
case .some(.fromStart(let offset)):
guard offset <= arr.count else {
throw Error.indexOutOfBounds(offset, arr.count)
}
if offset == arr.count {
arr.append(value)
} else {
arr.insert(value, at: offset)
}
case .some(.fromEnd(let offset)):
guard offset <= arr.count else {
throw Error.indexOutOfBounds(arr.count - offset, arr.count)
}
if offset == 0 {
arr.append(value)
} else {
arr.insert(value, at: arr.count - offset)
}
default:
throw Error.indexRequiredToMutateArray(parent)
}
},
object: { obj in
if let member = segment.member {
obj[member] = value
} else {
throw Error.memberRequiredToMutateObject(parent)
}
},
other: { _ in
throw Error.cannotAddValue(path)
})
} else {
// throw Error.cannotAddValue(path)
json = value
}
case .remove(let path):
if let (parent, segment) = path.deselect {
try json.mutate(
parent,
array: { arr in
switch segment.index {
case .some(.fromStart(let offset)):
guard offset < arr.count else {
throw Error.indexOutOfBounds(offset, arr.count)
}
arr.remove(at: offset)
case .some(.fromEnd(let offset)):
guard offset <= arr.count && offset > 0 else {
throw Error.indexOutOfBounds(arr.count - offset, arr.count)
}
arr.remove(at: arr.count - offset)
default:
throw Error.indexRequiredToMutateArray(parent)
}
},
object: { obj in
if let member = segment.member, obj[member] != nil {
obj.removeValue(forKey: member)
} else {
throw Error.memberRequiredToMutateObject(parent)
}
},
other: { _ in
throw Error.cannotRemoveValue(path)
})
} else {
throw Error.cannotRemoveValue(path)
}
case .replace(let path, let value):
if let (parent, segment) = path.deselect {
try json.mutate(
parent,
array: { arr in
switch segment.index {
case .some(.fromStart(let offset)):
guard offset < arr.count else {
throw Error.indexOutOfBounds(offset, arr.count)
}
arr[offset] = value
case .some(.fromEnd(let offset)):
guard offset <= arr.count && offset > 0 else {
throw Error.indexOutOfBounds(arr.count - offset, arr.count)
}
arr[arr.count - offset] = value
default:
throw Error.indexRequiredToMutateArray(parent)
}
},
object: { obj in
if let member = segment.member {
if obj[member] == nil {
throw Error.cannotReplaceValue(path)
} else {
obj[member] = value
}
} else {
throw Error.memberRequiredToMutateObject(parent)
}
},
other: { _ in
throw Error.cannotReplaceValue(path)
})
} else {
json = value
}
case .move(let path, let from):
if let value = from.get(from: json) {
try JSONPatchOperation.remove(from).apply(to: &json)
try JSONPatchOperation.add(path, value).apply(to: &json)
} else {
throw Error.valueNotFound(from)
}
case .copy(let path, let from):
if let value = from.get(from: json) {
try JSONPatchOperation.add(path, value).apply(to: &json)
} else {
throw Error.valueNotFound(from)
}
case .test(let path, let value):
if let current = json[ref: path] {
guard current == value else {
throw Error.testFailed(path)
}
} else {
throw Error.valueNotFound(path)
}
}
}
/// Returns a pretty-printed representation of this JSONPatch operation with sorted keys in
/// object representations. Dates are encoded using ISO 8601. Floating-point numbers
/// denoting infinity are represented with the term "Infinity" respectively "-Infinity".
/// NaN values are denoted with "NaN".
public var description: String {
return (try? self.string(
formatting: [.prettyPrinted, .sortedKeys],
dateEncodingStrategy: .iso8601,
floatEncodingStrategy: .convertToString(positiveInfinity: "Infinity",
negativeInfinity: "-Infinity",
nan: "NaN"))) ?? "<invalid JSON>"
}
/// Description for debugging purposes.
public var debugDescription: String {
switch self {
case .add(let path, let value):
return "\(self.op.rawValue)(\(path), \(value)"
case .remove(let path):
return "\(self.op.rawValue)(\(path))"
case .replace(let path, let value):
return "\(self.op.rawValue)(\(path), \(value))"
case .move(let path, let from):
return "\(self.op.rawValue)(\(path), \(from))"
case .copy(let path, let from):
return "\(self.op.rawValue)(\(path), \(from))"
case .test(let path, let value):
return "\(self.op.rawValue)(\(path), \(value))"
}
}
}