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