You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

723 lines
25 KiB

  1. # Copyright (c) 2011, SmartFile <btimby@smartfile.com>
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are met:
  6. # * Redistributions of source code must retain the above copyright
  7. # notice, this list of conditions and the following disclaimer.
  8. # * Redistributions in binary form must reproduce the above copyright
  9. # notice, this list of conditions and the following disclaimer in the
  10. # documentation and/or other materials provided with the distribution.
  11. # * Neither the name of the organization nor the
  12. # names of its contributors may be used to endorse or promote products
  13. # derived from this software without specific prior written permission.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
  19. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. import os
  26. import stat
  27. import sys
  28. import time
  29. import warnings
  30. from libarchive import _libarchive
  31. from io import StringIO
  32. PY3 = sys.version_info[0] >= 3
  33. # Suggested block size for libarchive. Libarchive may adjust it.
  34. BLOCK_SIZE = 10240
  35. MTIME_FORMAT = ''
  36. # Default encoding scheme.
  37. ENCODING = 'utf-8'
  38. # Functions to initialize read/write for various libarchive supported formats and filters.
  39. FORMATS = {
  40. None: (_libarchive.archive_read_support_format_all, None),
  41. 'tar': (_libarchive.archive_read_support_format_tar, _libarchive.archive_write_set_format_ustar),
  42. 'pax': (_libarchive.archive_read_support_format_tar, _libarchive.archive_write_set_format_pax),
  43. 'gnu': (_libarchive.archive_read_support_format_gnutar, _libarchive.archive_write_set_format_gnutar),
  44. 'zip': (_libarchive.archive_read_support_format_zip, _libarchive.archive_write_set_format_zip),
  45. 'rar': (_libarchive.archive_read_support_format_rar, None),
  46. '7zip': (_libarchive.archive_read_support_format_7zip, None),
  47. 'ar': (_libarchive.archive_read_support_format_ar, None),
  48. 'cab': (_libarchive.archive_read_support_format_cab, None),
  49. 'cpio': (_libarchive.archive_read_support_format_cpio, _libarchive.archive_write_set_format_cpio_newc),
  50. 'iso': (_libarchive.archive_read_support_format_iso9660, _libarchive.archive_write_set_format_iso9660),
  51. 'lha': (_libarchive.archive_read_support_format_lha, None),
  52. 'xar': (_libarchive.archive_read_support_format_xar, _libarchive.archive_write_set_format_xar),
  53. }
  54. FILTERS = {
  55. None: (_libarchive.archive_read_support_filter_all, _libarchive.archive_write_add_filter_none),
  56. 'gz': (_libarchive.archive_read_support_filter_gzip, _libarchive.archive_write_add_filter_gzip),
  57. 'bz2': (_libarchive.archive_read_support_filter_bzip2, _libarchive.archive_write_add_filter_bzip2),
  58. }
  59. # Map file extensions to formats and filters. To support quick detection.
  60. FORMAT_EXTENSIONS = {
  61. '.tar': 'tar',
  62. '.zip': 'zip',
  63. '.rar': 'rar',
  64. '.7z': '7zip',
  65. '.ar': 'ar',
  66. '.cab': 'cab',
  67. '.rpm': 'cpio',
  68. '.cpio': 'cpio',
  69. '.iso': 'iso',
  70. '.lha': 'lha',
  71. '.xar': 'xar',
  72. }
  73. FILTER_EXTENSIONS = {
  74. '.gz': 'gz',
  75. '.bz2': 'bz2',
  76. }
  77. class EOF(Exception):
  78. '''Raised by ArchiveInfo.from_archive() when unable to read the next
  79. archive header.'''
  80. pass
  81. def version():
  82. '''Returns the version of the libarchive library.'''
  83. return _libarchive.archive_version_string().split()[1]
  84. def get_error(archive):
  85. '''Retrieves the last error description for the given archive instance.'''
  86. return _libarchive.archive_error_string(archive)
  87. def call_and_check(func, archive, *args):
  88. '''Executes a libarchive function and raises an exception when appropriate.'''
  89. ret = func(*args)
  90. if ret == _libarchive.ARCHIVE_OK:
  91. return
  92. elif ret == _libarchive.ARCHIVE_WARN:
  93. warnings.warn('Warning executing function: %s.' % get_error(archive), RuntimeWarning)
  94. elif ret == _libarchive.ARCHIVE_EOF:
  95. raise EOF()
  96. else:
  97. raise Exception('Problem executing function, message is: %s.' % get_error(archive))
  98. def get_func(name, items, index):
  99. item = items.get(name, None)
  100. if item is None:
  101. return None
  102. return item[index]
  103. def guess_format(filename):
  104. if isinstance(filename, int):
  105. filename = ext = ''
  106. else:
  107. filename, ext = os.path.splitext(filename)
  108. filter = FILTER_EXTENSIONS.get(ext)
  109. if filter:
  110. filename, ext = os.path.splitext(filename)
  111. format = FORMAT_EXTENSIONS.get(ext)
  112. return format, filter
  113. def is_archive_name(filename, formats=None):
  114. '''Quick check to see if the given file has an extension indiciating that it is
  115. an archive. The format parameter can be used to limit what archive format is acceptable.
  116. If omitted, all supported archive formats will be checked.
  117. This function will return the name of the most likely archive format, None if the file is
  118. unlikely to be an archive.'''
  119. if formats is None:
  120. formats = list(FORMAT_EXTENSIONS.values())
  121. format, filter = guess_format(filename)
  122. if format in formats:
  123. return format
  124. def is_archive(f, formats=(None,), filters=(None,)):
  125. '''Check to see if the given file is actually an archive. The format parameter
  126. can be used to specify which archive format is acceptable. If ommitted, all supported
  127. archive formats will be checked. It opens the file using libarchive. If no error is
  128. received, the file was successfully detected by the libarchive bidding process.
  129. This procedure is quite costly, so you should avoid calling it unless you are reasonably
  130. sure that the given file is an archive. In other words, you may wish to filter large
  131. numbers of file names using is_archive_name() before double-checking the positives with
  132. this function.
  133. This function will return True if the file can be opened as an archive using the given
  134. format(s)/filter(s).'''
  135. need_close = False
  136. if isinstance(f, str):
  137. f = open(f, 'rb')
  138. need_close = True
  139. a = _libarchive.archive_read_new()
  140. for format in formats:
  141. format = get_func(format, FORMATS, 0)
  142. if format is None:
  143. return False
  144. format(a)
  145. for filter in filters:
  146. filter = get_func(filter, FILTERS, 0)
  147. if filter is None:
  148. return False
  149. filter(a)
  150. try:
  151. try:
  152. call_and_check(_libarchive.archive_read_open_fd, a, a, f.fileno(), BLOCK_SIZE)
  153. return True
  154. except:
  155. return False
  156. finally:
  157. _libarchive.archive_read_close(a)
  158. _libarchive.archive_read_free(a)
  159. if need_close:
  160. f.close()
  161. class EntryReadStream(object):
  162. '''A file-like object for reading an entry from the archive.'''
  163. def __init__(self, archive, size):
  164. self.archive = archive
  165. self.closed = False
  166. self.size = size
  167. self.bytes = 0
  168. def __enter__(self):
  169. return self
  170. def __exit__(self, *args):
  171. return
  172. def __iter__(self):
  173. if self.closed:
  174. return
  175. while True:
  176. data = self.read(BLOCK_SIZE)
  177. if not data:
  178. break
  179. yield data
  180. def __len__(self):
  181. return self.size
  182. def tell(self):
  183. return self.bytes
  184. def read(self, bytes=-1):
  185. if self.closed:
  186. return
  187. if self.bytes == self.size:
  188. # EOF already reached.
  189. return
  190. if bytes < 0:
  191. bytes = self.size - self.bytes
  192. elif self.bytes + bytes > self.size:
  193. # Limit read to remaining bytes
  194. bytes = self.size - self.bytes
  195. # Read requested bytes
  196. data = _libarchive.archive_read_data_into_str(self.archive._a, bytes)
  197. self.bytes += len(data)
  198. return data
  199. def close(self):
  200. if self.closed:
  201. return
  202. # Call archive.close() with _defer True to let it know we have been
  203. # closed and it is now safe to actually close.
  204. self.archive.close(_defer=True)
  205. self.archive = None
  206. self.closed = True
  207. class EntryWriteStream(object):
  208. '''A file-like object for writing an entry to an archive.
  209. If the size is known ahead of time and provided, then the file contents
  210. are not buffered but flushed directly to the archive. If size is omitted,
  211. then the file contents are buffered and flushed in the close() method.'''
  212. def __init__(self, archive, pathname, size=None):
  213. self.archive = archive
  214. self.entry = Entry(pathname=pathname, mtime=time.time(), mode=stat.S_IFREG)
  215. if size is None:
  216. self.buffer = StringIO()
  217. else:
  218. self.buffer = None
  219. self.entry.size = size
  220. self.entry.to_archive(self.archive)
  221. self.bytes = 0
  222. self.closed = False
  223. def __enter__(self):
  224. return self
  225. def __exit__(self, *args):
  226. self.close()
  227. def __del__(self):
  228. self.close()
  229. def __len__(self):
  230. return self.bytes
  231. def tell(self):
  232. return self.bytes
  233. def write(self, data):
  234. if self.closed:
  235. raise Exception('Cannot write to closed stream.')
  236. if self.buffer:
  237. if PY3:
  238. self.buffer.write(data)
  239. else:
  240. self.buffer.write(unicode(data, ENCODING))
  241. else:
  242. _libarchive.archive_write_data_from_str(self.archive._a, data.encode(ENCODING))
  243. self.bytes += len(data)
  244. def close(self):
  245. if self.closed:
  246. return
  247. if self.buffer:
  248. self.entry.size = self.buffer.tell()
  249. self.entry.to_archive(self.archive)
  250. _libarchive.archive_write_data_from_str(self.archive._a, self.buffer.getvalue().encode(ENCODING))
  251. _libarchive.archive_write_finish_entry(self.archive._a)
  252. # Call archive.close() with _defer True to let it know we have been
  253. # closed and it is now safe to actually close.
  254. self.archive.close(_defer=True)
  255. self.archive = None
  256. self.closed = True
  257. class Entry(object):
  258. '''An entry within an archive. Represents the header data and it's location within the archive.'''
  259. def __init__(self, pathname=None, size=None, mtime=None, mode=None, hpos=None, encoding=ENCODING):
  260. # , symlink=None
  261. self.pathname = pathname
  262. self.size = size
  263. self.mtime = mtime
  264. self.mode = mode
  265. self.hpos = hpos
  266. self.encoding = encoding
  267. self.symlink = ""
  268. @property
  269. def header_position(self):
  270. return self.hpos
  271. @classmethod
  272. def from_archive(cls, archive, encoding=ENCODING):
  273. '''Instantiates an Entry class and sets all the properties from an archive header.'''
  274. e = _libarchive.archive_entry_new()
  275. try:
  276. call_and_check(_libarchive.archive_read_next_header2, archive._a, archive._a, e)
  277. mode = _libarchive.archive_entry_filetype(e)
  278. mode |= _libarchive.archive_entry_perm(e)
  279. if PY3:
  280. pathname = _libarchive.archive_entry_pathname(e)
  281. else:
  282. pathname = _libarchive.archive_entry_pathname(e).decode(encoding)
  283. entry = cls(
  284. pathname=pathname,
  285. size=_libarchive.archive_entry_size(e),
  286. mtime=_libarchive.archive_entry_mtime(e),
  287. mode=mode,
  288. hpos=archive.header_position,
  289. )
  290. if entry.issym():
  291. symLinkPath = _libarchive.archive_entry_symlink(e)
  292. entry.symlink = symLinkPath
  293. finally:
  294. _libarchive.archive_entry_free(e)
  295. return entry
  296. @classmethod
  297. def from_file(cls, f, entry=None, encoding=ENCODING):
  298. '''Instantiates an Entry class and sets all the properties from a file on the file system.
  299. f can be a file-like object or a path.'''
  300. if entry is None:
  301. entry = cls(encoding=encoding)
  302. if entry.pathname is None:
  303. if isinstance(f, str):
  304. st = os.stat(f)
  305. entry.pathname = f
  306. entry.size = st.st_size
  307. entry.mtime = st.st_mtime
  308. entry.mode = st.st_mode
  309. elif hasattr(f, 'fileno'):
  310. st = os.fstat(f.fileno())
  311. entry.pathname = getattr(f, 'name', None)
  312. entry.size = st.st_size
  313. entry.mtime = st.st_mtime
  314. entry.mode = st.st_mode
  315. else:
  316. entry.pathname = getattr(f, 'pathname', None)
  317. entry.size = getattr(f, 'size', 0)
  318. entry.mtime = getattr(f, 'mtime', time.time())
  319. entry.mode = stat.S_IFREG
  320. return entry
  321. def to_archive(self, archive):
  322. '''Creates an archive header and writes it to the given archive.'''
  323. e = _libarchive.archive_entry_new()
  324. try:
  325. if PY3:
  326. _libarchive.archive_entry_set_pathname(e, self.pathname)
  327. else:
  328. _libarchive.archive_entry_set_pathname(e, self.pathname.encode(self.encoding))
  329. _libarchive.archive_entry_set_filetype(e, stat.S_IFMT(self.mode))
  330. _libarchive.archive_entry_set_perm(e, stat.S_IMODE(self.mode))
  331. _libarchive.archive_entry_set_size(e, self.size)
  332. _libarchive.archive_entry_set_mtime(e, self.mtime, 0)
  333. if stat.S_ISLNK(self.mode):
  334. _libarchive.archive_entry_set_symlink(e, self.symlink)
  335. call_and_check(_libarchive.archive_write_header, archive._a, archive._a, e)
  336. finally:
  337. _libarchive.archive_entry_free(e)
  338. def isdir(self):
  339. return stat.S_ISDIR(self.mode)
  340. def isfile(self):
  341. return stat.S_ISREG(self.mode)
  342. def issym(self):
  343. return stat.S_ISLNK(self.mode)
  344. def isfifo(self):
  345. return stat.S_ISFIFO(self.mode)
  346. def ischr(self):
  347. return stat.S_ISCHR(self.mode)
  348. def isblk(self):
  349. return stat.S_ISBLK(self.mode)
  350. class Archive(object):
  351. '''A low-level archive reader which provides forward-only iteration. Consider
  352. this a light-weight pythonic libarchive wrapper.'''
  353. def __init__(
  354. self,
  355. f,
  356. mode='r',
  357. format=None,
  358. filter=None,
  359. entry_class=Entry,
  360. encoding=ENCODING,
  361. blocksize=BLOCK_SIZE,
  362. password=None,
  363. ):
  364. assert mode in ('r', 'w', 'wb', 'a'), 'Mode should be "r", "w", "wb", or "a".'
  365. self._stream = None
  366. self.encoding = encoding
  367. self.blocksize = blocksize
  368. self.password = password
  369. if isinstance(f, str):
  370. self.filename = f
  371. f = open(f, mode)
  372. # Only close it if we opened it...
  373. self._defer_close = True
  374. elif hasattr(f, 'fileno'):
  375. self.filename = getattr(f, 'name', None)
  376. # Leave the fd alone, caller should manage it...
  377. self._defer_close = False
  378. else:
  379. raise Exception('Provided file is not path or open file.')
  380. self.f = f
  381. self.mode = mode
  382. # Guess the format/filter from file name (if not provided)
  383. if self.filename:
  384. if format is None:
  385. format = guess_format(self.filename)[0]
  386. if filter is None:
  387. filter = guess_format(self.filename)[1]
  388. self.format = format
  389. self.filter = filter
  390. # The class to use for entries.
  391. self.entry_class = entry_class
  392. # Select filter/format functions.
  393. if self.mode == 'r':
  394. self.format_func = get_func(self.format, FORMATS, 0)
  395. if self.format_func is None:
  396. raise Exception('Unsupported format %s' % format)
  397. self.filter_func = get_func(self.filter, FILTERS, 0)
  398. if self.filter_func is None:
  399. raise Exception('Unsupported filter %s' % filter)
  400. else:
  401. # TODO: how to support appending?
  402. if self.format is None:
  403. raise Exception('You must specify a format for writing.')
  404. self.format_func = get_func(self.format, FORMATS, 1)
  405. if self.format_func is None:
  406. raise Exception('Unsupported format %s' % format)
  407. self.filter_func = get_func(self.filter, FILTERS, 1)
  408. if self.filter_func is None:
  409. raise Exception('Unsupported filter %s' % filter)
  410. # Open the archive, apply filter/format functions.
  411. self.init()
  412. def __iter__(self):
  413. while True:
  414. try:
  415. yield self.entry_class.from_archive(self, encoding=self.encoding)
  416. except EOF:
  417. break
  418. def __enter__(self):
  419. return self
  420. def __exit__(self, type, value, traceback):
  421. self.denit()
  422. def __del__(self):
  423. self.close()
  424. def init(self):
  425. if self.mode == 'r':
  426. self._a = _libarchive.archive_read_new()
  427. else:
  428. self._a = _libarchive.archive_write_new()
  429. self.format_func(self._a)
  430. self.filter_func(self._a)
  431. if self.mode == 'r':
  432. if self.password:
  433. self.add_passphrase(self.password)
  434. call_and_check(_libarchive.archive_read_open_fd, self._a, self._a, self.f.fileno(), self.blocksize)
  435. else:
  436. if self.password:
  437. self.set_passphrase(self.password)
  438. call_and_check(_libarchive.archive_write_open_fd, self._a, self._a, self.f.fileno())
  439. def denit(self):
  440. '''Closes and deallocates the archive reader/writer.'''
  441. if getattr(self, '_a', None) is None:
  442. return
  443. try:
  444. if self.mode == 'r':
  445. _libarchive.archive_read_close(self._a)
  446. _libarchive.archive_read_free(self._a)
  447. elif self.mode == 'w':
  448. _libarchive.archive_write_close(self._a)
  449. _libarchive.archive_write_free(self._a)
  450. finally:
  451. # We only want one try at this...
  452. self._a = None
  453. def close(self, _defer=False):
  454. # _defer == True is how a stream can notify Archive that the stream is
  455. # now closed. Calling it directly in not recommended.
  456. if _defer:
  457. # This call came from our open stream.
  458. self._stream = None
  459. if not self._defer_close:
  460. # We are not yet ready to close.
  461. return
  462. if self._stream is not None:
  463. # We have a stream open! don't close, but remember we were asked to.
  464. self._defer_close = True
  465. return
  466. self.denit()
  467. # If there is a file attached...
  468. if hasattr(self, 'f'):
  469. # Make sure it is not already closed...
  470. if getattr(self.f, 'closed', False):
  471. return
  472. # Flush it if not read-only...
  473. if hasattr(self.f, "mode") and self.f.mode != 'r' and self.f.mode != 'rb':
  474. if hasattr(self.f, "flush"):
  475. self.f.flush()
  476. if hasattr(self.f, "fileno"):
  477. os.fsync(self.f.fileno())
  478. # and then close it, if we opened it...
  479. if getattr(self, '_close', None):
  480. self.f.close()
  481. @property
  482. def header_position(self):
  483. '''The position within the file.'''
  484. return _libarchive.archive_read_header_position(self._a)
  485. def iterpaths(self):
  486. for entry in self:
  487. yield entry.pathname
  488. def read(self, size):
  489. '''Read current archive entry contents into string.'''
  490. return _libarchive.archive_read_data_into_str(self._a, size)
  491. def readpath(self, f):
  492. '''Write current archive entry contents to file. f can be a file-like object or
  493. a path.'''
  494. if isinstance(f, str):
  495. basedir = os.path.dirname(f)
  496. if not os.path.exists(basedir):
  497. os.makedirs(basedir)
  498. f = open(f, 'w')
  499. return _libarchive.archive_read_data_into_fd(self._a, f.fileno())
  500. def readstream(self, size):
  501. '''Returns a file-like object for reading current archive entry contents.'''
  502. self._stream = EntryReadStream(self, size)
  503. return self._stream
  504. def write(self, member, data=None):
  505. '''Writes a string buffer to the archive as the given entry.'''
  506. if isinstance(member, str):
  507. member = self.entry_class(pathname=member, encoding=self.encoding)
  508. if data:
  509. member.size = len(data)
  510. member.to_archive(self)
  511. if data:
  512. if PY3:
  513. if isinstance(data, bytes):
  514. result = _libarchive.archive_write_data_from_str(self._a, data)
  515. else:
  516. result = _libarchive.archive_write_data_from_str(self._a, data.encode(self.encoding))
  517. else:
  518. result = _libarchive.archive_write_data_from_str(self._a, data)
  519. _libarchive.archive_write_finish_entry(self._a)
  520. def writepath(self, f, pathname=None, folder=False):
  521. '''Writes a file to the archive. f can be a file-like object or a path. Uses
  522. write() to do the actual writing.'''
  523. member = self.entry_class.from_file(f, encoding=self.encoding)
  524. if isinstance(f, str):
  525. if os.path.isfile(f):
  526. f = open(f, 'r')
  527. if pathname:
  528. member.pathname = pathname
  529. if folder and not member.isdir():
  530. member.mode = stat.S_IFDIR
  531. if hasattr(f, 'read'):
  532. # TODO: optimize this to write directly from f to archive.
  533. self.write(member, data=f.read())
  534. else:
  535. self.write(member)
  536. def writestream(self, pathname, size=None):
  537. '''Returns a file-like object for writing a new entry.'''
  538. self._stream = EntryWriteStream(self, pathname, size)
  539. return self._stream
  540. def printlist(self, s=sys.stdout):
  541. for entry in self:
  542. s.write(entry.size)
  543. s.write('\t')
  544. s.write(entry.mtime.strftime(MTIME_FORMAT))
  545. s.write('\t')
  546. s.write(entry.pathname)
  547. s.flush()
  548. def add_passphrase(self, password):
  549. '''Adds a password to the archive.'''
  550. _libarchive.archive_read_add_passphrase(self._a, password)
  551. def set_passphrase(self, password):
  552. '''Sets a password for the archive.'''
  553. _libarchive.archive_write_set_passphrase(self._a, password)
  554. class SeekableArchive(Archive):
  555. '''A class that provides random-access to archive entries. It does this by using one
  556. or many Archive instances to seek to the correct location. The best performance will
  557. occur when reading archive entries in the order in which they appear in the archive.
  558. Reading out of order will cause the archive to be closed and opened each time a
  559. reverse seek is needed.'''
  560. def __init__(self, f, **kwargs):
  561. self._stream = None
  562. # Convert file to open file. We need this to reopen the archive.
  563. mode = kwargs.setdefault('mode', 'r')
  564. if isinstance(f, str):
  565. f = open(f, mode)
  566. super(SeekableArchive, self).__init__(f, **kwargs)
  567. self.entries = []
  568. self.eof = False
  569. def __iter__(self):
  570. for entry in self.entries:
  571. yield entry
  572. if not self.eof:
  573. try:
  574. for entry in super(SeekableArchive, self).__iter__():
  575. self.entries.append(entry)
  576. yield entry
  577. except StopIteration:
  578. self.eof = True
  579. def reopen(self):
  580. '''Seeks the underlying fd to 0 position, then opens the archive. If the archive
  581. is already open, this will effectively re-open it (rewind to the beginning).'''
  582. self.denit()
  583. self.f.seek(0)
  584. self.init()
  585. def getentry(self, pathname):
  586. '''Take a name or entry object and returns an entry object.'''
  587. for entry in self:
  588. if entry.pathname == pathname:
  589. return entry
  590. raise KeyError(pathname)
  591. def seek(self, entry):
  592. '''Seeks the archive to the requested entry. Will reopen if necessary.'''
  593. move = entry.header_position - self.header_position
  594. if move != 0:
  595. if move < 0:
  596. # can't move back, re-open archive:
  597. self.reopen()
  598. # move to proper position in stream
  599. for curr in super(SeekableArchive, self).__iter__():
  600. if curr.header_position == entry.header_position:
  601. break
  602. def read(self, member):
  603. '''Return the requested archive entry contents as a string.'''
  604. entry = self.getentry(member)
  605. self.seek(entry)
  606. return super(SeekableArchive, self).read(entry.size)
  607. def readpath(self, member, f):
  608. entry = self.getentry(member)
  609. self.seek(entry)
  610. return super(SeekableArchive, self).readpath(f)
  611. def readstream(self, member):
  612. '''Returns a file-like object for reading requested archive entry contents.'''
  613. entry = self.getentry(member)
  614. self.seek(entry)
  615. self._stream = EntryReadStream(self, entry.size)
  616. return self._stream