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.
 
 
 
 
 

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