jsonpatch 1.41__py3-none-any.whl → 1.43__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpatch
3
- Version: 1.41
3
+ Version: 1.43
4
4
  Summary: Apply JSON-Patches (RFC 6902)
5
5
  Home-page: https://github.com/stefankoegl/python-json-patch
6
6
  Author: Stefan Kögl
@@ -0,0 +1,10 @@
1
+ jsonpatch.py,sha256=zvcCUHmwJlvO-N6Us1x9MbFr3yDlAIDwQ9UI9naakRY,58552
2
+ jsonpatch_cli.py,sha256=Vavn3OY4KrowXNTRDbgsNPcd9vTGLkIgz0Hr6Uwr5mk,6480
3
+ jsonpatch-1.43.dist-info/licenses/AUTHORS,sha256=hOtEnBGbfDegKjzMDEl5vuVJyczbI2PlYE2ho4LjGNQ,140
4
+ jsonpatch-1.43.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
5
+ jsonpatch-stubs/__init__.pyi,sha256=6J9-1EYqLQBCCAuEI7nhIP_DW5zpm3zRWdGMlnFWAqo,5315
6
+ jsonpatch-1.43.dist-info/METADATA,sha256=aP_SW3YwB4xYnasRgvkYbflg12ztJBxX9BQ5VmHH5Ck,4287
7
+ jsonpatch-1.43.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ jsonpatch-1.43.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
9
+ jsonpatch-1.43.dist-info/top_level.txt,sha256=AGmziZtf5TSFAtbhYlhDGjQg1POmwzF9HwLdbzPkoio,40
10
+ jsonpatch-1.43.dist-info/RECORD,,
@@ -35,6 +35,7 @@ class JsonPatchException(Exception):
35
35
 
36
36
  class InvalidJsonPatch(JsonPatchException): ...
37
37
  class JsonPatchConflict(JsonPatchException): ...
38
+ class JsonPatchPathNotFound(JsonPatchConflict): ...
38
39
  class JsonPatchTestFailed(JsonPatchException, AssertionError): ...
39
40
 
40
41
  def multidict(ordered_pairs: Iterable[tuple[str, Any]]) -> dict[str, Any]: ...
@@ -43,6 +44,7 @@ def apply_patch(
43
44
  patch: str | bytes | Iterable[_Operation],
44
45
  in_place: bool = False,
45
46
  pointer_cls: type[JsonPointer] = ...,
47
+ atomic: bool = False,
46
48
  ) -> Any: ...
47
49
  def make_patch(
48
50
  src: Any,
@@ -118,7 +120,7 @@ class JsonPatch:
118
120
  generate_test_ops: bool = False,
119
121
  ) -> Self: ...
120
122
  def to_string(self, dumps: Callable[[Any], str] | None = None) -> str: ...
121
- def apply(self, obj: Any, in_place: bool = False) -> Any: ...
123
+ def apply(self, obj: Any, in_place: bool = False, atomic: bool = False) -> Any: ...
122
124
 
123
125
  # Computes the operations for JsonPatch.from_diff; mostly an implementation
124
126
  # detail, so its internal methods are typed loosely.
jsonpatch.py CHANGED
@@ -55,7 +55,7 @@ _EXACT_MATCH_LIMIT = 500 ** 2
55
55
 
56
56
  # Will be parsed by setup.py to determine package metadata
57
57
  __author__ = 'Stefan Kögl <stefan@skoegl.net>'
58
- __version__ = '1.41'
58
+ __version__ = '1.43'
59
59
  __website__ = 'https://github.com/stefankoegl/python-json-patch'
60
60
  __license__ = 'BSD-3-Clause'
61
61
 
