/lib-python/2.7/plat-mac/applesingle.py

https://bitbucket.org/dac_io/pypy · Python · 146 lines · 121 code · 10 blank · 15 comment · 22 complexity · e2e0fb9d35b82f22612c4bd7612a4596 MD5 · raw file

  1. r"""Routines to decode AppleSingle files
  2. """
  3. from warnings import warnpy3k
  4. warnpy3k("In 3.x, the applesingle module is removed.", stacklevel=2)
  5. import struct
  6. import sys
  7. try:
  8. import MacOS
  9. import Carbon.File
  10. except:
  11. class MacOS:
  12. def openrf(path, mode):
  13. return open(path + '.rsrc', mode)
  14. openrf = classmethod(openrf)
  15. class Carbon:
  16. class File:
  17. class FSSpec:
  18. pass
  19. class FSRef:
  20. pass
  21. class Alias:
  22. pass
  23. # all of the errors in this module are really errors in the input
  24. # so I think it should test positive against ValueError.
  25. class Error(ValueError):
  26. pass
  27. # File header format: magic, version, unused, number of entries
  28. AS_HEADER_FORMAT=">LL16sh"
  29. AS_HEADER_LENGTH=26
  30. # The flag words for AppleSingle
  31. AS_MAGIC=0x00051600
  32. AS_VERSION=0x00020000
  33. # Entry header format: id, offset, length
  34. AS_ENTRY_FORMAT=">lll"
  35. AS_ENTRY_LENGTH=12
  36. # The id values
  37. AS_DATAFORK=1
  38. AS_RESOURCEFORK=2
  39. AS_IGNORE=(3,4,5,6,8,9,10,11,12,13,14,15)
  40. class AppleSingle(object):
  41. datafork = None
  42. resourcefork = None
  43. def __init__(self, fileobj, verbose=False):
  44. header = fileobj.read(AS_HEADER_LENGTH)
  45. try:
  46. magic, version, ig, nentry = struct.unpack(AS_HEADER_FORMAT, header)
  47. except ValueError, arg:
  48. raise Error, "Unpack header error: %s" % (arg,)
  49. if verbose:
  50. print 'Magic: 0x%8.8x' % (magic,)
  51. print 'Version: 0x%8.8x' % (version,)
  52. print 'Entries: %d' % (nentry,)
  53. if magic != AS_MAGIC:
  54. raise Error, "Unknown AppleSingle magic number 0x%8.8x" % (magic,)
  55. if version != AS_VERSION:
  56. raise Error, "Unknown AppleSingle version number 0x%8.8x" % (version,)
  57. if nentry <= 0:
  58. raise Error, "AppleSingle file contains no forks"
  59. headers = [fileobj.read(AS_ENTRY_LENGTH) for i in xrange(nentry)]
  60. self.forks = []
  61. for hdr in headers:
  62. try:
  63. restype, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr)
  64. except ValueError, arg:
  65. raise Error, "Unpack entry error: %s" % (arg,)
  66. if verbose:
  67. print "Fork %d, offset %d, length %d" % (restype, offset, length)
  68. fileobj.seek(offset)
  69. data = fileobj.read(length)
  70. if len(data) != length:
  71. raise Error, "Short read: expected %d bytes got %d" % (length, len(data))
  72. self.forks.append((restype, data))
  73. if restype == AS_DATAFORK:
  74. self.datafork = data
  75. elif restype == AS_RESOURCEFORK:
  76. self.resourcefork = data
  77. def tofile(self, path, resonly=False):
  78. outfile = open(path, 'wb')
  79. data = False
  80. if resonly:
  81. if self.resourcefork is None:
  82. raise Error, "No resource fork found"
  83. fp = open(path, 'wb')
  84. fp.write(self.resourcefork)
  85. fp.close()
  86. elif (self.resourcefork is None and self.datafork is None):
  87. raise Error, "No useful forks found"
  88. else:
  89. if self.datafork is not None:
  90. fp = open(path, 'wb')
  91. fp.write(self.datafork)
  92. fp.close()
  93. if self.resourcefork is not None:
  94. fp = MacOS.openrf(path, '*wb')
  95. fp.write(self.resourcefork)
  96. fp.close()
  97. def decode(infile, outpath, resonly=False, verbose=False):
  98. """decode(infile, outpath [, resonly=False, verbose=False])
  99. Creates a decoded file from an AppleSingle encoded file.
  100. If resonly is True, then it will create a regular file at
  101. outpath containing only the resource fork from infile.
  102. Otherwise it will create an AppleDouble file at outpath
  103. with the data and resource forks from infile. On platforms
  104. without the MacOS module, it will create inpath and inpath+'.rsrc'
  105. with the data and resource forks respectively.
  106. """
  107. if not hasattr(infile, 'read'):
  108. if isinstance(infile, Carbon.File.Alias):
  109. infile = infile.ResolveAlias()[0]
  110. if hasattr(Carbon.File, "FSSpec"):
  111. if isinstance(infile, (Carbon.File.FSSpec, Carbon.File.FSRef)):
  112. infile = infile.as_pathname()
  113. else:
  114. if isinstance(infile, Carbon.File.FSRef):
  115. infile = infile.as_pathname()
  116. infile = open(infile, 'rb')
  117. asfile = AppleSingle(infile, verbose=verbose)
  118. asfile.tofile(outpath, resonly=resonly)
  119. def _test():
  120. if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4:
  121. print 'Usage: applesingle.py [-r] applesinglefile decodedfile'
  122. sys.exit(1)
  123. if sys.argv[1] == '-r':
  124. resonly = True
  125. del sys.argv[1]
  126. else:
  127. resonly = False
  128. decode(sys.argv[1], sys.argv[2], resonly=resonly)
  129. if __name__ == '__main__':
  130. _test()