jsonpatch 1.47__py3-none-any.whl → 1.48__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.47
3
+ Version: 1.48
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,9 @@
1
+ jsonpatch.py,sha256=SAqrta5PE-_bEL7lg9ZR-aRLYvDe9rlwms9k8rmZdDQ,72326
2
+ jsonpatch_cli.py,sha256=ouGStiuN87nsfrGe1svTgR8WVH0EhiLnu_KW5OFg9ys,8363
3
+ jsonpatch-1.48.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
4
+ jsonpatch-stubs/__init__.pyi,sha256=Bg2Z-QYkBV2nFsw410s5GcQxI-GV4Jb00eYHBP7ciFw,5498
5
+ jsonpatch-1.48.dist-info/METADATA,sha256=jJAfj1tggk6NjVE-0jo5ew0b8tdirIXF28ccYW3HJ-o,4860
6
+ jsonpatch-1.48.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ jsonpatch-1.48.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
8
+ jsonpatch-1.48.dist-info/top_level.txt,sha256=AGmziZtf5TSFAtbhYlhDGjQg1POmwzF9HwLdbzPkoio,40
9
+ jsonpatch-1.48.dist-info/RECORD,,
jsonpatch.py CHANGED
@@ -59,7 +59,7 @@ _JSONPOINTER_FROM_PARTS = JsonPointer.from_parts.__func__
59
59
 
60
60
  # Will be parsed by setup.py to determine package metadata
61
61
  __author__ = 'Stefan Kögl <stefan@skoegl.net>'
62
- __version__ = '1.47'
62
+ __version__ = '1.48'
63
63
  __website__ = 'https://github.com/stefankoegl/python-json-patch'
64
64
  __license__ = 'BSD-3-Clause'
65
65
 
@@ -205,6 +205,9 @@ def make_patch(src, dst, pointer_cls=JsonPointer, generate_test_ops=False):
205
205
  fails on documents that differ from `src` there.
206
206
  :type generate_test_ops: bool
207
207
 
208
+ :raises TypeError: if the documents differ in an object member whose
209
+ name is not a string, see :meth:`JsonPatch.from_diff`.
210
+
208
211
  >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
209
212
  >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
210
213
  >>> patch = make_patch(src, dst)
@@ -437,6 +440,23 @@ def _reorder(mapping, keys):
437
440
  mapping[key] = mapping.pop(key)
438
441
 
439
442
 
443
+ def _plain_operation(operation, pointer_cls):
444
+ """Returns operation as a dict whose 'path' and 'from' are strings.
445
+
446
+ Both can be given as pointer objects instead. These are replaced by
447
+ their paths, so that the operation is JSON-serializable, and can be
448
+ compared to one that was given the paths. This is done in a copy; an
449
+ operation that is a dict already and has no pointer objects is returned
450
+ as it is.
451
+ """
452
+ paths = {member: operation[member].path for member in ('path', 'from')
453
+ if member in operation and
454
+ isinstance(operation[member], pointer_cls)}
455
+ if paths:
456
+ return dict(operation, **paths)
457
+ return operation if isinstance(operation, dict) else dict(operation)
458
+
459
+
440
460
  class PatchOperation:
441
461
  """A single operation inside a JSON Patch."""
442
462
 
@@ -491,13 +511,17 @@ class PatchOperation:
491
511
  def __hash__(self):
492
512
  # Other members can hold arrays or objects, which are unhashable.
493
513
  # Operations that compare equal still have equal 'op' and 'path'.
494
- return hash((self.operation.get('op'), self.operation['path']))
514
+ operation = _plain_operation(self.operation, self.pointer_cls)
515
+ return hash((operation.get('op'), operation['path']))
495
516
 
496
517
  def __eq__(self, other):
497
518
  if not isinstance(other, PatchOperation):
498
519
  return False
499
520
  # e.g. tests for 1 and for true behave differently
