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.
 
 
 
 
 

728 lines
26 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. self.buffer.write(data)
  238. else:
  239. _libarchive.archive_write_data_from_str(self.archive._a, data.encode(ENCODING))
  240. self.bytes += len(data)
  241. def close(self):
  242. if self.closed:
  243. return
  244. if self.buffer:
  245. self.entry.size = self.buffer.tell()
  246. self.entry.to_archive(self.archive)
  247. _libarchive.archive_write_data_from_str(self.archive._a, self.buffer.getvalue().encode(ENCODING))
  248. _libarchive.archive_write_finish_entry(self.archive._a)
  249. # Call archive.close() with _defer True to let it know we have been
  250. # closed and it is now safe to actually close.
  251. self.archive.close(_defer=True)
  252. self.archive = None
  253. self.closed = True
  254. class Entry(object):
  255. '''An entry within an archive. Represents the header data and it's location within the archive.'''
  256. def __init__(self, pathname=None, size=None, mtime=None, mode=None, hpos=None, encoding=ENCODING):
  257. self.pathname = pathname
  258. self.size = size
  259. self.mtime = mtime
  260. self.mode = mode
  261. self.hpos = hpos
  262. self.encoding = encoding
  263. self.symlink = ""
  264. @property
  265. def header_position(self):
  266. return self.hpos
  267. @classmethod
  268. def from_archive(cls, archive, encoding=ENCODING):
  269. '''Instantiates an Entry class and sets all the properties from an archive header.'''
  270. e = _libarchive.archive_entry_new()
  271. try:
  272. call_and_check(_libarchive.archive_read_next_header2, archive._a, archive._a, e)
  273. mode = _libarchive.archive_entry_filetype(e)
  274. mode |= _libarchive.archive_entry_perm(e)
  275. if PY3:
  276. pathname = _libarchive.archive_entry_pathname(e)
  277. else:
  278. pathname = _libarchive.archive_entry_pathname(e).decode(encoding)
  279. entry = cls(
  280. pathname=pathname,
  281. size=_libarchive.archive_entry_size(e),
  282. mtime=_libarchive.archive_entry_mtime(e),
  283. mode=mode,
  284. hpos=archive.header_position,
  285. )
  286. if entry.issym():
  287. symLinkPath = _libarchive.archive_entry_symlink(e)
  288. entry.symlink = symLinkPath
  289. finally:
  290. _libarchive.archive_entry_free(e)
  291. return entry
  292. @classmethod
  293. def from_file(cls, f, entry=None, encoding=ENCODING):
  294. '''Instantiates an Entry class and sets all the properties from a file on the file system.
  295. f can be a file-like object or a path.'''
  296. if entry is None:
  297. entry = cls(encoding=encoding)
  298. if entry.pathname is None:
  299. if isinstance(f, str):
  300. st = os.stat(f)
  301. entry.pathname = f
  302. entry.size = st.st_size
  303. entry.mtime = st.st_mtime
  304. entry.mode = st.st_mode
  305. elif hasattr(f, 'fileno'):
  306. st = os.fstat(f.fileno())
  307. entry.pathname = getattr(f, 'name', None)
  308. entry.size = st.st_size
  309. entry.mtime = st.st_mtime
  310. entry.mode = st.st_mode
  311. else:
  312. entry.pathname = getattr(f, 'pathname', None)
  313. entry.size = getattr(f, 'size', 0)
  314. entry.mtime = getattr(f, 'mtime', time.time())
  315. entry.mode = stat.S_IFREG
  316. return entry
  317. def to_archive(self, archive):
  318. '''Creates an archive header and writes it to the given archive.'''
  319. e = _libarchive.archive_entry_new()
  320. try:
  321. if PY3:
  322. _libarchive.archive_entry_set_pathname(e, self.pathname)
  323. else:
  324. _libarchive.archive_entry_set_pathname(e, self.pathname.encode(self.encoding))
  325. _libarchive.archive_entry_set_filetype(e, stat.S_IFMT(self.mode))
  326. _libarchive.archive_entry_set_perm(e, stat.S_IMODE(self.mode))
  327. _libarchive.archive_entry_set_size(e, self.size)
  328. _libarchive.archive_entry_set_mtime(e, self.mtime, 0)
  329. if stat.S_ISLNK(self.mode):
  330. _libarchive.archive_entry_set_symlink(e, self.symlink)
  331. call_and_check(_libarchive.archive_write_header, archive._a, archive._a, e)
  332. finally:
  333. _libarchive.archive_entry_free(e)
  334. def isdir(self):
  335. return stat.S_ISDIR(self.mode)
  336. def isfile(self):
  337. return stat.S_ISREG(self.mode)
  338. def issym(self):
  339. return stat.S_ISLNK(self.mode)
  340. def isfifo(self):
  341. return stat.S_ISFIFO(self.mode)
  342. def ischr(self):
  343. return stat.S_ISCHR(self.mode)
  344. def isblk(self):
  345. return stat.S_ISBLK(self.mode)
  346. class Archive(object):
  347. '''A low-level archive reader which provides forward-only iteration. Consider
  348. this a light-weight pythonic libarchive wrapper.'''
  349. def __init__(
  350. self,
  351. f,
  352. mode='r',
  353. format=None,
  354. filter=None,
  355. entry_class=Entry,
  356. encoding=ENCODING,
  357. blocksize=BLOCK_SIZE,
  358. password=None,
  359. ):
  360. assert mode in ('r', 'w', 'wb', 'a'), 'Mode should be "r", "w", "wb", or "a".'
  361. self._stream = None
  362. self.encoding = encoding
  363. self.blocksize = blocksize
  364. self.password = password
  365. if isinstance(f, str):
  366. self.filename = f
  367. f = open(f, mode)
  368. # Only close it if we opened it...
  369. self._defer_close = True
  370. elif hasattr(f, 'fileno'):
  371. self.filename = getattr(f, 'name', None)
  372. # Leave the fd alone, caller should manage it...
  373. self._defer_close = False
  374. else:
  375. raise Exception('Provided file is not path or open file.')
  376. self.f = f
  377. self.mode = mode
  378. # Guess the format/filter from file name (if not provided)
  379. if self.filename:
  380. if format is None:
  381. format = guess_format(self.filename)[0]
  382. if filter is None:
  383. filter = guess_format(self.filename)[1]
  384. self.format = format
  385. self.filter = filter
  386. # The class to use for entries.
  387. self.entry_class = entry_class
  388. # Select filter/format functions.
  389. if self.mode == 'r':
  390. self.format_func = get_func(self.format, FORMATS, 0)
  391. if self.format_func is None:
  392. raise Exception('Unsupported format %s' % format)
  393. self.filter_func = get_func(self.filter, FILTERS, 0)
  394. if self.filter_func is None:
  395. raise Exception('Unsupported filter %s' % filter)
  396. else:
  397. # TODO: how to support appending?
  398. if self.format is None:
  399. raise Exception('You must specify a format for writing.')
  400. self.format_func = get_func(self.format, FORMATS, 1)
  401. if self.format_func is None:
  402. raise Exception('Unsupported format %s' % format)
  403. self.filter_func = get_func(self.filter, FILTERS, 1)
  404. if self.filter_func is None:
  405. raise Exception('Unsupported filter %s' % filter)
  406. # Open the archive, apply filter/format functions.
  407. self.init()
  408. def __iter__(self):
  409. while True:
  410. try:
  411. yield self.entry_class.from_archive(self, encoding=self.encoding)
  412. except EOF:
  413. break
  414. def __enter__(self):
  415. return self
  416. def __exit__(self, type, value, traceback):
  417. self.denit()
  418. def __del__(self):
  419. self.close()
  420. def set_initial_options(self):
  421. pass
  422. def init(self):
  423. if self.mode == 'r':
  424. self._a = _libarchive.archive_read_new()
  425. else:
  426. self._a = _libarchive.archive_write_new()
  427. self.format_func(self._a)
  428. self.filter_func(self._a)
  429. self.set_initial_options()
  430. if self.mode == 'r':
  431. if self.password:
  432. if isinstance(self.password, list):
  433. for pwd in self.password:
  434. self.add_passphrase(pwd)
  435. else:
  436. self.add_passphrase(self.password)
  437. call_and_check(_libarchive.archive_read_open_fd, self._a, self._a, self.f.fileno(), self.blocksize)
  438. else:
  439. if self.password:
  440. self.set_passphrase(self.password)
  441. call_and_check(_libarchive.archive_write_open_fd, self._a, self._a, self.f.fileno())
  442. def denit(self):
  443. '''Closes and deallocates the archive reader/writer.'''
  444. if getattr(self, '_a', None) is None:
  445. return
  446. try:
  447. if self.mode == 'r':
  448. _libarchive.archive_read_close(self._a)
  449. _libarchive.archive_read_free(self._a)
  450. elif self.mode == 'w':
  451. _libarchive.archive_write_close(self._a)
  452. _libarchive.archive_write_free(self._a)
  453. finally:
  454. # We only want one try at this...
  455. self._a = None
  456. def close(self, _defer=False):
  457. # _defer == True is how a stream can notify Archive that the stream is
  458. # now closed. Calling it directly in not recommended.
  459. if _defer:
  460. # This call came from our open stream.
  461. self._stream = None
  462. if not self._defer_close:
  463. # We are not yet ready to close.
  464. return
  465. if self._stream is not None:
  466. # We have a stream open! don't close, but remember we were asked to.
  467. self._defer_close = True
  468. return
  469. self.denit()
  470. # If there is a file attached...
  471. if hasattr(self, 'f'):
  472. # Make sure it is not already closed...
  473. if getattr(self.f, 'closed', False):
  474. return
  475. # Flush it if not read-only...
  476. if hasattr(self.f, "mode") and self.f.mode != 'r' and self.f.mode != 'rb':
  477. if hasattr(self.f, "flush"):
  478. self.f.flush()
  479. if hasattr(self.f, "fileno"):
  480. os.fsync(self.f.fileno())
  481. # and then close it, if we opened it...
  482. if getattr(self, '_close', None):
  483. self.f.close()
  484. @property
  485. def header_position(self):
  486. '''The position within the file.'''
  487. return _libarchive.archive_read_header_position(self._a)
  488. def iterpaths(self):
  489. for entry in self:
  490. yield entry.pathname
  491. def read(self, size):
  492. '''Read current archive entry contents into string.'''
  493. return _libarchive.archive_read_data_into_str(self._a, size)
  494. def readpath(self, f):
  495. '''Write current archive entry contents to file. f can be a file-like object or
  496. a path.'''
  497. if isinstance(f, str):
  498. basedir = os.path.dirname(f)
  499. if not os.path.exists(basedir):
  500. os.makedirs(basedir)
  501. f = open(f, 'w')
  502. return _libarchive.archive_read_data_into_fd(self._a, f.fileno())
  503. def readstream(self, size):
  504. '''Returns a file-like object for reading current archive entry contents.'''
  505. self._stream = EntryReadStream(self, size)
  506. return self._stream
  507. def write(self, member, data=None):
  508. '''Writes a string buffer to the archive as the given entry.'''
  509. if isinstance(member, str):
  510. member = self.entry_class(pathname=member, encoding=self.encoding,
  511. mtime=time.time(), mode=stat.S_IFREG)
  512. if data:
  513. member.size = len(data)
  514. member.to_archive(self)
  515. if data:
  516. if PY3:
  517. if isinstance(data, bytes):
  518. result = _libarchive.archive_write_data_from_str(self._a, data)
  519. else:
  520. result = _libarchive.archive_write_data_from_str(self._a, data.encode(self.encoding))
  521. else:
  522. result = _libarchive.archive_write_data_from_str(self._a, data)
  523. _libarchive.archive_write_finish_entry(self._a)
  524. def writepath(self, f, pathname=None, folder=False):
  525. '''Writes a file to the archive. f can be a file-like object or a path. Uses
  526. write() to do the actual writing.'''
  527. member = self.entry_class.from_file(f, encoding=self.encoding)
  528. if isinstance(f, str):
  529. if os.path.isfile(f):
  530. f = open(f, 'r')
  531. if pathname:
  532. member.pathname = pathname
  533. if folder and not member.isdir():
  534. member.mode = stat.S_IFDIR
  535. if hasattr(f, 'read'):
  536. # TODO: optimize this to write directly from f to archive.
  537. self.write(member, data=f.read())
  538. else:
  539. self.write(member)
  540. def writestream(self, pathname, size=None):
  541. '''Returns a file-like object for writing a new entry.'''
  542. self._stream = EntryWriteStream(self, pathname, size)
  543. return self._stream
  544. def printlist(self, s=sys.stdout):
  545. for entry in self:
  546. s.write(entry.size)
  547. s.write('\t')
  548. s.write(entry.mtime.strftime(MTIME_FORMAT))
  549. s.write('\t')
  550. s.write(entry.pathname)
  551. s.flush()
  552. def add_passphrase(self, password):
  553. '''Adds a password to the archive.'''
  554. _libarchive.archive_read_add_passphrase(self._a, password)
  555. def set_passphrase(self, password):
  556. '''Sets a password for the archive.'''
  557. _libarchive.archive_write_set_passphrase(self._a, password)
  558. class SeekableArchive(Archive):
  559. '''A class that provides random-access to archive entries. It does this by using one
  560. or many Archive instances to seek to the correct location. The best performance will
  561. occur when reading archive entries in the order in which they appear in the archive.
  562. Reading out of order will cause the archive to be closed and opened each time a
  563. reverse seek is needed.'''
  564. def __init__(self, f, **kwargs):
  565. self._stream = None
  566. # Convert file to open file. We need this to reopen the archive.
  567. mode = kwargs.setdefault('mode', 'r')
  568. if isinstance(f, str):
  569. f = open(f, mode)
  570. super(SeekableArchive, self).__init__(f, **kwargs)
  571. self.entries = []
  572. self.eof = False
  573. def __iter__(self):
  574. for entry in self.entries:
  575. yield entry
  576. if not self.eof:
  577. try:
  578. for entry in super(SeekableArchive, self).__iter__():
  579. self.entries.append(entry)
  580. yield entry
  581. except StopIteration:
  582. self.eof = True
  583. def reopen(self):
  584. '''Seeks the underlying fd to 0 position, then opens the archive. If the archive
  585. is already open, this will effectively re-open it (rewind to the beginning).'''
  586. self.denit()
  587. self.f.seek(0)
  588. self.init()
  589. def getentry(self, pathname):
  590. '''Take a name or entry object and returns an entry object.'''
  591. for entry in self:
  592. if entry.pathname == pathname:
  593. return entry
  594. raise KeyError(pathname)
  595. def seek(self, entry):
  596. '''Seeks the archive to the requested entry. Will reopen if necessary.'''
  597. move = entry.header_position - self.header_position
  598. if move != 0:
  599. if move < 0:
  600. # can't move back, re-open archive:
  601. self.reopen()
  602. # move to proper position in stream
  603. for curr in super(SeekableArchive, self).__iter__():
  604. if curr.header_position == entry.header_position:
  605. break
  606. def read(self, member):
  607. '''Return the requested archive entry contents as a string.'''
  608. entry = self.getentry(member)
  609. self.seek(entry)
  610. return super(SeekableArchive, self).read(entry.size)
  611. def readpath(self, member, f):
  612. entry = self.getentry(member)
  613. self.seek(entry)
  614. return super(SeekableArchive, self).readpath(f)
  615. def readstream(self, member):
  616. '''Returns a file-like object for reading requested archive entry contents.'''
  617. entry = self.getentry(member)
  618. self.seek(entry)
  619. self._stream = EntryReadStream(self, entry.size)
  620. return self._stream