pax_global_header00006660000000000000000000000064132562363630014523gustar00rootroot0000000000000052 comment=b82eeaa35ca587a5446dc3fb16a9d54657390075 path.py-11.0.1/000077500000000000000000000000001325623636300131665ustar00rootroot00000000000000path.py-11.0.1/.flake8000066400000000000000000000000341325623636300143360ustar00rootroot00000000000000[flake8] ignore = W191,W503 path.py-11.0.1/.gitignore000066400000000000000000000001171325623636300151550ustar00rootroot00000000000000__pycache__ *.pyc *.egg-info *.egg .eggs/ MANIFEST build dist .tox docs/_build path.py-11.0.1/.readthedocs.yml000066400000000000000000000001121325623636300162460ustar00rootroot00000000000000python: version: 3 extra_requirements: - docs pip_install: true path.py-11.0.1/.travis.yml000066400000000000000000000012431325623636300152770ustar00rootroot00000000000000dist: trusty sudo: false language: python python: - 2.7 - 3.4 - &latest_py3 3.6 jobs: fast_finish: true include: - stage: deploy if: tag IS present python: *latest_py3 install: skip script: skip deploy: provider: pypi on: tags: true all_branches: true user: jaraco password: secure: fggUs33qP6DB+j/q7KGScfohgGq7OwsW5BMW6ZZvSlq+9pnNDZxSVrfCw0wb9vdq/Hb9nH4Of+wDoyh+Ul6GN28GRX7qj1HTjbc65nhRp9aA1Ib9Y3KJwGR8k5gPJZmx/zKP0r7COSXsOdXDkVSJ/UjCfuKhcsSHpi0lAYG6BSA= distributions: dists skip_cleanup: true skip_upload_docs: true cache: pip install: - pip install tox tox-venv script: tox path.py-11.0.1/CHANGES.rst000066400000000000000000000220411325623636300147670ustar00rootroot0000000000000011.0.1 ------ - #136: Fixed test failures on BSD. - Refreshed package metadata. 11.0 ---- - Drop support for Python 3.3. 10.6 ---- - Renamed ``namebase`` to ``stem`` to match API of pathlib. Kept ``namebase`` as a deprecated alias for compatibility. - Added new ``with_suffix`` method, useful for renaming the extension on a Path:: orig = Path('mydir/mypath.bat') renamed = orig.rename(orig.with_suffix('.cmd')) 10.5 ---- - Packaging refresh and readme updates. 10.4 ---- - #130: Removed surrogate_escape handler as it's no longer used. 10.3.1 ------ - #124: Fixed ``rmdir_p`` raising ``FileNotFoundError`` when directory does not exist on Windows. 10.3 ---- - #115: Added a new performance-optimized implementation for listdir operations, optimizing ``listdir``, ``walk``, ``walkfiles``, ``walkdirs``, and ``fnmatch``, presented as the ``FastPath`` class. Please direct feedback on this implementation to the ticket, especially if the performance benefits justify it replacing the default ``Path`` class. 10.2 ---- - Symlink no longer requires the ``newlink`` parameter and will default to the basename of the target in the current working directory. 10.1 ---- - #123: Implement ``Path.__fspath__`` per PEP 519. 10.0 ---- - Once again as in 8.0 remove deprecated ``path.path``. 9.1 --- - #121: Removed workaround for #61 added in 5.2. ``path.py`` now only supports file system paths that can be effectively decoded to text. It is the responsibility of the system implementer to ensure that filenames on the system are decodeable by ``sys.getfilesystemencoding()``. 9.0 --- - Drop support for Python 2.6 and 3.2 as integration dependencies (pip) no longer support these versions. 8.3 --- - Merge with latest skeleton, adding badges and test runs by default under tox instead of pytest-runner. - Documentation is no longer hosted with PyPI. 8.2.1 ----- - #112: Update Travis CI usage to only deploy on Python 3.5. 8.2 --- - Refreshed project metadata based on `jaraco's project skeleton _. - Releases are now automatically published via Travis-CI. - #111: More aggressively trap errors when importing ``pkg_resources``. 8.1.2 ----- - #105: By using unicode literals, avoid errors rendering the backslash in __get_owner_windows. 8.1.1 ----- - #102: Reluctantly restored reference to path.path in ``__all__``. 8.1 --- - #102: Restored ``path.path`` with a DeprecationWarning. 8.0 --- Removed ``path.path``. Clients must now refer to the canonical name, ``path.Path`` as introduced in 6.2. 7.7 --- - #88: Added support for resolving certain directories on a system to platform-friendly locations using the `appdirs `_ library. The ``Path.special`` method returns an ``SpecialResolver`` instance that will resolve a path in a scope (i.e. 'site' or 'user') and class (i.e. 'config', 'cache', 'data'). For example, to create a config directory for "My App":: config_dir = Path.special("My App").user.config.makedirs_p() ``config_dir`` will exist in a user context and will be in a suitable platform-friendly location. As ``path.py`` does not currently have any dependencies, and to retain that expectation for a compatible upgrade path, ``appdirs`` must be installed to avoid an ImportError when invoking ``special``. - #88: In order to support "multipath" results, where multiple paths are returned in a single, ``os.pathsep``-separated string, a new class MultiPath now represents those special results. This functionality is experimental and may change. Feedback is invited. 7.6.2 ----- - Re-release of 7.6.1 without unintended feature. 7.6.1 ----- - #101: Supress error when `path.py` is not present as a distribution. 7.6 --- - Pull Request #100: Add ``merge_tree`` method for merging two existing directory trees. - Uses `setuptools_scm `_ for version management. 7.5 --- - #97: ``__rdiv__`` and ``__rtruediv__`` are now defined. 7.4 --- - #93: chown now appears in docs and raises NotImplementedError if ``os.chown`` isn't present. - #92: Added compatibility support for ``.samefile`` on platforms without ``os.samefile``. 7.3 --- - #91: Releases now include a universal wheel. 7.2 --- - In chmod, added support for multiple symbolic masks (separated by commas). - In chmod, fixed issue in setting of symbolic mask with '=' where unreferenced permissions were cleared. 7.1 --- - #23: Added support for symbolic masks to ``.chmod``. 7.0 --- - The ``open`` method now uses ``io.open`` and supports all of the parameters to that function. ``open`` will always raise an ``OSError`` on failure, even on Python 2. - Updated ``write_text`` to support additional newline patterns. - The ``text`` method now always returns text (never bytes), and thus requires an encoding parameter be supplied if the default encoding is not sufficient to decode the content of the file. 6.2 --- - ``path`` class renamed to ``Path``. The ``path`` name remains as an alias for compatibility. 6.1 --- - ``chown`` now accepts names in addition to numeric IDs. 6.0 --- - Drop support for Python 2.5. Python 2.6 or later required. - Installation now requires setuptools. 5.3 --- - Allow arbitrary callables to be passed to path.walk ``errors`` parameter. Enables workaround for issues such as #73 and #56. 5.2 --- - #61: path.listdir now decodes filenames from os.listdir when loading characters from a file. On Python 3, the behavior is unchanged. On Python 2, the behavior will now mimick that of Python 3, attempting to decode all filenames and paths using the encoding indicated by ``sys.getfilesystemencoding()``, and escaping any undecodable characters using the 'surrogateescape' handler. 5.1 --- - #53: Added ``path.in_place`` for editing files in place. 5.0 --- - ``path.fnmatch`` now takes an optional parameter ``normcase`` and this parameter defaults to self.module.normcase (using case normalization most pertinent to the path object itself). Note that this change means that any paths using a custom ntpath module on non-Windows systems will have different fnmatch behavior. Before:: # on Unix >>> p = path('Foo') >>> p.module = ntpath >>> p.fnmatch('foo') False After:: # on any OS >>> p = path('Foo') >>> p.module = ntpath >>> p.fnmatch('foo') True To maintain the original behavior, either don't define the 'module' for the path or supply explicit normcase function:: >>> p.fnmatch('foo', normcase=os.path.normcase) # result always varies based on OS, same as fnmatch.fnmatch For most use-cases, the default behavior should remain the same. - Issue #50: Methods that accept patterns (``listdir``, ``files``, ``dirs``, ``walk``, ``walkdirs``, ``walkfiles``, and ``fnmatch``) will now use a ``normcase`` attribute if it is present on the ``pattern`` parameter. The path module now provides a ``CaseInsensitivePattern`` wrapper for strings suitable for creating case-insensitive patterns for those methods. 4.4 --- - Issue #44: _hash method would open files in text mode, producing invalid results on Windows. Now files are opened in binary mode, producing consistent results. - Issue #47: Documentation is dramatically improved with Intersphinx links to the Python os.path functions and documentation for all methods and properties. 4.3 --- - Issue #32: Add ``chdir`` and ``cd`` methods. 4.2 --- - ``open()`` now passes all positional and keyword arguments through to the underlying ``builtins.open`` call. 4.1 --- - Native Python 2 and Python 3 support without using 2to3 during the build process. 4.0 --- - Added a ``chunks()`` method to a allow quick iteration over pieces of a file at a given path. - Issue #28: Fix missing argument to ``samefile``. - Initializer no longer enforces `isinstance basestring` for the source object. Now any object that supplies ``__unicode__`` can be used by a ``path`` (except None). Clients that depend on a ValueError being raised for ``int`` and other non-string objects should trap these types internally. - Issue #30: ``chown`` no longer requires both uid and gid to be provided and will not mutate the ownership if nothing is provided. 3.2 --- - Issue #22: ``__enter__`` now returns self. 3.1 --- - Issue #20: `relpath` now supports a "start" parameter to match the signature of `os.path.relpath`. 3.0 --- - Minimum Python version is now 2.5. 2.6 --- - Issue #5: Implemented `path.tempdir`, which returns a path object which is a temporary directory and context manager for cleaning up the directory. - Issue #12: One can now construct path objects from a list of strings by simply using path.joinpath. For example:: path.joinpath('a', 'b', 'c') # or path.joinpath(*path_elements) 2.5 --- - Issue #7: Add the ability to do chaining of operations that formerly only returned None. - Issue #4: Raise a TypeError when constructed from None. path.py-11.0.1/LICENSE000066400000000000000000000020321325623636300141700ustar00rootroot00000000000000Copyright 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. path.py-11.0.1/MANIFEST.in000066400000000000000000000000161325623636300147210ustar00rootroot00000000000000include *.rst path.py-11.0.1/README.rst000066400000000000000000000072421325623636300146620ustar00rootroot00000000000000.. image:: https://img.shields.io/pypi/v/path.py.svg :target: https://pypi.org/project/path.py .. image:: https://img.shields.io/pypi/pyversions/path.py.svg .. image:: https://img.shields.io/travis/jaraco/path.py/master.svg :target: https://travis-ci.org/jaraco/path.py .. image:: https://img.shields.io/appveyor/ci/jaraco/path.py/master.svg :target: https://ci.appveyor.com/project/jaraco/path.py/branch/master .. image:: https://readthedocs.org/projects/pathpy/badge/?version=latest :target: https://pathpy.readthedocs.io/en/latest/?badge=latest ``path.py`` implements path objects as first-class entities, allowing common operations on files to be invoked on those path objects directly. For example: .. code-block:: python from path import Path d = Path('/home/guido/bin') for f in d.files('*.py'): f.chmod(0o755) ``path.py`` is `hosted at Github `_. Find `the documentation here `_. Guides and Testimonials ======================= Yasoob wrote the Python 101 `Writing a Cleanup Script `_ based on ``path.py``. Installing ========== Path.py may be installed using ``setuptools``, ``distribute``, or ``pip``:: pip install path.py The latest release is always updated to the `Python Package Index `_. You may also always download the source distribution (zip/tarball), extract it, and run ``python setup.py`` to install it. Advantages ========== Python 3.4 introduced `pathlib `_, which shares many characteristics with ``path.py``. In particular, it provides an object encapsulation for representing filesystem paths. One may have imagined ``pathlib`` would supersede ``path.py``. But the implementation and the usage quickly diverge, and ``path.py`` has several advantages over ``pathlib``: - ``path.py`` implements ``Path`` objects as a subclass of ``str`` (unicode on Python 2), and as a result these ``Path`` objects may be passed directly to other APIs that expect simple text representations of paths, whereas with ``pathlib``, one must first cast values to strings before passing them to APIs unaware of ``pathlib``. - ``path.py`` goes beyond exposing basic functionality of a path and exposes commonly-used behaviors on a path, providing methods like ``rmtree`` (from shlib) and ``remove_p`` (remove a file if it exists). - As a PyPI-hosted package, ``path.py`` is free to iterate faster than a stdlib package. Contributions are welcome and encouraged. Alternatives ============ In addition to `pathlib `_, the `pylib project `_ implements a `LocalPath `_ class, which shares some behaviors and interfaces with ``path.py``. Development =========== To install a development version, use the Github links to clone or download a snapshot of the latest code. Alternatively, if you have git installed, you may be able to use ``pip`` to install directly from the repository:: pip install git+https://github.com/jaraco/path.py.git Testing ======= Tests are continuously run by Travis-CI: |BuildStatus|_ .. |BuildStatus| image:: https://secure.travis-ci.org/jaraco/path.py.png .. _BuildStatus: http://travis-ci.org/jaraco/path.py To run the tests, refer to the ``.travis.yml`` file for the steps run on the Travis-CI hosts. Releasing ========= Tagged releases are automatically published to PyPI by Travis-CI, assuming the tests pass. path.py-11.0.1/appveyor.yml000066400000000000000000000007061325623636300155610ustar00rootroot00000000000000environment: 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 tox tox-venv" - "tox" version: '{build}' path.py-11.0.1/docs/000077500000000000000000000000001325623636300141165ustar00rootroot00000000000000path.py-11.0.1/docs/Makefile000066400000000000000000000151551325623636300155650ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = -W SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pathpy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pathpy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/pathpy" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pathpy" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." path.py-11.0.1/docs/api.rst000066400000000000000000000002551325623636300154230ustar00rootroot00000000000000=== API === .. important:: The documented methods' signatures are not always correct. See :class:`path.Path`. .. automodule:: path :members: :undoc-members: path.py-11.0.1/docs/conf.py000066400000000000000000000023341325623636300154170ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- extensions = [ 'sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker', 'sphinx.ext.intersphinx', ] pygments_style = 'sphinx' html_theme = 'alabaster' html_static_path = ['_static'] htmlhelp_basename = 'pathpydoc' templates_path = ['_templates'] exclude_patterns = ['_build'] source_suffix = '.rst' master_doc = 'index' intersphinx_mapping = {'python': ('http://docs.python.org/', None)} link_files = { '../CHANGES.rst': dict( using=dict( GH='https://github.com', ), replace=[ dict( pattern=r'(Issue )?#(?P\d+)', url='{package_url}/issues/{issue}', ), dict( pattern=r"Pull Request ?#(?P\d+)", url='{package_url}/pull/{pull_request}', ), 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}/', ), ], ), } path.py-11.0.1/docs/history.rst000066400000000000000000000001211325623636300163430ustar00rootroot00000000000000:tocdepth: 1 .. _changes: History ******* .. include:: ../CHANGES (links).rst path.py-11.0.1/docs/index.rst000066400000000000000000000003431325623636300157570ustar00rootroot00000000000000Welcome to path.py's documentation! =================================== Contents: .. toctree:: :maxdepth: 1 api history Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` path.py-11.0.1/path.py000066400000000000000000001713551325623636300145100ustar00rootroot00000000000000# # Copyright (c) 2010 Mikhail Gusarov # # 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. # """ path.py - An object representing a path to a file or directory. https://github.com/jaraco/path.py Example:: from path import Path d = Path('/home/guido/bin') for f in d.files('*.py'): f.chmod(0o755) """ from __future__ import unicode_literals import sys import warnings import os import fnmatch import glob import shutil import hashlib import errno import tempfile import functools import operator import re import contextlib import io import distutils.dir_util import importlib import itertools try: import win32security except ImportError: pass try: import pwd except ImportError: pass try: import grp except ImportError: pass ############################################################################## # Python 2/3 support PY3 = sys.version_info >= (3,) PY2 = not PY3 string_types = str, text_type = str getcwdu = os.getcwd if PY2: import __builtin__ string_types = __builtin__.basestring, text_type = __builtin__.unicode getcwdu = os.getcwdu map = itertools.imap @contextlib.contextmanager def io_error_compat(): try: yield except IOError as io_err: # On Python 2, io.open raises IOError; transform to OSError for # future compatibility. os_err = OSError(*io_err.args) os_err.filename = getattr(io_err, 'filename', None) raise os_err ############################################################################## __all__ = ['Path', 'CaseInsensitivePattern'] LINESEPS = ['\r\n', '\r', '\n'] U_LINESEPS = LINESEPS + ['\u0085', '\u2028', '\u2029'] NEWLINE = re.compile('|'.join(LINESEPS)) U_NEWLINE = re.compile('|'.join(U_LINESEPS)) NL_END = re.compile(r'(?:{0})$'.format(NEWLINE.pattern)) U_NL_END = re.compile(r'(?:{0})$'.format(U_NEWLINE.pattern)) try: import pkg_resources __version__ = pkg_resources.require('path.py')[0].version except Exception: __version__ = 'unknown' class TreeWalkWarning(Warning): pass # from jaraco.functools def compose(*funcs): compose_two = lambda f1, f2: lambda *args, **kwargs: f1(f2(*args, **kwargs)) # noqa return functools.reduce(compose_two, funcs) def simple_cache(func): """ Save results for the :meth:'path.using_module' classmethod. When Python 3.2 is available, use functools.lru_cache instead. """ saved_results = {} def wrapper(cls, module): if module in saved_results: return saved_results[module] saved_results[module] = func(cls, module) return saved_results[module] return wrapper class ClassProperty(property): def __get__(self, cls, owner): return self.fget.__get__(None, owner)() class multimethod(object): """ Acts like a classmethod when invoked from the class and like an instancemethod when invoked from the instance. """ def __init__(self, func): self.func = func def __get__(self, instance, owner): return ( functools.partial(self.func, owner) if instance is None else functools.partial(self.func, owner, instance) ) class Path(text_type): """ Represents a filesystem path. For documentation on individual methods, consult their counterparts in :mod:`os.path`. Some methods are additionally included from :mod:`shutil`. The functions are linked directly into the class namespace such that they will be bound to the Path instance. For example, ``Path(src).copy(target)`` is equivalent to ``shutil.copy(src, target)``. Therefore, when referencing the docs for these methods, assume `src` references `self`, the Path instance. """ module = os.path """ The path module to use for path operations. .. seealso:: :mod:`os.path` """ def __init__(self, other=''): if other is None: raise TypeError("Invalid initial value for path: None") @classmethod @simple_cache def using_module(cls, module): subclass_name = cls.__name__ + '_' + module.__name__ if PY2: subclass_name = str(subclass_name) bases = (cls,) ns = {'module': module} return type(subclass_name, bases, ns) @ClassProperty @classmethod def _next_class(cls): """ What class should be used to construct new instances from this class """ return cls # --- Special Python methods. def __repr__(self): return '%s(%s)' % (type(self).__name__, super(Path, self).__repr__()) # Adding a Path and a string yields a Path. def __add__(self, more): try: return self._next_class(super(Path, self).__add__(more)) except TypeError: # Python bug return NotImplemented def __radd__(self, other): if not isinstance(other, string_types): return NotImplemented return self._next_class(other.__add__(self)) # The / operator joins Paths. def __div__(self, rel): """ fp.__div__(rel) == fp / rel == fp.joinpath(rel) Join two path components, adding a separator character if needed. .. seealso:: :func:`os.path.join` """ return self._next_class(self.module.join(self, rel)) # Make the / operator work even when true division is enabled. __truediv__ = __div__ # The / operator joins Paths the other way around def __rdiv__(self, rel): """ fp.__rdiv__(rel) == rel / fp Join two path components, adding a separator character if needed. .. seealso:: :func:`os.path.join` """ return self._next_class(self.module.join(rel, self)) # Make the / operator work even when true division is enabled. __rtruediv__ = __rdiv__ def __enter__(self): self._old_dir = self.getcwd() os.chdir(self) return self def __exit__(self, *_): os.chdir(self._old_dir) def __fspath__(self): return self @classmethod def getcwd(cls): """ Return the current working directory as a path object. .. seealso:: :func:`os.getcwdu` """ return cls(getcwdu()) # # --- Operations on Path strings. def abspath(self): """ .. seealso:: :func:`os.path.abspath` """ return self._next_class(self.module.abspath(self)) def normcase(self): """ .. seealso:: :func:`os.path.normcase` """ return self._next_class(self.module.normcase(self)) def normpath(self): """ .. seealso:: :func:`os.path.normpath` """ return self._next_class(self.module.normpath(self)) def realpath(self): """ .. seealso:: :func:`os.path.realpath` """ return self._next_class(self.module.realpath(self)) def expanduser(self): """ .. seealso:: :func:`os.path.expanduser` """ return self._next_class(self.module.expanduser(self)) def expandvars(self): """ .. seealso:: :func:`os.path.expandvars` """ return self._next_class(self.module.expandvars(self)) def dirname(self): """ .. seealso:: :attr:`parent`, :func:`os.path.dirname` """ return self._next_class(self.module.dirname(self)) def basename(self): """ .. seealso:: :attr:`name`, :func:`os.path.basename` """ return self._next_class(self.module.basename(self)) def expand(self): """ Clean up a filename by calling :meth:`expandvars()`, :meth:`expanduser()`, and :meth:`normpath()` on it. This is commonly everything needed to clean up a filename read from a configuration file, for example. """ return self.expandvars().expanduser().normpath() @property def stem(self): """ The same as :meth:`name`, but with one file extension stripped off. >>> Path('/home/guido/python.tar.gz').stem 'python.tar' """ base, ext = self.module.splitext(self.name) return base @property def namebase(self): warnings.warn("Use .stem instead of .namebase", DeprecationWarning) return self.stem @property def ext(self): """ The file extension, for example ``'.py'``. """ f, ext = self.module.splitext(self) return ext def with_suffix(self, suffix): """ Return a new path with the file suffix changed (or added, if none) >>> Path('/home/guido/python.tar.gz').with_suffix(".foo") Path('/home/guido/python.tar.foo') >>> Path('python').with_suffix('.zip') Path('python.zip') >>> Path('filename.ext').with_suffix('zip') Traceback (most recent call last): ... ValueError: Invalid suffix 'zip' """ if not suffix.startswith('.'): raise ValueError("Invalid suffix {suffix!r}".format(**locals())) return self.stripext() + suffix @property def drive(self): """ The drive specifier, for example ``'C:'``. This is always empty on systems that don't use drive specifiers. """ drive, r = self.module.splitdrive(self) return self._next_class(drive) parent = property( dirname, None, None, """ This path's parent directory, as a new Path object. For example, ``Path('/usr/local/lib/libpython.so').parent == Path('/usr/local/lib')`` .. seealso:: :meth:`dirname`, :func:`os.path.dirname` """) name = property( basename, None, None, """ The name of this file or directory without the full path. For example, ``Path('/usr/local/lib/libpython.so').name == 'libpython.so'`` .. seealso:: :meth:`basename`, :func:`os.path.basename` """) def splitpath(self): """ p.splitpath() -> Return ``(p.parent, p.name)``. .. seealso:: :attr:`parent`, :attr:`name`, :func:`os.path.split` """ parent, child = self.module.split(self) return self._next_class(parent), child def splitdrive(self): """ p.splitdrive() -> Return ``(p.drive, )``. Split the drive specifier from this path. If there is no drive specifier, :samp:`{p.drive}` is empty, so the return value is simply ``(Path(''), p)``. This is always the case on Unix. .. seealso:: :func:`os.path.splitdrive` """ drive, rel = self.module.splitdrive(self) return self._next_class(drive), rel def splitext(self): """ p.splitext() -> Return ``(p.stripext(), p.ext)``. Split the filename extension from this path and return the two parts. Either part may be empty. The extension is everything from ``'.'`` to the end of the last path segment. This has the property that if ``(a, b) == p.splitext()``, then ``a + b == p``. .. seealso:: :func:`os.path.splitext` """ filename, ext = self.module.splitext(self) return self._next_class(filename), ext def stripext(self): """ p.stripext() -> Remove one file extension from the path. For example, ``Path('/home/guido/python.tar.gz').stripext()`` returns ``Path('/home/guido/python.tar')``. """ return self.splitext()[0] def splitunc(self): """ .. seealso:: :func:`os.path.splitunc` """ unc, rest = self.module.splitunc(self) return self._next_class(unc), rest @property def uncshare(self): """ The UNC mount point for this path. This is empty for paths on local drives. """ unc, r = self.module.splitunc(self) return self._next_class(unc) @multimethod def joinpath(cls, first, *others): """ Join first to zero or more :class:`Path` components, adding a separator character (:samp:`{first}.module.sep`) if needed. Returns a new instance of :samp:`{first}._next_class`. .. seealso:: :func:`os.path.join` """ if not isinstance(first, cls): first = cls(first) return first._next_class(first.module.join(first, *others)) def splitall(self): r""" Return a list of the path components in this path. The first item in the list will be a Path. Its value will be either :data:`os.curdir`, :data:`os.pardir`, empty, or the root directory of this path (for example, ``'/'`` or ``'C:\\'``). The other items in the list will be strings. ``path.Path.joinpath(*result)`` will yield the original path. """ parts = [] loc = self while loc != os.curdir and loc != os.pardir: prev = loc loc, child = prev.splitpath() if loc == prev: break parts.append(child) parts.append(loc) parts.reverse() return parts def relpath(self, start='.'): """ Return this path as a relative path, based from `start`, which defaults to the current working directory. """ cwd = self._next_class(start) return cwd.relpathto(self) def relpathto(self, dest): """ Return a relative path from `self` to `dest`. If there is no relative path from `self` to `dest`, for example if they reside on different drives in Windows, then this returns ``dest.abspath()``. """ origin = self.abspath() dest = self._next_class(dest).abspath() orig_list = origin.normcase().splitall() # Don't normcase dest! We want to preserve the case. dest_list = dest.splitall() if orig_list[0] != self.module.normcase(dest_list[0]): # Can't get here from there. return dest # Find the location where the two paths start to differ. i = 0 for start_seg, dest_seg in zip(orig_list, dest_list): if start_seg != self.module.normcase(dest_seg): break i += 1 # Now i is the point where the two paths diverge. # Need a certain number of "os.pardir"s to work up # from the origin to the point of divergence. segments = [os.pardir] * (len(orig_list) - i) # Need to add the diverging part of dest_list. segments += dest_list[i:] if len(segments) == 0: # If they happen to be identical, use os.curdir. relpath = os.curdir else: relpath = self.module.join(*segments) return self._next_class(relpath) # --- Listing, searching, walking, and matching def listdir(self, pattern=None): """ D.listdir() -> List of items in this directory. Use :meth:`files` or :meth:`dirs` instead if you want a listing of just files or just subdirectories. The elements of the list are Path objects. With the optional `pattern` argument, this only lists items whose names match the given pattern. .. seealso:: :meth:`files`, :meth:`dirs` """ if pattern is None: pattern = '*' return [ self / child for child in os.listdir(self) if self._next_class(child).fnmatch(pattern) ] def dirs(self, pattern=None): """ D.dirs() -> List of this directory's subdirectories. The elements of the list are Path objects. This does not walk recursively into subdirectories (but see :meth:`walkdirs`). With the optional `pattern` argument, this only lists directories whose names match the given pattern. For example, ``d.dirs('build-*')``. """ return [p for p in self.listdir(pattern) if p.isdir()] def files(self, pattern=None): """ D.files() -> List of the files in this directory. The elements of the list are Path objects. This does not walk into subdirectories (see :meth:`walkfiles`). With the optional `pattern` argument, this only lists files whose names match the given pattern. For example, ``d.files('*.pyc')``. """ return [p for p in self.listdir(pattern) if p.isfile()] def walk(self, pattern=None, errors='strict'): """ D.walk() -> iterator over files and subdirs, recursively. The iterator yields Path objects naming each child item of this directory and its descendants. This requires that ``D.isdir()``. This performs a depth-first traversal of the directory tree. Each directory is returned just before all its children. The `errors=` keyword argument controls behavior when an error occurs. The default is ``'strict'``, which causes an exception. Other allowed values are ``'warn'`` (which reports the error via :func:`warnings.warn()`), and ``'ignore'``. `errors` may also be an arbitrary callable taking a msg parameter. """ class Handlers: def strict(msg): raise def warn(msg): warnings.warn(msg, TreeWalkWarning) def ignore(msg): pass if not callable(errors) and errors not in vars(Handlers): raise ValueError("invalid errors parameter") errors = vars(Handlers).get(errors, errors) try: childList = self.listdir() except Exception: exc = sys.exc_info()[1] tmpl = "Unable to list directory '%(self)s': %(exc)s" msg = tmpl % locals() errors(msg) return for child in childList: if pattern is None or child.fnmatch(pattern): yield child try: isdir = child.isdir() except Exception: exc = sys.exc_info()[1] tmpl = "Unable to access '%(child)s': %(exc)s" msg = tmpl % locals() errors(msg) isdir = False if isdir: for item in child.walk(pattern, errors): yield item def walkdirs(self, pattern=None, errors='strict'): """ D.walkdirs() -> iterator over subdirs, recursively. With the optional `pattern` argument, this yields only directories whose names match the given pattern. For example, ``mydir.walkdirs('*test')`` yields only directories with names ending in ``'test'``. The `errors=` keyword argument controls behavior when an error occurs. The default is ``'strict'``, which causes an exception. The other allowed values are ``'warn'`` (which reports the error via :func:`warnings.warn()`), and ``'ignore'``. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: dirs = self.dirs() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in dirs: if pattern is None or child.fnmatch(pattern): yield child for subsubdir in child.walkdirs(pattern, errors): yield subsubdir def walkfiles(self, pattern=None, errors='strict'): """ D.walkfiles() -> iterator over files in D, recursively. The optional argument `pattern` limits the results to files with names that match the pattern. For example, ``mydir.walkfiles('*.tmp')`` yields only files with the ``.tmp`` extension. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: childList = self.listdir() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in childList: try: isfile = child.isfile() isdir = not isfile and child.isdir() except Exception: if errors == 'ignore': continue elif errors == 'warn': warnings.warn( "Unable to access '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) continue else: raise if isfile: if pattern is None or child.fnmatch(pattern): yield child elif isdir: for f in child.walkfiles(pattern, errors): yield f def fnmatch(self, pattern, normcase=None): """ Return ``True`` if `self.name` matches the given `pattern`. `pattern` - A filename pattern with wildcards, for example ``'*.py'``. If the pattern contains a `normcase` attribute, it is applied to the name and path prior to comparison. `normcase` - (optional) A function used to normalize the pattern and filename before matching. Defaults to :meth:`self.module`, which defaults to :meth:`os.path.normcase`. .. seealso:: :func:`fnmatch.fnmatch` """ default_normcase = getattr(pattern, 'normcase', self.module.normcase) normcase = normcase or default_normcase name = normcase(self.name) pattern = normcase(pattern) return fnmatch.fnmatchcase(name, pattern) def glob(self, pattern): """ Return a list of Path objects that match the pattern. `pattern` - a path relative to this directory, with wildcards. For example, ``Path('/users').glob('*/bin/*')`` returns a list of all the files users have in their :file:`bin` directories. .. seealso:: :func:`glob.glob` """ cls = self._next_class return [cls(s) for s in glob.glob(self / pattern)] # # --- Reading or writing an entire file at once. def open(self, *args, **kwargs): """ Open this file and return a corresponding :class:`file` object. Keyword arguments work as in :func:`io.open`. If the file cannot be opened, an :class:`~exceptions.OSError` is raised. """ with io_error_compat(): return io.open(self, *args, **kwargs) def bytes(self): """ Open this file, read all bytes, return them as a string. """ with self.open('rb') as f: return f.read() def chunks(self, size, *args, **kwargs): """ Returns a generator yielding chunks of the file, so it can be read piece by piece with a simple for loop. Any argument you pass after `size` will be passed to :meth:`open`. :example: >>> hash = hashlib.md5() >>> for chunk in Path("path.py").chunks(8192, mode='rb'): ... hash.update(chunk) This will read the file by chunks of 8192 bytes. """ with self.open(*args, **kwargs) as f: for chunk in iter(lambda: f.read(size) or None, None): yield chunk def write_bytes(self, bytes, append=False): """ Open this file and write the given bytes to it. Default behavior is to overwrite any existing file. Call ``p.write_bytes(bytes, append=True)`` to append instead. """ if append: mode = 'ab' else: mode = 'wb' with self.open(mode) as f: f.write(bytes) def text(self, encoding=None, errors='strict'): r""" Open this file, read it in, return the content as a string. All newline sequences are converted to ``'\n'``. Keyword arguments will be passed to :meth:`open`. .. seealso:: :meth:`lines` """ with self.open(mode='r', encoding=encoding, errors=errors) as f: return U_NEWLINE.sub('\n', f.read()) def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two differences between :meth:`write_text` and :meth:`write_bytes`: newline handling and Unicode handling. See below. Parameters: `text` - str/unicode - The text to be written. `encoding` - str - The Unicode encoding that will be used. This is ignored if `text` isn't a Unicode string. `errors` - str - How to handle Unicode encoding errors. Default is ``'strict'``. See ``help(unicode.encode)`` for the options. This is ignored if `text` isn't a Unicode string. `linesep` - keyword argument - str/unicode - The sequence of characters to be used to mark end-of-line. The default is :data:`os.linesep`. You can also specify ``None`` to leave all newlines as they are in `text`. `append` - keyword argument - bool - Specifies what to do if the file already exists (``True``: append to the end of it; ``False``: overwrite it.) The default is ``False``. --- Newline handling. ``write_text()`` converts all standard end-of-line sequences (``'\n'``, ``'\r'``, and ``'\r\n'``) to your platform's default end-of-line sequence (see :data:`os.linesep`; on Windows, for example, the end-of-line marker is ``'\r\n'``). If you don't like your platform's default, you can override it using the `linesep=` keyword argument. If you specifically want ``write_text()`` to preserve the newlines as-is, use ``linesep=None``. This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: ``u'\x85'``, ``u'\r\x85'``, and ``u'\u2028'``. (This is slightly different from when you open a file for writing with ``fopen(filename, "w")`` in C or ``open(filename, 'w')`` in Python.) --- Unicode If `text` isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The `encoding` and `errors` arguments are not used and must be omitted. If `text` is Unicode, it is first converted to :func:`bytes` using the specified `encoding` (or the default encoding if `encoding` isn't specified). The `errors` argument applies only to this conversion. """ if isinstance(text, text_type): if linesep is not None: text = U_NEWLINE.sub(linesep, text) text = text.encode(encoding or sys.getdefaultencoding(), errors) else: assert encoding is None text = NEWLINE.sub(linesep, text) self.write_bytes(text, append=append) def lines(self, encoding=None, errors='strict', retain=True): r""" Open this file, read all lines, return them in a list. Optional arguments: `encoding` - The Unicode encoding (or character set) of the file. The default is ``None``, meaning the content of the file is read as 8-bit characters and returned as a list of (non-Unicode) str objects. `errors` - How to handle Unicode errors; see help(str.decode) for the options. Default is ``'strict'``. `retain` - If ``True``, retain newline characters; but all newline character combinations (``'\r'``, ``'\n'``, ``'\r\n'``) are translated to ``'\n'``. If ``False``, newline characters are stripped off. Default is ``True``. This uses ``'U'`` mode. .. seealso:: :meth:`text` """ if encoding is None and retain: with self.open('U') as f: return f.readlines() else: return self.text(encoding, errors).splitlines(retain) def write_lines(self, lines, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given lines of text to this file. By default this overwrites any existing file at this path. This puts a platform-specific newline sequence on every line. See `linesep` below. `lines` - A list of strings. `encoding` - A Unicode encoding to use. This applies only if `lines` contains any Unicode strings. `errors` - How to handle errors in Unicode encoding. This also applies only to Unicode strings. linesep - The desired line-ending. This line-ending is applied to every line. If a line already has any standard line ending (``'\r'``, ``'\n'``, ``'\r\n'``, ``u'\x85'``, ``u'\r\x85'``, ``u'\u2028'``), that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent (``'\r\n'`` on Windows, ``'\n'`` on Unix, etc.). Specify ``None`` to write the lines as-is, like :meth:`file.writelines`. Use the keyword argument ``append=True`` to append lines to the file. The default is to overwrite the file. .. warning :: When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the `encoding=` parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later. """ with self.open('ab' if append else 'wb') as f: for line in lines: isUnicode = isinstance(line, text_type) if linesep is not None: pattern = U_NL_END if isUnicode else NL_END line = pattern.sub('', line) + linesep if isUnicode: line = line.encode( encoding or sys.getdefaultencoding(), errors) f.write(line) def read_md5(self): """ Calculate the md5 hash for this file. This reads through the entire file. .. seealso:: :meth:`read_hash` """ return self.read_hash('md5') def _hash(self, hash_name): """ Returns a hash object for the file at the current path. `hash_name` should be a hash algo name (such as ``'md5'`` or ``'sha1'``) that's available in the :mod:`hashlib` module. """ m = hashlib.new(hash_name) for chunk in self.chunks(8192, mode="rb"): m.update(chunk) return m def read_hash(self, hash_name): """ Calculate given hash for this file. List of supported hashes can be obtained from :mod:`hashlib` package. This reads the entire file. .. seealso:: :meth:`hashlib.hash.digest` """ return self._hash(hash_name).digest() def read_hexhash(self, hash_name): """ Calculate given hash for this file, returning hexdigest. List of supported hashes can be obtained from :mod:`hashlib` package. This reads the entire file. .. seealso:: :meth:`hashlib.hash.hexdigest` """ return self._hash(hash_name).hexdigest() # --- Methods for querying the filesystem. # N.B. On some platforms, the os.path functions may be implemented in C # (e.g. isdir on Windows, Python 3.2.2), and compiled functions don't get # bound. Playing it safe and wrapping them all in method calls. def isabs(self): """ .. seealso:: :func:`os.path.isabs` """ return self.module.isabs(self) def exists(self): """ .. seealso:: :func:`os.path.exists` """ return self.module.exists(self) def isdir(self): """ .. seealso:: :func:`os.path.isdir` """ return self.module.isdir(self) def isfile(self): """ .. seealso:: :func:`os.path.isfile` """ return self.module.isfile(self) def islink(self): """ .. seealso:: :func:`os.path.islink` """ return self.module.islink(self) def ismount(self): """ .. seealso:: :func:`os.path.ismount` """ return self.module.ismount(self) def samefile(self, other): """ .. seealso:: :func:`os.path.samefile` """ if not hasattr(self.module, 'samefile'): other = Path(other).realpath().normpath().normcase() return self.realpath().normpath().normcase() == other return self.module.samefile(self, other) def getatime(self): """ .. seealso:: :attr:`atime`, :func:`os.path.getatime` """ return self.module.getatime(self) atime = property( getatime, None, None, """ Last access time of the file. .. seealso:: :meth:`getatime`, :func:`os.path.getatime` """) def getmtime(self): """ .. seealso:: :attr:`mtime`, :func:`os.path.getmtime` """ return self.module.getmtime(self) mtime = property( getmtime, None, None, """ Last-modified time of the file. .. seealso:: :meth:`getmtime`, :func:`os.path.getmtime` """) def getctime(self): """ .. seealso:: :attr:`ctime`, :func:`os.path.getctime` """ return self.module.getctime(self) ctime = property( getctime, None, None, """ Creation time of the file. .. seealso:: :meth:`getctime`, :func:`os.path.getctime` """) def getsize(self): """ .. seealso:: :attr:`size`, :func:`os.path.getsize` """ return self.module.getsize(self) size = property( getsize, None, None, """ Size of the file, in bytes. .. seealso:: :meth:`getsize`, :func:`os.path.getsize` """) if hasattr(os, 'access'): def access(self, mode): """ Return ``True`` if current user has access to this path. mode - One of the constants :data:`os.F_OK`, :data:`os.R_OK`, :data:`os.W_OK`, :data:`os.X_OK` .. seealso:: :func:`os.access` """ return os.access(self, mode) def stat(self): """ Perform a ``stat()`` system call on this path. .. seealso:: :meth:`lstat`, :func:`os.stat` """ return os.stat(self) def lstat(self): """ Like :meth:`stat`, but do not follow symbolic links. .. seealso:: :meth:`stat`, :func:`os.lstat` """ return os.lstat(self) def __get_owner_windows(self): """ Return the name of the owner of this file or directory. Follow symbolic links. Return a name of the form ``r'DOMAIN\\User Name'``; may be a group. .. seealso:: :attr:`owner` """ desc = win32security.GetFileSecurity( self, win32security.OWNER_SECURITY_INFORMATION) sid = desc.GetSecurityDescriptorOwner() account, domain, typecode = win32security.LookupAccountSid(None, sid) return domain + '\\' + account def __get_owner_unix(self): """ Return the name of the owner of this file or directory. Follow symbolic links. .. seealso:: :attr:`owner` """ st = self.stat() return pwd.getpwuid(st.st_uid).pw_name def __get_owner_not_implemented(self): raise NotImplementedError("Ownership not available on this platform.") if 'win32security' in globals(): get_owner = __get_owner_windows elif 'pwd' in globals(): get_owner = __get_owner_unix else: get_owner = __get_owner_not_implemented owner = property( get_owner, None, None, """ Name of the owner of this file or directory. .. seealso:: :meth:`get_owner`""") if hasattr(os, 'statvfs'): def statvfs(self): """ Perform a ``statvfs()`` system call on this path. .. seealso:: :func:`os.statvfs` """ return os.statvfs(self) if hasattr(os, 'pathconf'): def pathconf(self, name): """ .. seealso:: :func:`os.pathconf` """ return os.pathconf(self, name) # # --- Modifying operations on files and directories def utime(self, times): """ Set the access and modified times of this file. .. seealso:: :func:`os.utime` """ os.utime(self, times) return self def chmod(self, mode): """ Set the mode. May be the new mode (os.chmod behavior) or a `symbolic mode `_. .. seealso:: :func:`os.chmod` """ if isinstance(mode, string_types): mask = _multi_permission_mask(mode) mode = mask(self.stat().st_mode) os.chmod(self, mode) return self def chown(self, uid=-1, gid=-1): """ Change the owner and group by names rather than the uid or gid numbers. .. seealso:: :func:`os.chown` """ if hasattr(os, 'chown'): if 'pwd' in globals() and isinstance(uid, string_types): uid = pwd.getpwnam(uid).pw_uid if 'grp' in globals() and isinstance(gid, string_types): gid = grp.getgrnam(gid).gr_gid os.chown(self, uid, gid) else: msg = "Ownership not available on this platform." raise NotImplementedError(msg) return self def rename(self, new): """ .. seealso:: :func:`os.rename` """ os.rename(self, new) return self._next_class(new) def renames(self, new): """ .. seealso:: :func:`os.renames` """ os.renames(self, new) return self._next_class(new) # # --- Create/delete operations on directories def mkdir(self, mode=0o777): """ .. seealso:: :func:`os.mkdir` """ os.mkdir(self, mode) return self def mkdir_p(self, mode=0o777): """ Like :meth:`mkdir`, but does not raise an exception if the directory already exists. """ try: self.mkdir(mode) except OSError: _, e, _ = sys.exc_info() if e.errno != errno.EEXIST: raise return self def makedirs(self, mode=0o777): """ .. seealso:: :func:`os.makedirs` """ os.makedirs(self, mode) return self def makedirs_p(self, mode=0o777): """ Like :meth:`makedirs`, but does not raise an exception if the directory already exists. """ try: self.makedirs(mode) except OSError: _, e, _ = sys.exc_info() if e.errno != errno.EEXIST: raise return self def rmdir(self): """ .. seealso:: :func:`os.rmdir` """ os.rmdir(self) return self def rmdir_p(self): """ Like :meth:`rmdir`, but does not raise an exception if the directory is not empty or does not exist. """ try: self.rmdir() except OSError: _, e, _ = sys.exc_info() bypass_codes = errno.ENOTEMPTY, errno.EEXIST, errno.ENOENT if e.errno not in bypass_codes: raise return self def removedirs(self): """ .. seealso:: :func:`os.removedirs` """ os.removedirs(self) return self def removedirs_p(self): """ Like :meth:`removedirs`, but does not raise an exception if the directory is not empty or does not exist. """ try: self.removedirs() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST: raise return self # --- Modifying operations on files def touch(self): """ Set the access/modified times of this file to the current time. Create the file if it does not exist. """ fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0o666) os.close(fd) os.utime(self, None) return self def remove(self): """ .. seealso:: :func:`os.remove` """ os.remove(self) return self def remove_p(self): """ Like :meth:`remove`, but does not raise an exception if the file does not exist. """ try: self.unlink() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOENT: raise return self def unlink(self): """ .. seealso:: :func:`os.unlink` """ os.unlink(self) return self def unlink_p(self): """ Like :meth:`unlink`, but does not raise an exception if the file does not exist. """ self.remove_p() return self # --- Links if hasattr(os, 'link'): def link(self, newpath): """ Create a hard link at `newpath`, pointing to this file. .. seealso:: :func:`os.link` """ os.link(self, newpath) return self._next_class(newpath) if hasattr(os, 'symlink'): def symlink(self, newlink=None): """ Create a symbolic link at `newlink`, pointing here. If newlink is not supplied, the symbolic link will assume the name self.basename(), creating the link in the cwd. .. seealso:: :func:`os.symlink` """ if newlink is None: newlink = self.basename() os.symlink(self, newlink) return self._next_class(newlink) if hasattr(os, 'readlink'): def readlink(self): """ Return the path to which this symbolic link points. The result may be an absolute or a relative path. .. seealso:: :meth:`readlinkabs`, :func:`os.readlink` """ return self._next_class(os.readlink(self)) def readlinkabs(self): """ Return the path to which this symbolic link points. The result is always an absolute path. .. seealso:: :meth:`readlink`, :func:`os.readlink` """ p = self.readlink() if p.isabs(): return p else: return (self.parent / p).abspath() # High-level functions from shutil # These functions will be bound to the instance such that # Path(name).copy(target) will invoke shutil.copy(name, target) copyfile = shutil.copyfile copymode = shutil.copymode copystat = shutil.copystat copy = shutil.copy copy2 = shutil.copy2 copytree = shutil.copytree if hasattr(shutil, 'move'): move = shutil.move rmtree = shutil.rmtree def rmtree_p(self): """ Like :meth:`rmtree`, but does not raise an exception if the directory does not exist. """ try: self.rmtree() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOENT: raise return self def chdir(self): """ .. seealso:: :func:`os.chdir` """ os.chdir(self) cd = chdir def merge_tree(self, dst, symlinks=False, *args, **kwargs): """ Copy entire contents of self to dst, overwriting existing contents in dst with those in self. If the additional keyword `update` is True, each `src` will only be copied if `dst` does not exist, or `src` is newer than `dst`. Note that the technique employed stages the files in a temporary directory first, so this function is not suitable for merging trees with large files, especially if the temporary directory is not capable of storing a copy of the entire source tree. """ update = kwargs.pop('update', False) with tempdir() as _temp_dir: # first copy the tree to a stage directory to support # the parameters and behavior of copytree. stage = _temp_dir / str(hash(self)) self.copytree(stage, symlinks, *args, **kwargs) # now copy everything from the stage directory using # the semantics of dir_util.copy_tree distutils.dir_util.copy_tree( stage, dst, preserve_symlinks=symlinks, update=update, ) # # --- Special stuff from os if hasattr(os, 'chroot'): def chroot(self): """ .. seealso:: :func:`os.chroot` """ os.chroot(self) if hasattr(os, 'startfile'): def startfile(self): """ .. seealso:: :func:`os.startfile` """ os.startfile(self) return self # in-place re-writing, courtesy of Martijn Pieters # http://www.zopatista.com/python/2013/11/26/inplace-file-rewriting/ @contextlib.contextmanager def in_place( self, mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None, ): """ A context in which a file may be re-written in-place with new content. Yields a tuple of :samp:`({readable}, {writable})` file objects, where `writable` replaces `readable`. If an exception occurs, the old file is restored, removing the written data. Mode *must not* use ``'w'``, ``'a'``, or ``'+'``; only read-only-modes are allowed. A :exc:`ValueError` is raised on invalid modes. For example, to add line numbers to a file:: p = Path(filename) assert p.isfile() with p.in_place() as (reader, writer): for number, line in enumerate(reader, 1): writer.write('{0:3}: '.format(number))) writer.write(line) Thereafter, the file at `filename` will have line numbers in it. """ import io if set(mode).intersection('wa+'): raise ValueError('Only read-only file modes can be used') # move existing file to backup, create new file with same permissions # borrowed extensively from the fileinput module backup_fn = self + (backup_extension or os.extsep + 'bak') try: os.unlink(backup_fn) except os.error: pass os.rename(self, backup_fn) readable = io.open( backup_fn, mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) try: perm = os.fstat(readable.fileno()).st_mode except OSError: writable = open( self, 'w' + mode.replace('r', ''), buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) else: os_mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC if hasattr(os, 'O_BINARY'): os_mode |= os.O_BINARY fd = os.open(self, os_mode, perm) writable = io.open( fd, "w" + mode.replace('r', ''), buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) try: if hasattr(os, 'chmod'): os.chmod(self, perm) except OSError: pass try: yield readable, writable except Exception: # move backup back readable.close() writable.close() try: os.unlink(self) except os.error: pass os.rename(backup_fn, self) raise else: readable.close() writable.close() finally: try: os.unlink(backup_fn) except os.error: pass @ClassProperty @classmethod def special(cls): """ Return a SpecialResolver object suitable referencing a suitable directory for the relevant platform for the given type of content. For example, to get a user config directory, invoke: dir = Path.special().user.config Uses the `appdirs `_ to resolve the paths in a platform-friendly way. To create a config directory for 'My App', consider: dir = Path.special("My App").user.config.makedirs_p() If the ``appdirs`` module is not installed, invocation of special will raise an ImportError. """ return functools.partial(SpecialResolver, cls) class SpecialResolver(object): class ResolverScope: def __init__(self, paths, scope): self.paths = paths self.scope = scope def __getattr__(self, class_): return self.paths.get_dir(self.scope, class_) def __init__(self, path_class, *args, **kwargs): appdirs = importlib.import_module('appdirs') # let appname default to None until # https://github.com/ActiveState/appdirs/issues/55 is solved. not args and kwargs.setdefault('appname', None) vars(self).update( path_class=path_class, wrapper=appdirs.AppDirs(*args, **kwargs), ) def __getattr__(self, scope): return self.ResolverScope(self, scope) def get_dir(self, scope, class_): """ Return the callable function from appdirs, but with the result wrapped in self.path_class """ prop_name = '{scope}_{class_}_dir'.format(**locals()) value = getattr(self.wrapper, prop_name) MultiPath = Multi.for_class(self.path_class) return MultiPath.detect(value) class Multi: """ A mix-in for a Path which may contain multiple Path separated by pathsep. """ @classmethod def for_class(cls, path_cls): name = 'Multi' + path_cls.__name__ if PY2: name = str(name) return type(name, (cls, path_cls), {}) @classmethod def detect(cls, input): if os.pathsep not in input: cls = cls._next_class return cls(input) def __iter__(self): return iter(map(self._next_class, self.split(os.pathsep))) @ClassProperty @classmethod def _next_class(cls): """ Multi-subclasses should use the parent class """ return next( class_ for class_ in cls.__mro__ if not issubclass(class_, Multi) ) class tempdir(Path): """ A temporary directory via :func:`tempfile.mkdtemp`, and constructed with the same parameters that you can use as a context manager. Example: with tempdir() as d: # do stuff with the Path object "d" # here the directory is deleted automatically .. seealso:: :func:`tempfile.mkdtemp` """ @ClassProperty @classmethod def _next_class(cls): return Path def __new__(cls, *args, **kwargs): dirname = tempfile.mkdtemp(*args, **kwargs) return super(tempdir, cls).__new__(cls, dirname) def __init__(self, *args, **kwargs): pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if not exc_value: self.rmtree() def _multi_permission_mask(mode): """ Support multiple, comma-separated Unix chmod symbolic modes. >>> _multi_permission_mask('a=r,u+w')(0) == 0o644 True """ def compose(f, g): return lambda *args, **kwargs: g(f(*args, **kwargs)) return functools.reduce(compose, map(_permission_mask, mode.split(','))) def _permission_mask(mode): """ Convert a Unix chmod symbolic mode like ``'ugo+rwx'`` to a function suitable for applying to a mask to affect that change. >>> mask = _permission_mask('ugo+rwx') >>> mask(0o554) == 0o777 True >>> _permission_mask('go-x')(0o777) == 0o766 True >>> _permission_mask('o-x')(0o445) == 0o444 True >>> _permission_mask('a+x')(0) == 0o111 True >>> _permission_mask('a=rw')(0o057) == 0o666 True >>> _permission_mask('u=x')(0o666) == 0o166 True >>> _permission_mask('g=')(0o157) == 0o107 True """ # parse the symbolic mode parsed = re.match('(?P[ugoa]+)(?P[-+=])(?P[rwx]*)$', mode) if not parsed: raise ValueError("Unrecognized symbolic mode", mode) # generate a mask representing the specified permission spec_map = dict(r=4, w=2, x=1) specs = (spec_map[perm] for perm in parsed.group('what')) spec = functools.reduce(operator.or_, specs, 0) # now apply spec to each subject in who shift_map = dict(u=6, g=3, o=0) who = parsed.group('who').replace('a', 'ugo') masks = (spec << shift_map[subj] for subj in who) mask = functools.reduce(operator.or_, masks) op = parsed.group('op') # if op is -, invert the mask if op == '-': mask ^= 0o777 # if op is =, retain extant values for unreferenced subjects if op == '=': masks = (0o7 << shift_map[subj] for subj in who) retain = functools.reduce(operator.or_, masks) ^ 0o777 op_map = { '+': operator.or_, '-': operator.and_, '=': lambda mask, target: target & retain ^ mask, } return functools.partial(op_map[op], mask) class CaseInsensitivePattern(text_type): """ A string with a ``'normcase'`` property, suitable for passing to :meth:`listdir`, :meth:`dirs`, :meth:`files`, :meth:`walk`, :meth:`walkdirs`, or :meth:`walkfiles` to match case-insensitive. For example, to get all files ending in .py, .Py, .pY, or .PY in the current directory:: from path import Path, CaseInsensitivePattern as ci Path('.').files(ci('*.py')) """ @property def normcase(self): return __import__('ntpath').normcase class FastPath(Path): """ Performance optimized version of Path for use on embedded platforms and other systems with limited CPU. See #115 and #116 for background. """ def listdir(self, pattern=None): children = os.listdir(self) if pattern is None: return [self / child for child in children] pattern, normcase = self.__prepare(pattern) return [ self / child for child in children if self._next_class(child).__fnmatch(pattern, normcase) ] def walk(self, pattern=None, errors='strict'): class Handlers: def strict(msg): raise def warn(msg): warnings.warn(msg, TreeWalkWarning) def ignore(msg): pass if not callable(errors) and errors not in vars(Handlers): raise ValueError("invalid errors parameter") errors = vars(Handlers).get(errors, errors) if pattern: pattern, normcase = self.__prepare(pattern) else: normcase = None return self.__walk(pattern, normcase, errors) def __walk(self, pattern, normcase, errors): """ Prepared version of walk """ try: childList = self.listdir() except Exception: exc = sys.exc_info()[1] tmpl = "Unable to list directory '%(self)s': %(exc)s" msg = tmpl % locals() errors(msg) return for child in childList: if pattern is None or child.__fnmatch(pattern, normcase): yield child try: isdir = child.isdir() except Exception: exc = sys.exc_info()[1] tmpl = "Unable to access '%(child)s': %(exc)s" msg = tmpl % locals() errors(msg) isdir = False if isdir: for item in child.__walk(pattern, normcase, errors): yield item def walkdirs(self, pattern=None, errors='strict'): if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") if pattern: pattern, normcase = self.__prepare(pattern) else: normcase = None return self.__walkdirs(pattern, normcase, errors) def __walkdirs(self, pattern, normcase, errors): """ Prepared version of walkdirs """ try: dirs = self.dirs() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in dirs: if pattern is None or child.__fnmatch(pattern, normcase): yield child for subsubdir in child.__walkdirs(pattern, normcase, errors): yield subsubdir def walkfiles(self, pattern=None, errors='strict'): if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") if pattern: pattern, normcase = self.__prepare(pattern) else: normcase = None return self.__walkfiles(pattern, normcase, errors) def __walkfiles(self, pattern, normcase, errors): """ Prepared version of walkfiles """ try: childList = self.listdir() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in childList: try: isfile = child.isfile() isdir = not isfile and child.isdir() except Exception: if errors == 'ignore': continue elif errors == 'warn': warnings.warn( "Unable to access '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) continue else: raise if isfile: if pattern is None or child.__fnmatch(pattern, normcase): yield child elif isdir: for f in child.__walkfiles(pattern, normcase, errors): yield f def __fnmatch(self, pattern, normcase): """ Return ``True`` if `self.name` matches the given `pattern`, prepared version. `pattern` - A filename pattern with wildcards, for example ``'*.py'``. The pattern is expected to be normcase'd already. `normcase` - A function used to normalize the pattern and filename before matching. .. seealso:: :func:`Path.fnmatch` """ return fnmatch.fnmatchcase(normcase(self.name), pattern) def __prepare(self, pattern, normcase=None): """ Prepares a fmatch_pattern for use with ``FastPath.__fnmatch`. `pattern` - A filename pattern with wildcards, for example ``'*.py'``. If the pattern contains a `normcase` attribute, it is applied to the name and path prior to comparison. `normcase` - (optional) A function used to normalize the pattern and filename before matching. Defaults to :meth:`self.module`, which defaults to :meth:`os.path.normcase`. .. seealso:: :func:`FastPath.__fnmatch` """ if not normcase: normcase = getattr(pattern, 'normcase', self.module.normcase) pattern = normcase(pattern) return pattern, normcase def fnmatch(self, pattern, normcase=None): if not pattern: raise ValueError("No pattern provided") pattern, normcase = self.__prepare(pattern, normcase) return self.__fnmatch(pattern, normcase) path.py-11.0.1/pytest.ini000066400000000000000000000001731325623636300152200ustar00rootroot00000000000000[pytest] norecursedirs=dist build .tox .eggs addopts=--doctest-modules --flake8 doctest_optionflags=ALLOW_UNICODE ELLIPSIS path.py-11.0.1/setup.cfg000066400000000000000000000002071325623636300150060ustar00rootroot00000000000000[aliases] release = dists upload dists = clean --all sdist bdist_wheel [bdist_wheel] universal = 1 [metadata] license_file = LICENSE path.py-11.0.1/setup.py000066400000000000000000000035641325623636300147100ustar00rootroot00000000000000#!/usr/bin/env python # Project skeleton maintained at https://github.com/jaraco/skeleton import io import setuptools with io.open('README.rst', encoding='utf-8') as readme: long_description = readme.read() name = 'path.py' description = 'A module wrapper for os.path' nspkg_technique = 'native' """ Does this package use "native" namespace packages or pkg_resources "managed" namespace packages? """ params = dict( name=name, use_scm_version=True, author="Jason Orendorff", author_email="jason.orendorff@gmail.com", maintainer="Jason R. Coombs", maintainer_email="jaraco@jaraco.com", description=description or name, long_description=long_description, url="https://github.com/jaraco/" + name, py_modules=['path', 'test_path'], python_requires='>=2.7,!=3.1,!=3.2,!=3.3', install_requires=[ ], extras_require={ 'testing': [ # upstream 'pytest>=2.8', 'pytest-sugar>=0.9.1', 'collective.checkdocs', 'pytest-flake8', # local 'appdirs', 'packaging', # required for checkdocs on README.rst 'pygments', ], 'docs': [ # upstream 'sphinx', 'jaraco.packaging>=3.2', 'rst.linker>=1.9', # local ], }, setup_requires=[ 'setuptools_scm>=1.15.0', ], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], entry_points={ }, ) if __name__ == '__main__': setuptools.setup(**params) path.py-11.0.1/test_path.py000066400000000000000000001133701325623636300155400ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Tests for the path module. This suite runs on Linux, OS X, and Windows right now. To extend the platform support, just add appropriate pathnames for your platform (os.name) in each place where the p() function is called. Then report the result. If you can't get the test to run at all on your platform, there's probably a bug in path.py -- please report the issue in the issue tracker at https://github.com/jaraco/path.py. TestScratchDir.test_touch() takes a while to run. It sleeps a few seconds to allow some time to pass between calls to check the modify time on files. """ from __future__ import unicode_literals, absolute_import, print_function import codecs import os import sys import shutil import time import ntpath import posixpath import textwrap import platform import importlib import operator import pytest import packaging.version import path from path import tempdir from path import CaseInsensitivePattern as ci from path import SpecialResolver from path import Multi Path = None def p(**choices): """ Choose a value from several possible values, based on os.name """ return choices[os.name] @pytest.fixture(autouse=True, params=[path.Path, path.FastPath]) def path_class(request, monkeypatch): """ Invoke tests on any number of Path classes. """ monkeypatch.setitem(globals(), 'Path', request.param) def mac_version(target, comparator=operator.ge): """ Return True if on a Mac whose version passes the comparator. """ current_ver = packaging.version.parse(platform.mac_ver()[0]) target_ver = packaging.version.parse(target) return ( platform.system() == 'Darwin' and comparator(current_ver, target_ver) ) class TestBasics: def test_relpath(self): root = Path(p(nt='C:\\', posix='/')) foo = root / 'foo' quux = foo / 'quux' bar = foo / 'bar' boz = bar / 'Baz' / 'Boz' up = Path(os.pardir) # basics assert root.relpathto(boz) == Path('foo') / 'bar' / 'Baz' / 'Boz' assert bar.relpathto(boz) == Path('Baz') / 'Boz' assert quux.relpathto(boz) == up / 'bar' / 'Baz' / 'Boz' assert boz.relpathto(quux) == up / up / up / 'quux' assert boz.relpathto(bar) == up / up # Path is not the first element in concatenation assert root.relpathto(boz) == 'foo' / Path('bar') / 'Baz' / 'Boz' # x.relpathto(x) == curdir assert root.relpathto(root) == os.curdir assert boz.relpathto(boz) == os.curdir # Make sure case is properly noted (or ignored) assert boz.relpathto(boz.normcase()) == os.curdir # relpath() cwd = Path(os.getcwd()) assert boz.relpath() == cwd.relpathto(boz) if os.name == 'nt': # Check relpath across drives. d = Path('D:\\') assert d.relpathto(boz) == boz def test_construction_from_none(self): """ """ try: Path(None) except TypeError: pass else: raise Exception("DID NOT RAISE") def test_construction_from_int(self): """ Path class will construct a path as a string of the number """ assert Path(1) == '1' def test_string_compatibility(self): """ Test compatibility with ordinary strings. """ x = Path('xyzzy') assert x == 'xyzzy' assert x == str('xyzzy') # sorting items = [Path('fhj'), Path('fgh'), 'E', Path('d'), 'A', Path('B'), 'c'] items.sort() assert items == ['A', 'B', 'E', 'c', 'd', 'fgh', 'fhj'] # Test p1/p1. p1 = Path("foo") p2 = Path("bar") assert p1 / p2 == p(nt='foo\\bar', posix='foo/bar') def test_properties(self): # Create sample path object. f = p(nt='C:\\Program Files\\Python\\Lib\\xyzzy.py', posix='/usr/local/python/lib/xyzzy.py') f = Path(f) # .parent nt_lib = 'C:\\Program Files\\Python\\Lib' posix_lib = '/usr/local/python/lib' expected = p(nt=nt_lib, posix=posix_lib) assert f.parent == expected # .name assert f.name == 'xyzzy.py' assert f.parent.name == p(nt='Lib', posix='lib') # .ext assert f.ext == '.py' assert f.parent.ext == '' # .drive assert f.drive == p(nt='C:', posix='') def test_methods(self): # .abspath() assert Path(os.curdir).abspath() == os.getcwd() # .getcwd() cwd = Path.getcwd() assert isinstance(cwd, Path) assert cwd == os.getcwd() def test_UNC(self): if hasattr(os.path, 'splitunc'): p = Path(r'\\python1\share1\dir1\file1.txt') assert p.uncshare == r'\\python1\share1' assert p.splitunc() == os.path.splitunc(str(p)) def test_explicit_module(self): """ The user may specify an explicit path module to use. """ nt_ok = Path.using_module(ntpath)(r'foo\bar\baz') posix_ok = Path.using_module(posixpath)(r'foo/bar/baz') posix_wrong = Path.using_module(posixpath)(r'foo\bar\baz') assert nt_ok.dirname() == r'foo\bar' assert posix_ok.dirname() == r'foo/bar' assert posix_wrong.dirname() == '' assert nt_ok / 'quux' == r'foo\bar\baz\quux' assert posix_ok / 'quux' == r'foo/bar/baz/quux' def test_explicit_module_classes(self): """ Multiple calls to path.using_module should produce the same class. """ nt_path = Path.using_module(ntpath) assert nt_path is Path.using_module(ntpath) assert nt_path.__name__ == 'Path_ntpath' def test_joinpath_on_instance(self): res = Path('foo') foo_bar = res.joinpath('bar') assert foo_bar == p(nt='foo\\bar', posix='foo/bar') def test_joinpath_to_nothing(self): res = Path('foo') assert res.joinpath() == res def test_joinpath_on_class(self): "Construct a path from a series of strings" foo_bar = Path.joinpath('foo', 'bar') assert foo_bar == p(nt='foo\\bar', posix='foo/bar') def test_joinpath_fails_on_empty(self): "It doesn't make sense to join nothing at all" try: Path.joinpath() except TypeError: pass else: raise Exception("did not raise") def test_joinpath_returns_same_type(self): path_posix = Path.using_module(posixpath) res = path_posix.joinpath('foo') assert isinstance(res, path_posix) res2 = res.joinpath('bar') assert isinstance(res2, path_posix) assert res2 == 'foo/bar' class TestSelfReturn: """ Some methods don't necessarily return any value (e.g. makedirs, makedirs_p, rename, mkdir, touch, chroot). These methods should return self anyhow to allow methods to be chained. """ def test_makedirs_p(self, tmpdir): """ Path('foo').makedirs_p() == Path('foo') """ p = Path(tmpdir) / "newpath" ret = p.makedirs_p() assert p == ret def test_makedirs_p_extant(self, tmpdir): p = Path(tmpdir) ret = p.makedirs_p() assert p == ret def test_rename(self, tmpdir): p = Path(tmpdir) / "somefile" p.touch() target = Path(tmpdir) / "otherfile" ret = p.rename(target) assert target == ret def test_mkdir(self, tmpdir): p = Path(tmpdir) / "newdir" ret = p.mkdir() assert p == ret def test_touch(self, tmpdir): p = Path(tmpdir) / "empty file" ret = p.touch() assert p == ret class TestScratchDir: """ Tests that run in a temporary directory (does not test tempdir class) """ def test_context_manager(self, tmpdir): """Can be used as context manager for chdir.""" d = Path(tmpdir) subdir = d / 'subdir' subdir.makedirs() old_dir = os.getcwd() with subdir: assert os.getcwd() == os.path.realpath(subdir) assert os.getcwd() == old_dir def test_touch(self, tmpdir): # NOTE: This test takes a long time to run (~10 seconds). # It sleeps several seconds because on Windows, the resolution # of a file's mtime and ctime is about 2 seconds. # # atime isn't tested because on Windows the resolution of atime # is something like 24 hours. threshold = 1 d = Path(tmpdir) f = d / 'test.txt' t0 = time.time() - threshold f.touch() t1 = time.time() + threshold assert f.exists() assert f.isfile() assert f.size == 0 assert t0 <= f.mtime <= t1 if hasattr(os.path, 'getctime'): ct = f.ctime assert t0 <= ct <= t1 time.sleep(threshold * 2) fobj = open(f, 'ab') fobj.write('some bytes'.encode('utf-8')) fobj.close() time.sleep(threshold * 2) t2 = time.time() - threshold f.touch() t3 = time.time() + threshold assert t0 <= t1 < t2 <= t3 # sanity check assert f.exists() assert f.isfile() assert f.size == 10 assert t2 <= f.mtime <= t3 if hasattr(os.path, 'getctime'): ct2 = f.ctime if os.name == 'nt': # On Windows, "ctime" is CREATION time assert ct == ct2 assert ct2 < t2 else: assert ( # ctime is unchanged ct == ct2 or # ctime is approximately the mtime ct2 == pytest.approx(f.mtime, 0.001) ) def test_listing(self, tmpdir): d = Path(tmpdir) assert d.listdir() == [] f = 'testfile.txt' af = d / f assert af == os.path.join(d, f) af.touch() try: assert af.exists() assert d.listdir() == [af] # .glob() assert d.glob('testfile.txt') == [af] assert d.glob('test*.txt') == [af] assert d.glob('*.txt') == [af] assert d.glob('*txt') == [af] assert d.glob('*') == [af] assert d.glob('*.html') == [] assert d.glob('testfile') == [] finally: af.remove() # Try a test with 20 files files = [d / ('%d.txt' % i) for i in range(20)] for f in files: fobj = open(f, 'w') fobj.write('some text\n') fobj.close() try: files2 = d.listdir() files.sort() files2.sort() assert files == files2 finally: for f in files: try: f.remove() except Exception: pass @pytest.mark.xfail( platform.system() == 'Linux' and path.PY2, reason="Can't decode bytes in FS. See #121", ) @pytest.mark.xfail( mac_version('10.13'), reason="macOS disallows invalid encodings", ) @pytest.mark.xfail( platform.system() == 'Windows' and path.PY3, reason="Can't write latin characters. See #133", ) def test_listdir_other_encoding(self, tmpdir): """ Some filesystems allow non-character sequences in path names. ``.listdir`` should still function in this case. See issue #61 for details. """ assert Path(tmpdir).listdir() == [] tmpdir_bytes = str(tmpdir).encode('ascii') filename = 'r\xe9\xf1emi'.encode('latin-1') pathname = os.path.join(tmpdir_bytes, filename) with open(pathname, 'wb'): pass # first demonstrate that os.listdir works assert os.listdir(tmpdir_bytes) # now try with path.py results = Path(tmpdir).listdir() assert len(results) == 1 res, = results assert isinstance(res, Path) # OS X seems to encode the bytes in the filename as %XX characters. if platform.system() == 'Darwin': assert res.basename() == 'r%E9%F1emi' return assert len(res.basename()) == len(filename) def test_makedirs(self, tmpdir): d = Path(tmpdir) # Placeholder file so that when removedirs() is called, # it doesn't remove the temporary directory itself. tempf = d / 'temp.txt' tempf.touch() try: foo = d / 'foo' boz = foo / 'bar' / 'baz' / 'boz' boz.makedirs() try: assert boz.isdir() finally: boz.removedirs() assert not foo.exists() assert d.exists() foo.mkdir(0o750) boz.makedirs(0o700) try: assert boz.isdir() finally: boz.removedirs() assert not foo.exists() assert d.exists() finally: os.remove(tempf) def assertSetsEqual(self, a, b): ad = {} for i in a: ad[i] = None bd = {} for i in b: bd[i] = None assert ad == bd def test_shutil(self, tmpdir): # Note: This only tests the methods exist and do roughly what # they should, neglecting the details as they are shutil's # responsibility. d = Path(tmpdir) testDir = d / 'testdir' testFile = testDir / 'testfile.txt' testA = testDir / 'A' testCopy = testA / 'testcopy.txt' testLink = testA / 'testlink.txt' testB = testDir / 'B' testC = testB / 'C' testCopyOfLink = testC / testA.relpathto(testLink) # Create test dirs and a file testDir.mkdir() testA.mkdir() testB.mkdir() f = open(testFile, 'w') f.write('x' * 10000) f.close() # Test simple file copying. testFile.copyfile(testCopy) assert testCopy.isfile() assert testFile.bytes() == testCopy.bytes() # Test copying into a directory. testCopy2 = testA / testFile.name testFile.copy(testA) assert testCopy2.isfile() assert testFile.bytes() == testCopy2.bytes() # Make a link for the next test to use. if hasattr(os, 'symlink'): testFile.symlink(testLink) else: testFile.copy(testLink) # fallback # Test copying directory tree. testA.copytree(testC) assert testC.isdir() self.assertSetsEqual( testC.listdir(), [testC / testCopy.name, testC / testFile.name, testCopyOfLink]) assert not testCopyOfLink.islink() # Clean up for another try. testC.rmtree() assert not testC.exists() # Copy again, preserving symlinks. testA.copytree(testC, True) assert testC.isdir() self.assertSetsEqual( testC.listdir(), [testC / testCopy.name, testC / testFile.name, testCopyOfLink]) if hasattr(os, 'symlink'): assert testCopyOfLink.islink() assert testCopyOfLink.readlink() == testFile # Clean up. testDir.rmtree() assert not testDir.exists() self.assertList(d.listdir(), []) def assertList(self, listing, expected): assert sorted(listing) == sorted(expected) def test_patterns(self, tmpdir): d = Path(tmpdir) names = ['x.tmp', 'x.xtmp', 'x2g', 'x22', 'x.txt'] dirs = [d, d / 'xdir', d / 'xdir.tmp', d / 'xdir.tmp' / 'xsubdir'] for e in dirs: if not e.isdir(): e.makedirs() for name in names: (e / name).touch() self.assertList(d.listdir('*.tmp'), [d / 'x.tmp', d / 'xdir.tmp']) self.assertList(d.files('*.tmp'), [d / 'x.tmp']) self.assertList(d.dirs('*.tmp'), [d / 'xdir.tmp']) self.assertList(d.walk(), [e for e in dirs if e != d] + [e / n for e in dirs for n in names]) self.assertList(d.walk('*.tmp'), [e / 'x.tmp' for e in dirs] + [d / 'xdir.tmp']) self.assertList(d.walkfiles('*.tmp'), [e / 'x.tmp' for e in dirs]) self.assertList(d.walkdirs('*.tmp'), [d / 'xdir.tmp']) def test_unicode(self, tmpdir): d = Path(tmpdir) p = d / 'unicode.txt' def test(enc): """ Test that path works with the specified encoding, which must be capable of representing the entire range of Unicode codepoints. """ given = ( 'Hello world\n' '\u0d0a\u0a0d\u0d15\u0a15\r\n' '\u0d0a\u0a0d\u0d15\u0a15\x85' '\u0d0a\u0a0d\u0d15\u0a15\u2028' '\r' 'hanging' ) clean = ( 'Hello world\n' '\u0d0a\u0a0d\u0d15\u0a15\n' '\u0d0a\u0a0d\u0d15\u0a15\n' '\u0d0a\u0a0d\u0d15\u0a15\n' '\n' 'hanging' ) givenLines = [ ('Hello world\n'), ('\u0d0a\u0a0d\u0d15\u0a15\r\n'), ('\u0d0a\u0a0d\u0d15\u0a15\x85'), ('\u0d0a\u0a0d\u0d15\u0a15\u2028'), ('\r'), ('hanging')] expectedLines = [ ('Hello world\n'), ('\u0d0a\u0a0d\u0d15\u0a15\n'), ('\u0d0a\u0a0d\u0d15\u0a15\n'), ('\u0d0a\u0a0d\u0d15\u0a15\n'), ('\n'), ('hanging')] expectedLines2 = [ ('Hello world'), ('\u0d0a\u0a0d\u0d15\u0a15'), ('\u0d0a\u0a0d\u0d15\u0a15'), ('\u0d0a\u0a0d\u0d15\u0a15'), (''), ('hanging')] # write bytes manually to file f = codecs.open(p, 'w', enc) f.write(given) f.close() # test all 3 path read-fully functions, including # path.lines() in unicode mode. assert p.bytes() == given.encode(enc) assert p.text(enc) == clean assert p.lines(enc) == expectedLines assert p.lines(enc, retain=False) == expectedLines2 # If this is UTF-16, that's enough. # The rest of these will unfortunately fail because append=True # mode causes an extra BOM to be written in the middle of the file. # UTF-16 is the only encoding that has this problem. if enc == 'UTF-16': return # Write Unicode to file using path.write_text(). # This test doesn't work with a hanging line. cleanNoHanging = clean + '\n' p.write_text(cleanNoHanging, enc) p.write_text(cleanNoHanging, enc, append=True) # Check the result. expectedBytes = 2 * cleanNoHanging.replace('\n', os.linesep).encode(enc) expectedLinesNoHanging = expectedLines[:] expectedLinesNoHanging[-1] += '\n' assert p.bytes() == expectedBytes assert p.text(enc) == 2 * cleanNoHanging assert p.lines(enc) == 2 * expectedLinesNoHanging assert p.lines(enc, retain=False) == 2 * expectedLines2 # Write Unicode to file using path.write_lines(). # The output in the file should be exactly the same as last time. p.write_lines(expectedLines, enc) p.write_lines(expectedLines2, enc, append=True) # Check the result. assert p.bytes() == expectedBytes # Now: same test, but using various newline sequences. # If linesep is being properly applied, these will be converted # to the platform standard newline sequence. p.write_lines(givenLines, enc) p.write_lines(givenLines, enc, append=True) # Check the result. assert p.bytes() == expectedBytes # Same test, using newline sequences that are different # from the platform default. def testLinesep(eol): p.write_lines(givenLines, enc, linesep=eol) p.write_lines(givenLines, enc, linesep=eol, append=True) expected = 2 * cleanNoHanging.replace('\n', eol).encode(enc) assert p.bytes() == expected testLinesep('\n') testLinesep('\r') testLinesep('\r\n') testLinesep('\x0d\x85') # Again, but with linesep=None. p.write_lines(givenLines, enc, linesep=None) p.write_lines(givenLines, enc, linesep=None, append=True) # Check the result. expectedBytes = 2 * given.encode(enc) assert p.bytes() == expectedBytes assert p.text(enc) == 2 * clean expectedResultLines = expectedLines[:] expectedResultLines[-1] += expectedLines[0] expectedResultLines += expectedLines[1:] assert p.lines(enc) == expectedResultLines test('UTF-8') test('UTF-16BE') test('UTF-16LE') test('UTF-16') def test_chunks(self, tmpdir): p = (tempdir() / 'test.txt').touch() txt = "0123456789" size = 5 p.write_text(txt) for i, chunk in enumerate(p.chunks(size)): assert chunk == txt[i * size:i * size + size] assert i == len(txt) / size - 1 @pytest.mark.skipif( not hasattr(os.path, 'samefile'), reason="samefile not present", ) def test_samefile(self, tmpdir): f1 = (tempdir() / '1.txt').touch() f1.write_text('foo') f2 = (tempdir() / '2.txt').touch() f1.write_text('foo') f3 = (tempdir() / '3.txt').touch() f1.write_text('bar') f4 = (tempdir() / '4.txt') f1.copyfile(f4) assert os.path.samefile(f1, f2) == f1.samefile(f2) assert os.path.samefile(f1, f3) == f1.samefile(f3) assert os.path.samefile(f1, f4) == f1.samefile(f4) assert os.path.samefile(f1, f1) == f1.samefile(f1) def test_rmtree_p(self, tmpdir): d = Path(tmpdir) sub = d / 'subfolder' sub.mkdir() (sub / 'afile').write_text('something') sub.rmtree_p() assert not sub.exists() try: sub.rmtree_p() except OSError: self.fail("Calling `rmtree_p` on non-existent directory " "should not raise an exception.") def test_rmdir_p_exists(self, tmpdir): """ Invocation of rmdir_p on an existant directory should remove the directory. """ d = Path(tmpdir) sub = d / 'subfolder' sub.mkdir() sub.rmdir_p() assert not sub.exists() def test_rmdir_p_nonexistent(self, tmpdir): """ A non-existent file should not raise an exception. """ d = Path(tmpdir) sub = d / 'subfolder' assert not sub.exists() sub.rmdir_p() class TestMergeTree: @pytest.fixture(autouse=True) def testing_structure(self, tmpdir): self.test_dir = Path(tmpdir) self.subdir_a = self.test_dir / 'A' self.test_file = self.subdir_a / 'testfile.txt' self.test_link = self.subdir_a / 'testlink.txt' self.subdir_b = self.test_dir / 'B' self.subdir_a.mkdir() self.subdir_b.mkdir() with open(self.test_file, 'w') as f: f.write('x' * 10000) if hasattr(os, 'symlink'): self.test_file.symlink(self.test_link) else: self.test_file.copy(self.test_link) def check_link(self): target = Path(self.subdir_b / self.test_link.name) check = target.islink if hasattr(os, 'symlink') else target.isfile assert check() def test_with_nonexisting_dst_kwargs(self): self.subdir_a.merge_tree(self.subdir_b, symlinks=True) assert self.subdir_b.isdir() expected = set(( self.subdir_b / self.test_file.name, self.subdir_b / self.test_link.name, )) assert set(self.subdir_b.listdir()) == expected self.check_link() def test_with_nonexisting_dst_args(self): self.subdir_a.merge_tree(self.subdir_b, True) assert self.subdir_b.isdir() expected = set(( self.subdir_b / self.test_file.name, self.subdir_b / self.test_link.name, )) assert set(self.subdir_b.listdir()) == expected self.check_link() def test_with_existing_dst(self): self.subdir_b.rmtree() self.subdir_a.copytree(self.subdir_b, True) self.test_link.remove() test_new = self.subdir_a / 'newfile.txt' test_new.touch() with open(self.test_file, 'w') as f: f.write('x' * 5000) self.subdir_a.merge_tree(self.subdir_b, True) assert self.subdir_b.isdir() expected = set(( self.subdir_b / self.test_file.name, self.subdir_b / self.test_link.name, self.subdir_b / test_new.name, )) assert set(self.subdir_b.listdir()) == expected self.check_link() assert len(Path(self.subdir_b / self.test_file.name).bytes()) == 5000 def test_copytree_parameters(self): """ merge_tree should accept parameters to copytree, such as 'ignore' """ ignore = shutil.ignore_patterns('testlink*') self.subdir_a.merge_tree(self.subdir_b, ignore=ignore) assert self.subdir_b.isdir() assert self.subdir_b.listdir() == [self.subdir_b / self.test_file.name] class TestChdir: def test_chdir_or_cd(self, tmpdir): """ tests the chdir or cd method """ d = Path(str(tmpdir)) cwd = d.getcwd() # ensure the cwd isn't our tempdir assert str(d) != str(cwd) # now, we're going to chdir to tempdir d.chdir() # we now ensure that our cwd is the tempdir assert str(d.getcwd()) == str(tmpdir) # we're resetting our path d = Path(cwd) # we ensure that our cwd is still set to tempdir assert str(d.getcwd()) == str(tmpdir) # we're calling the alias cd method d.cd() # now, we ensure cwd isn'r tempdir assert str(d.getcwd()) == str(cwd) assert str(d.getcwd()) != str(tmpdir) class TestSubclass: def test_subclass_produces_same_class(self): """ When operations are invoked on a subclass, they should produce another instance of that subclass. """ class PathSubclass(Path): pass p = PathSubclass('/foo') subdir = p / 'bar' assert isinstance(subdir, PathSubclass) class TestTempDir: def test_constructor(self): """ One should be able to readily construct a temporary directory """ d = tempdir() assert isinstance(d, path.Path) assert d.exists() assert d.isdir() d.rmdir() assert not d.exists() def test_next_class(self): """ It should be possible to invoke operations on a tempdir and get Path classes. """ d = tempdir() sub = d / 'subdir' assert isinstance(sub, path.Path) d.rmdir() def test_context_manager(self): """ One should be able to use a tempdir object as a context, which will clean up the contents after. """ d = tempdir() res = d.__enter__() assert res is d (d / 'somefile.txt').touch() assert not isinstance(d / 'somefile.txt', tempdir) d.__exit__(None, None, None) assert not d.exists() def test_context_manager_exception(self): """ The context manager will not clean up if an exception occurs. """ d = tempdir() d.__enter__() (d / 'somefile.txt').touch() assert not isinstance(d / 'somefile.txt', tempdir) d.__exit__(TypeError, TypeError('foo'), None) assert d.exists() def test_context_manager_using_with(self): """ The context manager will allow using the with keyword and provide a temporry directory that will be deleted after that. """ with tempdir() as d: assert d.isdir() assert not d.isdir() class TestUnicode: @pytest.fixture(autouse=True) def unicode_name_in_tmpdir(self, tmpdir): # build a snowman (dir) in the temporary directory Path(tmpdir).joinpath('☃').mkdir() def test_walkdirs_with_unicode_name(self, tmpdir): for res in Path(tmpdir).walkdirs(): pass class TestPatternMatching: def test_fnmatch_simple(self): p = Path('FooBar') assert p.fnmatch('Foo*') assert p.fnmatch('Foo[ABC]ar') def test_fnmatch_custom_mod(self): p = Path('FooBar') p.module = ntpath assert p.fnmatch('foobar') assert p.fnmatch('FOO[ABC]AR') def test_fnmatch_custom_normcase(self): def normcase(path): return path.upper() p = Path('FooBar') assert p.fnmatch('foobar', normcase=normcase) assert p.fnmatch('FOO[ABC]AR', normcase=normcase) def test_listdir_simple(self): p = Path('.') assert len(p.listdir()) == len(os.listdir('.')) def test_listdir_empty_pattern(self): p = Path('.') assert p.listdir('') == [] def test_listdir_patterns(self, tmpdir): p = Path(tmpdir) (p / 'sub').mkdir() (p / 'File').touch() assert p.listdir('s*') == [p / 'sub'] assert len(p.listdir('*')) == 2 def test_listdir_custom_module(self, tmpdir): """ Listdir patterns should honor the case sensitivity of the path module used by that Path class. """ always_unix = Path.using_module(posixpath) p = always_unix(tmpdir) (p / 'sub').mkdir() (p / 'File').touch() assert p.listdir('S*') == [] always_win = Path.using_module(ntpath) p = always_win(tmpdir) assert p.listdir('S*') == [p / 'sub'] assert p.listdir('f*') == [p / 'File'] def test_listdir_case_insensitive(self, tmpdir): """ Listdir patterns should honor the case sensitivity of the path module used by that Path class. """ p = Path(tmpdir) (p / 'sub').mkdir() (p / 'File').touch() assert p.listdir(ci('S*')) == [p / 'sub'] assert p.listdir(ci('f*')) == [p / 'File'] assert p.files(ci('S*')) == [] assert p.dirs(ci('f*')) == [] def test_walk_case_insensitive(self, tmpdir): p = Path(tmpdir) (p / 'sub1' / 'foo').makedirs_p() (p / 'sub2' / 'foo').makedirs_p() (p / 'sub1' / 'foo' / 'bar.Txt').touch() (p / 'sub2' / 'foo' / 'bar.TXT').touch() (p / 'sub2' / 'foo' / 'bar.txt.bz2').touch() files = list(p.walkfiles(ci('*.txt'))) assert len(files) == 2 assert p / 'sub2' / 'foo' / 'bar.TXT' in files assert p / 'sub1' / 'foo' / 'bar.Txt' in files @pytest.mark.skipif( sys.version_info < (2, 6), reason="in_place requires io module in Python 2.6", ) class TestInPlace: reference_content = textwrap.dedent(""" The quick brown fox jumped over the lazy dog. """.lstrip()) reversed_content = textwrap.dedent(""" .god yzal eht revo depmuj xof nworb kciuq ehT """.lstrip()) alternate_content = textwrap.dedent(""" Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """.lstrip()) @classmethod def create_reference(cls, tmpdir): p = Path(tmpdir) / 'document' with p.open('w') as stream: stream.write(cls.reference_content) return p def test_line_by_line_rewrite(self, tmpdir): doc = self.create_reference(tmpdir) # reverse all the text in the document, line by line with doc.in_place() as (reader, writer): for line in reader: r_line = ''.join(reversed(line.strip())) + '\n' writer.write(r_line) with doc.open() as stream: data = stream.read() assert data == self.reversed_content def test_exception_in_context(self, tmpdir): doc = self.create_reference(tmpdir) with pytest.raises(RuntimeError) as exc: with doc.in_place() as (reader, writer): writer.write(self.alternate_content) raise RuntimeError("some error") assert "some error" in str(exc) with doc.open() as stream: data = stream.read() assert 'Lorem' not in data assert 'lazy dog' in data class TestSpecialPaths: @pytest.fixture(autouse=True, scope='class') def appdirs_installed(cls): pytest.importorskip('appdirs') @pytest.fixture def feign_linux(self, monkeypatch): monkeypatch.setattr("platform.system", lambda: "Linux") monkeypatch.setattr("sys.platform", "linux") monkeypatch.setattr("os.pathsep", ":") # remove any existing import of appdirs, as it sets up some # state during import. sys.modules.pop('appdirs') def test_basic_paths(self): appdirs = importlib.import_module('appdirs') expected = appdirs.user_config_dir() assert SpecialResolver(Path).user.config == expected expected = appdirs.site_config_dir() assert SpecialResolver(Path).site.config == expected expected = appdirs.user_config_dir('My App', 'Me') assert SpecialResolver(Path, 'My App', 'Me').user.config == expected def test_unix_paths(self, tmpdir, monkeypatch, feign_linux): fake_config = tmpdir / '_config' monkeypatch.setitem(os.environ, 'XDG_CONFIG_HOME', str(fake_config)) expected = str(tmpdir / '_config') assert SpecialResolver(Path).user.config == expected def test_unix_paths_fallback(self, tmpdir, monkeypatch, feign_linux): "Without XDG_CONFIG_HOME set, ~/.config should be used." fake_home = tmpdir / '_home' monkeypatch.delitem(os.environ, 'XDG_CONFIG_HOME', raising=False) monkeypatch.setitem(os.environ, 'HOME', str(fake_home)) expected = Path('~/.config').expanduser() assert SpecialResolver(Path).user.config == expected def test_property(self): assert isinstance(Path.special().user.config, Path) assert isinstance(Path.special().user.data, Path) assert isinstance(Path.special().user.cache, Path) def test_other_parameters(self): """ Other parameters should be passed through to appdirs function. """ res = Path.special(version="1.0", multipath=True).site.config assert isinstance(res, Path) def test_multipath(self, feign_linux, monkeypatch, tmpdir): """ If multipath is provided, on Linux return the XDG_CONFIG_DIRS """ fake_config_1 = str(tmpdir / '_config1') fake_config_2 = str(tmpdir / '_config2') config_dirs = os.pathsep.join([fake_config_1, fake_config_2]) monkeypatch.setitem(os.environ, 'XDG_CONFIG_DIRS', config_dirs) res = Path.special(multipath=True).site.config assert isinstance(res, Multi) assert fake_config_1 in res assert fake_config_2 in res assert '_config1' in str(res) def test_reused_SpecialResolver(self): """ Passing additional args and kwargs to SpecialResolver should be passed through to each invocation of the function in appdirs. """ appdirs = importlib.import_module('appdirs') adp = SpecialResolver(Path, version="1.0") res = adp.user.config expected = appdirs.user_config_dir(version="1.0") assert res == expected class TestMultiPath: def test_for_class(self): """ Multi.for_class should return a subclass of the Path class provided. """ cls = Multi.for_class(Path) assert issubclass(cls, Path) assert issubclass(cls, Multi) expected_name = 'Multi' + Path.__name__ assert cls.__name__ == expected_name def test_detect_no_pathsep(self): """ If no pathsep is provided, multipath detect should return an instance of the parent class with no Multi mix-in. """ path = Multi.for_class(Path).detect('/foo/bar') assert isinstance(path, Path) assert not isinstance(path, Multi) def test_detect_with_pathsep(self): """ If a pathsep appears in the input, detect should return an instance of a Path with the Multi mix-in. """ inputs = '/foo/bar', '/baz/bing' input = os.pathsep.join(inputs) path = Multi.for_class(Path).detect(input) assert isinstance(path, Multi) def test_iteration(self): """ Iterating over a MultiPath should yield instances of the parent class. """ inputs = '/foo/bar', '/baz/bing' input = os.pathsep.join(inputs) path = Multi.for_class(Path).detect(input) items = iter(path) first = next(items) assert first == '/foo/bar' assert isinstance(first, Path) assert not isinstance(first, Multi) assert next(items) == '/baz/bing' assert path == input if __name__ == '__main__': pytest.main() path.py-11.0.1/tox.ini000066400000000000000000000006301325623636300145000ustar00rootroot00000000000000[tox] envlist = python minversion = 2.4 [testenv] deps = setuptools>=31.0.1 # workaround for yaml/pyyaml#126 # git+https://github.com/yaml/pyyaml@master#egg=pyyaml;python_version=="3.7" commands = py.test {posargs} python setup.py checkdocs usedevelop = True extras = testing [testenv:build-docs] extras = docs testing changedir = docs commands = python -m sphinx . {toxinidir}/build/html