500
- return _json_equal(self.operation, other.operation)
521
+ # and paths are equal to pointer objects for them
522
+ return _json_equal(
523
+ _plain_operation(self.operation, self.pointer_cls),
524
+ _plain_operation(other.operation, other.pointer_cls))
501
525
 
502
526
  @property
503
527
  def path(self):
@@ -962,8 +986,7 @@ class JsonPatch:
962
986
  self._get_operation(op)
963
987
  # Keep validation errors tied to the original input, but expose
964
988
  # concrete, JSON-serializable operation dictionaries on success.
965
- if not isinstance(op, dict):
966
- self.patch[index] = dict(op)
989
+ self.patch[index] = _plain_operation(op, self.pointer_cls)
967
990
 
968
991
  def __str__(self):
969
992
  """str(self) -> self.to_string()"""
@@ -1043,6 +1066,13 @@ class JsonPatch:
1043
1066
 
1044
1067
  :return: :class:`JsonPatch` instance.
1045
1068
 
1069
+ :raises TypeError: if the documents differ in, or inside of, an
1070
+ object member whose name is not a string, such
1071
+ as the ``1`` of ``{1: 'a'}``. The path of an
1072
+ operation can't refer to such a member, which
1073
+ does not exist in JSON. Other differences of
1074
+ documents with such members are no problem.
1075
+
1046
1076
  >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
1047
1077
  >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
1048
1078
  >>> patch = JsonPatch.from_diff(src, dst)
@@ -1055,7 +1085,7 @@ class JsonPatch:
1055
1085
  optimization=optimization,
1056
1086
  generate_test_ops=generate_test_ops)
1057
1087
  builder._compare_values((), None, src, dst)
1058
- ops = copy.deepcopy(list(builder.execute()))
1088
+ ops = _json_copy(list(builder.execute()))
1059
1089
  return cls(ops, pointer_cls=pointer_cls)
1060
1090
 
1061
1091
  def to_string(self, dumps=None):
@@ -1175,7 +1205,7 @@ class JsonPatchWithAppend(JsonPatch):
1175
1205
  optimization=optimization,
1176
1206
  generate_test_ops=generate_test_ops)
1177
1207
  builder._compare_values((), None, src, dst)
1178
- ops = copy.deepcopy(list(builder.execute()))
1208
+ ops = _json_copy(list(builder.execute()))
1179
1209
  return cls(ops, pointer_cls=pointer_cls)
1180
1210
 
1181
1211
 
@@ -1184,6 +1214,10 @@ class DiffBuilder:
1184
1214
  def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer,
1185
1215
  optimization=True, generate_test_ops=False):
1186
1216
  self.dumps = dumps
1217
+ # json.dumps builds a JSONEncoder for every call; the default dumps
1218
+ # is called once per added and removed value, so cache its encoder
1219
+ self._canonical_dumps = (json.JSONEncoder(sort_keys=True).encode
1220
+ if dumps is json.dumps else None)
1187
1221
  self.pointer_cls = pointer_cls
1188
1222
  self.optimization = optimization
1189
1223
  self.generate_test_ops = generate_test_ops
@@ -1201,6 +1235,17 @@ class DiffBuilder:
1201
1235
  def _move_key(self, value):
1202
1236
  """ A key of value, which is equal for values that are equal in JSON,
1203
1237
  so that e.g. [1] is not moved where [true] is added """
1238
+ if self._canonical_dumps is not None:
1239
+ try:
1240
+ # sort_keys gives the same string as _sorted_members for JSON
1241
+ # documents, without building a sorted copy of every added or
1242
+ # removed subtree
1243
+ return self._canonical_dumps(value)
1244
+ except (TypeError, ValueError, RecursionError):
1245
+ # Values like UserDict and UserList are normalized by
1246
+ # _sorted_members, but the encoder cannot serialize them as
1247
+ # they are, so fall through to the generic path below
1248
+ pass
1204
1249
  try:
1205
1250
  # Serialized like in _differing_runs
1206
1251
  return self.dumps(_sorted_members(value))
