zipp-1.0.0/0000775000372000037200000000000013607174360013343 5ustar travistravis00000000000000zipp-1.0.0/.flake80000664000372000037200000000036613607174340014521 0ustar travistravis00000000000000[flake8] max-line-length = 88 ignore = # W503 violates spec https://github.com/PyCQA/pycodestyle/issues/513 W503 # W504 has issues https://github.com/OCA/maintainer-quality-tools/issues/545 W504 # Black creates whitespace before colon E203 zipp-1.0.0/.pre-commit-config.yaml0000664000372000037200000000012213607174340017615 0ustar travistravis00000000000000repos: - repo: https://github.com/ambv/black rev: 18.9b0 hooks: - id: black zipp-1.0.0/.readthedocs.yml0000664000372000037200000000011213607174340016421 0ustar travistravis00000000000000python: version: 3 extra_requirements: - docs pip_install: true zipp-1.0.0/.travis.yml0000664000372000037200000000073013607174340015452 0ustar travistravis00000000000000dist: xenial language: python python: - 2.7 - 3.5 - &latest_py3 3.7 jobs: fast_finish: true include: - stage: deploy if: tag IS present python: *latest_py3 before_script: skip script: tox -e release cache: pip install: - pip install tox tox-venv before_script: # Disable IPv6. Ref travis-ci/travis-ci#8361 - if [ "${TRAVIS_OS_NAME}" == "linux" ]; then sudo sh -c 'echo 0 > /proc/sys/net/ipv6/conf/all/disable_ipv6'; fi script: tox zipp-1.0.0/CHANGES.rst0000664000372000037200000000217113607174340015144 0ustar travistravis00000000000000v1.0.0 ====== Re-release of 0.6 to correspond with release as found in Python 3.8. v0.6.0 ====== #12: When adding implicit dirs, ensure that ancestral directories are added and that duplicates are excluded. The library now relies on `more_itertools `_. v0.5.2 ====== #7: Parent of a directory now actually returns the parent. v0.5.1 ====== Declared package as backport. v0.5.0 ====== Add ``.joinpath()`` method and ``.parent`` property. Now a backport release of the ``zipfile.Path`` class. v0.4.0 ====== #4: Add support for zip files with implied directories. v0.3.3 ====== #3: Fix issue where ``.name`` on a directory was empty. v0.3.2 ====== #2: Fix TypeError on Python 2.7 when classic division is used. v0.3.1 ====== #1: Fix TypeError on Python 3.5 when joining to a path-like object. v0.3.0 ====== Add support for constructing a ``zipp.Path`` from any path-like object. ``zipp.Path`` is now a new-style class on Python 2.7. v0.2.1 ====== Fix issue with ``__str__``. v0.2.0 ====== Drop reliance on future-fstrings. v0.1.0 ====== Initial release with basic functionality. zipp-1.0.0/LICENSE0000664000372000037200000000203213607174340014343 0ustar travistravis00000000000000Copyright Jason R. Coombs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. zipp-1.0.0/PKG-INFO0000664000372000037200000000305313607174360014441 0ustar travistravis00000000000000Metadata-Version: 2.1 Name: zipp Version: 1.0.0 Summary: Backport of pathlib-compatible object wrapper for zip files Home-page: https://github.com/jaraco/zipp Author: Jason R. Coombs Author-email: jaraco@jaraco.com License: UNKNOWN Description: .. image:: https://img.shields.io/pypi/v/zipp.svg :target: https://pypi.org/project/zipp .. image:: https://img.shields.io/pypi/pyversions/zipp.svg .. image:: https://img.shields.io/travis/jaraco/zipp/master.svg :target: https://travis-ci.org/jaraco/zipp .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: Black .. image:: https://img.shields.io/appveyor/ci/jaraco/zipp/master.svg :target: https://ci.appveyor.com/project/jaraco/zipp/branch/master .. .. image:: https://readthedocs.org/projects/zipp/badge/?version=latest .. :target: https://zipp.readthedocs.io/en/latest/?badge=latest A pathlib-compatible Zipfile object wrapper. A backport of the `Path object `_. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Requires-Python: >=2.7 Provides-Extra: testing Provides-Extra: docs zipp-1.0.0/README.rst0000664000372000037200000000147613607174340015040 0ustar travistravis00000000000000.. image:: https://img.shields.io/pypi/v/zipp.svg :target: https://pypi.org/project/zipp .. image:: https://img.shields.io/pypi/pyversions/zipp.svg .. image:: https://img.shields.io/travis/jaraco/zipp/master.svg :target: https://travis-ci.org/jaraco/zipp .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: Black .. image:: https://img.shields.io/appveyor/ci/jaraco/zipp/master.svg :target: https://ci.appveyor.com/project/jaraco/zipp/branch/master .. .. image:: https://readthedocs.org/projects/zipp/badge/?version=latest .. :target: https://zipp.readthedocs.io/en/latest/?badge=latest A pathlib-compatible Zipfile object wrapper. A backport of the `Path object `_. zipp-1.0.0/appveyor.yml0000664000372000037200000000072413607174340015734 0ustar travistravis00000000000000environment: APPVEYOR: true matrix: - PYTHON: "C:\\Python36-x64" - PYTHON: "C:\\Python27-x64" install: # symlink python from a directory with a space - "mklink /d \"C:\\Program Files\\Python\" %PYTHON%" - "SET PYTHON=\"C:\\Program Files\\Python\"" - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" build: off cache: - '%LOCALAPPDATA%\pip\Cache' test_script: - "python -m pip install -U tox tox-venv virtualenv" - "tox" version: '{build}' zipp-1.0.0/conftest.py0000664000372000037200000000000013607174340015526 0ustar travistravis00000000000000zipp-1.0.0/docs/0000775000372000037200000000000013607174360014273 5ustar travistravis00000000000000zipp-1.0.0/docs/conf.py0000664000372000037200000000136313607174340015573 0ustar travistravis00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker'] master_doc = "index" link_files = { '../CHANGES.rst': dict( using=dict(GH='https://github.com'), replace=[ dict( pattern=r'(Issue #|\B#)(?P\d+)', url='{package_url}/issues/{issue}', ), dict( pattern=r'^(?m)((?Pv?\d+(\.\d+){1,2}))\n[-=]+\n', with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n', ), dict( pattern=r'PEP[- ](?P\d+)', url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/', ), ], ) } zipp-1.0.0/docs/history.rst0000664000372000037200000000012113607174340016516 0ustar travistravis00000000000000:tocdepth: 2 .. _changes: History ******* .. include:: ../CHANGES (links).rst zipp-1.0.0/docs/index.rst0000664000372000037200000000044013607174340016130 0ustar travistravis00000000000000Welcome to zipp documentation! ======================================== .. toctree:: :maxdepth: 1 history .. automodule:: zipp :members: :undoc-members: :show-inheritance: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` zipp-1.0.0/pyproject.toml0000664000372000037200000000024713607174340016260 0ustar travistravis00000000000000[build-system] requires = ["setuptools>=34.4", "wheel", "setuptools_scm>=1.15"] build-backend = "setuptools.build_meta" [tool.black] skip-string-normalization = true zipp-1.0.0/setup.cfg0000664000372000037200000000153413607174360015167 0ustar travistravis00000000000000[bdist_wheel] universal = 1 [metadata] license_file = LICENSE name = zipp author = Jason R. Coombs author_email = jaraco@jaraco.com description = Backport of pathlib-compatible object wrapper for zip files long_description = file:README.rst url = https://github.com/jaraco/zipp classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: MIT License Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 [options] py_modules = zipp packages = find: include_package_data = true python_requires = >=2.7 install_requires = more_itertools setup_requires = setuptools_scm >= 1.15.0 [options.extras_require] testing = pathlib2 contextlib2 unittest2 docs = sphinx jaraco.packaging >= 3.2 rst.linker >= 1.9 [options.entry_points] [egg_info] tag_build = tag_date = 0 zipp-1.0.0/setup.py0000664000372000037200000000016013607174340015050 0ustar travistravis00000000000000#!/usr/bin/env python import setuptools if __name__ == "__main__": setuptools.setup(use_scm_version=True) zipp-1.0.0/skeleton.md0000664000372000037200000001772613607174340015524 0ustar travistravis00000000000000# Overview This project is merged with [skeleton](https://github.com/jaraco/skeleton). What is skeleton? It's the scaffolding of a Python project jaraco [introduced in his blog](https://blog.jaraco.com/a-project-skeleton-for-python-projects/). It seeks to provide a means to re-use techniques and inherit advances when managing projects for distribution. ## An SCM Managed Approach While maintaining dozens of projects in PyPI, jaraco derives best practices for project distribution and publishes them in the [skeleton repo](https://github.com/jaraco/skeleton), a git repo capturing the evolution and culmination of these best practices. It's intended to be used by a new or existing project to adopt these practices and honed and proven techniques. Adopters are encouraged to use the project directly and maintain a small deviation from the technique, make their own fork for more substantial changes unique to their environment or preferences, or simply adopt the skeleton once and abandon it thereafter. The primary advantage to using an SCM for maintaining these techniques is that those tools help facilitate the merge between the template and its adopting projects. Another advantage to using an SCM-managed approach is that tools like GitHub recognize that a change in the skeleton is the _same change_ across all projects that merge with that skeleton. Without the ancestry, with a traditional copy/paste approach, a [commit like this](https://github.com/jaraco/skeleton/commit/12eed1326e1bc26ce256e7b3f8cd8d3a5beab2d5) would produce notifications in the upstream project issue for each and every application, but because it's centralized, GitHub provides just the one notification when the change is added to the skeleton. # Usage ## new projects To use skeleton for a new project, simply pull the skeleton into a new project: ``` $ git init my-new-project $ cd my-new-project $ git pull gh://jaraco/skeleton ``` Now customize the project to suit your individual project needs. ## existing projects If you have an existing project, you can still incorporate the skeleton by merging it into the codebase. ``` $ git merge skeleton --allow-unrelated-histories ``` The `--allow-unrelated-histories` is necessary because the history from the skeleton was previously unrelated to the existing codebase. Resolve any merge conflicts and commit to the master, and now the project is based on the shared skeleton. ## Updating Whenever a change is needed or desired for the general technique for packaging, it can be made in the skeleton project and then merged into each of the derived projects as needed, recommended before each release. As a result, features and best practices for packaging are centrally maintained and readily trickle into a whole suite of packages. This technique lowers the amount of tedious work necessary to create or maintain a project, and coupled with other techniques like continuous integration and deployment, lowers the cost of creating and maintaining refined Python projects to just a few, familiar git operations. Thereafter, the target project can make whatever customizations it deems relevant to the scaffolding. The project may even at some point decide that the divergence is too great to merit renewed merging with the original skeleton. This approach applies maximal guidance while creating minimal constraints. # Features The features/techniques employed by the skeleton include: - PEP 517/518 based build relying on setuptools as the build tool - setuptools declarative configuration using setup.cfg - tox for running tests - A README.rst as reStructuredText with some popular badges, but with readthedocs and appveyor badges commented out - A CHANGES.rst file intended for publishing release notes about the project - Use of [black](https://black.readthedocs.io/en/stable/) for code formatting (disabled on unsupported Python 3.5 and earlier) ## Packaging Conventions A pyproject.toml is included to enable PEP 517 and PEP 518 compatibility and declares the requirements necessary to build the project on setuptools (a minimum version compatible with setup.cfg declarative config). The setup.cfg file implements the following features: - Assumes universal wheel for release - Advertises the project's LICENSE file (MIT by default) - Reads the README.rst file into the long description - Some common Trove classifiers - Includes all packages discovered in the repo - Data files in the package are also included (not just Python files) - Declares the required Python versions - Declares install requirements (empty by default) - Declares setup requirements for legacy environments - Supplies two 'extras': - testing: requirements for running tests - docs: requirements for building docs - these extras split the declaration into "upstream" (requirements as declared by the skeleton) and "local" (those specific to the local project); these markers help avoid merge conflicts - Placeholder for defining entry points Additionally, the setup.py file declares `use_scm_version` which relies on [setuptools_scm](https://pypi.org/project/setuptools_scm) to do two things: - derive the project version from SCM tags - ensure that all files committed to the repo are automatically included in releases ## Running Tests The skeleton assumes the developer has [tox](https://pypi.org/project/tox) installed. The developer is expected to run `tox` to run tests on the current Python version using [pytest](https://pypi.org/project/pytest). Other environments (invoked with `tox -e {name}`) supplied include: - a `build-docs` environment to build the documentation - a `release` environment to publish the package to PyPI A pytest.ini is included to define common options around running tests. In particular: - rely on default test discovery in the current directory - avoid recursing into common directories not containing tests - run doctests on modules and invoke flake8 tests - in doctests, allow unicode literals and regular literals to match, allowing for doctests to run on Python 2 and 3. Also enable ELLIPSES, a default that would be undone by supplying the prior option. - filters out known warnings caused by libraries/functionality included by the skeleton Relies a .flake8 file to correct some default behaviors: - disable mutually incompatible rules W503 and W504 - support for black format ## Continuous Integration The project is pre-configured to run tests in [Travis-CI](https://travis-ci.org) (.travis.yml). Any new project must be enabled either through their web site or with the `travis enable` command. Features include: - test against Python 2 and 3 - run on Ubuntu Xenial - correct for broken IPv6 Also provided is a minimal template for running under Appveyor (Windows). ### Continuous Deployments In addition to running tests, an additional deploy stage is configured to automatically release tagged commits to PyPI using [API tokens](https://pypi.org/help/#apitoken). The release process expects an authorized token to be configured with Travis as the TWINE_PASSWORD environment variable. After the Travis project is created, configure the token through the web UI or with a command like the following (bash syntax): ``` TWINE_PASSWORD={token} travis env copy TWINE_PASSWORD ``` ## Building Documentation Documentation is automatically built by [Read the Docs](https://readthedocs.org) when the project is registered with it, by way of the .readthedocs.yml file. To test the docs build manually, a tox env may be invoked as `tox -e build-docs`. Both techniques rely on the dependencies declared in `setup.cfg/options.extras_require.docs`. In addition to building the sphinx docs scaffolded in `docs/`, the docs build a `history.html` file that first injects release dates and hyperlinks into the CHANGES.rst before incorporating it as history in the docs. ## Cutting releases By default, tagged commits are released through the continuous integration deploy stage. Releases may also be cut manually by invoking the tox environment `release` with the PyPI token set as the TWINE_PASSWORD: ``` TWINE_PASSWORD={token} tox -e release ``` zipp-1.0.0/test_zipp.py0000664000372000037200000001302713607174340015737 0ustar travistravis00000000000000# coding: utf-8 from __future__ import division, unicode_literals import io import zipfile import posixpath import contextlib import tempfile import shutil try: import pathlib except ImportError: import pathlib2 as pathlib if not hasattr(contextlib, 'ExitStack'): import contextlib2 contextlib.ExitStack = contextlib2.ExitStack try: import unittest unittest.TestCase.subTest except AttributeError: import unittest2 as unittest import zipp __metaclass__ = type consume = tuple def add_dirs(zf): """ Given a writable zip file zf, inject directory entries for any directories implied by the presence of children. """ for name in zipp.Path._implied_dirs(zf.namelist()): zf.writestr(name, b"") return zf def build_alpharep_fixture(): """ Create a zip file with this structure: . ├── a.txt ├── b │ ├── c.txt │ ├── d │ │ └── e.txt │ └── f.txt └── g └── h └── i.txt This fixture has the following key characteristics: - a file at the root (a) - a file two levels deep (b/d/e) - multiple files in a directory (b/c, b/f) - a directory containing only a directory (g/h) "alpha" because it uses alphabet "rep" because it's a representative example """ data = io.BytesIO() zf = zipfile.ZipFile(data, "w") zf.writestr("a.txt", b"content of a") zf.writestr("b/c.txt", b"content of c") zf.writestr("b/d/e.txt", b"content of e") zf.writestr("b/f.txt", b"content of f") zf.writestr("g/h/i.txt", b"content of i") zf.filename = "alpharep.zip" return zf @contextlib.contextmanager def temp_dir(): tmpdir = tempfile.mkdtemp() try: yield pathlib.Path(tmpdir) finally: shutil.rmtree(tmpdir) class TestPath(unittest.TestCase): def setUp(self): self.fixtures = contextlib.ExitStack() self.addCleanup(self.fixtures.close) def zipfile_alpharep(self): with self.subTest(): yield build_alpharep_fixture() with self.subTest(): yield add_dirs(build_alpharep_fixture()) def zipfile_ondisk(self): tmpdir = pathlib.Path(self.fixtures.enter_context(temp_dir())) for alpharep in self.zipfile_alpharep(): buffer = alpharep.fp alpharep.close() path = tmpdir / alpharep.filename with path.open("wb") as strm: strm.write(buffer.getvalue()) yield path def test_iterdir_and_types(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) assert root.is_dir() a, b, g = root.iterdir() assert a.is_file() assert b.is_dir() assert g.is_dir() c, f, d = b.iterdir() assert c.is_file() and f.is_file() e, = d.iterdir() assert e.is_file() h, = g.iterdir() i, = h.iterdir() assert i.is_file() def test_open(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) a, b, g = root.iterdir() with a.open() as strm: data = strm.read() assert data == b"content of a" def test_read(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) a, b, g = root.iterdir() assert a.read_text() == "content of a" assert a.read_bytes() == b"content of a" def test_joinpath(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) a = root.joinpath("a") assert a.is_file() e = root.joinpath("b").joinpath("d").joinpath("e.txt") assert e.read_text() == "content of e" def test_traverse_truediv(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) a = root / "a" assert a.is_file() e = root / "b" / "d" / "e.txt" assert e.read_text() == "content of e" def test_traverse_simplediv(self): """ Disable the __future__.division when testing traversal. """ for alpharep in self.zipfile_alpharep(): code = compile( source="zipp.Path(alpharep) / 'a'", filename="(test)", mode="eval", dont_inherit=True, ) eval(code) def test_pathlike_construction(self): """ zipp.Path should be constructable from a path-like object """ for zipfile_ondisk in self.zipfile_ondisk(): pathlike = pathlib.Path(str(zipfile_ondisk)) zipp.Path(pathlike) def test_traverse_pathlike(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) root / pathlib.Path("a") def test_parent(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) assert (root / 'a').parent.at == '' assert (root / 'a' / 'b').parent.at == 'a/' def test_dir_parent(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) assert (root / 'b').parent.at == '' assert (root / 'b/').parent.at == '' def test_missing_dir_parent(self): for alpharep in self.zipfile_alpharep(): root = zipp.Path(alpharep) assert (root / 'missing dir/').parent.at == '' zipp-1.0.0/tox.ini0000664000372000037200000000121713607174340014655 0ustar travistravis00000000000000[tox] envlist = python minversion = 3.2 # https://github.com/jaraco/skeleton/issues/6 tox_pip_extensions_ext_venv_update = true [testenv] deps = setuptools>=31.0.1 commands = python -m unittest discover usedevelop = True extras = testing [testenv:build-docs] extras = docs testing changedir = docs commands = python -m sphinx . {toxinidir}/build/html [testenv:release] skip_install = True deps = pep517>=0.5 twine>=1.13 path.py passenv = TWINE_PASSWORD setenv = TWINE_USERNAME = {env:TWINE_USERNAME:__token__} commands = python -c "import path; path.Path('dist').rmtree_p()" python -m pep517.build . python -m twine upload dist/* zipp-1.0.0/zipp.egg-info/0000775000372000037200000000000013607174360016017 5ustar travistravis00000000000000zipp-1.0.0/zipp.egg-info/PKG-INFO0000664000372000037200000000305313607174360017115 0ustar travistravis00000000000000Metadata-Version: 2.1 Name: zipp Version: 1.0.0 Summary: Backport of pathlib-compatible object wrapper for zip files Home-page: https://github.com/jaraco/zipp Author: Jason R. Coombs Author-email: jaraco@jaraco.com License: UNKNOWN Description: .. image:: https://img.shields.io/pypi/v/zipp.svg :target: https://pypi.org/project/zipp .. image:: https://img.shields.io/pypi/pyversions/zipp.svg .. image:: https://img.shields.io/travis/jaraco/zipp/master.svg :target: https://travis-ci.org/jaraco/zipp .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: Black .. image:: https://img.shields.io/appveyor/ci/jaraco/zipp/master.svg :target: https://ci.appveyor.com/project/jaraco/zipp/branch/master .. .. image:: https://readthedocs.org/projects/zipp/badge/?version=latest .. :target: https://zipp.readthedocs.io/en/latest/?badge=latest A pathlib-compatible Zipfile object wrapper. A backport of the `Path object `_. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Requires-Python: >=2.7 Provides-Extra: testing Provides-Extra: docs zipp-1.0.0/zipp.egg-info/SOURCES.txt0000664000372000037200000000056713607174360017713 0ustar travistravis00000000000000.flake8 .pre-commit-config.yaml .readthedocs.yml .travis.yml CHANGES.rst LICENSE README.rst appveyor.yml conftest.py pyproject.toml setup.cfg setup.py skeleton.md test_zipp.py tox.ini zipp.py docs/conf.py docs/history.rst docs/index.rst zipp.egg-info/PKG-INFO zipp.egg-info/SOURCES.txt zipp.egg-info/dependency_links.txt zipp.egg-info/requires.txt zipp.egg-info/top_level.txtzipp-1.0.0/zipp.egg-info/dependency_links.txt0000664000372000037200000000000113607174360022065 0ustar travistravis00000000000000 zipp-1.0.0/zipp.egg-info/requires.txt0000664000372000037200000000015613607174360020421 0ustar travistravis00000000000000more_itertools [docs] sphinx jaraco.packaging>=3.2 rst.linker>=1.9 [testing] pathlib2 contextlib2 unittest2 zipp-1.0.0/zipp.egg-info/top_level.txt0000664000372000037200000000000513607174360020544 0ustar travistravis00000000000000zipp zipp-1.0.0/zipp.py0000664000372000037200000001162313607174340014700 0ustar travistravis00000000000000# coding: utf-8 from __future__ import division import io import sys import posixpath import zipfile import functools import itertools import more_itertools __metaclass__ = type def _parents(path): """ Given a path with elements separated by posixpath.sep, generate all parents of that path. >>> list(_parents('b/d')) ['b'] >>> list(_parents('/b/d/')) ['/b'] >>> list(_parents('b/d/f/')) ['b/d', 'b'] >>> list(_parents('b')) [] >>> list(_parents('')) [] """ return itertools.islice(_ancestry(path), 1, None) def _ancestry(path): """ Given a path with elements separated by posixpath.sep, generate all elements of that path >>> list(_ancestry('b/d')) ['b/d', 'b'] >>> list(_ancestry('/b/d/')) ['/b/d', '/b'] >>> list(_ancestry('b/d/f/')) ['b/d/f', 'b/d', 'b'] >>> list(_ancestry('b')) ['b'] >>> list(_ancestry('')) [] """ path = path.rstrip(posixpath.sep) while path and path != posixpath.sep: yield path path, tail = posixpath.split(path) class Path: """ A pathlib-compatible interface for zip files. Consider a zip file with this structure:: . ├── a.txt └── b ├── c.txt └── d └── e.txt >>> data = io.BytesIO() >>> zf = zipfile.ZipFile(data, 'w') >>> zf.writestr('a.txt', 'content of a') >>> zf.writestr('b/c.txt', 'content of c') >>> zf.writestr('b/d/e.txt', 'content of e') >>> zf.filename = 'abcde.zip' Path accepts the zipfile object itself or a filename >>> root = Path(zf) From there, several path operations are available. Directory iteration (including the zip file itself): >>> a, b = root.iterdir() >>> a Path('abcde.zip', 'a.txt') >>> b Path('abcde.zip', 'b/') name property: >>> b.name 'b' join with divide operator: >>> c = b / 'c.txt' >>> c Path('abcde.zip', 'b/c.txt') >>> c.name 'c.txt' Read text: >>> c.read_text() 'content of c' existence: >>> c.exists() True >>> (b / 'missing.txt').exists() False Coercion to string: >>> str(c) 'abcde.zip/b/c.txt' """ __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})" def __init__(self, root, at=""): self.root = ( root if isinstance(root, zipfile.ZipFile) else zipfile.ZipFile(self._pathlib_compat(root)) ) self.at = at @staticmethod def _pathlib_compat(path): """ For path-like objects, convert to a filename for compatibility on Python 3.6.1 and earlier. """ try: return path.__fspath__() except AttributeError: return str(path) @property def open(self): return functools.partial(self.root.open, self.at) @property def name(self): return posixpath.basename(self.at.rstrip("/")) def read_text(self, *args, **kwargs): with self.open() as strm: return io.TextIOWrapper(strm, *args, **kwargs).read() def read_bytes(self): with self.open() as strm: return strm.read() def _is_child(self, path): return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/") def _next(self, at): return Path(self.root, at) def is_dir(self): return not self.at or self.at.endswith("/") def is_file(self): return not self.is_dir() def exists(self): return self.at in self._names() def iterdir(self): if not self.is_dir(): raise ValueError("Can't listdir a file") subs = map(self._next, self._names()) return filter(self._is_child, subs) def __str__(self): return posixpath.join(self.root.filename, self.at) def __repr__(self): return self.__repr.format(self=self) def joinpath(self, add): add = self._pathlib_compat(add) next = posixpath.join(self.at, add) next_dir = posixpath.join(self.at, add, "") names = self._names() return self._next(next_dir if next not in names and next_dir in names else next) __truediv__ = joinpath @staticmethod def _implied_dirs(names): return more_itertools.unique_everseen( parent + "/" for name in names for parent in _parents(name) if parent + "/" not in names ) @classmethod def _add_implied_dirs(cls, names): return names + list(cls._implied_dirs(names)) @property def parent(self): parent_at = posixpath.dirname(self.at.rstrip('/')) if parent_at: parent_at += '/' return self._next(parent_at) def _names(self): return self._add_implied_dirs(self.root.namelist()) if sys.version_info < (3,): __div__ = __truediv__