当前位置: 首页>>代码示例>>Python>>正文


Python zipfile.ZipInfo方法代码示例

本文整理汇总了Python中zipfile.ZipInfo方法的典型用法代码示例。如果您正苦于以下问题:Python zipfile.ZipInfo方法的具体用法?Python zipfile.ZipInfo怎么用?Python zipfile.ZipInfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块zipfile的用法示例。

在下文中一共展示了zipfile.ZipInfo方法的27个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: next

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def next(self):
    """Returns the next input from this input reader as (ZipInfo, opener) tuple.

    Returns:
      The next input from this input reader, in the form of a 2-tuple.
      The first element of the tuple is a zipfile.ZipInfo object.
      The second element of the tuple is a zero-argument function that, when
      called, returns the complete body of the file.
    """
    if not self._zip:
      self._zip = zipfile.ZipFile(self._reader(self._blob_key))
      # Get a list of entries, reversed so we can pop entries off in order
      self._entries = self._zip.infolist()[self._start_index:self._end_index]
      self._entries.reverse()
    if not self._entries:
      raise StopIteration()
    entry = self._entries.pop()
    self._start_index += 1
    return (entry, lambda: self._read(entry)) 
开发者ID:elsigh,项目名称:browserscope,代码行数:21,代码来源:input_readers.py


示例2: _read

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def _read(self, entry):
    """Read entry content.

    Args:
      entry: zip file entry as zipfile.ZipInfo.
    Returns:
      Entry content as string.
    """
    start_time = time.time()
    content = self._zip.read(entry.filename)

    ctx = context.get()
    if ctx:
      operation.counters.Increment(COUNTER_IO_READ_BYTES, len(content))(ctx)
      operation.counters.Increment(
          COUNTER_IO_READ_MSEC, int((time.time() - start_time) * 1000))(ctx)

    return content 
开发者ID:elsigh,项目名称:browserscope,代码行数:20,代码来源:input_readers.py


示例3: _write_to_zip

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def _write_to_zip(self, wheel, rel_path):
        sio = StringIO()
        yield sio

        # The default is a fixed timestamp rather than the current time, so
        # that building a wheel twice on the same computer can automatically
        # give you the exact same result.
        date_time = (2016, 1, 1, 0, 0, 0)
        zi = zipfile.ZipInfo(rel_path, date_time)
        zi.external_attr = (0o644 & 0xFFFF) << 16  # Unix attributes
        b = sio.getvalue().encode("utf-8")
        hashsum = hashlib.sha256(b)
        hash_digest = urlsafe_b64encode(hashsum.digest()).decode("ascii").rstrip("=")

        wheel.writestr(zi, b, compress_type=zipfile.ZIP_DEFLATED)
        self._records.append((rel_path, hash_digest, len(b))) 
开发者ID:python-poetry,项目名称:poetry,代码行数:18,代码来源:wheel.py


示例4: _write_to_zip

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def _write_to_zip(self, wheel, rel_path):
        sio = StringIO()
        yield sio

        # The default is a fixed timestamp rather than the current time, so
        # that building a wheel twice on the same computer can automatically
        # give you the exact same result.
        date_time = (2016, 1, 1, 0, 0, 0)
        zi = zipfile.ZipInfo(rel_path, date_time)
        b = sio.getvalue().encode("utf-8")
        hashsum = hashlib.sha256(b)
        hash_digest = urlsafe_b64encode(hashsum.digest()).decode("ascii").rstrip("=")

        wheel.writestr(zi, b, compress_type=zipfile.ZIP_DEFLATED)
        stream.echo(f" - Adding: {rel_path}", verbosity=stream.DETAIL)
        self._records.append((rel_path, hash_digest, str(len(b)))) 
开发者ID:frostming,项目名称:pdm,代码行数:18,代码来源:wheel.py