@@ -1252,8 +1297,7 @@ class DiffBuilder:
1252
1297
  op_second['op'] == 'add':
1253
1298
  yield {
1254
1299
  'op': 'replace',
1255
- 'path': path_join(op_second['path'],
1256
- self.pointer_cls),
1300
+ 'path': self._path(op_second['path']),
1257
1301
  'value': op_second['value'],
1258
1302
  }
1259
1303
  i += 2
@@ -1262,11 +1306,20 @@ class DiffBuilder:
1262
1306
  operation = operations[i]
1263
1307
  for member in ('from', 'path'):
1264
1308
  if member in operation:
1265
- operation[member] = path_join(operation[member],
1266
- self.pointer_cls)
1309
+ operation[member] = self._path(operation[member])
1267
1310
  yield operation
1268
1311
  i += 1
1269
1312
 
1313
+ def _path(self, parts):
1314
+ """ The path of an operation, in the syntax of pointer_cls """
1315
+ for part in parts:
1316
+ if isinstance(part, _NonStringKey):
1317
+ raise TypeError(
1318
+ "can't create an operation for the object member "
1319
+ "{0!r}: its name is not a string, which the path of an "
1320
+ "operation can't refer to".format(part.key))
1321
+ return path_join(parts, self.pointer_cls)
1322
+
1270
1323
  def _replay(self):
1271
1324
  """ Applies the operations to the arrays of the source document, and
1272
1325
  returns them with the array indices at which they apply """
@@ -1406,13 +1459,13 @@ class DiffBuilder:
1406
1459
  intersection = [key for key in src if key in dst]
1407
1460
 
1408
1461
  for key in removed_keys:
1409
- self._item_removed(path, str(key), src[key])
1462
+ self._item_removed(path, _member_name(key), src[key])
1410
1463
 
1411
1464
  for key in added_keys:
1412
- self._item_added(path, str(key), dst[key])
1465
+ self._item_added(path, _member_name(key), dst[key])
1413
1466
 
1414
1467
  for key in intersection:
1415
- self._compare_values(path, str(key), src[key], dst[key])
1468
+ self._compare_values(path, _member_name(key), src[key], dst[key])
1416
1469
 
1417
1470
  def _differing_runs(self, src, dst):
1418
1471
  """ Returns (i1, i2, j1, j2) for each run of items src[i1:i2] that is
@@ -1548,6 +1601,37 @@ class _AppendDiffBuilder(DiffBuilder):
1548
1601
  super()._item_replaced(path, key, item, old_item)
1549
1602
 
1550
1603
 
1604
+ class _NonStringKey(str):
1605
+ """ Takes the place of an object key that is not a string in the parts
1606
+ of an operation.
1607
+
1608
+ A path can only refer to members whose names are strings: '/1' is the
1609
+ member '1', not the member 1. Members with other names are compared like
1610
+ all others, as nothing is wrong unless they differ; an operation for
1611
+ such a member, or for something in it, can't be written, though (see
1612
+ DiffBuilder._path). """
1613
+
1614
+ def __new__(cls, key):
1615
+ self = super().__new__(cls, key)
1616
+ self.key = key
1617
+ return self
1618
+
1619
+ # The member 1 is not the member '1', which this is equal to as a str
1620
+ def __eq__(self, other):
1621
+ return isinstance(other, _NonStringKey) and self.key == other.key
1622
+
1623
+ def __ne__(self, other):
1624
+ return not self == other
1625
+
1626
+ def __hash__(self):
1627
+ return hash(self.key)
1628
+
1629
+
1630
+ def _member_name(key):
1631
+ """ The part of an operation for the object key """
1632
+ return key if isinstance(key, str) else _NonStringKey(key)
1633
+
1634
+
1551
1635
  def _positional_cost(old, new):
1552
1636
  """ Estimates how many operations change old into new, if the items of