@@ -90,6 +90,24 @@ class JsonPatchConflict(JsonPatchException):
90
90
  """
91
91
 
92
92
 
93
+ class JsonPatchPathNotFound(JsonPatchConflict):
94
+ """Raised if the location an operation has to act on does not exist.
95
+
96
+ This is the case for
97
+
98
+ - a ``remove`` or ``replace`` whose ``path`` refers to a non-existent
99
+ object member or array element, and
100
+ - a ``move`` or ``copy`` whose ``from`` refers to a non-existent object
101
+ member or array element.
102
+
103
+ It is a subclass of :class:`JsonPatchConflict`, so existing code that
104
+ catches :class:`JsonPatchConflict` continues to work. It can be caught on
105
+ its own to tell a missing location apart from other conflicts, for
106
+ example to implement a ``remove`` that ignores members which are already
107
+ absent (see the tutorial).
108
+ """
109
+
110
+
93
111
  class JsonPatchTestFailed(JsonPatchException, AssertionError):
94
112
  """ A Test operation failed """
95
113
 
@@ -113,7 +131,8 @@ def multidict(ordered_pairs):
113
131
  _jsonloads = functools.partial(json.loads, object_pairs_hook=multidict)
114
132
 
115
133
 
116
- def apply_patch(doc, patch, in_place=False, pointer_cls=JsonPointer):
134
+ def apply_patch(doc, patch, in_place=False, pointer_cls=JsonPointer,
135
+ atomic=False):
117
136
  """Apply patch operations to the specified JSON document.
118
137
 
119
138
  :param doc: JSON document, including arrays and scalar values.
@@ -129,6 +148,12 @@ def apply_patch(doc, patch, in_place=False, pointer_cls=JsonPointer):
129
148
  :param pointer_cls: JSON pointer class to use.
130
149
  :type pointer_cls: Type[JsonPointer]
131
150
 
151
+ :param atomic: With ``in_place=True``, undo the changes of all preceding
152
+ operations if an operation fails, so that ``doc`` is
153
+ either fully patched or left unchanged. See
154
+ :meth:`JsonPatch.apply`.
155
+ :type atomic: bool
156
+
132
157
  :return: Resulting document, which may have a different type from ``doc``.
133
158
  :rtype: object
134
159
 
@@ -150,7 +175,7 @@ def apply_patch(doc, patch, in_place=False, pointer_cls=JsonPointer):
150
175
  patch = JsonPatch.from_string(patch, pointer_cls=pointer_cls)
151
176
  else:
152
177
  patch = JsonPatch(patch, pointer_cls=pointer_cls)
153
- return patch.apply(doc, in_place)
178
+ return patch.apply(doc, in_place, atomic=atomic)
154
179
 
155
180
 
156
181
  def make_patch(src, dst, pointer_cls=JsonPointer, generate_test_ops=False):
@@ -186,6 +211,149 @@ def make_patch(src, dst, pointer_cls=JsonPointer, generate_test_ops=False):
186
211
  generate_test_ops=generate_test_ops)
187
212
 
188
213
 
