Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion Doc/library/plistlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/PropertyLists/>`_
Expand Down Expand Up @@ -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``.
Expand All @@ -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
Expand Down
9 changes: 9 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
------

Expand Down
24 changes: 22 additions & 2 deletions Lib/plistlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -115,6 +115,9 @@ def __hash__(self):
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
"""

# CF$UID KEY
CFUID_KEY = "CF$UID"


# Regex to find any control chars, except for \t \n and \r
_controlCharPat = re.compile(
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -252,14 +257,26 @@ 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)

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):
Expand Down Expand Up @@ -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))

Expand Down
42 changes: 40 additions & 2 deletions Lib/test/test_plistlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Comment thread
Artoria2e5 marked this conversation as resolved.
Resolved
self.assertEqual(plistlib.loads(plistlib.dumps(data, fmt=fmt)), data)

dict_data = {
'uid0': UID(0),
'uid2': UID(2),
Expand All @@ -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'<dict><key>CF$UID</key><integer>1</integer></dict>'

def wrap(body):
return b'<plist version="1.0">' + body + b'</plist>'

self.assertEqual(plistlib.loads(wrap(uid_xml)), UID(1))
self.assertEqual(plistlib.loads(wrap(b'<array>' + uid_xml + b'</array>')),
[UID(1)])
self.assertEqual(
plistlib.loads(wrap(b'<dict><key>a</key><dict><key>b</key>'
+ uid_xml + b'</dict></dict>')),
{'a': {'b': UID(1)}})
self.assertEqual(
plistlib.loads(wrap(b'<dict><key></key>' + uid_xml + b'</dict>')),
{'': UID(1)})
# Only dicts with a single integer CF$UID key are UIDs.
self.assertEqual(
plistlib.loads(wrap(b'<dict><key>CF$UID</key><integer>1</integer>'
b'<key>x</key><true/></dict>')),
{'CF$UID': 1, 'x': True})
self.assertEqual(
plistlib.loads(wrap(b'<dict><key>CF$UID</key><true/></dict>')),
{'CF$UID': True})

def test_uid_data(self):
uid = UID(1)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Add support for reading and writing :class:`plistlib.UID` tokens in XML
plists.
Loading