diff --git a/Doc/library/plistlib.rst b/Doc/library/plistlib.rst index 72140e41675c350..6e661e391f42358 100644 --- a/Doc/library/plistlib.rst +++ b/Doc/library/plistlib.rst @@ -40,6 +40,10 @@ or :class:`datetime.datetime` objects. .. versionchanged:: 3.9 Old API removed. +.. versionchanged:: 3.16 + Support added for reading and writing :class:`UID` tokens in XML + plists. + .. seealso:: `PList manual page `_ @@ -143,6 +147,9 @@ The following classes are available: Wraps an :class:`int`. This is used when reading or writing NSKeyedArchiver encoded data, which contains UID (see PList manual). + In XML plists, a UID is written as a dictionary with a single + :data:`CFUID_KEY` key. + .. attribute:: data Int value of the UID. It must be in the range ``0 <= data < 2**64``. @@ -161,11 +168,18 @@ The following constants are available: .. data:: FMT_BINARY - The binary format for plist files + The binary format for plist files. .. versionadded:: 3.4 +.. data:: CFUID_KEY + + The dictionary key used to represent a :class:`UID` in XML-format plist + files. + + .. versionadded:: 3.16 + The module defines the following exceptions: .. exception:: InvalidFileException diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 7995da012858245..2a9583ce653881c 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -618,6 +618,15 @@ pickle :class:`!WeakMethod` and :class:`!WeakSet` can now also be copied. (Contributed by Serhiy Storchaka in :gh:`74876`.) +plistlib +-------- + +* :mod:`plistlib` now supports reading and writing :class:`plistlib.UID` + tokens in XML plists. In XML, a UID is represented as a dictionary with a + single :data:`plistlib.CFUID_KEY` key, matching the format written by + Apple's ``NSKeyedArchiver``. + (Contributed by Mingye Wang in :gh:`83913`.) + quopri ------ diff --git a/Lib/plistlib.py b/Lib/plistlib.py index 822fbcf17b16d08..93f8f4a87398264 100644 --- a/Lib/plistlib.py +++ b/Lib/plistlib.py @@ -55,7 +55,7 @@ print(pl["foo"]) """ __all__ = [ - "InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID" + "InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID", "CFUID_KEY" ] import binascii @@ -115,6 +115,9 @@ def __hash__(self): """ +# CF$UID KEY +CFUID_KEY = "CF$UID" + # Regex to find any control chars, except for \t \n and \r _controlCharPat = re.compile( @@ -195,6 +198,8 @@ def __init__(self, dict_type, aware_datetime=False): self.stack = [] self.current_key = None self.root = None + # Key under which each dict was added to its parent. + self._dict_keys = [] self._dict_type = dict_type self._aware_datetime = aware_datetime @@ -252,6 +257,7 @@ def get_data(self): def begin_dict(self, attrs): d = self._dict_type() + self._dict_keys.append(self.current_key) self.add_object(d) self.stack.append(d) @@ -259,7 +265,18 @@ def end_dict(self): if self.current_key: raise ValueError("missing value for key '%s' at line %d" % (self.current_key,self.parser.CurrentLineNumber)) - self.stack.pop() + d = self.stack.pop() + key = self._dict_keys.pop() + # A dict with a single CF$UID key is how XML plists encode a UID. + if (len(d) == 1 and CFUID_KEY in d + and type(d[CFUID_KEY]) is int): + uid = UID(d[CFUID_KEY]) + if not self.stack: + self.root = uid + elif isinstance(self.stack[-1], dict): + self.stack[-1][key] = uid + else: + self.stack[-1][-1] = uid def end_key(self): if self.current_key or not isinstance(self.stack[-1], dict): @@ -389,6 +406,9 @@ def write_value(self, value): elif isinstance(value, (tuple, list)): self.write_array(value) + elif isinstance(value, UID): + self.write_dict({CFUID_KEY: int(value.data)}) + else: raise TypeError("unsupported type: %s" % type(value)) diff --git a/Lib/test/test_plistlib.py b/Lib/test/test_plistlib.py index fd6036c033ffb85..5b14201f17edda8 100644 --- a/Lib/test/test_plistlib.py +++ b/Lib/test/test_plistlib.py @@ -17,6 +17,7 @@ from test import support from test.support import os_helper from io import BytesIO +from xml.etree import ElementTree from plistlib import UID @@ -599,7 +600,9 @@ def test_indentation_dict_mix(self): def test_uid(self): data = UID(1) - self.assertEqual(plistlib.loads(plistlib.dumps(data, fmt=plistlib.FMT_BINARY)), data) + for fmt in ALL_FORMATS: + self.assertEqual(plistlib.loads(plistlib.dumps(data, fmt=fmt)), data) + dict_data = { 'uid0': UID(0), 'uid2': UID(2), @@ -608,7 +611,42 @@ def test_uid(self): 'uid32': UID(2 ** 32), 'uid63': UID(2 ** 63) } - self.assertEqual(plistlib.loads(plistlib.dumps(dict_data, fmt=plistlib.FMT_BINARY)), dict_data) + for fmt in ALL_FORMATS: + self.assertEqual(plistlib.loads(plistlib.dumps(dict_data, fmt=fmt)), dict_data) + + def test_uid_xml_format(self): + # XML plists encode a UID as a dict with a single CFUID_KEY key. + data = plistlib.dumps({'uid': UID(42)}, fmt=plistlib.FMT_XML) + root = ElementTree.fromstring(data) + uid_dict = root.find('dict/dict') + self.assertIsNotNone(uid_dict) + self.assertEqual(uid_dict.find('key').text, plistlib.CFUID_KEY) + self.assertEqual(uid_dict.find('integer').text, '42') + + def test_uid_xml_parse(self): + uid_xml = b'CF$UID1' + + def wrap(body): + return b'' + body + b'' + + self.assertEqual(plistlib.loads(wrap(uid_xml)), UID(1)) + self.assertEqual(plistlib.loads(wrap(b'' + uid_xml + b'')), + [UID(1)]) + self.assertEqual( + plistlib.loads(wrap(b'ab' + + uid_xml + b'')), + {'a': {'b': UID(1)}}) + self.assertEqual( + plistlib.loads(wrap(b'' + uid_xml + b'')), + {'': UID(1)}) + # Only dicts with a single integer CF$UID key are UIDs. + self.assertEqual( + plistlib.loads(wrap(b'CF$UID1' + b'x')), + {'CF$UID': 1, 'x': True}) + self.assertEqual( + plistlib.loads(wrap(b'CF$UID')), + {'CF$UID': True}) def test_uid_data(self): uid = UID(1) diff --git a/Misc/NEWS.d/next/Library/2020-02-24-12-48-58.gh-issue-83913.4qZX4h.rst b/Misc/NEWS.d/next/Library/2020-02-24-12-48-58.gh-issue-83913.4qZX4h.rst new file mode 100644 index 000000000000000..457a12230a60c1d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-02-24-12-48-58.gh-issue-83913.4qZX4h.rst @@ -0,0 +1,2 @@ +Add support for reading and writing :class:`plistlib.UID` tokens in XML +plists.