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.
 
 
 
 
 

731 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 get_error(archive):
  84. '''Retrieves the last error description for the given archive instance.'''
  85. return _libarchive.archive_error_string(archive)
  86. def call_and_check(func, archive, *args):
  87. '''Executes a libarchive function and raises an exception when appropriate.'''
  88. ret = func(*args)
  89. if ret == _libarchive.ARCHIVE_OK:
  90. return
  91. elif ret == _libarchive.ARCHIVE_WARN:
  92. warnings.warn('Warning executing function: %s.' % get_error(archive), RuntimeWarning)
  93. elif ret == _libarchive.ARCHIVE_EOF:
  94. raise EOF()
  95. else:
  96. raise Exception('Problem executing function, message is: %s.' % get_error(archive))
  97. def get_func(name, items, index):
  98. item = items.get(name, None)
  99. if item is None:
  100. return None
  101. return item[index]
  102. def guess_format(filename):
  103. if isinstance(filename, int):
  104. filename = ext = ''
  105. else:
  106. filename, ext = os.path.splitext(filename)
  107. filter = FILTER_EXTENSIONS.get(ext)
  108. if filter:
  109. filename, ext = os.path.splitext(filename)
  110. format = FORMAT_EXTENSIONS.get(ext)
  111. return format, filter
  112. def is_archive_name(filename, formats=None):
  113. '''Quick check to see if the given file has an extension indiciating that it is
  114. an archive. The format parameter can be used to limit what archive format is acceptable.
  115. If omitted, all supported archive formats will be checked.
  116. This function will return the name of the most likely archive format, None if the file is
  117. unlikely to be an archive.'''
  118. if formats is None:
  119. formats = list(FORMAT_EXTENSIONS.values())
  120. format, filter = guess_format(filename)
  121. if format in formats:
  122. return format
  123. def is_archive(f, formats=(None,), filters=(None,)):
  124. '''Check to see if the given file is actually an archive. The format parameter
  125. can be used to specify which archive format is acceptable. If ommitted, all supported
  126. archive formats will be checked. It opens the file using libarchive. If no error is
  127. received, the file was successfully detected by the libarchive bidding process.
  128. This procedure is quite costly, so you should avoid calling it unless you are reasonably
  129. sure that the given file is an archive. In other words, you may wish to filter large
  130. numbers of file names using is_archive_name() before double-checking the positives with
  131. this function.
  132. This function will return True if the file can be opened as an archive using the given
  133. format(s)/filter(s).'''
  134. need_close: bool = False
  135. if isinstance(f, str):
  136. f = open(f, 'rb')
  137. need_close = True
  138. a = _libarchive.archive_read_new()
  139. for format in formats:
  140. format = get_func(format, FORMATS, 0)
  141. if format is None:
  142. return False
  143. format(a)
  144. for filter in filters:
  145. filter = get_func(filter, FILTERS, 0)
  146. if filter is None:
  147. return False
  148. filter(a)
  149. try:
  150. try:
  151. call_and_check(_libarchive.archive_read_open_fd, a, a, f.fileno(), BLOCK_SIZE)
  152. return True
  153. except:
  154. return False
  155. finally:
  156. _libarchive.archive_read_close(a)
  157. _libarchive.archive_read_free(a)
  158. if need_close:
  159. f.close()
  160. class EntryReadStream(object):
  161. '''A file-like object for reading an entry from the archive.'''
  162. def __init__(self, archive, size):
  163. self.archive = archive
  164. self.closed = False
  165. self.size = size
  166. self.bytes = 0
  167. def __enter__(self):
  168. return self
  169. def __exit__(self, *args):
  170. return
  171. def __iter__(self):
  172. if self.closed:
  173. return
  174. while True:
  175. data = self.read(BLOCK_SIZE)
  176. if not data:
  177. break
  178. yield data
  179. def __len__(self):
  180. return self.size
  181. def tell(self):
  182. return self.bytes
  183. def read(self, bytes=-1):
  184. if self.closed:
  185. return
  186. if self.bytes == self.size:
  187. # EOF already reached.
  188. return
  189. if bytes < 0:
  190. bytes = self.size - self.bytes
  191. elif self.bytes + bytes > self.size:
  192. # Limit read to remaining bytes
  193. bytes = self.size - self.bytes
  194. # Read requested bytes
  195. data = _libarchive.archive_read_data_into_str(self.archive._a, bytes)
  196. self.bytes += len(data)
  197. return data
  198. def close(self):
  199. if self.closed:
  200. return
  201. # Call archive.close() with _defer True to let it know we have been
  202. # closed and it is now safe to actually close.
  203. self.archive.close(_defer=True)
  204. self.archive = None
  205. self.closed = True
  206. class EntryWriteStream(object):
  207. '''A file-like object for writing an entry to an archive.
  208. If the size is known ahead of time and provided, then the file contents
  209. are not buffered but flushed directly to the archive. If size is omitted,
  210. then the file contents are buffered and flushed in the close() method.'''
  211. def __init__(self, archive, pathname, size=None):
  212. self.archive = archive
  213. self.entry = Entry(pathname=pathname, mtime=time.time(), mode=stat.S_IFREG)
  214. if size is None:
  215. self.buffer = StringIO()
  216. else:
  217. self.buffer = None
  218. self.entry.size = size
  219. self.entry.to_archive(self.archive)
  220. self.bytes = 0
  221. self.closed = False
  222. def __enter__(self):
  223. return self
  224. def __exit__(self, *args):
  225. self.close()
  226. def __del__(self):
  227. self.close()
  228. def __len__(self):
  229. return self.bytes
  230. def tell(self):
  231. return self.bytes
  232. def write(self, data):
  233. if self.closed:
  234. raise Exception('Cannot write to closed stream.')
  235. if self.buffer:
  236. self.buffer.write(data)
  237. else:
  238. _libarchive.archive_write_data_from_str(self.archive._a, data.encode('utf-8'))
  239. self.bytes += len(data)
  240. def close(self):
  241. if self.closed:
  242. return
  243. if self.buffer:
  244. self.entry.size = self.buffer.tell()
  245. self.entry.to_archive(self.archive)
  246. _libarchive.archive_write_data_from_str(self.archive._a, self.buffer.getvalue().encode('utf-8'))
  247. _libarchive.archive_write_finish_entry(self.archive._a)
  248. # Call archive.close() with _defer True to let it know we have been
  249. # closed and it is now safe to actually close.
  250. self.archive.close(_defer=True)
  251. self.archive = None
  252. self.closed = True
  253. class Entry(object):
  254. '''An entry within an archive. Represents the header data and it's location within the archive.'''
  255. def __init__(self, pathname=None, size=None, mtime=None, mode=None, hpos=None, encoding=ENCODING):
  256. # , symlink=None
  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. # if self.issym() and symlink:
  265. # self.symlink = symlink
  266. # else:
  267. # self.symlink = None
  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. print("issym")
  292. symLinkPath = _libarchive.archive_entry_symlink(e)
  293. entry.symlink = symLinkPath
  294. print(symLinkPath)
  295. finally:
  296. _libarchive.archive_entry_free(e)
  297. return entry
  298. @classmethod
  299. def from_file(cls, f, entry=None, encoding=ENCODING):
  300. '''Instantiates an Entry class and sets all the properties from a file on the file system.
  301. f can be a file-like object or a path.'''
  302. if entry is None:
  303. entry = cls(encoding=encoding)
  304. if entry.pathname is None:
  305. if isinstance(f, str):
  306. st = os.stat(f)
  307. entry.pathname = f
  308. entry.size = st.st_size
  309. entry.mtime = st.st_mtime
  310. entry.mode = st.st_mode
  311. elif hasattr(f, 'fileno'):
  312. st = os.fstat(f.fileno())
  313. entry.pathname = getattr(f, 'name', None)
  314. entry.size = st.st_size
  315. entry.mtime = st.st_mtime
  316. entry.mode = st.st_mode
  317. else:
  318. entry.pathname = getattr(f, 'pathname', None)
  319. entry.size = getattr(f, 'size', 0)
  320. entry.mtime = getattr(f, 'mtime', time.time())
  321. entry.mode = stat.S_IFREG
  322. if stat.S_ISLNK(entry.mode):
  323. print("yo")
  324. return entry
  325. def to_archive(self, archive):
  326. '''Creates an archive header and writes it to the given archive.'''
  327. e = _libarchive.archive_entry_new()
  328. try:
  329. if PY3:
  330. _libarchive.archive_entry_set_pathname(e, self.pathname)
  331. else:
  332. _libarchive.archive_entry_set_pathname(e, self.pathname.encode(self.encoding))
  333. _libarchive.archive_entry_set_filetype(e, stat.S_IFMT(self.mode))
  334. _libarchive.archive_entry_set_perm(e, stat.S_IMODE(self.mode))
  335. _libarchive.archive_entry_set_size(e, self.size)
  336. _libarchive.archive_entry_set_mtime(e, self.mtime, 0)
  337. if stat.S_ISLNK(self.mode):
  338. _libarchive.archive_entry_set_symlink(e, self.symlink)
  339. call_and_check(_libarchive.archive_write_header, archive._a, archive._a, e)
  340. # todo
  341. # self.hpos = archive.header_position
  342. finally:
  343. _libarchive.archive_entry_free(e)
  344. def isdir(self):
  345. return stat.S_ISDIR(self.mode)
  346. def isfile(self):
  347. return stat.S_ISREG(self.mode)
  348. def issym(self):
  349. return stat.S_ISLNK(self.mode)
  350. def isfifo(self):
  351. return stat.S_ISFIFO(self.mode)
  352. def ischr(self):
  353. return stat.S_ISCHR(self.mode)
  354. def isblk(self):
  355. return stat.S_ISBLK(self.mode)
  356. class Archive(object):
  357. '''A low-level archive reader which provides forward-only iteration. Consider
  358. this a light-weight pythonic libarchive wrapper.'''
  359. def __init__(
  360. self,
  361. f,
  362. mode='r',
  363. format=None,
  364. filter=None,
  365. entry_class=Entry,
  366. encoding=ENCODING,
  367. blocksize=BLOCK_SIZE,
  368. password=None,
  369. ):
  370. assert mode in ('r', 'w', 'wb', 'a'), 'Mode should be "r", "w", "wb", or "a".'
  371. self._stream = None
  372. self.encoding = encoding
  373. self.blocksize = blocksize
  374. self.password = password
  375. if isinstance(f, str):
  376. self.filename = f
  377. f = open(f, mode)
  378. # Only close it if we opened it...
  379. self._defer_close = True
  380. elif hasattr(f, 'fileno'):
  381. self.filename = getattr(f, 'name', None)
  382. # Leave the fd alone, caller should manage it...
  383. self._defer_close = False
  384. else:
  385. raise Exception('Provided file is not path or open file.')
  386. self.f = f
  387. self.mode = mode
  388. # Guess the format/filter from file name (if not provided)
  389. if self.filename:
  390. if format is None:
  391. format = guess_format(self.filename)[0]
  392. if filter is None:
  393. filter = guess_format(self.filename)[1]
  394. self.format = format
  395. self.filter = filter
  396. # The class to use for entries.
  397. self.entry_class = entry_class
  398. # Select filter/format functions.
  399. if self.mode == 'r':
  400. self.format_func = get_func(self.format, FORMATS, 0)
  401. if self.format_func is None:
  402. raise Exception('Unsupported format %s' % format)
  403. self.filter_func = get_func(self.filter, FILTERS, 0)
  404. if self.filter_func is None:
  405. raise Exception('Unsupported filter %s' % filter)
  406. else:
  407. # TODO: how to support appending?
  408. if self.format is None:
  409. raise Exception('You must specify a format for writing.')
  410. self.format_func = get_func(self.format, FORMATS, 1)
  411. if self.format_func is None:
  412. raise Exception('Unsupported format %s' % format)
  413. self.filter_func = get_func(self.filter, FILTERS, 1)
  414. if self.filter_func is None:
  415. raise Exception('Unsupported filter %s' % filter)
  416. # Open the archive, apply filter/format functions.
  417. self.init()
  418. def __iter__(self):
  419. while True:
  420. try:
  421. yield self.entry_class.from_archive(self, encoding=self.encoding)
  422. except EOF:
  423. break
  424. def __enter__(self):
  425. return self
  426. def __exit__(self, type, value, traceback):
  427. self.denit()
  428. def __del__(self):
  429. self.close()
  430. def init(self):
  431. if self.mode == 'r':
  432. self._a = _libarchive.archive_read_new()
  433. else:
  434. self._a = _libarchive.archive_write_new()
  435. self.format_func(self._a)
  436. self.filter_func(self._a)
  437. if self.mode == 'r':
  438. if self.password:
  439. self.add_passphrase(self.password)
  440. call_and_check(_libarchive.archive_read_open_fd, self._a, self._a, self.f.fileno(), self.blocksize)
  441. else:
  442. if self.password:
  443. self.set_passphrase(self.password)
  444. call_and_check(_libarchive.archive_write_open_fd, self._a, self._a, self.f.fileno())
  445. def denit(self):
  446. '''Closes and deallocates the archive reader/writer.'''
  447. if getattr(self, '_a', None) is None:
  448. return
  449. try:
  450. if self.mode == 'r':
  451. _libarchive.archive_read_close(self._a)
  452. _libarchive.archive_read_free(self._a)
  453. elif self.mode == 'w':
  454. _libarchive.archive_write_close(self._a)
  455. _libarchive.archive_write_free(self._a)
  456. finally:
  457. # We only want one try at this...
  458. self._a = None
  459. def close(self, _defer=False):
  460. # _defer == True is how a stream can notify Archive that the stream is
  461. # now closed. Calling it directly in not recommended.
  462. if _defer:
  463. # This call came from our open stream.
  464. self._stream = None
  465. if not self._defer_close:
  466. # We are not yet ready to close.
  467. return
  468. if self._stream is not None:
  469. # We have a stream open! don't close, but remember we were asked to.
  470. self._defer_close = True
  471. return
  472. self.denit()
  473. # If there is a file attached...
  474. if hasattr(self, 'f'):
  475. # Make sure it is not already closed...
  476. if getattr(self.f, 'closed', False):
  477. return
  478. # Flush it if not read-only...
  479. if hasattr(self.f, "mode") and self.f.mode != 'r' and self.f.mode != 'rb':
  480. if hasattr(self.f, "flush"):
  481. self.f.flush()
  482. if hasattr(self.f, "fileno"):
  483. os.fsync(self.f.fileno())
  484. # and then close it, if we opened it...
  485. if getattr(self, '_close', None):
  486. self.f.close()
  487. @property
  488. def header_position(self):
  489. '''The position within the file.'''
  490. return _libarchive.archive_read_header_position(self._a)
  491. def iterpaths(self):
  492. for entry in self:
  493. yield entry.pathname
  494. def read(self, size):
  495. '''Read current archive entry contents into string.'''
  496. return _libarchive.archive_read_data_into_str(self._a, size)
  497. def readpath(self, f):
  498. '''Write current archive entry contents to file. f can be a file-like object or
  499. a path.'''
  500. if isinstance(f, str):
  501. basedir = os.path.dirname(f)
  502. if not os.path.exists(basedir):
  503. os.makedirs(basedir)
  504. f = open(f, 'w')
  505. return _libarchive.archive_read_data_into_fd(self._a, f.fileno())
  506. def readstream(self, size):
  507. '''Returns a file-like object for reading current archive entry contents.'''
  508. self._stream = EntryReadStream(self, size)
  509. return self._stream
  510. def write(self, member, data=None):
  511. '''Writes a string buffer to the archive as the given entry.'''
  512. if isinstance(member, str):
  513. member = self.entry_class(pathname=member, encoding=self.encoding)
  514. if data:
  515. member.size = len(data)
  516. member.to_archive(self)
  517. if data:
  518. if PY3:
  519. if isinstance(data, bytes):
  520. result = _libarchive.archive_write_data_from_str(self._a, data)
  521. else:
  522. result = _libarchive.archive_write_data_from_str(self._a, data.encode('utf8'))
  523. else:
  524. result = _libarchive.archive_write_data_from_str(self._a, data)
  525. _libarchive.archive_write_finish_entry(self._a)
  526. def writepath(self, f, pathname=None, folder=False):
  527. '''Writes a file to the archive. f can be a file-like object or a path. Uses
  528. write() to do the actual writing.'''
  529. member = self.entry_class.from_file(f, encoding=self.encoding)
  530. if isinstance(f, str):
  531. if os.path.isfile(f):
  532. f = open(f, 'r')
  533. if pathname:
  534. member.pathname = pathname
  535. if folder and not member.isdir():
  536. member.mode = stat.S_IFDIR
  537. if hasattr(f, 'read'):
  538. # TODO: optimize this to write directly from f to archive.
  539. self.write(member, data=f.read())
  540. else:
  541. self.write(member)
  542. def writestream(self, pathname, size=None):
  543. '''Returns a file-like object for writing a new entry.'''
  544. self._stream = EntryWriteStream(self, pathname, size)
  545. return self._stream
  546. def printlist(self, s=sys.stdout):
  547. for entry in self:
  548. s.write(entry.size)
  549. s.write('\t')
  550. s.write(entry.mtime.strftime(MTIME_FORMAT))
  551. s.write('\t')
  552. s.write(entry.pathname)
  553. s.flush()
  554. def add_passphrase(self, password):
  555. '''Adds a password to the archive.'''
  556. _libarchive.archive_read_add_passphrase(self._a, password)
  557. def set_passphrase(self, password):
  558. '''Sets a password for the archive.'''
  559. _libarchive.archive_write_set_passphrase(self._a, password)
  560. class SeekableArchive(Archive):
  561. '''A class that provides random-access to archive entries. It does this by using one
  562. or many Archive instances to seek to the correct location. The best performance will
  563. occur when reading archive entries in the order in which they appear in the archive.
  564. Reading out of order will cause the archive to be closed and opened each time a
  565. reverse seek is needed.'''
  566. def __init__(self, f, **kwargs):
  567. self._stream = None
  568. # Convert file to open file. We need this to reopen the archive.
  569. mode = kwargs.setdefault('mode', 'r')
  570. if isinstance(f, str):
  571. f = open(f, mode)
  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