1553
1637
  arrays are compared by position """
@@ -1581,6 +1665,37 @@ def _json_equal(first, second):
1581
1665
  return first == second
1582
1666
 
1583
1667
 
1668
+ def _json_copy(value, memo=None):
1669
+ """ Copies a JSON value like copy.deepcopy, but without the generic
1670
+ dispatch for dicts, lists and scalars, which dominate patch creation.
1671
+
1672
+ Values that are not plain JSON containers keep the copy.deepcopy
1673
+ behaviour, and shared references are preserved through memo. """
1674
+ if value is None or type(value) in (str, int, float, bool):
1675
+ return value
1676
+ if memo is None:
1677
+ memo = {}
1678
+ value_id = id(value)
1679
+ copied = memo.get(value_id)
1680
+ if copied is not None:
1681
+ return copied
1682
+ value_type = type(value)
1683
+ if value_type is dict:
1684
+ # memo must hold the new dict before the children are copied, so
1685
+ # that self-referential documents terminate like copy.deepcopy
1686
+ copied = memo[value_id] = {}
1687
+ for key, item in value.items():
1688
+ # copy.deepcopy copies the keys too, through the same memo, so
1689
+ # that a key and a value that are the same object stay shared
1690
+ copied[_json_copy(key, memo)] = _json_copy(item, memo)
1691
+ return copied
1692
+ if value_type is list:
1693
+ copied = memo[value_id] = []
1694
+ copied.extend(_json_copy(item, memo) for item in value)
1695
+ return copied
1696
+ return copy.deepcopy(value, memo)
1697
+
1698
+
1584
1699
  def _sorted_members(value):
1585
1700
  """ Copies the arrays and objects in value, with the members of objects
