PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/plistlib.py

https://bitbucket.org/bwesterb/pypy
Python | 474 lines | 467 code | 0 blank | 7 comment | 2 complexity | b10e69fbde65e611f2d7d517c73890cb MD5 | raw file
  1. r"""plistlib.py -- a tool to generate and parse MacOSX .plist files.
  2. The PropertyList (.plist) file format is a simple XML pickle supporting
  3. basic object types, like dictionaries, lists, numbers and strings.
  4. Usually the top level object is a dictionary.
  5. To write out a plist file, use the writePlist(rootObject, pathOrFile)
  6. function. 'rootObject' is the top level object, 'pathOrFile' is a
  7. filename or a (writable) file object.
  8. To parse a plist from a file, use the readPlist(pathOrFile) function,
  9. with a file name or a (readable) file object as the only argument. It
  10. returns the top level object (again, usually a dictionary).
  11. To work with plist data in strings, you can use readPlistFromString()
  12. and writePlistToString().
  13. Values can be strings, integers, floats, booleans, tuples, lists,
  14. dictionaries, Data or datetime.datetime objects. String values (including
  15. dictionary keys) may be unicode strings -- they will be written out as
  16. UTF-8.
  17. The <data> plist type is supported through the Data class. This is a
  18. thin wrapper around a Python string.
  19. Generate Plist example:
  20. pl = dict(
  21. aString="Doodah",
  22. aList=["A", "B", 12, 32.1, [1, 2, 3]],
  23. aFloat=0.1,
  24. anInt=728,
  25. aDict=dict(
  26. anotherString="<hello & hi there!>",
  27. aUnicodeValue=u'M\xe4ssig, Ma\xdf',
  28. aTrueValue=True,
  29. aFalseValue=False,
  30. ),
  31. someData=Data("<binary gunk>"),
  32. someMoreData=Data("<lots of binary gunk>" * 10),
  33. aDate=datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
  34. )
  35. # unicode keys are possible, but a little awkward to use:
  36. pl[u'\xc5benraa'] = "That was a unicode key."
  37. writePlist(pl, fileName)
  38. Parse Plist example:
  39. pl = readPlist(pathOrFile)
  40. print pl["aKey"]
  41. """
  42. __all__ = [
  43. "readPlist", "writePlist", "readPlistFromString", "writePlistToString",
  44. "readPlistFromResource", "writePlistToResource",
  45. "Plist", "Data", "Dict"
  46. ]
  47. # Note: the Plist and Dict classes have been deprecated.
  48. import binascii
  49. import datetime
  50. from cStringIO import StringIO
  51. import re
  52. import warnings
  53. def readPlist(pathOrFile):
  54. """Read a .plist file. 'pathOrFile' may either be a file name or a
  55. (readable) file object. Return the unpacked root object (which
  56. usually is a dictionary).
  57. """
  58. didOpen = 0
  59. if isinstance(pathOrFile, (str, unicode)):
  60. pathOrFile = open(pathOrFile)
  61. didOpen = 1
  62. p = PlistParser()
  63. rootObject = p.parse(pathOrFile)
  64. if didOpen:
  65. pathOrFile.close()
  66. return rootObject
  67. def writePlist(rootObject, pathOrFile):
  68. """Write 'rootObject' to a .plist file. 'pathOrFile' may either be a
  69. file name or a (writable) file object.
  70. """
  71. didOpen = 0
  72. if isinstance(pathOrFile, (str, unicode)):
  73. pathOrFile = open(pathOrFile, "w")
  74. didOpen = 1
  75. writer = PlistWriter(pathOrFile)
  76. writer.writeln("<plist version=\"1.0\">")
  77. writer.writeValue(rootObject)
  78. writer.writeln("</plist>")
  79. if didOpen:
  80. pathOrFile.close()
  81. def readPlistFromString(data):
  82. """Read a plist data from a string. Return the root object.
  83. """
  84. return readPlist(StringIO(data))
  85. def writePlistToString(rootObject):
  86. """Return 'rootObject' as a plist-formatted string.
  87. """
  88. f = StringIO()
  89. writePlist(rootObject, f)
  90. return f.getvalue()
  91. def readPlistFromResource(path, restype='plst', resid=0):
  92. """Read plst resource from the resource fork of path.
  93. """
  94. warnings.warnpy3k("In 3.x, readPlistFromResource is removed.",
  95. stacklevel=2)
  96. from Carbon.File import FSRef, FSGetResourceForkName
  97. from Carbon.Files import fsRdPerm
  98. from Carbon import Res
  99. fsRef = FSRef(path)
  100. resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm)
  101. Res.UseResFile(resNum)
  102. plistData = Res.Get1Resource(restype, resid).data
  103. Res.CloseResFile(resNum)
  104. return readPlistFromString(plistData)
  105. def writePlistToResource(rootObject, path, restype='plst', resid=0):
  106. """Write 'rootObject' as a plst resource to the resource fork of path.
  107. """
  108. warnings.warnpy3k("In 3.x, writePlistToResource is removed.", stacklevel=2)
  109. from Carbon.File import FSRef, FSGetResourceForkName
  110. from Carbon.Files import fsRdWrPerm
  111. from Carbon import Res
  112. plistData = writePlistToString(rootObject)
  113. fsRef = FSRef(path)
  114. resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdWrPerm)
  115. Res.UseResFile(resNum)
  116. try:
  117. Res.Get1Resource(restype, resid).RemoveResource()
  118. except Res.Error:
  119. pass
  120. res = Res.Resource(plistData)
  121. res.AddResource(restype, resid, '')
  122. res.WriteResource()
  123. Res.CloseResFile(resNum)
  124. class DumbXMLWriter:
  125. def __init__(self, file, indentLevel=0, indent="\t"):
  126. self.file = file
  127. self.stack = []
  128. self.indentLevel = indentLevel
  129. self.indent = indent
  130. def beginElement(self, element):
  131. self.stack.append(element)
  132. self.writeln("<%s>" % element)
  133. self.indentLevel += 1
  134. def endElement(self, element):
  135. assert self.indentLevel > 0
  136. assert self.stack.pop() == element
  137. self.indentLevel -= 1
  138. self.writeln("</%s>" % element)
  139. def simpleElement(self, element, value=None):
  140. if value is not None:
  141. value = _escapeAndEncode(value)
  142. self.writeln("<%s>%s</%s>" % (element, value, element))
  143. else:
  144. self.writeln("<%s/>" % element)
  145. def writeln(self, line):
  146. if line:
  147. self.file.write(self.indentLevel * self.indent + line + "\n")
  148. else:
  149. self.file.write("\n")
  150. # Contents should conform to a subset of ISO 8601
  151. # (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'. Smaller units may be omitted with
  152. # a loss of precision)
  153. _dateParser = re.compile(r"(?P<year>\d\d\d\d)(?:-(?P<month>\d\d)(?:-(?P<day>\d\d)(?:T(?P<hour>\d\d)(?::(?P<minute>\d\d)(?::(?P<second>\d\d))?)?)?)?)?Z")
  154. def _dateFromString(s):
  155. order = ('year', 'month', 'day', 'hour', 'minute', 'second')
  156. gd = _dateParser.match(s).groupdict()
  157. lst = []
  158. for key in order:
  159. val = gd[key]
  160. if val is None:
  161. break
  162. lst.append(int(val))
  163. return datetime.datetime(*lst)
  164. def _dateToString(d):
  165. return '%04d-%02d-%02dT%02d:%02d:%02dZ' % (
  166. d.year, d.month, d.day,
  167. d.hour, d.minute, d.second
  168. )
  169. # Regex to find any control chars, except for \t \n and \r
  170. _controlCharPat = re.compile(
  171. r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f"
  172. r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]")
  173. def _escapeAndEncode(text):
  174. m = _controlCharPat.search(text)
  175. if m is not None:
  176. raise ValueError("strings can't contains control characters; "
  177. "use plistlib.Data instead")
  178. text = text.replace("\r\n", "\n") # convert DOS line endings
  179. text = text.replace("\r", "\n") # convert Mac line endings
  180. text = text.replace("&", "&amp;") # escape '&'
  181. text = text.replace("<", "&lt;") # escape '<'
  182. text = text.replace(">", "&gt;") # escape '>'
  183. return text.encode("utf-8") # encode as UTF-8
  184. PLISTHEADER = """\
  185. <?xml version="1.0" encoding="UTF-8"?>
  186. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  187. """
  188. class PlistWriter(DumbXMLWriter):
  189. def __init__(self, file, indentLevel=0, indent="\t", writeHeader=1):
  190. if writeHeader:
  191. file.write(PLISTHEADER)
  192. DumbXMLWriter.__init__(self, file, indentLevel, indent)
  193. def writeValue(self, value):
  194. if isinstance(value, (str, unicode)):
  195. self.simpleElement("string", value)
  196. elif isinstance(value, bool):
  197. # must switch for bool before int, as bool is a
  198. # subclass of int...
  199. if value:
  200. self.simpleElement("true")
  201. else:
  202. self.simpleElement("false")
  203. elif isinstance(value, (int, long)):
  204. self.simpleElement("integer", "%d" % value)
  205. elif isinstance(value, float):
  206. self.simpleElement("real", repr(value))
  207. elif isinstance(value, dict):
  208. self.writeDict(value)
  209. elif isinstance(value, Data):
  210. self.writeData(value)
  211. elif isinstance(value, datetime.datetime):
  212. self.simpleElement("date", _dateToString(value))
  213. elif isinstance(value, (tuple, list)):
  214. self.writeArray(value)
  215. else:
  216. raise TypeError("unsuported type: %s" % type(value))
  217. def writeData(self, data):
  218. self.beginElement("data")
  219. self.indentLevel -= 1
  220. maxlinelength = 76 - len(self.indent.replace("\t", " " * 8) *
  221. self.indentLevel)
  222. for line in data.asBase64(maxlinelength).split("\n"):
  223. if line:
  224. self.writeln(line)
  225. self.indentLevel += 1
  226. self.endElement("data")
  227. def writeDict(self, d):
  228. self.beginElement("dict")
  229. items = d.items()
  230. items.sort()
  231. for key, value in items:
  232. if not isinstance(key, (str, unicode)):
  233. raise TypeError("keys must be strings")
  234. self.simpleElement("key", key)
  235. self.writeValue(value)
  236. self.endElement("dict")
  237. def writeArray(self, array):
  238. self.beginElement("array")
  239. for value in array:
  240. self.writeValue(value)
  241. self.endElement("array")
  242. class _InternalDict(dict):
  243. # This class is needed while Dict is scheduled for deprecation:
  244. # we only need to warn when a *user* instantiates Dict or when
  245. # the "attribute notation for dict keys" is used.
  246. def __getattr__(self, attr):
  247. try:
  248. value = self[attr]
  249. except KeyError:
  250. raise AttributeError, attr
  251. from warnings import warn
  252. warn("Attribute access from plist dicts is deprecated, use d[key] "
  253. "notation instead", PendingDeprecationWarning, 2)
  254. return value
  255. def __setattr__(self, attr, value):
  256. from warnings import warn
  257. warn("Attribute access from plist dicts is deprecated, use d[key] "
  258. "notation instead", PendingDeprecationWarning, 2)
  259. self[attr] = value
  260. def __delattr__(self, attr):
  261. try:
  262. del self[attr]
  263. except KeyError:
  264. raise AttributeError, attr
  265. from warnings import warn
  266. warn("Attribute access from plist dicts is deprecated, use d[key] "
  267. "notation instead", PendingDeprecationWarning, 2)
  268. class Dict(_InternalDict):
  269. def __init__(self, **kwargs):
  270. from warnings import warn
  271. warn("The plistlib.Dict class is deprecated, use builtin dict instead",
  272. PendingDeprecationWarning, 2)
  273. super(Dict, self).__init__(**kwargs)
  274. class Plist(_InternalDict):
  275. """This class has been deprecated. Use readPlist() and writePlist()
  276. functions instead, together with regular dict objects.
  277. """
  278. def __init__(self, **kwargs):
  279. from warnings import warn
  280. warn("The Plist class is deprecated, use the readPlist() and "
  281. "writePlist() functions instead", PendingDeprecationWarning, 2)
  282. super(Plist, self).__init__(**kwargs)
  283. def fromFile(cls, pathOrFile):
  284. """Deprecated. Use the readPlist() function instead."""
  285. rootObject = readPlist(pathOrFile)
  286. plist = cls()
  287. plist.update(rootObject)
  288. return plist
  289. fromFile = classmethod(fromFile)
  290. def write(self, pathOrFile):
  291. """Deprecated. Use the writePlist() function instead."""
  292. writePlist(self, pathOrFile)
  293. def _encodeBase64(s, maxlinelength=76):
  294. # copied from base64.encodestring(), with added maxlinelength argument
  295. maxbinsize = (maxlinelength//4)*3
  296. pieces = []
  297. for i in range(0, len(s), maxbinsize):
  298. chunk = s[i : i + maxbinsize]
  299. pieces.append(binascii.b2a_base64(chunk))
  300. return "".join(pieces)
  301. class Data:
  302. """Wrapper for binary data."""
  303. def __init__(self, data):
  304. self.data = data
  305. def fromBase64(cls, data):
  306. # base64.decodestring just calls binascii.a2b_base64;
  307. # it seems overkill to use both base64 and binascii.
  308. return cls(binascii.a2b_base64(data))
  309. fromBase64 = classmethod(fromBase64)
  310. def asBase64(self, maxlinelength=76):
  311. return _encodeBase64(self.data, maxlinelength)
  312. def __cmp__(self, other):
  313. if isinstance(other, self.__class__):
  314. return cmp(self.data, other.data)
  315. elif isinstance(other, str):
  316. return cmp(self.data, other)
  317. else:
  318. return cmp(id(self), id(other))
  319. def __repr__(self):
  320. return "%s(%s)" % (self.__class__.__name__, repr(self.data))
  321. class PlistParser:
  322. def __init__(self):
  323. self.stack = []
  324. self.currentKey = None
  325. self.root = None
  326. def parse(self, fileobj):
  327. from xml.parsers.expat import ParserCreate
  328. parser = ParserCreate()
  329. parser.StartElementHandler = self.handleBeginElement
  330. parser.EndElementHandler = self.handleEndElement
  331. parser.CharacterDataHandler = self.handleData
  332. parser.ParseFile(fileobj)
  333. return self.root
  334. def handleBeginElement(self, element, attrs):
  335. self.data = []
  336. handler = getattr(self, "begin_" + element, None)
  337. if handler is not None:
  338. handler(attrs)
  339. def handleEndElement(self, element):
  340. handler = getattr(self, "end_" + element, None)
  341. if handler is not None:
  342. handler()
  343. def handleData(self, data):
  344. self.data.append(data)
  345. def addObject(self, value):
  346. if self.currentKey is not None:
  347. self.stack[-1][self.currentKey] = value
  348. self.currentKey = None
  349. elif not self.stack:
  350. # this is the root object
  351. self.root = value
  352. else:
  353. self.stack[-1].append(value)
  354. def getData(self):
  355. data = "".join(self.data)
  356. try:
  357. data = data.encode("ascii")
  358. except UnicodeError:
  359. pass
  360. self.data = []
  361. return data
  362. # element handlers
  363. def begin_dict(self, attrs):
  364. d = _InternalDict()
  365. self.addObject(d)
  366. self.stack.append(d)
  367. def end_dict(self):
  368. self.stack.pop()
  369. def end_key(self):
  370. self.currentKey = self.getData()
  371. def begin_array(self, attrs):
  372. a = []
  373. self.addObject(a)
  374. self.stack.append(a)
  375. def end_array(self):
  376. self.stack.pop()
  377. def end_true(self):
  378. self.addObject(True)
  379. def end_false(self):
  380. self.addObject(False)
  381. def end_integer(self):
  382. self.addObject(int(self.getData()))
  383. def end_real(self):
  384. self.addObject(float(self.getData()))
  385. def end_string(self):
  386. self.addObject(self.getData())
  387. def end_data(self):
  388. self.addObject(Data.fromBase64(self.getData()))
  389. def end_date(self):
  390. self.addObject(_dateFromString(self.getData()))