示例5: test_unsupportedCompression

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_unsupportedCompression(self):
        """
        A zipfile which describes an unsupported compression mechanism should
        raise BadZipfile.
        """
        fn = self.mktemp()
        with zipfile.ZipFile(fn, "w") as zf:
            zi = zipfile.ZipInfo("0")
            zf.writestr(zi, "some data")
            # Mangle its compression type in the central directory; can't do
            # this before the writestr call or zipfile will (correctly) tell us
            # not to pass bad compression types :)
            zi.compress_type = 1234

        with zipstream.ChunkingZipFile(fn) as czf:
            self.assertRaises(zipfile.BadZipfile, czf.readfile, "0") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:18,代码来源:test_zipstream.py


示例6: close

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def close(self):
        # Write RECORD
        if self.fp is not None and self.mode == 'w' and self._file_hashes:
            data = StringIO()
            writer = csv.writer(data, delimiter=',', quotechar='"', lineterminator='\n')
            writer.writerows((
                (
                    fname,
                    algorithm + "=" + hash_,
                    self._file_sizes[fname]
                )
                for fname, (algorithm, hash_) in self._file_hashes.items()
            ))
            writer.writerow((format(self.record_path), "", ""))
            zinfo = ZipInfo(native(self.record_path), date_time=get_zipinfo_datetime())
            zinfo.compress_type = ZIP_DEFLATED
            zinfo.external_attr = 0o664 << 16
            self.writestr(zinfo, as_bytes(data.getvalue()))

        ZipFile.close(self) 
开发者ID:pantsbuild,项目名称:pex,代码行数:22,代码来源:wheelfile.py


示例7: dir2zip

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def dir2zip(in_dir, zip_fname):
    """ Make a zip file `zip_fname` with contents of directory `in_dir`

    The recorded filenames are relative to `in_dir`, so doing a standard zip
    unpack of the resulting `zip_fname` in an empty directory will result in
    the original directory contents.

    Parameters
    ----------
    in_dir : str
        Directory path containing files to go in the zip archive
    zip_fname : str
        Filename of zip archive to write
    """
    z = zipfile.ZipFile(zip_fname, 'w',
                        compression=zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(in_dir):
        for file in files:
            in_fname = pjoin(root, file)
            in_stat = os.stat(in_fname)
            # Preserve file permissions, but allow copy
            info = zipfile.ZipInfo(in_fname)
            info.filename = relpath(in_fname, in_dir)
            if os.path.sep == '\\':
                # Make the path unix friendly on windows.
                # PyPI won't accept wheels with windows path separators
                info.filename = relpath(in_fname, in_dir).replace('\\', '/')
            # Set time from modification time
            info.date_time = time.localtime(in_stat.st_mtime)
            # See https://stackoverflow.com/questions/434641/how-do-i-set-permissions-attributes-on-a-file-in-a-zip-file-using-pythons-zip/48435482#48435482 # noqa: E501
            # Also set regular file permissions
            perms = stat.S_IMODE(in_stat.st_mode) | stat.S_IFREG
            info.external_attr = perms << 16
            with open_readable(in_fname, 'rb') as fobj:
                contents = fobj.read()
            z.writestr(info, contents, zipfile.ZIP_DEFLATED)
    z.close() 
开发者ID:matthew-brett,项目名称:delocate,代码行数:39,代码来源:tools.py


示例8: _info_name

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def _info_name(info):
    """
    Returns a normalized file path for an archive info object

    :param info:
        An info object from _list_archive_members()

    :return:
        A unicode string with all directory separators normalized to "/"
    """

    if isinstance(info, zipfile.ZipInfo):
        return info.filename.replace('\\', '/')
    return info.name.replace('\\', '/') 
开发者ID:wbond,项目名称:oscrypto,代码行数:16,代码来源:deps.py


示例9: _write_content

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def _write_content(self, archive, path: str, content: str) -> None:
        content = content.encode('utf-8')

        # write content into archive
        zip_info = ZipInfo(path)
        archive.writestr(zip_info, content, compress_type=ZIP_DEFLATED)

        # calculate hashsum
        digest = sha256(content).digest()
        digest = urlsafe_b64encode(digest).decode().rstrip('=')
        self._records.append((path, digest, len(content))) 
开发者ID:dephell,项目名称:dephell,代码行数:13,代码来源:wheel.py


示例10: open

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 
开发者ID:jpush,项目名称:jbox,代码行数:36,代码来源:install.py


示例11: test_archive_dir

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_archive_dir(self):
        builder = Builder('test.zip')
        builder._archive_dir(self.zipfile, self.pj_root)
        ok_(isinstance(self.zipfile.getinfo('setup.pyc'), zipfile.ZipInfo)) 
开发者ID:marcy-terui,项目名称:lamvery,代码行数:6,代码来源:build_test.py


示例12: test_archive_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_archive_file(self):
        builder = Builder('test.zip')
        builder._archive_file(
            self.zipfile, os.path.join(self.pj_root, 'setup.py'))
        ok_(isinstance(self.zipfile.getinfo('setup.pyc'), zipfile.ZipInfo))
        builder._archive_file(
            self.zipfile, os.path.join(self.pj_root, 'README.md'))
        ok_(isinstance(self.zipfile.getinfo('README.md'), zipfile.ZipInfo)) 
开发者ID:marcy-terui,项目名称:lamvery,代码行数:10,代码来源:build_test.py


示例13: test_archive_dist

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_archive_dist(self):
        builder = Builder('test.zip')
        builder._archive_dist(self.zipfile, 'lamvery.js')
        ok_(isinstance(self.zipfile.getinfo('lamvery.js'), zipfile.ZipInfo)) 
开发者ID:marcy-terui,项目名称:lamvery,代码行数:6,代码来源:build_test.py


示例14: test_archive_single_file_key_error

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_archive_single_file_key_error(self):
        self._single_file = True
        builder = Builder('test.zip', single_file=True)
        builder._archive_file(
            self.zipfile, os.path.join(self.pj_root, 'setup.py'))
        ok_(isinstance(self.zipfile.getinfo('setup.pyc'), zipfile.ZipInfo)) 
开发者ID:marcy-terui,项目名称:lamvery,代码行数:8,代码来源:build_test.py


示例15: test_archive_single_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_archive_single_file(self):
        self._single_file = True
        builder = Builder('test.zip', single_file=True)
        builder._archive_file(
            self.zipfile, os.path.join(self.pj_root, 'setup.py'))
        ok_(isinstance(self.zipfile.getinfo('setup.py'), zipfile.ZipInfo)) 
开发者ID:marcy-terui,项目名称:lamvery,代码行数:8,代码来源:build_test.py


示例16: __init__

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def __init__(self, *args, **kwargs):
        if 'compress_type' in kwargs:
            compress_type = kwargs.pop('compress_type')
        super(ZipInfo, self).__init__(*args, **kwargs)
        self.compress_type = compress_type 
开发者ID:BasioMeusPuga,项目名称:Lector,代码行数:7,代码来源:unpack_structure.py


示例17: _extract

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def _extract(self, member, path=None, pwd=None):
    """for zipfile py2.5 borrowed from cpython"""
    if not isinstance(member, zipfile.ZipInfo):
        member = self.getinfo(member)

    if path is None:
        path = os.getcwd()

    return _extract_member(self, member, path, pwd) 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:11,代码来源:environment.py


示例18: _add_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def _add_file(self, wheel, full_path, rel_path):
        full_path, rel_path = str(full_path), str(rel_path)
        if os.sep != "/":
            # We always want to have /-separated paths in the zip file and in
            # RECORD
            rel_path = rel_path.replace(os.sep, "/")

        zinfo = zipfile.ZipInfo(rel_path)

        # Normalize permission bits to either 755 (executable) or 644
        st_mode = os.stat(full_path).st_mode
        new_mode = normalize_file_permissions(st_mode)
        zinfo.external_attr = (new_mode & 0xFFFF) << 16  # Unix attributes

        if stat.S_ISDIR(st_mode):
            zinfo.external_attr |= 0x10  # MS-DOS directory flag

        hashsum = hashlib.sha256()
        with open(full_path, "rb") as src:
            while True:
                buf = src.read(1024 * 8)
                if not buf:
                    break
                hashsum.update(buf)

            src.seek(0)
            wheel.writestr(zinfo, src.read(), compress_type=zipfile.ZIP_DEFLATED)

        size = os.stat(full_path).st_size
        hash_digest = urlsafe_b64encode(hashsum.digest()).decode("ascii").rstrip("=")

        self._records.append((rel_path, hash_digest, size)) 
开发者ID:python-poetry,项目名称:poetry,代码行数:34,代码来源:wheel.py


示例19: doTest

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def doTest(self, expected_ext, files, *modules, **kw):
        z = ZipFile(TEMP_ZIP, "w")
        try:
            for name, (mtime, data) in files.items():
                zinfo = ZipInfo(name, time.localtime(mtime))
                zinfo.compress_type = self.compression
                z.writestr(zinfo, data)
            z.close()

            stuff = kw.get("stuff", None)
            if stuff is not None:
                # Prepend 'stuff' to the start of the zipfile
                f = open(TEMP_ZIP, "rb")
                data = f.read()
                f.close()

                f = open(TEMP_ZIP, "wb")
                f.write(stuff)
                f.write(data)
                f.close()

            sys.path.insert(0, TEMP_ZIP)

            mod = __import__(".".join(modules), globals(), locals(),
                             ["__dummy__"])

            call = kw.get('call')
            if call is not None:
                call(mod)

            if expected_ext:
                file = mod.get_file()
                self.assertEqual(file, os.path.join(TEMP_ZIP,
                                 *modules) + expected_ext)
        finally:
            z.close()
            os.remove(TEMP_ZIP) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:39,代码来源:test_zipimport.py


示例20: testZipImporterMethodsInSubDirectory

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def testZipImporterMethodsInSubDirectory(self):
        packdir = TESTPACK + os.sep
        packdir2 = packdir + TESTPACK2 + os.sep
        files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
                 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}

        z = ZipFile(TEMP_ZIP, "w")
        try:
            for name, (mtime, data) in files.items():
                zinfo = ZipInfo(name, time.localtime(mtime))
                zinfo.compress_type = self.compression
                z.writestr(zinfo, data)
            z.close()

            zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
            self.assertEqual(zi.archive, TEMP_ZIP)
            self.assertEqual(zi.prefix, packdir)
            self.assertEqual(zi.is_package(TESTPACK2), True)
            mod = zi.load_module(TESTPACK2)
            self.assertEqual(zi.get_filename(TESTPACK2), mod.__file__)

            self.assertEqual(zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
            self.assertEqual(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)

            mod_path = TESTPACK2 + os.sep + TESTMOD
            mod_name = module_path_to_dotted_name(mod_path)
            __import__(mod_name)
            mod = sys.modules[mod_name]
            self.assertEqual(zi.get_source(TESTPACK2), None)
            self.assertEqual(zi.get_source(mod_path), None)
            self.assertEqual(zi.get_filename(mod_path), mod.__file__)
            # To pass in the module name instead of the path, we must use the right importer
            loader = mod.__loader__
            self.assertEqual(loader.get_source(mod_name), None)
            self.assertEqual(loader.get_filename(mod_name), mod.__file__)
        finally:
            z.close()
            os.remove(TEMP_ZIP) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:40,代码来源:test_zipimport.py


示例21: zip_test_writestr_permissions

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def zip_test_writestr_permissions(self, f, compression):
        # Make sure that writestr creates files with mode 0600,
        # when it is passed a name rather than a ZipInfo instance.

        self.make_test_archive(f, compression)
        with zipfile.ZipFile(f, "r") as zipfp:
            zinfo = zipfp.getinfo('strfile')
            self.assertEqual(zinfo.external_attr, 0600 << 16) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:10,代码来源:test_zipfile.py


示例22: test_create_zipinfo_before_1980

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_create_zipinfo_before_1980(self):
        self.assertRaises(ValueError,
                          zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:5,代码来源:test_zipfile.py


示例23: test_get_jar_features

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_get_jar_features(self):
        tmpdir = tempfile.mkdtemp()
        jar_file_name = 'myfile.jar'

        # Ensure the file is read/write by the creator only
        saved_umask = os.umask(0077)

        path = os.path.join(tmpdir, jar_file_name)
        try:
            with ZipFile(path, "w") as myjar:
                myjar.writestr(ZipInfo('first.class',(1980,1,1,1,1,1)), "first secrets!")
                myjar.writestr(ZipInfo('second.class',(1980,1,1,1,1,1)), "second secrets!")
                myjar.writestr(ZipInfo('second.txt',(1980,1,1,1,1,1)), "second secrets!")

            jars = list(jar_utils.crawl_jar_files(root_dir=tmpdir))
            print jars
            jar_feature = jars[0][1]
            assert 'myfile.jar' == jar_feature.name
            assert '48ac85a26ffa7ff5cefdd5c73a9fb888' == jar_feature.jarhash
            assert ['ddc6eff37020aa858e26b1ba8a49ee0e',
                    'cbe2a13eb99c1c8ac5f30d0a04f8c492'] == jar_feature.hashes
            assert 'jar' == jars[0][2]

        except IOError as e:
            print 'IOError'
        finally:
            os.remove(path)
            os.umask(saved_umask)
            os.rmdir(tmpdir) 
开发者ID:cloudviz,项目名称:agentless-system-crawler,代码行数:31,代码来源:test_jar_utils.py


示例24: test_jar_host_crawler_plugin

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_jar_host_crawler_plugin(self, *args):
        tmpdir = tempfile.mkdtemp()
        jar_file_name = 'myfile.jar'

        # Ensure the file is read/write by the creator only
        saved_umask = os.umask(0077)

        path = os.path.join(tmpdir, jar_file_name)
        try:
            with ZipFile(path, "w") as myjar:
                myjar.writestr(ZipInfo('first.class',(1980,1,1,1,1,1)), "first secrets!")
                myjar.writestr(ZipInfo('second.class',(1980,1,1,1,1,1)), "second secrets!")
                myjar.writestr(ZipInfo('second.txt',(1980,1,1,1,1,1)), "second secrets!")

            fc = JarHostCrawler()
            jars = list(fc.crawl(root_dir=tmpdir))
            #jars = list(jar_utils.crawl_jar_files(root_dir=tmpdir))
            print jars
            jar_feature = jars[0][1]
            assert 'myfile.jar' == jar_feature.name
            assert '48ac85a26ffa7ff5cefdd5c73a9fb888' == jar_feature.jarhash
            assert ['ddc6eff37020aa858e26b1ba8a49ee0e',
                    'cbe2a13eb99c1c8ac5f30d0a04f8c492'] == jar_feature.hashes
            assert 'jar' == jars[0][2]

        except IOError as e:
            print 'IOError'
        finally:
            os.remove(path)
            os.umask(saved_umask) 
开发者ID:cloudviz,项目名称:agentless-system-crawler,代码行数:32,代码来源:test_jar_plugin.py


示例25: test_jar_container_crawler_plugin

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_jar_container_crawler_plugin(self, *args):
        tmpdir = tempfile.mkdtemp()
        jar_file_name = 'myfile.jar'

        # Ensure the file is read/write by the creator only
        saved_umask = os.umask(0077)

        path = os.path.join(tmpdir, jar_file_name)
        try:
            with ZipFile(path, "w") as myjar:
                myjar.writestr(ZipInfo('first.class',(1980,1,1,1,1,1)), "first secrets!")
                myjar.writestr(ZipInfo('second.class',(1980,1,1,1,1,1)), "second secrets!")
                myjar.writestr(ZipInfo('second.txt',(1980,1,1,1,1,1)), "second secrets!")

            fc = JarContainerCrawler()
            jars = list(fc.crawl(root_dir=tmpdir))
            #jars = list(jar_utils.crawl_jar_files(root_dir=tmpdir))
            print jars
            jar_feature = jars[0][1]
            assert 'myfile.jar' == jar_feature.name
            assert '48ac85a26ffa7ff5cefdd5c73a9fb888' == jar_feature.jarhash
            assert ['ddc6eff37020aa858e26b1ba8a49ee0e',
                    'cbe2a13eb99c1c8ac5f30d0a04f8c492'] == jar_feature.hashes
            assert 'jar' == jars[0][2]

        except IOError as e:
            print 'IOError'
        finally:
            os.remove(path) 
开发者ID:cloudviz,项目名称:agentless-system-crawler,代码行数:31,代码来源:test_plugins.py


示例26: test_jar_container_crawler_avoidsetns

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def test_jar_container_crawler_avoidsetns(self, *args):
        tmpdir = tempfile.mkdtemp()
        jar_file_name = 'myfile.jar'

        # Ensure the file is read/write by the creator only
        saved_umask = os.umask(0077)

        path = os.path.join(tmpdir, jar_file_name)
        try:
            with ZipFile(path, "w") as myjar:
                myjar.writestr(ZipInfo('first.class',(1980,1,1,1,1,1)), "first secrets!")
                myjar.writestr(ZipInfo('second.class',(1980,1,1,1,1,1)), "second secrets!")
                myjar.writestr(ZipInfo('second.txt',(1980,1,1,1,1,1)), "second secrets!")

            fc = JarContainerCrawler()
            jars = list(fc.crawl(root_dir=os.path.basename(tmpdir), avoid_setns=True))
            print jars
            jar_feature = jars[0][1]
            assert 'myfile.jar' == jar_feature.name
            assert '48ac85a26ffa7ff5cefdd5c73a9fb888' == jar_feature.jarhash
            assert ['ddc6eff37020aa858e26b1ba8a49ee0e',
                    'cbe2a13eb99c1c8ac5f30d0a04f8c492'] == jar_feature.hashes
            assert 'jar' == jars[0][2]

        except IOError as e:
            print 'IOError'
        finally:
            os.remove(path) 
开发者ID:cloudviz,项目名称:agentless-system-crawler,代码行数:30,代码来源:test_plugins.py


示例27: _add_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import ZipInfo [as 别名]
def _add_file(self, wheel, full_path, rel_path=None):
        if not rel_path:
            rel_path = full_path
        if os.sep != "/":
            # We always want to have /-separated paths in the zip file and in RECORD
            rel_path = rel_path.replace(os.sep, "/")
        stream.echo(f" - Adding: {rel_path}", verbosity=stream.DETAIL)
        zinfo = zipfile.ZipInfo(rel_path)

        # Normalize permission bits to either 755 (executable) or 644
        st_mode = os.stat(full_path).st_mode

        if stat.S_ISDIR(st_mode):
            zinfo.external_attr |= 0x10  # MS-DOS directory flag

        hashsum = hashlib.sha256()
        with open(full_path, "rb") as src:
            while True:
                buf = src.read(1024 * 8)
                if not buf:
                    break
                hashsum.update(buf)

            src.seek(0)
            wheel.writestr(zinfo, src.read(), compress_type=zipfile.ZIP_DEFLATED)

        size = os.stat(full_path).st_size
        hash_digest = urlsafe_b64encode(hashsum.digest()).decode("ascii").rstrip("=")

        self._records.append((rel_path, hash_digest, str(size))) 
开发者ID:frostming,项目名称:pdm,代码行数:32,代码来源:wheel.py



注:本文中的zipfile.ZipInfo方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。