1586
1701
  sorted by key """
jsonpatch_cli.py CHANGED
@@ -34,19 +34,38 @@ def _input_files(*streams):
34
34
  return inputs
35
35
 
36
36
 
37
- def jsondiff_main():
37
+ def _load(stream, loads=json.loads):
38
+ """ Parses the JSON document in stream; errors name the file """
38
39
  try:
39
- diff_files()
40
+ return loads(stream.read())
41
+ except ValueError as ex:
42
+ # invalid JSON or, as a UnicodeDecodeError, invalid UTF-8
43
+ name = getattr(stream, 'name', '<input>')
44
+ raise ValueError('{0}: {1}'.format(name, ex)) from ex
45
+
46
+
47
+ def _run(parser, program):
48
+ """ Runs a command line program. Errors in its input, and in reading
49
+ and writing files, are reported in one line, with exit status 2 """
50
+ try:
51
+ program()
40
52
  except KeyboardInterrupt:
41
53
  sys.exit(1)
54
+ except (jsonpatch.JsonPatchException, jsonpatch.JsonPointerException,
55
+ ValueError, OSError) as ex:
56
+ parser.exit(2, '{0}: error: {1}\n'.format(parser.prog, ex))
57
+
58
+
59
+ def jsondiff_main():
60
+ _run(jsondiff_parser, diff_files)
42
61
 
43
62
 
44
63
  def diff_files():
45
64
  """ Diffs two JSON files and prints a patch """
46
65
  args = jsondiff_parser.parse_args()
47
66
  with _input_files(args.FILE1, args.FILE2):
48
- doc1 = json.load(args.FILE1)
49
- doc2 = json.load(args.FILE2)
67
+ doc1 = _load(args.FILE1)
68
+ doc2 = _load(args.FILE2)
50
69
  patch = jsonpatch.make_patch(doc1, doc2, generate_test_ops=args.test_ops)
51
70
  if patch.patch:
52
71
  print(json.dumps(patch.patch, indent=args.indent, ensure_ascii=not args.preserve_unicode))
@@ -73,11 +92,25 @@ jsonpatch_parser.add_argument('-u', '--preserve-unicode', action='store_true',
73
92
  help='Output Unicode character as-is without using Code Point')
74
93
 
75
94
 
76
- def jsonpatch_main():
95
+ def _link_backup(original, temporary):
96
+ """ Links original to its backup name, replacing an older backup """
97
+ # link() does not overwrite an existing file, so the link is created
98
+ # under a temporary name, and then moved over an older backup
99
+ link = temporary + '.orig'
100
+ os.link(original, link)
77
101
  try:
78
- patch_files()
79
- except KeyboardInterrupt:
80
- sys.exit(1)
102
+ os.replace(link, original + '.orig')
103
+ finally:
104
+ # It is still there if replacing failed, and if the older backup is
105
+ # a link to original already, as replace() does nothing then
106
+ try:
107
+ os.unlink(link)
108
+ except OSError:
109
+ pass
110
+
111
+
112
+ def jsonpatch_main():
113
+ _run(jsonpatch_parser, patch_files)
81
114
 
82
115
 
83
116
  def patch_files():
@@ -86,8 +119,9 @@ def patch_files():
86
119
  # The inputs are closed before anything is written, as Windows cannot
87
120
  # replace ORIGINAL while it is open.
88
121
  with _input_files(args.ORIGINAL, args.PATCH):
89
- doc = json.load(args.ORIGINAL)
90
- result = jsonpatch.apply_patch(doc, args.PATCH.read())
122
+ doc = _load(args.ORIGINAL)
123
+ patch = _load(args.PATCH, jsonpatch.JsonPatch.from_string)
124
+ result = patch.apply(doc)
91
125
 
92
126
  if args.in_place:
93
127
  dirname = os.path.abspath(os.path.dirname(args.ORIGINAL.name))
@@ -121,7 +155,13 @@ def patch_files():
121
155
  # the original (if desired) and writing a new file.
122
156
 
123
157
  if args.backup:
124
- os.rename(args.ORIGINAL.name, args.ORIGINAL.name + '.orig')
158
+ # like in atomic mode, an older backup is replaced
159
+ os.replace(args.ORIGINAL.name, args.ORIGINAL.name + '.orig')
160
+ # A same-inode replace may leave the original name in place.
161
+ try:
162
+ os.unlink(args.ORIGINAL.name)
163
+ except FileNotFoundError:
164
+ pass
125
165
  fp = open(args.ORIGINAL.name, 'w', encoding='utf-8')
126
166
  atomic = False
127
167
 
@@ -157,11 +197,12 @@ def patch_files():
157
197
  if atomic:
158
198
  try:
159
199
  # Complete the atomic replace by linking the original
160
- # to a backup (if desired), fixing up the permissions
200
+ # to a backup (if desired), which replaces an older
201
+ # backup, fixing up the permissions
161
202
  # on the temporary file, and moving it into place.
162
203
 
163
204
  if args.backup:
164
- os.link(args.ORIGINAL.name, args.ORIGINAL.name + '.orig')
205
+ _link_backup(args.ORIGINAL.name, pathname)
165
206
  os.chmod(pathname, os.stat(args.ORIGINAL.name).st_mode)
166
207
  os.replace(pathname, args.ORIGINAL.name)
167
208
 
@@ -1,9 +0,0 @@
1
- jsonpatch.py,sha256=gRxBHP7TRKWjgTY8AMM3wqjFoTkFP7ef8aYx4OEX3yY,67287
2
- jsonpatch_cli.py,sha256=q_72_UMrOxKptom2038w0FM3zSMeA1ikY9vqFhVavdU,6707
3
- jsonpatch-1.47.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
4
- jsonpatch-stubs/__init__.pyi,sha256=Bg2Z-QYkBV2nFsw410s5GcQxI-GV4Jb00eYHBP7ciFw,5498
5
- jsonpatch-1.47.dist-info/METADATA,sha256=71D2bBUEJgpkqUkk74oPf4R5q191GaGsqq0dXkHs1P0,4860
6
- jsonpatch-1.47.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
- jsonpatch-1.47.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
8
- jsonpatch-1.47.dist-info/top_level.txt,sha256=AGmziZtf5TSFAtbhYlhDGjQg1POmwzF9HwLdbzPkoio,40
9
- jsonpatch-1.47.dist-info/RECORD,,