def is_archive(f, formats=(None, ), filters=(None, )): '''Check to see if the given file is actually an archive. The format parameter can be used to specify which archive format is acceptable. If ommitted, all supported archive formats will be checked. It opens the file using libarchive. If no error is received, the file was successfully detected by the libarchive bidding process. This procedure is quite costly, so you should avoid calling it unless you are reasonably sure that the given file is an archive. In other words, you may wish to filter large numbers of file names using is_archive_name() before double-checking the positives with this function. This function will return True if the file can be opened as an archive using the given format(s)/filter(s).''' if isinstance(f, str): f = open(f, 'r') a = _libarchive.archive_read_new() for format in formats: format = get_func(format, FORMATS, 0) if format is None: return False format(a) for filter in filters: filter = get_func(filter, FILTERS, 0) if filter is None: return False filter(a) try: try: call_and_check(_libarchive.archive_read_open_fd, a, a, f.fileno(), BLOCK_SIZE) return True except: return False finally: _libarchive.archive_read_close(a) _libarchive.archive_read_free(a)
def is_archive(f, formats=(None, ), filters=(None, )): '''Check to see if the given file is actually an archive. The format parameter can be used to specify which archive format is acceptable. If ommitted, all supported archive formats will be checked. It opens the file using libarchive. If no error is received, the file was successfully detected by the libarchive bidding process. This procedure is quite costly, so you should avoid calling it unless you are reasonably sure that the given file is an archive. In other words, you may wish to filter large numbers of file names using is_archive_name() before double-checking the positives with this function. This function will return True if the file can be opened as an archive using the given format(s)/filter(s).''' if isinstance(f, basestring): f = file(f, 'r') a = _libarchive.archive_read_new() for format in formats: format = get_func(format, FORMATS, 0) if format is None: return False format(a) for filter in filters: filter = get_func(filter, FILTERS, 0) if filter is None: return False filter(a) try: try: call_and_check(_libarchive.archive_read_open_fd, a, a, f.fileno(), BLOCK_SIZE) return True except: return False finally: _libarchive.archive_read_close(a) _libarchive.archive_read_free(a)
def denit(self): '''Closes and deallocates the archive reader/writer.''' if getattr(self, '_a', None) is None: return try: if self.mode == 'r': _libarchive.archive_read_close(self._a) _libarchive.archive_read_free(self._a) elif self.mode == 'w': _libarchive.archive_write_close(self._a) _libarchive.archive_write_free(self._a) finally: # We only want one try at this... self._a = None