214
+ class _NullJournal(object):
215
+ """Performs the changes of patch operations without recording them."""
216
+
217
+ @staticmethod
218
+ def setitem(container, key, value):
219
+ container[key] = value
220
+
221
+ @staticmethod
222
+ def delitem(container, key):
223
+ del container[key]
224
+
225
+ @staticmethod
226
+ def insert(container, index, value):
227
+ container.insert(index, value)
228
+
229
+ @staticmethod
230
+ def append(container, value):
231
+ container.append(value)
232
+
233
+
234
+ _NO_JOURNAL = _NullJournal()
235
+
236
+
237
+ class _Journal(object):
238
+ """Performs the changes of patch operations and records how to undo them.
239
+
240
+ Each undo step refers to the changed container itself rather than to a
241
+ path. As :meth:`rollback` undoes the steps in reverse order, every
242
+ container is in the same state as right after its change when the step is
243
+ undone, so list indices still refer to the same items. Removed and
244
+ replaced values are kept as they are; they are detached from the
245
+ document, so restoring them needs no copy.
246
+
247
+ Restoring a removed member adds it at the end of its mapping, so the
248
+ order of the members of each dict that loses one is recorded once, and
249
+ restored after all steps have been undone. This is limited to dicts
250
+ (including subclasses such as OrderedDict or Counter), whose order is the
251
+ order of insertion; moving a member of other mappings, such as a
252
+ ChainMap, to the end can add it to a different underlying mapping.
253
+ """
254
+
255
+ def __init__(self):
256
+ self._undo = []
257
+ # id of a mapping -> (mapping, its keys before the first removal)
258
+ self._orders = {}
259
+
260
+ def setitem(self, container, key, value):
261
+ if (isinstance(container, MutableMapping) and key not in container or
262
+ # a ChainMap adds the members of its other mappings that are
263
+ # set to its first one
264
+ isinstance(container, collections.ChainMap) and
265
+ key not in container.maps[0]):
266
+ container[key] = value
267
+ self._undo.append((_undo_delitem, container, key))
268
+ else:
269
+ old = container[key]
270
+ container[key] = value
271
+ self._undo.append((_undo_setitem, container, key, old))
272
+
273
+ def delitem(self, container, key):
274
+ # reading a missing member can create it, e.g. in a defaultdict
275
+ if isinstance(container, Mapping) and key not in container:
276
+ raise KeyError(key)
277
+ old = container[key]
278
+ if isinstance(container, MutableSequence):
279
+ del container[key]
280
+ self._undo.append((_undo_insert, container, key, old))
281
+ elif isinstance(container, MutableMapping):
282
+ if (isinstance(container, dict) and
283
+ id(container) not in self._orders):
284
+ self._orders[id(container)] = (container, list(container))
285
+ del container[key]
286
+ self._undo.append((_undo_setitem, container, key, old))
287
+ else:
288
+ del container[key]
289
+ self._undo.append((_undo_setitem, container, key, old))
290
+
291
+ def insert(self, container, index, value):
292
+ container.insert(index, value)
293
+ self._undo.append((_undo_delitem, container, index))
294
+
295
+ def append(self, container, value):
296
+ if (isinstance(container, collections.deque) and
297
+ container.maxlen is not None and
298
+ len(container) == container.maxlen):
299
+ # A full bounded deque drops its first item to make room
300
+ if container.maxlen:
301
+ dropped = container[0]
302
+ container.append(value)
303
+ self._undo.append((_undo_dropping_append, container, dropped))
304
+ else:
305
+ container.append(value) # it stays empty
306
+ return
307
+ container.append(value)
308
+ # the list may shrink again before this step is undone, but by then
309
+ # it has the same length as right after the append
310
+ self._undo.append((_undo_delitem, container, len(container) - 1))
311
+
312
+ def rollback(self):
313
+ """Undoes all recorded changes, the most recent one first."""
314
+ while self._undo:
315
+ step = self._undo.pop()
316
+ step[0](*step[1:])
317
+ for mapping, keys in self._orders.values():
318
+ _reorder(mapping, keys)
319
+ self._orders.clear()
320
+
321
+
322
+ def _undo_setitem(container, key, value):
323
+ container[key] = value
324
+
325
+
326
+ def _undo_delitem(container, key):
327
+ del container[key]
328
+
329
+
330
+ def _undo_insert(container, index, value):
331
+ container.insert(index, value)
332
+
333
+
334
+ def _undo_dropping_append(deque, dropped):
335
+ del deque[-1]
336
+ deque.appendleft(dropped)
337
+
338
+
339
+ def _reorder(mapping, keys):
340
+ """Restores the order of the members of a mapping after a rollback.
341
+
342
+ ``keys`` are its keys before its first removal. They can include
343
+ members that the patch added before, and that the rollback has removed
344
+ again; the original members appear in it in their original order.
345
+ """
346
+ keys = [key for key in keys if key in mapping]
347
+ start = next((index for index, (key, original)
348
+ in enumerate(zip(mapping, keys)) if key != original),
349
+ len(keys))
350
+ # Move the members from the first misplaced one on to the end. Unlike
351
+ # update(), which e.g. a Counter uses to add counts, this only uses the
352
+ # operations the rollback itself uses
353
+ for key in keys[start:]:
354
+ mapping[key] = mapping.pop(key)
355
+
356
+
189
357
  class PatchOperation(object):
190
358
  """A single operation inside a JSON Patch."""
191
359
 
@@ -225,7 +393,15 @@ class PatchOperation(object):
225
393
  raise InvalidJsonPatch("Invalid 'from'", op=self)
226
394
 
227
395
  def apply(self, obj):
228
- """Abstract method that applies a patch operation to the specified object."""
396
+ """Applies the patch operation to the specified object."""
397
+ return self._apply(obj, _NO_JOURNAL)
398
+
399
+ def _apply(self, obj, journal):
400
+ """Applies the operation, making all changes through ``journal``, so
401
+ that :meth:`JsonPatch.apply` can undo them with ``atomic=True``.
402
+
403
+ Subclasses either implement this method or override :meth:`apply`.
404
+ """
229
405
  raise NotImplementedError('should implement the patch operation.')
230
406
 
231
407
  def __hash__(self):
@@ -269,7 +445,7 @@ class PatchOperation(object):
269
445
  class RemoveOperation(PatchOperation):
270
446
  """Removes an object property or an array element."""
271
447
 
272
- def apply(self, obj):
448
+ def _apply(self, obj, journal):
273
449
  subobj, part = self.pointer.to_last(obj)
274
450
 
275
451
  if part is None:
@@ -279,10 +455,10 @@ class RemoveOperation(PatchOperation):
279
455
  raise JsonPointerException("invalid array index '{0}'".format(part))
280
456
 
281
457
  try:
282
- del subobj[part]
458
+ journal.delitem(subobj, part)
283
459
  except (KeyError, IndexError):
284
460
  msg = "can't remove a non-existent object '{0}'".format(part)
285
- raise JsonPatchConflict(msg, op=self)
461
+ raise JsonPatchPathNotFound(msg, op=self)
286
462
  except TypeError as ex:
287
463
  raise JsonPatchConflict(str(ex), op=self)
288
464
 
@@ -292,7 +468,7 @@ class RemoveOperation(PatchOperation):
292
468
  class AddOperation(PatchOperation):
293
469
  """Adds an object property or an array element."""
294
470
 
295
- def apply(self, obj):
471
+ def _apply(self, obj, journal):
296
472
  try:
297
473
  value = self.operation["value"]
298
474
  except KeyError:
@@ -301,9 +477,13 @@ class AddOperation(PatchOperation):
301
477
 
302
478
  # Insert a copy so the document does not share mutable values with
303
479
  # the patch; otherwise later operations would modify the patch itself.
304
- return self._add(obj, copy.deepcopy(value))
480
+ value = copy.deepcopy(value)
481
+ if journal is _NO_JOURNAL:
482
+ # subclasses may override _add without the journal parameter
483
+ return self._add(obj, value)
484
+ return self._add(obj, value, journal)
305
485
 
306
- def _add(self, obj, value):
486
+ def _add(self, obj, value, journal=_NO_JOURNAL):
307
487
  subobj, part = self.pointer.to_last(obj)
308
488
 
309
489
  if part is None:
@@ -311,16 +491,16 @@ class AddOperation(PatchOperation):
311
491
 
312
492
  if isinstance(subobj, MutableSequence):
313
493
  if part == '-':
314
- subobj.append(value) # pylint: disable=E1103
494
+ journal.append(subobj, value)
315
495
 
316
496
  elif part > len(subobj) or part < 0:
317
497
  raise JsonPatchConflict("can't insert outside of list", op=self)
318
498
 
319
499
  else:
320
- subobj.insert(part, value) # pylint: disable=E1103
500
+ journal.insert(subobj, part, value)
321
501
 
322
502
  elif isinstance(subobj, MutableMapping):
323
- subobj[part] = value
503
+ journal.setitem(subobj, part, value)
324
504
 
325
505
  else:
326
506
  raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part), op=self)
@@ -330,7 +510,7 @@ class AddOperation(PatchOperation):
330
510
  class ReplaceOperation(PatchOperation):
331
511
  """Replaces an object property or an array element by a new value."""
332
512
 
333
- def apply(self, obj):
513
+ def _apply(self, obj, journal):
334
514
  try:
335
515
  value = self.operation["value"]
336
516
  except KeyError:
@@ -352,23 +532,23 @@ class ReplaceOperation(PatchOperation):
352
532
  raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation", op=self)
353
533
 
354
534
  if part >= len(subobj) or part < 0:
355
- raise JsonPatchConflict("can't replace outside of list", op=self)
535
+ raise JsonPatchPathNotFound("can't replace outside of list", op=self)
356
536
 
357
537
  elif isinstance(subobj, MutableMapping):
358
538
  if part not in subobj:
359
539
  msg = "can't replace a non-existent object '{0}'".format(part)
360
- raise JsonPatchConflict(msg, op=self)
540
+ raise JsonPatchPathNotFound(msg, op=self)
361
541
  else:
362
542
  raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part), op=self)
363
543
 
364
- subobj[part] = value
544
+ journal.setitem(subobj, part, value)
365
545
  return obj
366
546
 
367
547
 
368
548
  class MoveOperation(PatchOperation):
369
549
  """Moves an object property or an array element to a new location."""
370
550
 
371
- def apply(self, obj):
551
+ def _apply(self, obj, journal):
372
552
  from_ptr = self._from_pointer()
373
553
 
374
554
  # Checked before anything is resolved, as removing an array element
@@ -386,7 +566,7 @@ class MoveOperation(PatchOperation):
386
566
  try:
387
567
  value = subobj[part]
388
568
  except (KeyError, IndexError) as ex:
389
- raise JsonPatchConflict(str(ex), op=self)
569
+ raise JsonPatchPathNotFound(str(ex), op=self)
390
570
 
391
571
  # If source and target are equal, this is a no-op
392
572
  if self.pointer == from_ptr:
@@ -396,14 +576,14 @@ class MoveOperation(PatchOperation):
396
576
  obj = RemoveOperation({
397
577
  'op': 'remove',
398
578
  'path': self.operation['from']
399
- }, pointer_cls=self.pointer_cls).apply(obj)
579
+ }, pointer_cls=self.pointer_cls)._apply(obj, journal)
400
580
 
401
581
  # the value has been detached from its old location, so no copy
402
582
  # needed
403
583
  obj = AddOperation({
404
584
  'op': 'add',
405
585
  'path': self.location,
406
- }, pointer_cls=self.pointer_cls)._add(obj, value)
586
+ }, pointer_cls=self.pointer_cls)._add(obj, value, journal)
407
587
  except JsonPatchException as ex:
408
588
  # report the failure against this operation rather than the
409
589
  # internal, synthetic remove / add operations
@@ -441,7 +621,7 @@ class MoveOperation(PatchOperation):
441
621
  class TestOperation(PatchOperation):
442
622
  """Test value by specified location."""
443
623
 
444
- def apply(self, obj):
624
+ def _apply(self, obj, journal):
445
625
  try:
446
626
  subobj, part = self.pointer.to_last(obj)
447
627
  if part is None:
@@ -468,21 +648,21 @@ class TestOperation(PatchOperation):
468
648
  class CopyOperation(PatchOperation):
469
649
  """ Copies an object property or an array element to a new location """
470
650
 
471
- def apply(self, obj):
651
+ def _apply(self, obj, journal):
472
652
  from_ptr = self._from_pointer()
473
653
 
474
654
  subobj, part = _to_existing_last(from_ptr, obj)
475
655
  try:
476
656
  value = copy.deepcopy(subobj if part is None else subobj[part])
477
657
  except (KeyError, IndexError) as ex:
478
- raise JsonPatchConflict(str(ex), op=self)
658
+ raise JsonPatchPathNotFound(str(ex), op=self)
479
659
 
480
660
  # value is already a deep copy, no need to copy it again
481
661
  try:
482
662
  obj = AddOperation({
483
663
  'op': 'add',
484
664
  'path': self.location,
485
- }, pointer_cls=self.pointer_cls)._add(obj, value)
665
+ }, pointer_cls=self.pointer_cls)._add(obj, value, journal)
486
666
  except JsonPatchException as ex:
487
667
  # report the failure against this operation rather than the
488
668
  # internal, synthetic add operation
@@ -492,6 +672,57 @@ class CopyOperation(PatchOperation):
492
672
  return obj
493
673
 
494
674
 
675
+ def _restore(obj, saved):
676
+ """Restores the contents of a document from a copy of it.
677
+
678
+ Only the items of mappings and sequences are restored, not other state
679
+ that a custom operation can change, such as attributes or the list of
680
+ mappings of a ChainMap.
681
+ """
682
+ if isinstance(obj, collections.ChainMap):
683
+ # restore each mapping, so that none takes over another's members
684
+ for mapping, saved_mapping in zip(obj.maps, saved.maps):
685
+ _restore(mapping, saved_mapping)
686
+ elif isinstance(obj, MutableMapping):
687
+ obj.clear()
688
+ obj.update(saved)
689
+ elif isinstance(obj, MutableSequence):
690
+ # not obj[:] = saved, as e.g. deque doesn't support slices
691
+ obj.clear()
692
+ obj.extend(saved)
693
+ # Immutable containers can't have changed, but their children can
694
+ elif isinstance(obj, Mapping):
695
+ for key in saved:
696
+ _restore(obj[key], saved[key])
697
+ elif isinstance(obj, Sequence) and not isinstance(obj, (str, bytes)):
698
+ for item, saved_item in zip(obj, saved):
699
+ _restore(item, saved_item)
700
+
701
+
702
+ _JOURNALED_OPERATIONS = (
703
+ RemoveOperation, AddOperation, ReplaceOperation, MoveOperation,
704
+ TestOperation, CopyOperation,
705
+ )
706
+
707
+
708
+ def _supports_journal(operation):
709
+ """Whether all changes of ``operation`` go through its journal, which is
710
+ the case for the built-in operations unless a subclass, or the operation
711
+ object itself, changes how they are applied."""
712
+ overridden = getattr(operation, '__dict__', {})
713
+ if any(name in overridden for name in ('apply', '_apply', '_add')):
714
+ return False
715
+ cls = type(operation)
716
+ if getattr(cls, 'apply', None) is not PatchOperation.apply:
717
+ return False
718
+ if not any(getattr(cls, '_apply', None) is base._apply
719
+ for base in _JOURNALED_OPERATIONS):
720
+ return False
721
+ if isinstance(operation, AddOperation) and cls._add is not AddOperation._add:
722
+ return False
723
+ return True
724
+
725
+
495
726
  class JsonPatch(object):
496
727
  """A JSON Patch is an iterable of Patch Operations.
497
728
 
@@ -638,6 +869,9 @@ class JsonPatch(object):
638
869
  one. The resulting patch transforms `src` into `dst`, so it has to be
639
870
  applied to `src` (or to a document equal to it).
640
871
 
872
+ Values in the patch are copied, so changing either input document
873
+ afterwards does not change the generated patch.
874
+
641
875
  :param src: Source JSON document, including arrays and scalar values.
642
876
  :type src: object
643
877
 
@@ -675,7 +909,7 @@ class JsonPatch(object):
675
909
  optimization=optimization,
676
910
  generate_test_ops=generate_test_ops)
677
911
  builder._compare_values((), None, src, dst)
678
- ops = list(builder.execute())
912
+ ops = copy.deepcopy(list(builder.execute()))
679
913
  return cls(ops, pointer_cls=pointer_cls)
680
914
 
681
915
  def to_string(self, dumps=None):
@@ -687,7 +921,7 @@ class JsonPatch(object):
687
921
  def _ops(self):
688
922
  return tuple(map(self._get_operation, self.patch))
689
923
 
690
- def apply(self, obj, in_place=False):
924
+ def apply(self, obj, in_place=False, atomic=False):
691
925
  """Applies the patch to a given object.
692
926
 
693
927
  :param obj: JSON document, including arrays and scalar values.
@@ -697,6 +931,21 @@ class JsonPatch(object):
697
931
  specified `obj` or to its copy.
698
932
  :type in_place: bool
699
933
 
934
+ :param atomic: With ``in_place=True``, undo the changes of all
935
+ preceding operations if an operation fails, so that
936
+ `obj` is either fully patched or left unchanged. This
937
+ does not copy the document; it only keeps the values
938
+ that the patch removes or replaces until it is
939
+ applied. Patches with custom operations, whose
940
+ changes can't be undone, copy the document instead.
941
+ Exact restoration is guaranteed for documents of
942
+ plain dicts and lists; members that containers such
943
+ as ``defaultdict`` add when they are only read are
944
+ not removed again (see the tutorial). Without
945
+ ``in_place=True``, `obj` is never changed, so this
946
+ has no effect.
947
+ :type atomic: bool
948
+
700
949
  :return: Resulting document. Use this return value even with
701
950
  ``in_place=True``, because a root replacement returns a new
702
951
  value rather than modifying the original container.
@@ -704,9 +953,35 @@ class JsonPatch(object):
704
953
 
705
954
  if not in_place:
706
955
  obj = copy.deepcopy(obj)
956
+ atomic = False
707
957
 
708
- for operation in self._ops:
709
- obj = operation.apply(obj)
958
+ ops = self._ops
959
+
960
+ if not atomic:
961
+ for operation in ops:
962
+ obj = operation.apply(obj)
963
+ return obj
964
+
965
+ if not all(map(_supports_journal, ops)):
966
+ # The changes of custom operations can't be undone, so restore
967
+ # the document from a copy instead
968
+ saved = copy.deepcopy(obj)
969
+ original = obj
970
+ try:
971
+ for operation in ops:
972
+ obj = operation.apply(obj)
973
+ except BaseException:
974
+ _restore(original, saved)
975
+ raise
976
+ return obj
977
+
978
+ journal = _Journal()
979
+ try:
980
+ for operation in ops:
981
+ obj = operation._apply(obj, journal)
982
+ except BaseException:
983
+ journal.rollback()
984
+ raise
710
985
 
711
986
  return obj
712
987
 
jsonpatch_cli.py CHANGED
@@ -8,6 +8,7 @@ import json
8
8
  import jsonpatch
9
9
  import tempfile
10
10
  import argparse
11
+ from contextlib import ExitStack
11
12
 
12
13
 
13
14
  jsondiff_parser = argparse.ArgumentParser(
@@ -35,8 +36,12 @@ def jsondiff_main():
35
36
  def diff_files():
36
37
  """ Diffs two JSON files and prints a patch """
37
38
  args = jsondiff_parser.parse_args()
38
- doc1 = json.load(args.FILE1)
39
- doc2 = json.load(args.FILE2)
39
+ with ExitStack() as inputs:
40
+ for stream in (args.FILE1, args.FILE2):
41
+ if stream is not sys.stdin:
42
+ inputs.enter_context(stream)
43
+ doc1 = json.load(args.FILE1)
44
+ doc2 = json.load(args.FILE2)
40
45
  patch = jsonpatch.make_patch(doc1, doc2, generate_test_ops=args.test_ops)
41
46
  if patch.patch:
42
47
  print(json.dumps(patch.patch, indent=args.indent, ensure_ascii=not(args.preserve_unicode)))
@@ -1,10 +0,0 @@
1
- jsonpatch.py,sha256=i0UN_UBxpx9ClyplHpbEEhVpHC-ckzcwqlAsPutxD28,47675
2
- jsonpatch_cli.py,sha256=ooxDB62_Vcx6ryCbyMHItkNgmZjp73ZOyxgV1IAcdVI,6274
3
- jsonpatch-1.41.dist-info/licenses/AUTHORS,sha256=hOtEnBGbfDegKjzMDEl5vuVJyczbI2PlYE2ho4LjGNQ,140
4
- jsonpatch-1.41.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
5
- jsonpatch-stubs/__init__.pyi,sha256=puuW3LKHkYNSMyGQ_0XqfDwqLjdHbSUTJU79gpPZy54,5215
6
- jsonpatch-1.41.dist-info/METADATA,sha256=je3-rYA4OmtMG6NM7sDfYCSU3MSttqM9CmKJ4ugSFEo,4287
7
- jsonpatch-1.41.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
- jsonpatch-1.41.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
9
- jsonpatch-1.41.dist-info/top_level.txt,sha256=AGmziZtf5TSFAtbhYlhDGjQg1POmwzF9HwLdbzPkoio,40
10
- jsonpatch-1.41.dist-info/RECORD,,