diff options
author | DongHun Kwak <dh0128.kwak@samsung.com> | 2021-04-05 16:13:24 +0900 |
---|---|---|
committer | DongHun Kwak <dh0128.kwak@samsung.com> | 2021-04-05 16:13:24 +0900 |
commit | 4bcc4a3117927eb1ae028f85d0bdf0df6fe6baff (patch) | |
tree | 273a13b80b38e386afd5998398cfed2157c43713 | |
parent | f40f74f2ace2b27dd83d01abae6e9a1a12ac0351 (diff) | |
download | python3-zipp-4bcc4a3117927eb1ae028f85d0bdf0df6fe6baff.tar.gz python3-zipp-4bcc4a3117927eb1ae028f85d0bdf0df6fe6baff.tar.bz2 python3-zipp-4bcc4a3117927eb1ae028f85d0bdf0df6fe6baff.zip |
Imported Upstream version 3.3.1upstream/3.3.1
-rw-r--r-- | .coveragerc | 5 | ||||
-rw-r--r-- | .flake8 | 9 | ||||
-rw-r--r-- | .github/workflows/main.yml | 42 | ||||
-rw-r--r-- | .pre-commit-config.yaml | 10 | ||||
-rw-r--r-- | .readthedocs.yml | 5 | ||||
-rw-r--r-- | .travis.yml | 19 | ||||
-rw-r--r-- | CHANGES.rst | 162 | ||||
-rw-r--r-- | LICENSE | 19 | ||||
-rw-r--r-- | PKG-INFO | 45 | ||||
-rw-r--r-- | README.rst | 27 | ||||
-rw-r--r-- | appveyor.yml | 24 | ||||
-rw-r--r-- | azure-pipelines.yml | 72 | ||||
-rw-r--r-- | conftest.py | 0 | ||||
-rw-r--r-- | docs/conf.py | 30 | ||||
-rw-r--r-- | docs/history.rst | 8 | ||||
-rw-r--r-- | docs/index.rst | 22 | ||||
-rw-r--r-- | mypy.ini | 2 | ||||
-rw-r--r-- | pyproject.toml | 22 | ||||
-rw-r--r-- | pytest.ini | 9 | ||||
-rw-r--r-- | setup.cfg | 46 | ||||
-rw-r--r-- | setup.py | 6 | ||||
-rw-r--r-- | skeleton.md | 170 | ||||
-rw-r--r-- | test_zipp.py | 354 | ||||
-rw-r--r-- | tox.ini | 39 | ||||
-rw-r--r-- | zipp.egg-info/PKG-INFO | 45 | ||||
-rw-r--r-- | zipp.egg-info/SOURCES.txt | 29 | ||||
-rw-r--r-- | zipp.egg-info/dependency_links.txt | 1 | ||||
-rw-r--r-- | zipp.egg-info/requires.txt | 18 | ||||
-rw-r--r-- | zipp.egg-info/top_level.txt | 1 | ||||
-rw-r--r-- | zipp.py | 314 |
30 files changed, 1555 insertions, 0 deletions
diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..4582306 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,5 @@ +[run] +omit = .tox/* + +[report] +show_missing = True @@ -0,0 +1,9 @@ +[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 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..b3dd81f --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,42 @@ +name: Automated Tests + +on: [push, pull_request] + +jobs: + test: + strategy: + matrix: + python: [3.6, 3.7, 3.8] + platform: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python }} + - name: Install tox + run: | + python -m pip install tox + - name: Run tests + run: tox + + release: + needs: test + if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v1 + with: + python-version: 3.8 + - name: Install tox + run: | + python -m pip install tox + - name: Release + run: tox -e release + env: + TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..6639c78 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,10 @@ +repos: +- repo: https://github.com/psf/black + rev: stable + hooks: + - id: black + +- repo: https://github.com/asottile/blacken-docs + rev: v1.8.0 + hooks: + - id: blacken-docs diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000..8ae4468 --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,5 @@ +python: + version: 3 + extra_requirements: + - docs + pip_install: true diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..eed7b0a --- /dev/null +++ b/.travis.yml @@ -0,0 +1,19 @@ +dist: bionic +language: python + +python: +- 3.6 +- &latest_py3 3.8 + +cache: pip + +install: +# ensure virtualenv is upgraded to avoid issues like jaraco/path#188 +- pip install -U --upgrade-strategy=eager tox + +before_script: + # Enable 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 diff --git a/CHANGES.rst b/CHANGES.rst new file mode 100644 index 0000000..ce08793 --- /dev/null +++ b/CHANGES.rst @@ -0,0 +1,162 @@ +v3.3.1 +====== + +bpo-42043: Add tests capturing subclassing requirements. + +v3.3.0 +====== + +#9: ``Path`` objects now expose a ``.filename`` attribute +and rely on that to resolve ``.name`` and ``.parent`` when +the ``Path`` object is at the root of the zipfile. + +v3.2.0 +====== + +#57 and bpo-40564: Mutate the passed ZipFile object +type instead of making a copy. Prevents issues when +both the local copy and the caller's copy attempt to +close the same file handle. + +#56 and bpo-41035: ``Path._next`` now honors +subclasses. + +#55: ``Path.is_file()`` now returns False for non-existent names. + +v3.1.0 +====== + +#47: ``.open`` now raises ``FileNotFoundError`` and +``IsADirectoryError`` when appropriate. + +v3.0.0 +====== + +#44: Merge with v1.2.0. + +v1.2.0 +====== + +#44: ``zipp.Path.open()`` now supports a compatible signature +as ``pathlib.Path.open()``, accepting text (default) or binary +modes and soliciting keyword parameters passed through to +``io.TextIOWrapper`` (encoding, newline, etc). The stream is +opened in text-mode by default now. ``open`` no +longer accepts ``pwd`` as a positional argument and does not +accept the ``force_zip64`` parameter at all. This change is +a backward-incompatible change for that single function. + +v2.2.1 +====== + +#43: Merge with v1.1.1. + +v1.1.1 +====== + +#43: Restored performance of implicit dir computation. + +v2.2.0 +====== + +#36: Rebuild package with minimum Python version declared both +in package metadata and in the python tag. + +v2.1.0 +====== + +#32: Merge with v1.1.0. + +v1.1.0 +====== + +#32: For read-only zip files, complexity of ``.exists`` and +``joinpath`` is now constant time instead of ``O(n)``, preventing +quadratic time in common use-cases and rendering large +zip files unusable for Path. Big thanks to Benjy Weinberger +for the bug report and contributed fix (#33). + +v2.0.1 +====== + +#30: Corrected version inference (from jaraco/skeleton#12). + +v2.0.0 +====== + +Require Python 3.6 or later. + +v1.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 <https://pypi.org/project/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. @@ -0,0 +1,19 @@ +Copyright 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. diff --git a/PKG-INFO b/PKG-INFO new file mode 100644 index 0000000..cd780e3 --- /dev/null +++ b/PKG-INFO @@ -0,0 +1,45 @@ +Metadata-Version: 2.1 +Name: zipp +Version: 3.3.1 +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: `PyPI link`_ + + .. image:: https://img.shields.io/pypi/pyversions/zipp.svg + :target: `PyPI link`_ + + .. _PyPI link: https://pypi.org/project/zipp + + .. image:: https://dev.azure.com/jaraco/zipp/_apis/build/status/jaraco.zipp?branchName=master + :target: https://dev.azure.com/jaraco/zipp/_build/latest?definitionId=1&branchName=master + + .. 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/psf/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 <https://docs.python.org/3.8/library/zipfile.html#path-objects>`_. + +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.6 +Provides-Extra: testing +Provides-Extra: docs diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..37bf085 --- /dev/null +++ b/README.rst @@ -0,0 +1,27 @@ +.. image:: https://img.shields.io/pypi/v/zipp.svg + :target: `PyPI link`_ + +.. image:: https://img.shields.io/pypi/pyversions/zipp.svg + :target: `PyPI link`_ + +.. _PyPI link: https://pypi.org/project/zipp + +.. image:: https://dev.azure.com/jaraco/zipp/_apis/build/status/jaraco.zipp?branchName=master + :target: https://dev.azure.com/jaraco/zipp/_build/latest?definitionId=1&branchName=master + +.. 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/psf/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 <https://docs.python.org/3.8/library/zipfile.html#path-objects>`_. diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000..c6f46e4 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,24 @@ +environment: + + APPVEYOR: true + + matrix: + - PYTHON: "C:\\Python36-x64" + - PYTHON: "C:\\Python38-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 virtualenv" + - "tox" + +version: '{build}' diff --git a/azure-pipelines.yml b/azure-pipelines.yml new file mode 100644 index 0000000..6d31899 --- /dev/null +++ b/azure-pipelines.yml @@ -0,0 +1,72 @@ +# Create the project in Azure with: +# az devops project create --name $name --organization https://dev.azure.com/$org/ --visibility public +# then configure the pipelines (through web UI) + +trigger: + branches: + include: + - '*' + tags: + include: + - '*' + +pool: + vmImage: $(pool_vm_image) + +variables: +- group: Azure secrets +- name: pool_vm_image + value: Ubuntu-18.04 + +stages: +- stage: Test + jobs: + + - job: 'Test' + strategy: + matrix: + Bionic Python 3.6: + python.version: '3.6' + Bionic Python 3.8: + python.version: '3.8' + Windows Python 3.8: + python.version: '3.8' + pool_vm_image: vs2017-win2016 + Windows Python Prerelease: + python.version: '3.9' + pool_vm_image: vs2017-win2016 + MacOS: + python.version: '3.8' + pool_vm_image: macos-10.15 + + maxParallel: 4 + + steps: + - task: NuGetToolInstaller@1 + displayName: 'Install NuGet' + condition: eq(variables['pool_vm_image'], 'vs2017-win2016') + + - powershell: | + nuget install python -Prerelease -OutputDirectory "$(Build.BinariesDirectory)" -ExcludeVersion -NonInteractive + Write-Host "##vso[task.prependpath]$(Build.BinariesDirectory)\python\tools" + Write-Host "##vso[task.prependpath]$(Build.BinariesDirectory)\python\tools\Scripts" + condition: and(succeeded(), and(eq(variables['python.version'], '3.9'), eq(variables['pool_vm_image'], 'vs2017-win2016'))) + + - task: UsePythonVersion@0 + inputs: + versionSpec: '$(python.version)' + architecture: 'x64' + condition: and(succeeded(), ne(variables['python.version'], '3.9')) + + - script: python -m pip install tox + displayName: 'Install tox' + + - script: | + tox -- --junit-xml=test-results.xml + displayName: 'run tests' + + - task: PublishTestResults@2 + inputs: + testResultsFiles: '**/test-results.xml' + testRunTitle: 'Python $(python.version)' + condition: succeededOrFailed() diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/conftest.py diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..e0e909f --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,30 @@ +#!/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<issue>\d+)', + url='{package_url}/issues/{issue}', + ), + dict( + pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n', + with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n', + ), + dict( + pattern=r'PEP[- ](?P<pep_number>\d+)', + url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/', + ), + dict( + pattern=r'(Python #|bpo-)(?P<python>\d+)', + url='http://bugs.python.org/issue{python}', + ), + ], + ) +} diff --git a/docs/history.rst b/docs/history.rst new file mode 100644 index 0000000..8e21750 --- /dev/null +++ b/docs/history.rst @@ -0,0 +1,8 @@ +:tocdepth: 2 + +.. _changes: + +History +******* + +.. include:: ../CHANGES (links).rst diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..ff49bf9 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,22 @@ +Welcome to zipp documentation! +======================================== + +.. toctree:: + :maxdepth: 1 + + history + + +.. automodule:: zipp + :members: + :undoc-members: + :show-inheritance: + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000..976ba02 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,2 @@ +[mypy] +ignore_missing_imports = True diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..79f088a --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +[build-system] +requires = ["setuptools>=42", "wheel", "setuptools_scm[toml]>=3.4.1"] +build-backend = "setuptools.build_meta" + +[tool.black] +skip-string-normalization = true + +[tool.setuptools_scm] + +# jaraco/skeleton#22 +[tool.jaraco.pytest.plugins.black] +addopts = "--black" + +# jaraco/skeleton#22 +[tool.jaraco.pytest.plugins.mypy] +addopts = "--mypy" + +[tool.jaraco.pytest.plugins.flake8] +addopts = "--flake8" + +[tool.jaraco.pytest.plugins.cov] +addopts = "--cov" diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..d7f0b11 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,9 @@ +[pytest] +norecursedirs=dist build .tox .eggs +addopts=--doctest-modules +doctest_optionflags=ALLOW_UNICODE ELLIPSIS +# workaround for warning pytest-dev/pytest#6178 +junit_family=xunit2 +filterwarnings= + # https://github.com/pytest-dev/pytest/issues/6928 + ignore:direct construction of .*Item has been deprecated:DeprecationWarning diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..acf2d39 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,46 @@ +[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 :: 3 + Programming Language :: Python :: 3 :: Only + +[options] +py_modules = zipp +packages = find: +include_package_data = true +python_requires = >=3.6 +install_requires = +setup_requires = setuptools_scm[toml] >= 3.4.1 + +[options.extras_require] +testing = + pytest >= 3.5, !=3.7.3 + pytest-checkdocs >= 1.2.3 + pytest-flake8 + pytest-black >= 0.3.7; python_implementation != "PyPy" + pytest-cov + pytest-mypy; python_implementation != "PyPy" + jaraco.test >= 3.2.0 + + jaraco.itertools + func-timeout +docs = + sphinx + jaraco.packaging >= 3.2 + rst.linker >= 1.9 + +[options.entry_points] + +[egg_info] +tag_build = +tag_date = 0 + diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..bac24a4 --- /dev/null +++ b/setup.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python + +import setuptools + +if __name__ == "__main__": + setuptools.setup() diff --git a/skeleton.md b/skeleton.md new file mode 100644 index 0000000..c6b0cd0 --- /dev/null +++ b/skeleton.md @@ -0,0 +1,170 @@ +# 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. + +For example, here's a session of the [path project](https://pypi.org/project/path) pulling non-conflicting changes from the skeleton: + +<img src="https://raw.githubusercontent.com/jaraco/skeleton/gh-pages/docs/refresh.svg"> + +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 Read the Docs 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) +- Integrated type checking through [mypy](https://github.com/python/mypy/). + +## 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 `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 on 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 through multiple CI providers. + +### Github Actions + +[Github Actions](https://docs.github.com/en/free-pro-team@latest/actions) are the preferred provider as they provide free, fast, multi-platform services with straightforward configuration. Configured in `.github/workflows`. + +Features include: +- test against multiple Python versions +- run on late (and updated) platform versions +- automated releases of tagged commits + +### Azure Pipelines + +[Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) were adopted for free, fast, multi-platform services. See azure-pipelines.yml for more details. + +Azure Pipelines require many [complicated setup steps](https://github.com/Azure/azure-devops-cli-extension/issues/968) that have not been readily automated. + +Features include: + +- test against multiple Python versions +- run on Ubuntu Bionic + +### Travis CI + +[Travis CI](https://travis-ci.org) is configured through .travis.yml. Any new project must be enabled either through their web site or with the `travis enable` command. + +Features include: +- test against Python 3 +- run on Ubuntu Bionic +- correct for broken IPv6 + +### AppVeyor + +A minimal template for running under AppVeyor (Windows) is provided. + +### Continuous Deployments + +In addition to running tests, an additional publish 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 each Github project (or org) `PYPI_TOKEN` [secret](https://docs.github.com/en/free-pro-team@latest/actions/reference/encrypted-secrets). Example: + +``` +pip-run -q setuptools jaraco.develop -- -m jaraco.develop.add-github-secret PYPI_TOKEN $TOKEN --project org/repo +``` + +<!-- note setuptools is required due to a [bug in munch](https://github.com/Infinidat/munch/issues/67) --> + +## 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 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 +``` diff --git a/test_zipp.py b/test_zipp.py new file mode 100644 index 0000000..f507305 --- /dev/null +++ b/test_zipp.py @@ -0,0 +1,354 @@ +import io +import zipfile +import contextlib +import pathlib +import unittest +import tempfile +import shutil +import string +import functools + +import jaraco.itertools +import func_timeout + +import zipp + +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.CompleteDirs._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) + + +def pass_alpharep(meth): + """ + Given a method, wrap it in a for loop that invokes method + with each subtest. + """ + + @functools.wraps(meth) + def wrapper(self): + for alpharep in self.zipfile_alpharep(): + meth(self, alpharep=alpharep) + + return wrapper + + +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, alpharep): + tmpdir = pathlib.Path(self.fixtures.enter_context(temp_dir())) + buffer = alpharep.fp + alpharep.close() + path = tmpdir / alpharep.filename + with path.open("wb") as strm: + strm.write(buffer.getvalue()) + return path + + @pass_alpharep + def test_iterdir_and_types(self, 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() + + @pass_alpharep + def test_is_file_missing(self, alpharep): + root = zipp.Path(alpharep) + assert not root.joinpath('missing.txt').is_file() + + @pass_alpharep + def test_iterdir_on_file(self, alpharep): + root = zipp.Path(alpharep) + a, b, g = root.iterdir() + with self.assertRaises(ValueError): + a.iterdir() + + @pass_alpharep + def test_subdir_is_dir(self, alpharep): + root = zipp.Path(alpharep) + assert (root / 'b').is_dir() + assert (root / 'b/').is_dir() + assert (root / 'g').is_dir() + assert (root / 'g/').is_dir() + + @pass_alpharep + def test_open(self, alpharep): + root = zipp.Path(alpharep) + a, b, g = root.iterdir() + with a.open() as strm: + data = strm.read() + assert data == "content of a" + + def test_open_write(self): + """ + If the zipfile is open for write, it should be possible to + write bytes or text to it. + """ + zf = zipp.Path(zipfile.ZipFile(io.BytesIO(), mode='w')) + with zf.joinpath('file.bin').open('wb') as strm: + strm.write(b'binary contents') + with zf.joinpath('file.txt').open('w') as strm: + strm.write('text file') + + def test_open_extant_directory(self): + """ + Attempting to open a directory raises IsADirectoryError. + """ + zf = zipp.Path(add_dirs(build_alpharep_fixture())) + with self.assertRaises(IsADirectoryError): + zf.joinpath('b').open() + + @pass_alpharep + def test_open_binary_invalid_args(self, alpharep): + root = zipp.Path(alpharep) + with self.assertRaises(ValueError): + root.joinpath('a.txt').open('rb', encoding='utf-8') + with self.assertRaises(ValueError): + root.joinpath('a.txt').open('rb', 'utf-8') + + def test_open_missing_directory(self): + """ + Attempting to open a missing directory raises FileNotFoundError. + """ + zf = zipp.Path(add_dirs(build_alpharep_fixture())) + with self.assertRaises(FileNotFoundError): + zf.joinpath('z').open() + + @pass_alpharep + def test_read(self, 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" + + @pass_alpharep + def test_joinpath(self, alpharep): + root = zipp.Path(alpharep) + a = root.joinpath("a.txt") + assert a.is_file() + e = root.joinpath("b").joinpath("d").joinpath("e.txt") + assert e.read_text() == "content of e" + + @pass_alpharep + def test_traverse_truediv(self, alpharep): + root = zipp.Path(alpharep) + a = root / "a.txt" + assert a.is_file() + e = root / "b" / "d" / "e.txt" + assert e.read_text() == "content of e" + + @pass_alpharep + def test_traverse_simplediv(self, alpharep): + """ + Disable the __future__.division when testing traversal. + """ + code = compile( + source="zipp.Path(alpharep) / 'a'", + filename="(test)", + mode="eval", + dont_inherit=True, + ) + eval(code) + + @pass_alpharep + def test_pathlike_construction(self, alpharep): + """ + zipp.Path should be constructable from a path-like object + """ + zipfile_ondisk = self.zipfile_ondisk(alpharep) + pathlike = pathlib.Path(str(zipfile_ondisk)) + zipp.Path(pathlike) + + @pass_alpharep + def test_traverse_pathlike(self, alpharep): + root = zipp.Path(alpharep) + root / pathlib.Path("a") + + @pass_alpharep + def test_parent(self, alpharep): + root = zipp.Path(alpharep) + assert (root / 'a').parent.at == '' + assert (root / 'a' / 'b').parent.at == 'a/' + + @pass_alpharep + def test_dir_parent(self, alpharep): + root = zipp.Path(alpharep) + assert (root / 'b').parent.at == '' + assert (root / 'b/').parent.at == '' + + @pass_alpharep + def test_missing_dir_parent(self, alpharep): + root = zipp.Path(alpharep) + assert (root / 'missing dir/').parent.at == '' + + @pass_alpharep + def test_mutability(self, alpharep): + """ + If the underlying zipfile is changed, the Path object should + reflect that change. + """ + root = zipp.Path(alpharep) + a, b, g = root.iterdir() + alpharep.writestr('foo.txt', 'foo') + alpharep.writestr('bar/baz.txt', 'baz') + assert any(child.name == 'foo.txt' for child in root.iterdir()) + assert (root / 'foo.txt').read_text() == 'foo' + (baz,) = (root / 'bar').iterdir() + assert baz.read_text() == 'baz' + + HUGE_ZIPFILE_NUM_ENTRIES = 2 ** 13 + + def huge_zipfile(self): + """Create a read-only zipfile with a huge number of entries entries.""" + strm = io.BytesIO() + zf = zipfile.ZipFile(strm, "w") + for entry in map(str, range(self.HUGE_ZIPFILE_NUM_ENTRIES)): + zf.writestr(entry, entry) + zf.mode = 'r' + return zf + + def test_joinpath_constant_time(self): + """ + Ensure joinpath on items in zipfile is linear time. + """ + root = zipp.Path(self.huge_zipfile()) + entries = jaraco.itertools.Counter(root.iterdir()) + for entry in entries: + entry.joinpath('suffix') + # Check the file iterated all items + assert entries.count == self.HUGE_ZIPFILE_NUM_ENTRIES + + @func_timeout.func_set_timeout(3) + def test_implied_dirs_performance(self): + data = ['/'.join(string.ascii_lowercase + str(n)) for n in range(10000)] + zipp.CompleteDirs._implied_dirs(data) + + @pass_alpharep + def test_read_does_not_close(self, alpharep): + alpharep = self.zipfile_ondisk(alpharep) + with zipfile.ZipFile(alpharep) as file: + for rep in range(2): + zipp.Path(file, 'a.txt').read_text() + + @pass_alpharep + def test_subclass(self, alpharep): + class Subclass(zipp.Path): + pass + + root = Subclass(alpharep) + assert isinstance(root / 'b', Subclass) + + @pass_alpharep + def test_filename(self, alpharep): + root = zipp.Path(alpharep) + assert root.filename == pathlib.Path('alpharep.zip') + + @pass_alpharep + def test_root_name(self, alpharep): + """ + The name of the root should be the name of the zipfile + """ + root = zipp.Path(alpharep) + assert root.name == 'alpharep.zip' == root.filename.name + + @pass_alpharep + def test_root_parent(self, alpharep): + root = zipp.Path(alpharep) + assert root.parent == pathlib.Path('.') + root.root.filename = 'foo/bar.zip' + assert root.parent == pathlib.Path('foo') + + @pass_alpharep + def test_root_unnamed(self, alpharep): + """ + It is an error to attempt to get the name + or parent of an unnamed zipfile. + """ + alpharep.filename = None + root = zipp.Path(alpharep) + with self.assertRaises(TypeError): + root.name + with self.assertRaises(TypeError): + root.parent + + # .name and .parent should still work on subs + sub = root / "b" + assert sub.name == "b" + assert sub.parent + + @pass_alpharep + def test_inheritance(self, alpharep): + cls = type('PathChild', (zipp.Path,), {}) + for alpharep in self.zipfile_alpharep(): + file = cls(alpharep).joinpath('some dir').parent + assert isinstance(file, cls) @@ -0,0 +1,39 @@ +[tox] +envlist = python +minversion = 3.2 +# https://github.com/jaraco/skeleton/issues/6 +tox_pip_extensions_ext_venv_update = true + + +[testenv] +deps = +commands = + pytest {posargs} +usedevelop = True +extras = testing + +[testenv:docs] +extras = + docs + testing +changedir = docs +commands = + python -m sphinx . {toxinidir}/build/html + +[testenv:release] +skip_install = True +deps = + pep517>=0.5 + twine[keyring]>=1.13 + path + jaraco.develop>=7.1 +passenv = + TWINE_PASSWORD + GITHUB_TOKEN +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/* + python -m jaraco.develop.create-github-release diff --git a/zipp.egg-info/PKG-INFO b/zipp.egg-info/PKG-INFO new file mode 100644 index 0000000..cd780e3 --- /dev/null +++ b/zipp.egg-info/PKG-INFO @@ -0,0 +1,45 @@ +Metadata-Version: 2.1 +Name: zipp +Version: 3.3.1 +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: `PyPI link`_ + + .. image:: https://img.shields.io/pypi/pyversions/zipp.svg + :target: `PyPI link`_ + + .. _PyPI link: https://pypi.org/project/zipp + + .. image:: https://dev.azure.com/jaraco/zipp/_apis/build/status/jaraco.zipp?branchName=master + :target: https://dev.azure.com/jaraco/zipp/_build/latest?definitionId=1&branchName=master + + .. 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/psf/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 <https://docs.python.org/3.8/library/zipfile.html#path-objects>`_. + +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.6 +Provides-Extra: testing +Provides-Extra: docs diff --git a/zipp.egg-info/SOURCES.txt b/zipp.egg-info/SOURCES.txt new file mode 100644 index 0000000..5ce9527 --- /dev/null +++ b/zipp.egg-info/SOURCES.txt @@ -0,0 +1,29 @@ +.coveragerc +.flake8 +.pre-commit-config.yaml +.readthedocs.yml +.travis.yml +CHANGES.rst +LICENSE +README.rst +appveyor.yml +azure-pipelines.yml +conftest.py +mypy.ini +pyproject.toml +pytest.ini +setup.cfg +setup.py +skeleton.md +test_zipp.py +tox.ini +zipp.py +.github/workflows/main.yml +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.txt
\ No newline at end of file diff --git a/zipp.egg-info/dependency_links.txt b/zipp.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/zipp.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/zipp.egg-info/requires.txt b/zipp.egg-info/requires.txt new file mode 100644 index 0000000..0f6264a --- /dev/null +++ b/zipp.egg-info/requires.txt @@ -0,0 +1,18 @@ + +[docs] +sphinx +jaraco.packaging>=3.2 +rst.linker>=1.9 + +[testing] +pytest!=3.7.3,>=3.5 +pytest-checkdocs>=1.2.3 +pytest-flake8 +pytest-cov +jaraco.test>=3.2.0 +jaraco.itertools +func-timeout + +[testing:platform_python_implementation != "PyPy"] +pytest-black>=0.3.7 +pytest-mypy diff --git a/zipp.egg-info/top_level.txt b/zipp.egg-info/top_level.txt new file mode 100644 index 0000000..e82f676 --- /dev/null +++ b/zipp.egg-info/top_level.txt @@ -0,0 +1 @@ +zipp @@ -0,0 +1,314 @@ +import io +import posixpath +import zipfile +import itertools +import contextlib +import sys +import pathlib + +if sys.version_info < (3, 7): + from collections import OrderedDict +else: + OrderedDict = dict + + +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) + + +_dedupe = OrderedDict.fromkeys +"""Deduplicate an iterable in original order""" + + +def _difference(minuend, subtrahend): + """ + Return items in minuend not in subtrahend, retaining order + with O(1) lookup. + """ + return itertools.filterfalse(set(subtrahend).__contains__, minuend) + + +class CompleteDirs(zipfile.ZipFile): + """ + A ZipFile subclass that ensures that implied directories + are always included in the namelist. + """ + + @staticmethod + def _implied_dirs(names): + parents = itertools.chain.from_iterable(map(_parents, names)) + as_dirs = (p + posixpath.sep for p in parents) + return _dedupe(_difference(as_dirs, names)) + + def namelist(self): + names = super(CompleteDirs, self).namelist() + return names + list(self._implied_dirs(names)) + + def _name_set(self): + return set(self.namelist()) + + def resolve_dir(self, name): + """ + If the name represents a directory, return that name + as a directory (with the trailing slash). + """ + names = self._name_set() + dirname = name + '/' + dir_match = name not in names and dirname in names + return dirname if dir_match else name + + @classmethod + def make(cls, source): + """ + Given a source (filename or zipfile), return an + appropriate CompleteDirs subclass. + """ + if isinstance(source, CompleteDirs): + return source + + if not isinstance(source, zipfile.ZipFile): + return cls(_pathlib_compat(source)) + + # Only allow for FastLookup when supplied zipfile is read-only + if 'r' not in source.mode: + cls = CompleteDirs + + source.__class__ = cls + return source + + +class FastLookup(CompleteDirs): + """ + ZipFile subclass to ensure implicit + dirs exist and are resolved rapidly. + """ + + def namelist(self): + with contextlib.suppress(AttributeError): + return self.__names + self.__names = super(FastLookup, self).namelist() + return self.__names + + def _name_set(self): + with contextlib.suppress(AttributeError): + return self.__lookup + self.__lookup = super(FastLookup, self)._name_set() + return self.__lookup + + +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) + + +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 = 'mem/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('mem/abcde.zip', 'a.txt') + >>> b + Path('mem/abcde.zip', 'b/') + + name property: + + >>> b.name + 'b' + + join with divide operator: + + >>> c = b / 'c.txt' + >>> c + Path('mem/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: + + >>> import os + >>> str(c).replace(os.sep, posixpath.sep) + 'mem/abcde.zip/b/c.txt' + + At the root, ``name``, ``filename``, and ``parent`` + resolve to the zipfile. Note these attributes are not + valid and will raise a ``ValueError`` if the zipfile + has no filename. + + >>> root.name + 'abcde.zip' + >>> str(root.filename).replace(os.sep, posixpath.sep) + 'mem/abcde.zip' + >>> str(root.parent) + 'mem' + """ + + __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})" + + def __init__(self, root, at=""): + """ + Construct a Path from a ZipFile or filename. + + Note: When the source is an existing ZipFile object, + its type (__class__) will be mutated to a + specialized type. If the caller wishes to retain the + original type, the caller should either create a + separate ZipFile object or pass a filename. + """ + self.root = FastLookup.make(root) + self.at = at + + def open(self, mode='r', *args, pwd=None, **kwargs): + """ + Open this entry as text or binary following the semantics + of ``pathlib.Path.open()`` by passing arguments through + to io.TextIOWrapper(). + """ + if self.is_dir(): + raise IsADirectoryError(self) + zip_mode = mode[0] + if not self.exists() and zip_mode == 'r': + raise FileNotFoundError(self) + stream = self.root.open(self.at, zip_mode, pwd=pwd) + if 'b' in mode: + if args or kwargs: + raise ValueError("encoding args invalid for binary operation") + return stream + return io.TextIOWrapper(stream, *args, **kwargs) + + @property + def name(self): + return pathlib.Path(self.at).name or self.filename.name + + @property + def filename(self): + return pathlib.Path(self.root.filename).joinpath(self.at) + + def read_text(self, *args, **kwargs): + with self.open('r', *args, **kwargs) as strm: + return strm.read() + + def read_bytes(self): + with self.open('rb') as strm: + return strm.read() + + def _is_child(self, path): + return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/") + + def _next(self, at): + return self.__class__(self.root, at) + + def is_dir(self): + return not self.at or self.at.endswith("/") + + def is_file(self): + return self.exists() and not self.is_dir() + + def exists(self): + return self.at in self.root._name_set() + + def iterdir(self): + if not self.is_dir(): + raise ValueError("Can't listdir a file") + subs = map(self._next, self.root.namelist()) + 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): + next = posixpath.join(self.at, _pathlib_compat(add)) + return self._next(self.root.resolve_dir(next)) + + __truediv__ = joinpath + + @property + def parent(self): + if not self.at: + return self.filename.parent + parent_at = posixpath.dirname(self.at.rstrip('/')) + if parent_at: + parent_at += '/' + return self._next(parent_at) |