Repository navigation
Expand file tree
/
Copy pathjsonpatch.py
More file actions
1562 lines (1252 loc) · 57.2 KB
/
Copy pathjsonpatch.py
File metadata and controls
1562 lines (1252 loc) · 57.2 KB
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# python-json-patch - An implementation of the JSON Patch format
# https://github.com/stefankoegl/python-json-patch
#
# Copyright (c) 2011 Stefan Kögl <stefan@skoegl.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
""" Apply JSON-Patches (RFC 6902) """
import bisect
import collections
import copy
import functools
import json
from collections.abc import (Mapping, MutableMapping, MutableSequence,
Sequence)
from difflib import SequenceMatcher
from types import MappingProxyType
from jsonpointer import JsonPointer, JsonPointerException
_ST_ADD = 0
_ST_REMOVE = 1
# Up to which product of their lengths DiffBuilder matches up all equal items
# of two lists
_EXACT_MATCH_LIMIT = 500 ** 2
# Will be parsed by setup.py to determine package metadata
__author__ = 'Stefan Kögl <stefan@skoegl.net>'
__version__ = '1.43'
__website__ = 'https://github.com/stefankoegl/python-json-patch'
__license__ = 'BSD-3-Clause'
class JsonPatchException(Exception):
"""Base Json Patch exception"""
def __init__(self, *args, **kwargs):
"""Initialize a new instance of a JsonPatchException
:param op: The operation that failed. It is attached to the exception
so that callers can inspect (or modify) the failing patch
operation. This is either a :class:`PatchOperation`
instance or, if the operation could not be constructed,
the raw operation object.
:type op: PatchOperation or dict or None
"""
self.op = kwargs.pop('op', None)
super(JsonPatchException, self).__init__(*args, **kwargs)
class InvalidJsonPatch(JsonPatchException):
""" Raised if an invalid JSON Patch is created """
class JsonPatchConflict(JsonPatchException):
"""Raised if patch could not be applied due to conflict situation such as:
- attempt to add object key when it already exists;
- attempt to operate with nonexistence object key;
- attempt to insert value to array at position beyond its size;
- etc.
"""
class JsonPatchPathNotFound(JsonPatchConflict):
"""Raised if the location an operation has to act on does not exist.
This is the case for
- a ``remove`` or ``replace`` whose ``path`` refers to a non-existent
object member or array element, and
- a ``move`` or ``copy`` whose ``from`` refers to a non-existent object
member or array element.
It is a subclass of :class:`JsonPatchConflict`, so existing code that
catches :class:`JsonPatchConflict` continues to work. It can be caught on
its own to tell a missing location apart from other conflicts, for
example to implement a ``remove`` that ignores members which are already
absent (see the tutorial).
"""
class JsonPatchTestFailed(JsonPatchException, AssertionError):
""" A Test operation failed """
def multidict(ordered_pairs):
"""Convert duplicate keys values to lists."""
# read all values into lists
mdict = collections.defaultdict(list)
for key, value in ordered_pairs:
mdict[key].append(value)
return dict(
# unpack lists that have only 1 item
(key, values[0] if len(values) == 1 else values)
for key, values in mdict.items()
)
# The "object_pairs_hook" parameter is used to handle duplicate keys when
# loading a JSON object.
_jsonloads = functools.partial(json.loads, object_pairs_hook=multidict)
def apply_patch(doc, patch, in_place=False, pointer_cls=JsonPointer,
atomic=False):
"""Apply patch operations to the specified JSON document.
:param doc: JSON document, including arrays and scalar values.
:type doc: object
:param patch: Iterable of operation dicts or a raw JSON-encoded string.
:type patch: iterable or str
:param in_place: While ``True`` patch will modify target document.
By default patch will be applied to document copy.
:type in_place: bool
:param pointer_cls: JSON pointer class to use.
:type pointer_cls: Type[JsonPointer]
:param atomic: With ``in_place=True``, undo the changes of all preceding
operations if an operation fails, so that ``doc`` is
either fully patched or left unchanged. See
:meth:`JsonPatch.apply`.
:type atomic: bool
:return: Resulting document, which may have a different type from ``doc``.
:rtype: object
>>> doc = {'foo': 'bar'}
>>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}]
>>> other = apply_patch(doc, patch)
>>> doc is not other
True
>>> other == {'foo': 'bar', 'baz': 'qux'}
True
>>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}]
>>> apply_patch(doc, patch, in_place=True) == {'foo': 'bar', 'baz': 'qux'}
True
>>> doc == other
True
"""
if isinstance(patch, (str, bytes)):
patch = JsonPatch.from_string(patch, pointer_cls=pointer_cls)
else:
patch = JsonPatch(patch, pointer_cls=pointer_cls)
return patch.apply(doc, in_place, atomic=atomic)
def make_patch(src, dst, pointer_cls=JsonPointer, generate_test_ops=False):
"""Generates patch by comparing two document objects. Actually is
a proxy to :meth:`JsonPatch.from_diff` method. The resulting patch
transforms `src` into `dst`, so it has to be applied to `src` (or to a
document equal to it).
:param src: Source JSON document, including arrays and scalar values.
:type src: object
:param dst: Target JSON document, including arrays and scalar values.
:type dst: object
:param pointer_cls: JSON pointer class to use.
:type pointer_cls: Type[JsonPointer]
:param generate_test_ops: Precede each ``remove`` and ``replace``
operation by a ``test`` operation that checks
the value it removes or replaces, so the patch
fails on documents that differ from `src` there.
:type generate_test_ops: bool
>>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
>>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
>>> patch = make_patch(src, dst)
>>> new = patch.apply(src)
>>> new == dst
True
"""
return JsonPatch.from_diff(src, dst, pointer_cls=pointer_cls,
generate_test_ops=generate_test_ops)
class _NullJournal(object):
"""Performs the changes of patch operations without recording them."""
@staticmethod
def setitem(container, key, value):
container[key] = value
@staticmethod
def delitem(container, key):
del container[key]
@staticmethod
def insert(container, index, value):
container.insert(index, value)
@staticmethod
def append(container, value):
container.append(value)
_NO_JOURNAL = _NullJournal()
class _Journal(object):
"""Performs the changes of patch operations and records how to undo them.
Each undo step refers to the changed container itself rather than to a
path. As :meth:`rollback` undoes the steps in reverse order, every
container is in the same state as right after its change when the step is
undone, so list indices still refer to the same items. Removed and
replaced values are kept as they are; they are detached from the
document, so restoring them needs no copy.
Restoring a removed member adds it at the end of its mapping, so the
order of the members of each dict that loses one is recorded once, and
restored after all steps have been undone. This is limited to dicts
(including subclasses such as OrderedDict or Counter), whose order is the
order of insertion; moving a member of other mappings, such as a
ChainMap, to the end can add it to a different underlying mapping.
"""
def __init__(self):
self._undo = []
# id of a mapping -> (mapping, its keys before the first removal)
self._orders = {}
def setitem(self, container, key, value):
if (isinstance(container, MutableMapping) and key not in container or
# a ChainMap adds the members of its other mappings that are
# set to its first one
isinstance(container, collections.ChainMap) and
key not in container.maps[0]):
container[key] = value
self._undo.append((_undo_delitem, container, key))
else:
old = container[key]
container[key] = value
self._undo.append((_undo_setitem, container, key, old))
def delitem(self, container, key):
# reading a missing member can create it, e.g. in a defaultdict
if isinstance(container, Mapping) and key not in container:
raise KeyError(key)
old = container[key]
if isinstance(container, MutableSequence):
del container[key]
self._undo.append((_undo_insert, container, key, old))
elif isinstance(container, MutableMapping):
if (isinstance(container, dict) and
id(container) not in self._orders):
self._orders[id(container)] = (container, list(container))
del container[key]
self._undo.append((_undo_setitem, container, key, old))
else:
del container[key]
self._undo.append((_undo_setitem, container, key, old))
def insert(self, container, index, value):
container.insert(index, value)
self._undo.append((_undo_delitem, container, index))
def append(self, container, value):
if (isinstance(container, collections.deque) and
container.maxlen is not None and
len(container) == container.maxlen):
# A full bounded deque drops its first item to make room
if container.maxlen:
dropped = container[0]
container.append(value)
self._undo.append((_undo_dropping_append, container, dropped))
else:
container.append(value) # it stays empty
return
container.append(value)
# the list may shrink again before this step is undone, but by then
# it has the same length as right after the append
self._undo.append((_undo_delitem, container, len(container) - 1))
def rollback(self):
"""Undoes all recorded changes, the most recent one first."""
while self._undo:
step = self._undo.pop()
step[0](*step[1:])
for mapping, keys in self._orders.values():
_reorder(mapping, keys)
self._orders.clear()
def _undo_setitem(container, key, value):
container[key] = value
def _undo_delitem(container, key):
del container[key]
def _undo_insert(container, index, value):
container.insert(index, value)
def _undo_dropping_append(deque, dropped):
del deque[-1]
deque.appendleft(dropped)
def _reorder(mapping, keys):
"""Restores the order of the members of a mapping after a rollback.
``keys`` are its keys before its first removal. They can include
members that the patch added before, and that the rollback has removed
again; the original members appear in it in their original order.
"""
keys = [key for key in keys if key in mapping]
start = next((index for index, (key, original)
in enumerate(zip(mapping, keys)) if key != original),
len(keys))
# Move the members from the first misplaced one on to the end. Unlike
# update(), which e.g. a Counter uses to add counts, this only uses the
# operations the rollback itself uses
for key in keys[start:]:
mapping[key] = mapping.pop(key)
class PatchOperation(object):
"""A single operation inside a JSON Patch."""
def __init__(self, operation, pointer_cls=JsonPointer):
self.pointer_cls = pointer_cls
if not operation.__contains__('path'):
raise InvalidJsonPatch("Operation must have a 'path' member", op=operation)
if isinstance(operation['path'], self.pointer_cls):
self.location = operation['path'].path
self.pointer = operation['path']
else:
self.location = operation['path']
try:
self.pointer = self.pointer_cls(self.location)
except TypeError:
raise InvalidJsonPatch("Invalid 'path'", op=operation)
self.operation = operation
def _from_pointer(self):
"""Builds the pointer of the 'from' member like __init__ builds the
one of 'path'."""
try:
from_ptr = self.operation['from']
except KeyError:
raise InvalidJsonPatch(
"The operation does not contain a 'from' member", op=self)
if isinstance(from_ptr, self.pointer_cls):
return from_ptr
try:
return self.pointer_cls(from_ptr)
except TypeError:
raise InvalidJsonPatch("Invalid 'from'", op=self)
def apply(self, obj):
"""Applies the patch operation to the specified object."""
return self._apply(obj, _NO_JOURNAL)
def _apply(self, obj, journal):
"""Applies the operation, making all changes through ``journal``, so
that :meth:`JsonPatch.apply` can undo them with ``atomic=True``.
Subclasses either implement this method or override :meth:`apply`.
"""
raise NotImplementedError('should implement the patch operation.')
def __hash__(self):
# Other members can hold arrays or objects, which are unhashable.
# Operations that compare equal still have equal 'op' and 'path'.
return hash((self.operation.get('op'), self.operation['path']))
def __eq__(self, other):
if not isinstance(other, PatchOperation):
return False
# e.g. tests for 1 and for true behave differently
return _json_equal(self.operation, other.operation)
def __ne__(self, other):
return not(self == other)
@property
def path(self):
return '/'.join(self.pointer.parts[:-1])
@property
def key(self):
return self.get_part(-1)
@key.setter
def key(self, value):
self.set_part(-1, value)
def get_part(self, index):
try:
return int(self.pointer.parts[index])
except ValueError:
return self.pointer.parts[index]
def set_part(self, index, value):
self.pointer.parts[index] = str(value)
self.location = self.pointer.path
self.operation['path'] = self.location
class RemoveOperation(PatchOperation):
"""Removes an object property or an array element."""
def _apply(self, obj, journal):
subobj, part = self.pointer.to_last(obj)
if part is None:
raise JsonPatchConflict("can't remove the whole document", op=self)
if isinstance(subobj, Sequence) and not isinstance(part, int):
raise JsonPointerException("invalid array index '{0}'".format(part))
try:
journal.delitem(subobj, part)
except (KeyError, IndexError):
msg = "can't remove a non-existent object '{0}'".format(part)
raise JsonPatchPathNotFound(msg, op=self)
except TypeError as ex:
raise JsonPatchConflict(str(ex), op=self)
return obj
class AddOperation(PatchOperation):
"""Adds an object property or an array element."""
def _apply(self, obj, journal):
try:
value = self.operation["value"]
except KeyError:
raise InvalidJsonPatch(
"The operation does not contain a 'value' member", op=self)
# Insert a copy so the document does not share mutable values with
# the patch; otherwise later operations would modify the patch itself.
value = copy.deepcopy(value)
if journal is _NO_JOURNAL:
# subclasses may override _add without the journal parameter
return self._add(obj, value)
return self._add(obj, value, journal)
def _add(self, obj, value, journal=_NO_JOURNAL):
subobj, part = self.pointer.to_last(obj)
if part is None:
return value # we're replacing the root, whatever its type
if isinstance(subobj, MutableSequence):
if part == '-':
journal.append(subobj, value)
elif part > len(subobj) or part < 0:
raise JsonPatchConflict("can't insert outside of list", op=self)
else:
journal.insert(subobj, part, value)
elif isinstance(subobj, MutableMapping):
journal.setitem(subobj, part, value)
else:
raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part), op=self)
return obj
class ReplaceOperation(PatchOperation):
"""Replaces an object property or an array element by a new value."""
def _apply(self, obj, journal):
try:
value = self.operation["value"]
except KeyError:
raise InvalidJsonPatch(
"The operation does not contain a 'value' member", op=self)
# copied for the same reason as in AddOperation.apply
value = copy.deepcopy(value)
subobj, part = self.pointer.to_last(obj)
if part is None:
return value
if isinstance(subobj, MutableSequence):
# '-' only refers to the (nonexistent) element after the end of
# an array; for an object it is an ordinary member name
if part == "-":
raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation", op=self)
if part >= len(subobj) or part < 0:
raise JsonPatchPathNotFound("can't replace outside of list", op=self)
elif isinstance(subobj, MutableMapping):
if part not in subobj:
msg = "can't replace a non-existent object '{0}'".format(part)
raise JsonPatchPathNotFound(msg, op=self)
else:
raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part), op=self)
journal.setitem(subobj, part, value)
return obj
class MoveOperation(PatchOperation):
"""Moves an object property or an array element to a new location."""
def _apply(self, obj, journal):
from_ptr = self._from_pointer()
# Checked before anything is resolved, as removing an array element
# shifts its siblings, so the target would resolve to a different
# location. This also covers moving the whole document ('from' is "").
if self.pointer != from_ptr and self.pointer.contains(from_ptr):
raise JsonPatchConflict('Cannot move values into their own children', op=self)
subobj, part = _to_existing_last(from_ptr, obj)
# Moving the whole document onto itself is a no-op
if part is None:
return obj
try:
value = subobj[part]
except (KeyError, IndexError) as ex:
raise JsonPatchPathNotFound(str(ex), op=self)
# If source and target are equal, this is a no-op
if self.pointer == from_ptr:
return obj
try:
obj = RemoveOperation({
'op': 'remove',
'path': self.operation['from']
}, pointer_cls=self.pointer_cls)._apply(obj, journal)
# the value has been detached from its old location, so no copy
# needed
obj = AddOperation({
'op': 'add',
'path': self.location,
}, pointer_cls=self.pointer_cls)._add(obj, value, journal)
except JsonPatchException as ex:
# report the failure against this operation rather than the
# internal, synthetic remove / add operations
ex.op = self
raise
return obj
@property
def from_path(self):
from_ptr = self._from_pointer()
return '/'.join(from_ptr.parts[:-1])
@property
def from_key(self):
return self.get_from_part(-1)
@from_key.setter
def from_key(self, value):
self.set_from_part(-1, value)
def get_from_part(self, index):
from_ptr = self._from_pointer()
try:
return int(from_ptr.parts[index])
except ValueError:
return from_ptr.parts[index]
def set_from_part(self, index, value):
from_ptr = self._from_pointer()
from_ptr.parts[index] = str(value)
self.operation['from'] = from_ptr.path
class TestOperation(PatchOperation):
"""Test value by specified location."""
def _apply(self, obj, journal):
try:
subobj, part = self.pointer.to_last(obj)
if part is None:
val = subobj
else:
val = self.pointer.walk(subobj, part)
except JsonPointerException as ex:
raise JsonPatchTestFailed(str(ex), op=self)
try:
value = self.operation['value']
except KeyError:
raise InvalidJsonPatch(
"The operation does not contain a 'value' member", op=self)
if not _json_equal(val, value):
msg = '{0} ({1}) is not equal to tested value {2} ({3})'
raise JsonPatchTestFailed(msg.format(val, type(val),
value, type(value)), op=self)
return obj
class CopyOperation(PatchOperation):
""" Copies an object property or an array element to a new location """
def _apply(self, obj, journal):
from_ptr = self._from_pointer()
subobj, part = _to_existing_last(from_ptr, obj)
try:
value = copy.deepcopy(subobj if part is None else subobj[part])
except (KeyError, IndexError) as ex:
raise JsonPatchPathNotFound(str(ex), op=self)
# value is already a deep copy, no need to copy it again
try:
obj = AddOperation({
'op': 'add',
'path': self.location,
}, pointer_cls=self.pointer_cls)._add(obj, value, journal)
except JsonPatchException as ex:
# report the failure against this operation rather than the
# internal, synthetic add operation
ex.op = self
raise
return obj
def _restore(obj, saved):
"""Restores the contents of a document from a copy of it.
Only the items of mappings and sequences are restored, not other state
that a custom operation can change, such as attributes or the list of
mappings of a ChainMap.
"""
if isinstance(obj, collections.ChainMap):
# restore each mapping, so that none takes over another's members
for mapping, saved_mapping in zip(obj.maps, saved.maps):
_restore(mapping, saved_mapping)
elif isinstance(obj, MutableMapping):
obj.clear()
obj.update(saved)
elif isinstance(obj, MutableSequence):
# not obj[:] = saved, as e.g. deque doesn't support slices
obj.clear()
obj.extend(saved)
# Immutable containers can't have changed, but their children can
elif isinstance(obj, Mapping):
for key in saved:
_restore(obj[key], saved[key])
elif isinstance(obj, Sequence) and not isinstance(obj, (str, bytes)):
for item, saved_item in zip(obj, saved):
_restore(item, saved_item)
_JOURNALED_OPERATIONS = (
RemoveOperation, AddOperation, ReplaceOperation, MoveOperation,
TestOperation, CopyOperation,
)
def _supports_journal(operation):
"""Whether all changes of ``operation`` go through its journal, which is
the case for the built-in operations unless a subclass, or the operation
object itself, changes how they are applied."""
overridden = getattr(operation, '__dict__', {})
if any(name in overridden for name in ('apply', '_apply', '_add')):
return False
cls = type(operation)
if getattr(cls, 'apply', None) is not PatchOperation.apply:
return False
if not any(getattr(cls, '_apply', None) is base._apply
for base in _JOURNALED_OPERATIONS):
return False
if isinstance(operation, AddOperation) and cls._add is not AddOperation._add:
return False
return True
class JsonPatch(object):
"""A JSON Patch is an iterable of Patch Operations.
Accepts sequences, iterators, generators, and other iterables of operation
dictionaries. Non-sequence inputs are materialized before validation so
the resulting patch can be applied repeatedly.
>>> patch = JsonPatch([
... {'op': 'add', 'path': '/foo', 'value': 'bar'},
... {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]},
... {'op': 'remove', 'path': '/baz/1'},
... {'op': 'test', 'path': '/baz', 'value': [1, 3]},
... {'op': 'replace', 'path': '/baz/0', 'value': 42},
... {'op': 'remove', 'path': '/baz/1'},
... ])
>>> doc = {}
>>> result = patch.apply(doc)
>>> expected = {'foo': 'bar', 'baz': [42]}
>>> result == expected
True
JsonPatch object is iterable, so you can easily access each patch
statement in a loop:
>>> lpatch = list(patch)
>>> expected = {'op': 'add', 'path': '/foo', 'value': 'bar'}
>>> lpatch[0] == expected
True
>>> lpatch == patch.patch
True
Also JsonPatch could be converted directly to :class:`bool` if it contains
any operation statements:
>>> bool(patch)
True
>>> bool(JsonPatch([]))
False
This behavior is very handy with :func:`make_patch` to write more readable
code:
>>> old = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
>>> new = {'baz': 'qux', 'numbers': [1, 4, 7]}
>>> patch = make_patch(old, new)
>>> if patch:
... # document have changed, do something useful
... patch.apply(old) #doctest: +ELLIPSIS
{...}
"""
json_dumper = staticmethod(json.dumps)
json_loader = staticmethod(_jsonloads)
operations = MappingProxyType({
'remove': RemoveOperation,
'add': AddOperation,
'replace': ReplaceOperation,
'move': MoveOperation,
'test': TestOperation,
'copy': CopyOperation,
})
def __init__(self, patch, pointer_cls=JsonPointer):
self.pointer_cls = pointer_cls
if isinstance(patch, (str, bytes, Mapping)):
raise InvalidJsonPatch("Document is expected to be sequence of operations")
try:
self.patch = patch if isinstance(patch, Sequence) else list(patch)
except TypeError:
raise InvalidJsonPatch("Document is expected to be sequence of operations")
# Verify that the structure of the patch document
# is correct by retrieving each patch element.
# Much of the validation is done in the initializer
# though some is delayed until the patch is applied.
for op in self.patch:
# We're only checking for strings in the following check
# for two reasons:
#
# - It should come from JSON, which only allows strings as
# dictionary keys, so having a string here unambiguously means
# someone used: {"op": ..., ...} instead of [{"op": ..., ...}].
#
# - There's no possible false positive: if someone give a sequence
# of mappings, this won't raise.
if isinstance(op, (str, bytes)):
raise InvalidJsonPatch("Document is expected to be sequence of "
"operations, got a sequence of strings.",
op=op)
self._get_operation(op)
def __str__(self):
"""str(self) -> self.to_string()"""
return self.to_string()
def __bool__(self):
return bool(self.patch)
__nonzero__ = __bool__
def __iter__(self):
return iter(self.patch)
def __hash__(self):
return hash(tuple(self._ops))
def __eq__(self, other):
if not isinstance(other, JsonPatch):
return False
return self._ops == other._ops
def __ne__(self, other):
return not(self == other)
@classmethod
def from_string(cls, patch_str, loads=None, pointer_cls=JsonPointer):
"""Creates JsonPatch instance from string source.
:param patch_str: JSON patch as raw string.
:type patch_str: str
:param loads: A function of one argument that loads a serialized
JSON string.
:type loads: Callable
:param pointer_cls: JSON pointer class to use.
:type pointer_cls: Type[JsonPointer]
:return: :class:`JsonPatch` instance.
"""
json_loader = loads or cls.json_loader
patch = json_loader(patch_str)
return cls(patch, pointer_cls=pointer_cls)
@classmethod
def from_diff(
cls, src, dst, optimization=True, dumps=None,
pointer_cls=JsonPointer, generate_test_ops=False,
):
"""Creates JsonPatch instance based on comparison of two document
objects. Json patch would be created for `src` argument against `dst`
one. The resulting patch transforms `src` into `dst`, so it has to be
applied to `src` (or to a document equal to it).
Values in the patch are copied, so changing either input document
afterwards does not change the generated patch.
:param src: Source JSON document, including arrays and scalar values.
:type src: object
:param dst: Target JSON document, including arrays and scalar values.
:type dst: object
:param optimization: Generate move operations for matching values.
Set to False to use only add, remove and replace.
:type optimization: bool
:param dumps: A function of one argument that produces a serialized
JSON string.
:type dumps: Callable
:param pointer_cls: JSON pointer class to use.
:type pointer_cls: Type[JsonPointer]
:param generate_test_ops: Precede each ``remove`` and ``replace``
operation by a ``test`` operation that checks
the value it removes or replaces, so the patch
fails on documents that differ from `src` there.
:type generate_test_ops: bool
:return: :class:`JsonPatch` instance.
>>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
>>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
>>> patch = JsonPatch.from_diff(src, dst)
>>> new = patch.apply(src)
>>> new == dst
True
"""
json_dumper = dumps or cls.json_dumper
builder = DiffBuilder(src, dst, json_dumper, pointer_cls=pointer_cls,
optimization=optimization,
generate_test_ops=generate_test_ops)
builder._compare_values((), None, src, dst)
ops = copy.deepcopy(list(builder.execute()))
return cls(ops, pointer_cls=pointer_cls)
def to_string(self, dumps=None):
"""Returns patch set as JSON string."""
json_dumper = dumps or self.json_dumper
return json_dumper(self.patch)
@property
def _ops(self):
return tuple(map(self._get_operation, self.patch))
def apply(self, obj, in_place=False, atomic=False):
"""Applies the patch to a given object.
:param obj: JSON document, including arrays and scalar values.
:type obj: object
:param in_place: Tweaks the way how patch would be applied - directly to
specified `obj` or to its copy.
:type in_place: bool
:param atomic: With ``in_place=True``, undo the changes of all
preceding operations if an operation fails, so that
`obj` is either fully patched or left unchanged. This
does not copy the document; it only keeps the values
that the patch removes or replaces until it is
applied. Patches with custom operations, whose
changes can't be undone, copy the document instead.
Exact restoration is guaranteed for documents of
plain dicts and lists; members that containers such
as ``defaultdict`` add when they are only read are
not removed again (see the tutorial). Without
``in_place=True``, `obj` is never changed, so this
has no effect.
:type atomic: bool
:return: Resulting document. Use this return value even with
``in_place=True``, because a root replacement returns a new
value rather than modifying the original container.
"""
if not in_place:
obj = copy.deepcopy(obj)
atomic = False
ops = self._ops
if not atomic:
for operation in ops:
obj = operation.apply(obj)
return obj
if not all(map(_supports_journal, ops)):
# The changes of custom operations can't be undone, so restore
# the document from a copy instead
saved = copy.deepcopy(obj)
original = obj
try:
for operation in ops:
obj = operation.apply(obj)
except BaseException:
_restore(original, saved)
raise
return obj
journal = _Journal()
try:
for operation in ops:
obj = operation._apply(obj, journal)
except BaseException:
journal.rollback()
raise
return obj
def _get_operation(self, operation):
if not isinstance(operation, Mapping):
raise InvalidJsonPatch("Operation must be an object", op=operation)
if 'op' not in operation:
raise InvalidJsonPatch("Operation does not contain 'op' member", op=operation)
op = operation['op']
if not isinstance(op, (str, bytes)):
raise InvalidJsonPatch("Operation's op must be a string", op=operation)
if op not in self.operations: