jsonpatch 1.43__py3-none-any.whl → 1.45__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.43
3
+ Version: 1.45
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
@@ -70,6 +70,16 @@ See source code for examples
70
70
  * CI: https://github.com/stefankoegl/python-json-patch/actions
71
71
  * Coveralls: https://coveralls.io/github/stefankoegl/python-json-patch
72
72
 
73
+ String append extension
74
+ -----------------------
75
+ `JsonPatchWithAppend` is a drop-in replacement for `JsonPatch` with a
76
+ non-RFC string `append` operation. Its `from_diff()` method sends only the
77
+ new suffix when an object member's string grows. `JsonPatch`, `make_patch()`
78
+ and `apply_patch()` retain their standard RFC 6902 behavior.
79
+
80
+ See the [tutorial](doc/tutorial.rst#string-append-extension) for examples.
81
+ Both sender and receiver must support the extension.
82
+
73
83
  Type hints
74
84
  ----------
75
85
  jsonpatch ships type stubs (in the `jsonpatch-stubs` directory, as
@@ -0,0 +1,10 @@
1
+ jsonpatch.py,sha256=5Vs9OIFV2aioCf4LuMX4CfltVoYwhQAHJGp7u6DtNW0,67433
2
+ jsonpatch_cli.py,sha256=Vavn3OY4KrowXNTRDbgsNPcd9vTGLkIgz0Hr6Uwr5mk,6480
3
+ jsonpatch-1.45.dist-info/licenses/AUTHORS,sha256=hOtEnBGbfDegKjzMDEl5vuVJyczbI2PlYE2ho4LjGNQ,140
4
+ jsonpatch-1.45.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
5
+ jsonpatch-stubs/__init__.pyi,sha256=ARV0JxPJ3TZbYk1hUbayPO3gJVP0geIQK6fftWM-4KY,5623
6
+ jsonpatch-1.45.dist-info/METADATA,sha256=255V0zWc9-62CxfdBebjRFLt0pal9KGRqBnC5vPnUPY,4748
7
+ jsonpatch-1.45.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ jsonpatch-1.45.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
9
+ jsonpatch-1.45.dist-info/top_level.txt,sha256=AGmziZtf5TSFAtbhYlhDGjQg1POmwzF9HwLdbzPkoio,40
10
+ jsonpatch-1.45.dist-info/RECORD,,
@@ -9,7 +9,8 @@
9
9
  # also accepts arbitrary Mapping / Sequence types, which a recursive JSON type
10
10
  # would reject.
11
11
 
12
- from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
12
+ from collections.abc import Callable, Iterable, Iterator, Mapping
13
+ from types import MappingProxyType
13
14
  from typing import Any, ClassVar
14
15
 
15
16
  # Re-exported, as jsonpatch.py imports them and users rely on that, e.g. to
@@ -52,12 +53,14 @@ def make_patch(
52
53
  pointer_cls: type[JsonPointer] = ...,
53
54
  generate_test_ops: bool = False,
54
55
  ) -> JsonPatch: ...
56
+ def path_split(path: str, pointer_cls: type[JsonPointer] = ...) -> tuple[str, ...]: ...
57
+ def path_join(parts: Iterable[str | int], pointer_cls: type[JsonPointer] = ...) -> str: ...
55
58
 
56
59
  class PatchOperation:
57
60
  pointer_cls: type[JsonPointer]
58
61
  location: str
59
62
  pointer: JsonPointer
60
- operation: _Operation
63
+ operation: dict[str, Any]
61
64
  def __init__(self, operation: _Operation, pointer_cls: type[JsonPointer] = ...) -> None: ...
62
65
  def apply(self, obj: Any) -> Any: ...
63
66
  def __hash__(self) -> int: ...
@@ -88,16 +91,17 @@ class MoveOperation(PatchOperation):
88
91
 
89
92
  class TestOperation(PatchOperation): ...
90
93
  class CopyOperation(PatchOperation): ...
94
+ class AppendOperation(PatchOperation): ...
91
95
 
92
96
  class JsonPatch:
93
97
  json_dumper: ClassVar[Callable[..., str]]
94
98
  json_loader: ClassVar[Callable[..., Any]]
95
- operations: ClassVar[Mapping[str, type[PatchOperation]]]
99
+ operations: ClassVar[MappingProxyType[str, type[PatchOperation]]]
96
100
  pointer_cls: type[JsonPointer]
97
- patch: Sequence[_Operation]
101
+ patch: list[dict[str, Any]]
98
102
  def __init__(self, patch: Iterable[_Operation], pointer_cls: type[JsonPointer] = ...) -> None: ...
99
103
  def __bool__(self) -> bool: ...
100
- def __iter__(self) -> Iterator[_Operation]: ...
104
+ def __iter__(self) -> Iterator[dict[str, Any]]: ...
101
105
  def __hash__(self) -> int: ...
102
106
  def __eq__(self, other: object) -> bool: ...
103
107
  def __ne__(self, other: object) -> bool: ...
@@ -122,6 +126,8 @@ class JsonPatch:
122
126
  def to_string(self, dumps: Callable[[Any], str] | None = None) -> str: ...
123
127
  def apply(self, obj: Any, in_place: bool = False, atomic: bool = False) -> Any: ...
124
128
 
129
+ class JsonPatchWithAppend(JsonPatch): ...
130
+
125
131
  # Computes the operations for JsonPatch.from_diff; mostly an implementation
126
132
  # detail, so its internal methods are typed loosely.
127
133
  class DiffBuilder:
jsonpatch.py CHANGED
@@ -53,9 +53,13 @@ _ST_REMOVE = 1
53
53
  _EXACT_MATCH_LIMIT = 500 ** 2
54
54
 
55
55
 
56
+ # The from_parts of pointer classes that don't override it, see path_join
57
+ _JSONPOINTER_FROM_PARTS = JsonPointer.from_parts.__func__
58
+
59
+
56
60
  # Will be parsed by setup.py to determine package metadata
57
61
  __author__ = 'Stefan Kögl <stefan@skoegl.net>'
58
- __version__ = '1.43'
62
+ __version__ = '1.45'
59
63
  __website__ = 'https://github.com/stefankoegl/python-json-patch'
60
64
  __license__ = 'BSD-3-Clause'
61
65
 
@@ -190,7 +194,9 @@ def make_patch(src, dst, pointer_cls=JsonPointer, generate_test_ops=False):
190
194
  :param dst: Target JSON document, including arrays and scalar values.
191
195
  :type dst: object
192
196
 
193
- :param pointer_cls: JSON pointer class to use.
197
+ :param pointer_cls: JSON pointer class to use. The paths of the
198
+ created operations are written with
199
+ :func:`path_join`, so they use its syntax.
194
200
  :type pointer_cls: Type[JsonPointer]
195
201
 
196
202
  :param generate_test_ops: Precede each ``remove`` and ``replace``
@@ -211,6 +217,83 @@ def make_patch(src, dst, pointer_cls=JsonPointer, generate_test_ops=False):
211
217
  generate_test_ops=generate_test_ops)
212
218
 
213
219
 
220
+ def path_split(path, pointer_cls=JsonPointer):
221
+ """Splits the ``path`` (or ``from``) of an operation into its parts.
222
+
223
+ The parts are the unescaped reference tokens of the JSON Pointer: ``~1``
224
+ becomes ``/`` and ``~0`` becomes ``~``. They are always strings, also
225
+ those that refer to array elements, as only the document a path is
226
+ applied to tells whether a part is an object key or an array index.
227
+
228
+ This is the reverse of :func:`path_join`.
229
+
230
+ :param path: The path, a JSON Pointer such as ``'/foo/0'``.
231
+ :type path: str
232
+
233
+ :param pointer_cls: JSON pointer class to parse the path with.
234
+ :type pointer_cls: Type[JsonPointer]
235
+
236
+ :return: The unescaped parts of the path; empty for the whole document
237
+ (the path ``''``).
238
+ :rtype: tuple[str, ...]
239
+
240
+ :raises JsonPointerException: if ``path`` is not a valid JSON Pointer.
241
+
242
+ >>> path_split('/foo/0')
243
+ ('foo', '0')
244
+ >>> path_split('/~1fields~1test/a~0b')
245
+ ('/fields/test', 'a~b')
246
+ >>> path_split('')
247
+ ()
248
+ """
249
+ return tuple(pointer_cls(path).parts)
250
+
251
+
252
+ def path_join(parts, pointer_cls=JsonPointer):
253
+ """Joins unescaped parts into a path, as used in the ``path`` (or
254
+ ``from``) of an operation.
255
+
256
+ Each part is converted to a string and escaped: ``~`` becomes ``~0`` and
257
+ ``/`` becomes ``~1``. Integers can be used for array indices.
258
+
259
+ This is the reverse of :func:`path_split`. :meth:`JsonPatch.from_diff`
260
+ and :func:`make_patch` use it to write the paths of the operations they
261
+ create, so these use the syntax of their ``pointer_cls``.
262
+
263
+ If ``pointer_cls`` overrides ``JsonPointer.from_parts``,
264
+ the path is ``pointer_cls.from_parts(parts).path``, so a pointer class
265
+ with a different path syntax overrides ``from_parts`` to build pointers
266
+ from parts. Otherwise the path is a JSON Pointer as defined by RFC 6901,
267
+ and ``pointer_cls`` is not used, as ``from_parts`` of ``JsonPointer``
268
+ always builds such a pointer.
269
+
270
+ :param parts: The object keys and array indices that lead to the
271
+ location; empty for the whole document.
272
+ :type parts: Iterable[str | int]
273
+
274
+ :param pointer_cls: JSON pointer class to build the path with.
275
+ :type pointer_cls: Type[JsonPointer]
276
+
277
+ :return: The path, a JSON Pointer.
278
+ :rtype: str
279
+
280
+ >>> path_join(['foo', 0])
281
+ '/foo/0'
282
+ >>> path_join(['/fields/test', 'a~b'])
283
+ '/~1fields~1test/a~0b'
284
+ >>> path_join([])
285
+ ''
286
+ """
287
+ from_parts = getattr(pointer_cls, 'from_parts', None)
288
+ if from_parts is None or \
289
+ getattr(from_parts, '__func__', None) is _JSONPOINTER_FROM_PARTS:
290
+ # Also for subclasses that only change how paths are parsed, which
291
+ # JsonPointer.from_parts would parse an RFC 6901 pointer with
292
+ return _to_pointer(parts)
293
+
294
+ return from_parts(parts).path
295
+
296
+
214
297
  class _NullJournal(object):
215
298
  """Performs the changes of patch operations without recording them."""
216
299
 
@@ -373,7 +456,8 @@ class PatchOperation(object):
373
456
  except TypeError:
374
457
  raise InvalidJsonPatch("Invalid 'path'", op=operation)
375
458
 
376
- self.operation = operation
459
+ # Setters update operation members, even when the input is read-only.
460
+ self.operation = operation if isinstance(operation, dict) else dict(operation)
377
461
 
378
462
  def _from_pointer(self):
379
463
  """Builds the pointer of the 'from' member like __init__ builds the
@@ -420,10 +504,20 @@ class PatchOperation(object):
420
504
 
421
505
  @property
422
506
  def path(self):
423
- return '/'.join(self.pointer.parts[:-1])
507
+ """The location of the object or array that contains the target of
508
+ the operation, i.e. its ``path`` without the last part, written in
509
+ the syntax of ``pointer_cls`` (see :func:`path_join`).
510
+
511
+ For example ``'/a/0'`` for the ``path`` ``'/a/0/b'``, and ``''`` for
512
+ a target at the top level of the document. The last part is
513
+ :attr:`key`.
514
+ """
515
+ return path_join(self.pointer.parts[:-1], self.pointer_cls)
424
516
 
425
517
  @property
426
518
  def key(self):
519
+ """The last part of ``path``, as returned by :meth:`get_part`.
520
+ Setting it changes the ``path`` member of the operation."""
427
521
  return self.get_part(-1)
428
522
 
429
523
  @key.setter
@@ -431,6 +525,20 @@ class PatchOperation(object):
431
525
  self.set_part(-1, value)
432
526
 
433
527
  def get_part(self, index):
528
+ """Returns the part of ``path`` at ``index``, unescaped.
529
+
530
+ The part is converted to an int if ``int()`` accepts it, and is a
531
+ str otherwise. Whether it is an array index or an object key is not
532
+ checked, as only the document tells, so numeric object keys are
533
+ converted as well: ``'01'`` and ``'1_0'`` become ``1`` and ``10``.
534
+ To get the exact keys, use :func:`path_split` or ``pointer.parts``.
535
+
536
+ >>> op = RemoveOperation({'op': 'remove', 'path': '/a/0/01/b'})
537
+ >>> [op.get_part(i) for i in range(4)]
538
+ ['a', 0, 1, 'b']
539
+ >>> path_split(op.location)
540
+ ('a', '0', '01', 'b')
541
+ """
434
542
  try:
435
543
  return int(self.pointer.parts[index])
436
544
  except ValueError:
@@ -594,11 +702,16 @@ class MoveOperation(PatchOperation):
594
702
 
595
703
  @property
596
704
  def from_path(self):
705
+ """Like :attr:`PatchOperation.path`, but of the ``from`` member: the location of
706
+ the object or array that contains the moved value."""
597
707
  from_ptr = self._from_pointer()
598
- return '/'.join(from_ptr.parts[:-1])
708
+ return path_join(from_ptr.parts[:-1], self.pointer_cls)
599
709
 
600
710
  @property
601
711
  def from_key(self):
712
+ """The last part of ``from``, as returned by
713
+ :meth:`get_from_part`. Setting it changes the ``from`` member of the
714
+ operation."""
602
715
  return self.get_from_part(-1)
603
716
 
604
717
  @from_key.setter
@@ -606,6 +719,8 @@ class MoveOperation(PatchOperation):
606
719
  self.set_from_part(-1, value)
607
720
 
608
721
  def get_from_part(self, index):
722
+ """Like :meth:`PatchOperation.get_part`, but returns the part of
723
+ ``from`` at ``index``: also numeric object keys become ints."""
609
724
  from_ptr = self._from_pointer()
610
725
  try:
611
726
  return int(from_ptr.parts[index])
@@ -672,6 +787,39 @@ class CopyOperation(PatchOperation):
672
787
  return obj
673
788
 
674
789
 
790
+ class AppendOperation(PatchOperation):
791
+ """Appends a string suffix to an existing string (not part of RFC 6902)."""
792
+
793
+ def _apply(self, obj, journal):
794
+ try:
795
+ value = self.operation['value']
796
+ except KeyError:
797
+ raise InvalidJsonPatch("The operation does not contain a 'value' member", op=self)
798
+ if not isinstance(value, str):
799
+ raise JsonPatchConflict("Cannot append a non-string value", op=self)
800
+
801
+ try:
802
+ subobj, part = self.pointer.to_last(obj)
803
+ except JsonPointerException as ex:
804
+ raise JsonPatchPathNotFound(str(ex), op=self)
805
+
806
+ if part is None:
807
+ raise JsonPatchConflict("Cannot append to root document", op=self)
808
+ if isinstance(subobj, MutableSequence):
809
+ if not isinstance(part, int) or part < 0 or part >= len(subobj):
810
+ raise JsonPatchPathNotFound("Cannot append outside of list", op=self)
811
+ elif isinstance(subobj, MutableMapping):
812
+ if part not in subobj:
813
+ raise JsonPatchPathNotFound("Cannot append to a non-existent member", op=self)
814
+ else:
815
+ raise JsonPatchConflict("Cannot append to a non-string value", op=self)
816
+
817
+ if not isinstance(subobj[part], str):
818
+ raise JsonPatchConflict("Cannot append to a non-string value", op=self)
819
+ journal.setitem(subobj, part, subobj[part] + value)
820
+ return obj
821
+
822
+
675
823
  def _restore(obj, saved):
676
824
  """Restores the contents of a document from a copy of it.
677
825
 
@@ -791,7 +939,7 @@ class JsonPatch(object):
791
939
  if isinstance(patch, (str, bytes, Mapping)):
792
940
  raise InvalidJsonPatch("Document is expected to be sequence of operations")
793
941
  try:
794
- self.patch = patch if isinstance(patch, Sequence) else list(patch)
942
+ self.patch = list(patch)
795
943
  except TypeError:
796
944
  raise InvalidJsonPatch("Document is expected to be sequence of operations")
797
945
 
@@ -799,7 +947,7 @@ class JsonPatch(object):
799
947
  # is correct by retrieving each patch element.
800
948
  # Much of the validation is done in the initializer
801
949
  # though some is delayed until the patch is applied.
802
- for op in self.patch:
950
+ for index, op in enumerate(self.patch):
803
951
  # We're only checking for strings in the following check
804
952
  # for two reasons:
805
953
  #
@@ -815,6 +963,10 @@ class JsonPatch(object):
815
963
  op=op)
816
964
 
817
965
  self._get_operation(op)
966
+ # Keep validation errors tied to the original input, but expose
967
+ # concrete, JSON-serializable operation dictionaries on success.
968
+ if not isinstance(op, dict):
969
+ self.patch[index] = dict(op)
818
970
 
819
971
  def __str__(self):
820
972
  """str(self) -> self.to_string()"""
@@ -886,7 +1038,9 @@ class JsonPatch(object):
886
1038
  JSON string.
887
1039
  :type dumps: Callable
888
1040
 
889
- :param pointer_cls: JSON pointer class to use.
1041
+ :param pointer_cls: JSON pointer class to use. The paths of the
1042
+ created operations are written with
1043
+ :func:`path_join`, so they use its syntax.
890
1044
  :type pointer_cls: Type[JsonPointer]
891
1045
 
892
1046
  :param generate_test_ops: Precede each ``remove`` and ``replace``
@@ -1004,6 +1158,35 @@ class JsonPatch(object):
1004
1158
  return cls(operation, pointer_cls=self.pointer_cls)
1005
1159
 
1006
1160
 
1161
+ class JsonPatchWithAppend(JsonPatch):
1162
+ """A JsonPatch with an optional, non-RFC string append operation.
1163
+
1164
+ Each append operation requires full ``op``, ``path`` and ``value`` members.
1165
+ It appends a string suffix to an existing object member or array element.
1166
+ The standard JsonPatch class and module-level helpers remain RFC 6902 only.
1167
+ """
1168
+
1169
+ operations = MappingProxyType(dict(JsonPatch.operations, append=AppendOperation))
1170
+
1171
+ @classmethod
1172
+ def from_diff(cls, src, dst, optimization=True, dumps=None,
1173
+ pointer_cls=JsonPointer, generate_test_ops=False):
1174
+ """Creates a patch, using append for string growth in object members.
1175
+
1176
+ Root strings and scalar array elements retain standard diff behavior.
1177
+ Options follow JsonPatch.from_diff; optimization=False disables moves,
1178
+ while append remains enabled. With generate_test_ops=True, an append
1179
+ is preceded by a test of the original string.
1180
+ """
1181
+ json_dumper = dumps or cls.json_dumper
1182
+ builder = _AppendDiffBuilder(src, dst, json_dumper, pointer_cls=pointer_cls,
1183
+ optimization=optimization,
1184
+ generate_test_ops=generate_test_ops)
1185
+ builder._compare_values((), None, src, dst)
1186
+ ops = copy.deepcopy(list(builder.execute()))
1187
+ return cls(ops, pointer_cls=pointer_cls)
1188
+
1189
+
1007
1190
  class DiffBuilder(object):
1008
1191
 
1009
1192
  def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer,
@@ -1077,7 +1260,8 @@ class DiffBuilder(object):
1077
1260
  op_second['op'] == 'add':
1078
1261
  yield {
1079
1262
  'op': 'replace',
1080
- 'path': _to_pointer(op_second['path']),
1263
+ 'path': path_join(op_second['path'],
1264
+ self.pointer_cls),
1081
1265
  'value': op_second['value'],
1082
1266
  }
1083
1267
  i += 2
@@ -1086,7 +1270,8 @@ class DiffBuilder(object):
1086
1270
  operation = operations[i]
1087
1271
  for member in ('from', 'path'):
1088
1272
  if member in operation:
1089
- operation[member] = _to_pointer(operation[member])
1273
+ operation[member] = path_join(operation[member],
1274
+ self.pointer_cls)
1090
1275
  yield operation
1091
1276
  i += 1
1092
1277
 
@@ -1357,6 +1542,20 @@ class DiffBuilder(object):
1357
1542
  self._item_replaced(path, key, dst, src)
1358
1543
 
1359
1544
 
1545
+ class _AppendDiffBuilder(DiffBuilder):
1546
+
1547
+ def _item_replaced(self, path, key, item, old_item):
1548
+ if (path or key is not None) and isinstance(old_item, str) and \
1549
+ isinstance(item, str) and len(item) > len(old_item) and \
1550
+ item.startswith(old_item):
1551
+ location = self._location(_path_join(path, key))
1552
+ self._insert_test(location, old_item)
1553
+ self.insert({'op': 'append', 'path': location,
1554
+ 'value': item[len(old_item):]})
1555
+ else:
1556
+ super()._item_replaced(path, key, item, old_item)
1557
+
1558
+
1360
1559
  def _positional_cost(old, new):
1361
1560
  """ Estimates how many operations change old into new, if the items of
1362
1561
  arrays are compared by position """
@@ -1521,6 +1720,7 @@ def _path_join(path, key):
1521
1720
 
1522
1721
 
1523
1722
  def _to_pointer(path):
1723
+ """ Fast path of path_join for JsonPointer """
1524
1724
  return ''.join('/' + str(part).replace('~', '~0').replace('/', '~1')
1525
1725
  for part in path)
1526
1726
 
@@ -1,10 +0,0 @@
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,,