rpaths-0.13/0000755000175000017500000000000013075176241013534 5ustar remramremram00000000000000rpaths-0.13/doc/0000755000175000017500000000000013075176241014301 5ustar remramremram00000000000000rpaths-0.13/doc/Makefile0000644000175000017500000001515212567223271015746 0ustar remramremram00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = 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/rpaths.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/rpaths.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/rpaths" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/rpaths" @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." rpaths-0.13/doc/conf.py0000644000175000017500000002020313075175655015605 0ustar remramremram00000000000000# -*- coding: utf-8 -*- # # rpaths documentation build configuration file, created by # sphinx-quickstart on Sat Jun 07 16:49:11 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'rpaths' copyright = u'2014, Remi Rampin' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.13' # The full version, including alpha/beta/rc tags. release = '0.13' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'rpathsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'rpaths.tex', u'rpaths Documentation', u'Remi Rampin', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'rpaths', u'rpaths Documentation', [u'Remi Rampin'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'rpaths', u'rpaths Documentation', u'Remi Rampin', 'rpaths', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/2/': None} rpaths-0.13/doc/index.rst0000644000175000017500000000427312567223271016151 0ustar remramremram00000000000000.. _index: rpaths: a compatible, object-oriented path manipulation library =============================================================== Introduction ------------ Python provides a module to manipulate filenames: :mod:`os.path`. However, it is very cumbersome to use (not object-oriented) and difficult to use safely (because of the bytes/unicode issue). This library provides classes allowing you to perform all the common operations on paths easily, using ad-hoc classes. Moreover, it aims at total Python 2/3 and Windows/POSIX interoperability. In every case, it will behave the "right way", even when dealing with POSIX filenames in broken unicode encodings. Development happens on Github: https://github.com/remram44/rpaths. Feel free to report bugs, request features or direct your patches there. Classes ------- rpaths is organized in two levels. It offers abstract path representations, which only perform parsing/string manipulation and don't actually perform any operation on a file system. When dealing with abstract paths, nothing stops you from manipulating POSIX paths on a Windows host and vice-versa. On top of these abstract paths comes the concrete :class:`~rpaths.Path` class, which represents the native type for the current system. It inherits from the correct abstract class, and adds the actual system operations allowing you to resolve, list, create or remove files. Note that, contrary to other path libraries, none of these types inherits from a built-in string class. However, you can build them from strings in a variety of ways and :func:`repr`, :func:`bytes` and :func:`unicode` will behave how you can expect. Abstract classes '''''''''''''''' Abstract path behavior is defined by the :class:`~rpaths.AbstractPath` class. You shouldn't use that directly, use :class:`~rpaths.PosixPath` and :class:`~rpaths.WindowsPath` which are its implementations. .. autoclass:: rpaths.AbstractPath :members: .. autoclass:: rpaths.PosixPath .. autoclass:: rpaths.WindowsPath Concrete class Path ''''''''''''''''''' The class Path represents a native path on your system. It inherits from either :class:`~rpaths.PosixPath` or :class:`~rpaths.WindowsPath`. .. autoclass:: rpaths.Path :members: rpaths-0.13/rpaths.egg-info/0000755000175000017500000000000013075176241016527 5ustar remramremram00000000000000rpaths-0.13/rpaths.egg-info/PKG-INFO0000644000175000017500000000172313075176240017626 0ustar remramremram00000000000000Metadata-Version: 1.1 Name: rpaths Version: 0.13 Summary: Path manipulation library Home-page: http://github.com/remram44/rpaths Author: Remi Rampin Author-email: remirampin@gmail.com License: BSD Description: rpaths is another path manipulation library. It is heavily inspired by Unipath and pathlib. It aims at total Python 2/3 and Windows/POSIX compatibility. To my knowledge, no other library can handle all the possible paths on every platform. Keywords: path,file,filename,pattern,fnmatch Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: System :: Filesystems rpaths-0.13/rpaths.egg-info/SOURCES.txt0000644000175000017500000000047013075176240020413 0ustar remramremram00000000000000CHANGELOG.md LICENSE MANIFEST.in README.md rpaths.py setup.cfg setup.py doc/Makefile doc/conf.py doc/index.rst rpaths.egg-info/PKG-INFO rpaths.egg-info/SOURCES.txt rpaths.egg-info/dependency_links.txt rpaths.egg-info/top_level.txt tests/__init__.py tests/__main__.py tests/test_abstract.py tests/test_concrete.pyrpaths-0.13/rpaths.egg-info/dependency_links.txt0000644000175000017500000000000113075176240022574 0ustar remramremram00000000000000 rpaths-0.13/rpaths.egg-info/top_level.txt0000644000175000017500000000000713075176240021255 0ustar remramremram00000000000000rpaths rpaths-0.13/tests/0000755000175000017500000000000013075176241014676 5ustar remramremram00000000000000rpaths-0.13/tests/__init__.py0000644000175000017500000000000012567223271016776 0ustar remramremram00000000000000rpaths-0.13/tests/__main__.py0000644000175000017500000000173113075175416016775 0ustar remramremram00000000000000import locale import os import sys try: import unittest2 as unittest except ImportError: import unittest top_level = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) start_dir = os.path.join(top_level, 'tests') if top_level not in sys.path: sys.path.insert(0, top_level) sys.path.append(start_dir) locale.setlocale(locale.LC_ALL, 'C') if not hasattr(unittest, 'skipIf'): sys.stderr.write("This testsuite will not work with pre-2.7 unittest. If " "running Python 2.6, you'll need to install the " "'unittest2' package.\n") sys.exit(1) class Program(unittest.TestProgram): def createTests(self): if self.testNames is None: self.test = self.testLoader.discover( start_dir=start_dir, pattern='test_*.py', top_level_dir=top_level) else: self.test = self.testLoader.loadTestsFromNames(self.testNames) Program() rpaths-0.13/tests/test_abstract.py0000644000175000017500000003671212567223271020124 0ustar remramremram00000000000000from __future__ import unicode_literals try: import unittest2 as unittest except ImportError: import unittest from rpaths import unicode, PY3, AbstractPath, PosixPath, WindowsPath class TestAbstract(unittest.TestCase): def test_construct(self): """Tests building an AbstractPath.""" with self.assertRaises(RuntimeError): AbstractPath('path/to/something') class TestWindows(unittest.TestCase): """Tests for WindowsPath. """ def test_construct(self): """Tests building paths.""" self.assertEqual(WindowsPath('C:\\', WindowsPath('some/dir'), 'with', 'files.txt').path, 'C:\\some\\dir\\with\\files.txt') with self.assertRaises(TypeError): WindowsPath(WindowsPath('C:\\somedir'), PosixPath('file.sh')) self.assertEqual((WindowsPath('Users\\R\xE9mi/Desktop') / WindowsPath(b'pictures/m\xE9chant.jpg')).path, 'Users\\R\xE9mi\\Desktop\\pictures\\m\xE9chant.jpg') self.assertEqual((WindowsPath('C:\\dir') / WindowsPath('D:\\other')).path, 'D:\\other') def test_plus(self): """Tests the plus operator.""" self.assertEqual((WindowsPath('some\\file.txt') + '.bak').path, 'some\\file.txt.bak') with self.assertRaises(TypeError): WindowsPath('some\\file.txt') + WindowsPath('.bak') with self.assertRaises(ValueError): WindowsPath('some\\file.txt') + '.bak/kidding' with self.assertRaises(ValueError): WindowsPath('some\\file.txt') + '/backup' def test_str(self): """Tests getting string representations (repr/bytes/unicode).""" latin = WindowsPath('C:\\r\xE9mi') nonlatin = WindowsPath('C:\\you like\u203D.txt') # repr() self.assertEqual(repr(latin), "WindowsPath(u'C:\\\\r\\xe9mi')") self.assertEqual(repr(nonlatin), "WindowsPath(u'C:\\\\you like\\u203d.txt')") # bytes() self.assertEqual(bytes(latin), b'C:\\r\xe9mi') self.assertEqual(bytes(nonlatin), b'C:\\you like?.txt') # unicode() self.assertEqual(unicode(latin), 'C:\\r\xe9mi') self.assertEqual(unicode(nonlatin), 'C:\\you like\u203d.txt') def test_parts(self): """Tests parent, ancestor, name, stem, ext.""" relative = WindowsPath('directory/users\\r\xE9mi/file.txt') absolute = WindowsPath('\\some/other\\thing.h\xE9h\xE9') self.assertEqual(relative.parent.path, 'directory\\users\\r\xE9mi') self.assertEqual(absolute.parent.path, '\\some\\other') self.assertEqual(absolute.ancestor(10).path, '\\') self.assertEqual(relative.name, 'file.txt') self.assertEqual(absolute.name, 'thing.h\xE9h\xE9') self.assertEqual(absolute.unicodename, 'thing.h\xE9h\xE9') self.assertEqual(absolute.stem, 'thing') self.assertEqual(absolute.ext, '.h\xE9h\xE9') self.assertEqual(relative._components(), ['directory', 'users', 'r\xE9mi', 'file.txt']) self.assertEqual(absolute._components(), ['\\', 'some', 'other', 'thing.h\xE9h\xE9']) def test_root(self): """Tests roots, drives and UNC shares.""" a = WindowsPath(b'some/relative/path') b = WindowsPath('alsorelative') c = WindowsPath(b'/this/is/absolute') d = WindowsPath('C:\\') e = WindowsPath(b'C:\\also/absolute') f = WindowsPath('\\\\SOMEMACHINE\\share\\some\\file') def split_root(f): return tuple(p.path for p in f.split_root()) self.assertEqual(split_root(a), ('.', 'some\\relative\\path')) self.assertEqual(split_root(b), ('.', 'alsorelative')) self.assertFalse(b.is_absolute) self.assertEqual(split_root(c), ('\\', 'this\\is\\absolute')) self.assertTrue(c.is_absolute) self.assertEqual(split_root(d), ('C:\\', '.')) self.assertTrue(d.is_absolute) self.assertEqual(d.root.path, 'C:\\') self.assertEqual(split_root(e), ('C:\\', 'also\\absolute')) # FIXME : normpath() doesn't behave consistently: puts \ at the end on # PY3, not on PY2. self.assertIn(split_root(f), [('\\\\SOMEMACHINE\\share', 'some\\file'), ('\\\\SOMEMACHINE\\share\\', 'some\\file')]) def test_rel_path_to(self): """Tests the rel_path_to method.""" self.assertEqual(WindowsPath('.').rel_path_to(WindowsPath('')).path, '.') self.assertEqual(WindowsPath('\\var\\log\\apache2\\').rel_path_to( '\\var\\www\\cat.jpg').path, '..\\..\\www\\cat.jpg') self.assertEqual(WindowsPath('C:\\var\\log\\apache2\\').rel_path_to( 'C:\\tmp\\access.log').path, '..\\..\\..\\tmp\\access.log') self.assertEqual(WindowsPath('var\\log').rel_path_to( 'var\\log\\apache2\\access.log').path, 'apache2\\access.log') self.assertEqual(WindowsPath('\\var\\log\\apache2').rel_path_to( '\\var\\log\\apache2').path, '.') self.assertEqual(WindowsPath('C:\\').rel_path_to( 'C:\\var\\log\\apache2\\access.log').path, 'var\\log\\apache2\\access.log') self.assertEqual(WindowsPath('\\tmp\\secretdir\\').rel_path_to( '\\').path, '..\\..') self.assertEqual(WindowsPath('C:\\tmp\\secretdir\\').rel_path_to( 'D:\\other\\file.txt').path, 'D:\\other\\file.txt') with self.assertRaises(TypeError): WindowsPath('C:\\mydir\\').rel_path_to(PosixPath('/tmp/file')) def test_lies_under(self): """Tests the lies_under method.""" self.assertTrue(WindowsPath('\\tmp') .lies_under('\\')) self.assertFalse(WindowsPath('C:\\tmp') .lies_under('C:\\var')) self.assertFalse(WindowsPath('\\tmp') .lies_under('C:\\tmp')) self.assertFalse(WindowsPath('C:\\') .lies_under('D:\\tmp')) self.assertTrue(WindowsPath('\\tmp\\some\\file\\here') .lies_under('\\tmp\\some')) self.assertFalse(WindowsPath('\\tmp\\some\\file\\here') .lies_under('\\tmp\\no')) self.assertFalse(WindowsPath('C:\\tmp\\some\\file\\here') .lies_under('C:\\no\\tmp\\some')) self.assertFalse(WindowsPath('\\tmp\\some\\file\\here') .lies_under('\\no\\some')) self.assertTrue(WindowsPath('C:\\tmp\\some\\file\\here') .lies_under('C:\\tmp\\some\\file\\here')) self.assertTrue(WindowsPath('\\') .lies_under('\\')) self.assertTrue(WindowsPath('') .lies_under('')) self.assertTrue(WindowsPath('test') .lies_under('')) self.assertFalse(WindowsPath('') .lies_under('test')) self.assertFalse(WindowsPath('test') .lies_under('\\')) def test_comparisons(self): """Tests the comparison operators.""" self.assertTrue(WindowsPath('\\tmp') == WindowsPath('\\tmp')) self.assertFalse(WindowsPath('C:\\file') != 'c:\\FILE') self.assertTrue('c:\\FILE' == WindowsPath('C:\\file')) self.assertFalse(WindowsPath('C:\\file') == WindowsPath('C:\\dir')) self.assertFalse(WindowsPath('some/file') == PosixPath('some/file')) self.assertTrue(WindowsPath('path/to/file1') < 'path/to/file2') self.assertFalse('path/to/file1' >= WindowsPath('path/to/file2')) if PY3: with self.assertRaises(TypeError): WindowsPath('some/file') < PosixPath('other/file') class TestPosix(unittest.TestCase): """Tests for PosixPath. """ def test_construct(self): """Tests building paths.""" self.assertEqual(PosixPath('/', PosixPath(b'r\xE9mis/dir'), 'with', 'files.txt').path, b'/r\xE9mis/dir/with/files.txt') with self.assertRaises(TypeError): PosixPath('/tmp/test', WindowsPath('folder'), 'cat.gif') self.assertEqual((PosixPath(b'/tmp/dir') / PosixPath('r\xE9mis/files/')).path, b'/tmp/dir/r\xC3\xA9mis/files') if PY3: self.assertEqual(PosixPath('/tmp/r\uDCE9mi').path, b'/tmp/r\xE9mi') self.assertEqual((PosixPath(b'/home/test') / PosixPath('/var/log')).path, b'/var/log') def test_plus(self): """Tests the plus operator.""" self.assertEqual((PosixPath('some/file.txt') + '.bak').path, b'some/file.txt.bak') with self.assertRaises(TypeError): PosixPath('some/file.txt') + PosixPath('.bak') with self.assertRaises(ValueError): PosixPath('some/file.txt') + '.bak/kidding' with self.assertRaises(ValueError): PosixPath('some/file.txt') + '/backup' def test_str(self): """Tests getting string representations (repr/bytes/unicode).""" utf = PosixPath(b'/tmp/r\xC3\xA9mi') nonutf = PosixPath(b'/tmp/r\xE9mi') # repr() self.assertEqual(repr(utf), "PosixPath(b'/tmp/r\\xc3\\xa9mi')") self.assertEqual(repr(nonutf), "PosixPath(b'/tmp/r\\xe9mi')") # bytes() self.assertEqual(bytes(utf), b'/tmp/r\xC3\xA9mi') self.assertEqual(bytes(nonutf), b'/tmp/r\xE9mi') # unicode() self.assertEqual(unicode(utf), '/tmp/r\xE9mi') self.assertEqual(unicode(nonutf), '/tmp/r\uDCE9mi' if PY3 else '/tmp/r\uFFFDmi') def test_parts(self): """Tests parent, ancestor, name, stem, ext.""" relative = PosixPath(b'directory/users/r\xE9mi/file.txt') absolute = PosixPath('/some/other/thing.h\xE9h\xE9') self.assertEqual(relative.parent.path, b'directory/users/r\xE9mi') self.assertEqual(absolute.parent.path, b'/some/other') self.assertEqual(absolute.ancestor(10).path, b'/') self.assertEqual(relative.name, b'file.txt') self.assertEqual(absolute.name, b'thing.h\xC3\xA9h\xC3\xA9') self.assertEqual(absolute.unicodename, 'thing.h\xE9h\xE9') self.assertEqual(absolute.stem, b'thing') self.assertEqual(absolute.ext, b'.h\xC3\xA9h\xC3\xA9') self.assertEqual(relative._components(), [b'directory', b'users', b'r\xE9mi', b'file.txt']) self.assertEqual(absolute._components(), [b'/', b'some', b'other', b'thing.h\xC3\xA9h\xC3\xA9']) def test_root(self): """Tests roots.""" a = PosixPath(b'some/relative/path') b = PosixPath('alsorelative') c = PosixPath(b'/this/is/absolute') d = PosixPath('/') def split_root(f): return tuple(p.path for p in f.split_root()) # FIXME : This behaves weirdly because of normpath(). Do we want this? self.assertEqual(split_root(a), (b'.', b'some/relative/path')) self.assertEqual(split_root(b), (b'.', b'alsorelative')) self.assertFalse(b.is_absolute) self.assertEqual(split_root(c), (b'/', b'this/is/absolute')) self.assertTrue(c.is_absolute) self.assertEqual(split_root(d), (b'/', b'.')) self.assertTrue(d.is_absolute) self.assertEqual(d.root.path, b'/') def test_rel_path_to(self): """Tests the rel_path_to method.""" self.assertEqual(PosixPath('.').rel_path_to(PosixPath('')).path, b'.') self.assertEqual(PosixPath(b'/var/log/apache2/').rel_path_to( b'/var/www/cat.jpg').path, b'../../www/cat.jpg') self.assertEqual(PosixPath(b'/var/log/apache2/').rel_path_to( b'/tmp/access.log').path, b'../../../tmp/access.log') self.assertEqual(PosixPath(b'var/log').rel_path_to( b'var/log/apache2/access.log').path, b'apache2/access.log') self.assertEqual(PosixPath(b'/var/log/apache2').rel_path_to( b'/var/log/apache2').path, b'.') self.assertEqual(PosixPath(b'/').rel_path_to( b'/var/log/apache2/access.log').path, b'var/log/apache2/access.log') self.assertEqual(PosixPath(b'/tmp/secretdir/').rel_path_to( b'/').path, b'../..') def test_lies_under(self): """ Tests the lies_under method.""" self.assertTrue(PosixPath(b'/tmp') .lies_under(b'/')) self.assertFalse(PosixPath(b'/tmp') .lies_under(b'/var')) self.assertTrue(PosixPath(b'/tmp/some/file/here') .lies_under(b'/tmp/some')) self.assertFalse(PosixPath(b'/tmp/some/file/here') .lies_under(b'/tmp/no')) self.assertFalse(PosixPath(b'/tmp/some/file/here') .lies_under(b'/no/tmp/some')) self.assertFalse(PosixPath(b'/tmp/some/file/here') .lies_under(b'/no/some')) self.assertTrue(PosixPath(b'/tmp/some/file/here') .lies_under(b'/tmp/some/file/here')) self.assertTrue(PosixPath(b'/') .lies_under(b'/')) self.assertTrue(PosixPath(b'') .lies_under(b'')) self.assertTrue(PosixPath(b'test') .lies_under(b'')) self.assertFalse(PosixPath(b'') .lies_under(b'test')) self.assertFalse(PosixPath(b'test') .lies_under(b'/')) def test_comparisons(self): """Tests the comparison operators.""" self.assertTrue(PosixPath(b'/tmp/r\xE9mi') == b'/tmp/r\xE9mi') self.assertTrue(PosixPath(b'/file') != b'/FILE') self.assertFalse(PosixPath(b'file') == PosixPath(b'dir')) self.assertFalse(WindowsPath('some/file') == PosixPath('some/file')) self.assertTrue(PosixPath(b'path/to/file1') < b'path/to/file2') self.assertFalse(b'path/to/file1' >= PosixPath(b'path/to/file2')) if PY3: with self.assertRaises(TypeError): WindowsPath('some/file') < PosixPath('other/file') rpaths-0.13/tests/test_concrete.py0000644000175000017500000003071213075175417020120 0ustar remramremram00000000000000from __future__ import unicode_literals import os import sys try: import unittest2 as unittest except ImportError: import unittest from rpaths import unicode, dict_union, Path, PosixPath, WindowsPath, \ Pattern, pattern2re windows_only = unittest.skipUnless(issubclass(Path, WindowsPath), "Only runs on Windows") posix_only = unittest.skipUnless(issubclass(Path, PosixPath), "Only runs on POSIX") class TestConcrete(unittest.TestCase): """Tests for Path. Because this tests the concrete Path, it needs to be run on both Windows and POSIX to ensure everything is correct. """ def test_cwd(self): """Tests cwd, in_dir.""" cwd = os.getcwd() if os.name == 'nt' and isinstance(cwd, bytes): cwd = cwd.decode('mbcs') elif os.name != 'nt' and isinstance(cwd, unicode): cwd = cwd.encode(sys.getfilesystemencoding()) self.assertEqual(Path.cwd().path, cwd) tmp = Path.tempdir().resolve() with tmp.in_dir(): self.assertEqual(Path.cwd(), tmp) self.assertNotEqual(Path.cwd(), tmp) self.assertTrue(tmp.exists()) tmp.rmdir() self.assertFalse(tmp.exists()) def test_tempfile(self): """Tests tempfile.""" fd, f = Path.tempfile() os.close(fd) try: self.assertTrue(f.exists()) self.assertTrue(f.is_file()) self.assertTrue(f.is_absolute) finally: f.remove() self.assertFalse(f.exists()) def test_rel_path_to(self): self.assertEqual(Path('some/prefix/and/a/directory/').rel_path_to( 'some/prefix/path/to/cat.jpg'), Path('../../../path/to/cat.jpg')) self.assertEqual(Path('some/prefix/').rel_path_to( Path('some/prefix/path/to/cat.jpg')), Path('path/to/cat.jpg')) def test_rewrite(self): tmp = Path.tempdir() try: # Create original file orig = tmp / 'unix.txt' # Write some contents with orig.open('wb') as fp: fp.write(b"Some\ncontent\nin here\n") if issubclass(Path, PosixPath): orig.chmod(0o755) # Rewrite it in place! with orig.rewrite(read_newline='\n', write_newline='\r\n') as (r, w): w.write(r.read()) with orig.open('rb') as fp: self.assertEqual(fp.read(), b"Some\r\ncontent\r\nin here\r\n") if issubclass(Path, PosixPath): self.assertTrue(orig.stat().st_mode & 0o100) finally: tmp.rmtree() class PathUTF8(Path): if os.name != 'nt': _encoding = 'utf-8' class TestLists(unittest.TestCase): """Tests listing methods. """ @classmethod def setUpClass(cls): """Builds a test hierarchy.""" cls.tmp = PathUTF8.tempdir() cls.tmp.open('w', 'file').close() cls.tmp.open('w', 'r\xE9mi\'s thing').close() d = cls.tmp.mkdir('r\xE9pertoire') d.open('w', 'file').close() d.mkdir('nested') if issubclass(Path, PosixPath): (d / 'last').symlink('..') else: d.open('w', 'last').close() @classmethod def tearDownClass(cls): """Removes the test files.""" cls.tmp.rmtree() def test_list_empty(self): """Lists an empty directory.""" d = self.tmp.mkdir('emptydir') try: self.assertEqual(d.listdir(), []) finally: d.rmdir() def compare_paths(self, root, actual, expected): expected = expected[issubclass(Path, PosixPath)] actual = set(p.path for p in actual) expected = set(os.path.join(root.path, f) for f in expected) self.assertEqual(actual, expected) def test_listdir(self): """Lists test directories.""" self.compare_paths(self.tmp, self.tmp.listdir(), (['file', 'r\xE9mi\'s thing', 'r\xE9pertoire'], [b'file', b'r\xC3\xA9mi\'s thing', b'r\xC3\xA9pertoire'])) self.compare_paths(self.tmp, self.tmp.listdir('*e'), (['file', 'r\xE9pertoire'], [b'file', b'r\xC3\xA9pertoire'])) self.compare_paths(self.tmp, self.tmp.listdir(lambda p: p.is_dir()), (['r\xE9pertoire'], [b'r\xC3\xA9pertoire'])) p2 = self.tmp / 'r\xE9pertoire' self.compare_paths(p2, p2.listdir(), (['file', 'nested', 'last'], [b'file', b'nested', b'last'])) self.compare_paths(p2, p2.listdir('*e'), (['file'], [b'file'])) def test_recursedir(self): """Uses recursedir to list a hierarchy.""" expected = (['file', 'r\xE9mi\'s thing', 'r\xE9pertoire', 'r\xE9pertoire\\file', 'r\xE9pertoire\\last', 'r\xE9pertoire\\nested'], [b'file', b'r\xC3\xA9mi\'s thing', b'r\xC3\xA9pertoire', b'r\xC3\xA9pertoire/file', b'r\xC3\xA9pertoire/last', b'r\xC3\xA9pertoire/nested']) self.compare_paths(self.tmp, self.tmp.recursedir(), expected) self.compare_paths(self.tmp, self.tmp.recursedir('*'), expected) self.compare_paths(self.tmp, self.tmp.recursedir('*e'), (['file', 'r\xE9pertoire', 'r\xE9pertoire\\file'], [b'file', b'r\xC3\xA9pertoire', b'r\xC3\xA9pertoire/file'])) self.compare_paths(self.tmp, self.tmp.recursedir(Pattern('/file')), (['file'], [b'file'])) self.compare_paths(self.tmp, self.tmp.recursedir('/r\xE9pertoire/file'), (['r\xE9pertoire\\file'], [b'r\xC3\xA9pertoire/file'])) self.compare_paths(self.tmp, self.tmp.recursedir(Pattern('/r\xE9pertoire/file')), (['r\xE9pertoire\\file'], [b'r\xC3\xA9pertoire/file'])) class TestPattern2Re(unittest.TestCase): """Tests the pattern2re() function, used to recognize extended patterns. """ def do_test_pattern(self, pattern, start, tests, interm=False): s, fr, ir = pattern2re(pattern) error = '' if s != start: error += "\n%r didn't start at %r (but %r)" % (pattern, start, s) if interm: r = ir suffix = " (interm=True)" else: r = fr suffix = "" for path, expected in tests: passed = r.search(path) if passed and not expected: error += "\n%r matched %r%s" % (pattern, path, suffix) elif not passed and expected: error += "\n%r didn't match %r%s" % (pattern, path, suffix) if error: self.fail(error) def test_components(self): """Tests how components are handled, with '*', '**', '/'.""" self.do_test_pattern( # Pattern does not contain a slash: only matches the filename, # line fnmatch r'*.txt', '', [('test.txt', True), ('some/test.txt', True), ('.txt/file.png', False), ('not_a.txt/thing.txt.jpg', False)]) self.do_test_pattern( # Pattern contains a slash: matches on the whole path r'/*.txt', '', [('test.txt', True), ('some/test.txt', False), ('.txt/file.png', False), ('not_a.txt/thing.txt.jpg', False)]) self.do_test_pattern( # Note that trailing slash is ignored; do not use this... r'mydir/*.txt/', 'mydir', [('test.txt', False), ('some/dir/test.txt', False), ('some/path/mydir/test.txt', False), ('mydir/thing.txt', True), ('.txt/file.png', False), ('mydir/thing.txt.jpg', False)]) self.do_test_pattern( # ** will match at least one component r'**/mydir/*.txt', '', [('test.txt', False), ('some/dir/test.txt', False), ('path/mydir/test.txt', True), ('path/notmydir/test.txt', False), ('some/path/mydir/test.txt', True), ('mydir/thing.txt', False), ('.txt/file.png', False), ('mydir/thing.txt.jpg', False)]) self.do_test_pattern('', '', [('file', True), ('other/thing/here', True)]) def test_wildcards(self): self.do_test_pattern( r'some?file*.txt', '', [('somefile.txt', False), ('some file.txt', True), ('some;filename.txt', True), ('wowsome file.txt', False), ('some filename.txt.exe', False), ('some/filename.txt', False), ('some file/name.txt', False)]) self.do_test_pattern( r'some\?file\*.txt', '', [('some file*.txt', False), ('some?file*.txt', True), ('some?filename.txt', False), ('some?file*.txt', True)]) self.do_test_pattern( r'**/file', '', [('file', False), ('path/file', True), ('path/to/file', True), ('not/afile', False)]) self.do_test_pattern( r'path/**/file', 'path', [('path/to/file', True), ('path/file', False), ('path/file', False), ('path/to/a/file', True), ('pathto/a/file', False), ('path/to/afile', False)]) self.do_test_pattern( r'path/**', 'path', [('path', False), ('path/file', True), ('path/to/file', True)]) def test_classes(self): self.do_test_pattern( r'some[ ?a]file', '', [('someafile', True), ('some file', True), ('some?file', True), ('some-file', False)]) self.do_test_pattern( # This one is a bit weird and not very useful but helps # prove that PCRE things get escaped correctly r'some[[:alpha:]]file', '', [('somea]file', True), ('some[]file', True), ('some:]file', True), ('someb]file', False), ('somebfile', False)]) def test_iterm(self): """Tests the int_regex return value.""" self.do_test_pattern( r'/usr/path/*.txt', 'usr/path', [('usr', True), ('usr/path', True), ('usr/lib', False)], interm=True) def test_pattern(self): """Tests the high-level Pattern class.""" for pattern in ('/usr/l*/**/*.txt', b'/usr/l*/**/*.txt'): pattern = Pattern(pattern) self.assertTrue(pattern.matches('/usr/lib/irc/test.txt')) self.assertTrue(pattern.matches(b'/usr/local/lib/test.txt')) self.assertFalse(pattern.matches('/usr/bin/test.txt')) self.assertTrue(pattern.may_contain_matches('/usr/lib')) self.assertTrue(pattern.may_contain_matches('/usr')) self.assertFalse(pattern.may_contain_matches(b'/usr/bin')) self.assertTrue(pattern.matches('usr/lib/irc/test.txt')) self.assertFalse(pattern.matches('smthg/usr/lib/irc/test.txt')) self.assertTrue(pattern.may_contain_matches('usr/lib')) self.assertTrue(pattern.may_contain_matches('usr')) self.assertTrue(pattern.matches(WindowsPath( 'usr\\localuser\\Binaries\\readme.txt'))) self.assertFalse(pattern.matches(WindowsPath( 'usr\\otheruser\\Binaries\\readme.txt'))) self.assertEqual(pattern.matches('usr\\lib\\thing\\readme.txt'), issubclass(Path, WindowsPath)) class TestDictUnion(unittest.TestCase): def test_union(self): common = {'a': 1, 'b': 2} t1 = {'a': 3, 'c': 5} t2 = {'a': 4, 'd': 8} self.assertEqual(dict_union(common, t1), {'a': 3, 'b': 2, 'c': 5}) self.assertEqual(dict_union(common, t2), {'a': 4, 'b': 2, 'd': 8}) self.assertEqual(common, {'a': 1, 'b': 2}) rpaths-0.13/CHANGELOG.md0000644000175000017500000000525613075175602015355 0ustar remramremram00000000000000Changelog ========= 0.13 (2017-04-17) ----------------- Enhancements: * Add documentation to sdist (by @ghisvail, #20) * Run tests with UTF-8 path encoding (this means they'll pass even on a machine with ASCII locale) 0.12 (2016-03-25) ----------------- Enhancements: * Don't follow symlinks in `recursedir()` * Allow `recursedir()` to keep going by passing it a `handle_errors` callback instead of letting it raise. Behavior change: * `recursedir()` now doesn't follow symlinks unless you set `follow_links=True` explicitely 0.11 (2015-08-26) ----------------- Enhancements: * Add a `Pattern` class, exposing pattern-matching outside of directory listing. 0.10 (2014-11-06) ----------------- Bugfixes: * Fixes a `rel_path_to()` bug on Python 3 * Fixes `'.'.rel_path_to('.')` exception * Fixes `tempfile()` and `tempdir()` not accepting Path as 'dir' parameter 0.9 (2014-10-20) ---------------- Features: * unicode() conversion uses `surrogateescape` on Python 3 0.8 (2014-08-15) ---------------- Bugfixes: * Fixes recursedir()'s recursing on too many folders Features: * chown() now has 'no change' defaults for uid and gid * Adds '+' operator to add a string to the end of the name of a path * Adds `Path#rewrite()` context-manager, for rewriting a file in-place 0.7 (2014-07-24) ---------------- Features: * Extended glob filters (à la git, /some/dir*/**/*.log) * Python 3.2 compatibility 0.6 (2014-07-21) ---------------- Bugfixes: * Fixes non-working `Path#rel_path_to()`. 0.5 (2014-06-26) ---------------- Features: * Adds `pattern` parameter to `listdir()` and `recursedir()` 0.4 (2014-06-19) ---------------- Bugfixes: * Adds missing `__all__` lists * Actually prevents the creation of `AbstractPath` directly (thanks to VnC-) Features: * Adds comparison operators 0.3 (2014-06-11) ---------------- Bugfixes: * `Path.read_link()` didn't work at all. * `AbstractPath.__eq__()` now returns False instead of raising TypeError if the objects are not compatible. Features: * Adds `AbstractPath.lies_under()` * `Path.open()` uses `io.open()`. It now accepts the buffering, encoding, errors, newline, closefd and opener arguments, and will return unicode instead of bytes if opened in text mode (the default) on Python 2. 0.2 (2014-06-09) ---------------- Bugfixes: * Makes `__hash__` use `normcase` (like `__eq__` does). * Removes `AbstractPath.relative()` since it only worked for `Path` anyway. * Fixes `*atime` methods. Features: * Adds docstrings everywhere. There is some HTML documentation at ReadTheDocs: http://rpaths.remram.fr/ 0.1 (2014-06-07) ---------------- * Basic functionality. * Stores paths as `unicode` or `bytes` depending on path type. * `AbstractPath`/`Path` separation. rpaths-0.13/LICENSE0000644000175000017500000000272612567223271014551 0ustar remramremram00000000000000Copyright (c) 2014, Remi Rampin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. rpaths-0.13/MANIFEST.in0000644000175000017500000000014513075175416015275 0ustar remramremram00000000000000include README.md include LICENSE include CHANGELOG.md graft tests graft doc global-exclude *.py[co] rpaths-0.13/README.md0000644000175000017500000000352413075175416015022 0ustar remramremram00000000000000[![Linux Build](https://travis-ci.org/remram44/rpaths.svg?branch=master)](https://travis-ci.org/remram44/rpaths) [![Win Build](https://ci.appveyor.com/api/projects/status/s7efr8aoqkyp69t0/branch/master)](https://ci.appveyor.com/project/remram44/rpaths) [![Coverage Status](http://codecov.io/github/remram44/rpaths/coverage.svg?branch=master)](http://codecov.io/github/remram44/rpaths/coverage.svg?branch=master) rpaths ====== rpaths is yet another path manipulation library. The [full documentation is built by ReadTheDocs] (http://rpaths.remram.fr/en/latest/). It pains me that I should have to write this, however after a survey of the existing packages, including [pathlib] (https://docs.python.org/3/library/pathlib.html) (included in the Python standard library since 3.4, see [PEP 428] (http://legacy.python.org/dev/peps/pep-0428/)), it appears that every one of them chokes on one valid filename or another. * [Unipath](https://github.com/mikeorr/Unipath) is very close. In fact it is, with pathlib, one of the main inspirations for this work. Unfortunately it makes its path inherit from unicode or bytes, which makes the abstract/concrete class separation too tricky. * [pathlib](https://bitbucket.org/pitrou/pathlib/) is affected with [a bug preventing it from representing some filenames on Windows on Python 2] (https://bitbucket.org/pitrou/pathlib/issue/25); this bug was marked as wontfix. Furthermore, it works very differently on Python 2 and 3, which I believe is very counter-productive. * [path.py](https://github.com/jaraco/path.py) is affected with [a bug making it fail when encountering some filenames on POSIX] (https://github.com/jaraco/path.py/issues/61). This is also believed to allow for DoS attacks. * [fpath](https://github.com/wackywendell/fpath) is affected with the [same bug](https://github.com/wackywendell/fpath/issues/5) as path.py. rpaths-0.13/rpaths.py0000644000175000017500000012045613075175671015425 0ustar remramremram00000000000000from __future__ import unicode_literals import contextlib import functools import io import ntpath import os import posixpath import re import shutil import sys import tempfile __all__ = ["unicode", "Path", "PY3", "PosixPath", "WindowsPath"] __version__ = '0.13' PY3 = sys.version_info[0] == 3 if PY3: unicode = str else: unicode = unicode backend_types = (unicode, bytes) MAX_CACHE = 128 if hasattr(functools, 'lru_cache'): memoize1 = functools.lru_cache(MAX_CACHE) else: def memoize1(f): _cache = {} @functools.wraps(f) def wrapped(arg): if arg in _cache: return _cache[arg] else: res = f(arg) if len(_cache) > MAX_CACHE: _cache.clear() _cache[arg] = res return res return wrapped def supports_unicode_filenames(lib): # Python is bugged; lib.supports_unicode_filenames is wrong return lib is ntpath def dict_union(*dcts): dct = {} for dct2 in dcts: dct.update(dct2) return dct class AbstractPath(object): """An abstract representation of a path. This represents a path on a system that may not be the current one. It doesn't provide any way to actually interact with the local file system. """ _lib = None def _to_backend(self, p): """Converts something to the correct path representation. If given a Path, this will simply unpack it, if it's the correct type. If given the correct backend, it will return that. If given bytes for unicode of unicode for bytes, it will encode/decode with a reasonable encoding. Note that these operations can raise UnicodeError! """ if isinstance(p, self._cmp_base): return p.path elif isinstance(p, self._backend): return p elif self._backend is unicode and isinstance(p, bytes): return p.decode(self._encoding) elif self._backend is bytes and isinstance(p, unicode): return p.encode(self._encoding, 'surrogateescape' if PY3 else 'strict') else: raise TypeError("Can't construct a %s from %r" % ( self.__class__.__name__, type(p))) def __init__(self, *parts): """Creates a path from one or more components. """ if self._lib is None: # pragma: no cover raise RuntimeError("Can't create an AbstractPath directly!") self._backend = (unicode if supports_unicode_filenames(self._lib) else bytes) self._sep = self._lib.sep if self._backend is unicode and isinstance(self._sep, bytes): self._sep = self._sep.decode('ascii') elif self._backend is bytes and isinstance(self._sep, unicode): self._sep = self._sep.encode('ascii') self.path = self._normpath( self._lib.join(*[self._to_backend(p) for p in parts])) @classmethod def _normpath(cls, p): """This gets a pathname into the proper form it will be stored as. """ return cls._lib.normpath(p) @classmethod def _normcase(cls, p): """This gets a pathname into the proper form for equality testing. """ return cls._lib.normcase(p) def __div__(self, other): """Joins two paths. """ return self.__class__(self, other) __truediv__ = __div__ def __add__(self, other): """Adds a suffix to some path (for example, '.bak'). """ if not isinstance(other, backend_types): raise TypeError("+ operator expects a str or bytes object, " "got %r" % type(other)) other = self._to_backend(other) if self._to_backend('/') in other or self._sep in other: raise ValueError("Can't add separators to filename with +, use /") return self.__class__(self.path + other) def __eq__(self, other): """Compares two paths. This will ignore the case on systems where it is not relevant. Note that if two paths are equal, they represent the same file, but the opposite might not be true. """ try: other = self._to_backend(other) except TypeError: return NotImplemented else: return (self._normcase(self.path) == self._normcase(other)) # functools.total_ordering is broken (cf http://bugs.python.org/issue10042) # so we don't use it def __ne__(self, other): return not (self == other) def __lt__(self, other): """Compares two paths. This will ignore the case on systems where it is not relevant. """ try: other = self._to_backend(other) except TypeError: return NotImplemented else: return self._normcase(self.path) < self._normcase(other) def __le__(self, other): """Compares two paths. This will ignore the case on systems where it is not relevant. """ try: other = self._to_backend(other) except TypeError: return NotImplemented else: return self._normcase(self.path) <= self._normcase(other) def __gt__(self, other): """Compares two paths. This will ignore the case on systems where it is not relevant. """ try: other = self._to_backend(other) except TypeError: return NotImplemented else: return self._normcase(self.path) > self._normcase(other) def __ge__(self, other): """Compares two paths. This will ignore the case on systems where it is not relevant. """ try: other = self._to_backend(other) except TypeError: return NotImplemented else: return self._normcase(self.path) >= self._normcase(other) def __hash__(self): return hash(self._normcase(self.path)) def __repr__(self): """Prints a representation of the path. Returns WindowsPath(u'C:\\somedir') or PosixPath(b'/tmp'). It always puts the 'b' or 'u' prefix (nobody likes Python 3.2 anyway). """ if self._backend is unicode: s = repr(self.path) if PY3: s = s.encode('ascii', 'backslashreplace').decode('ascii') if s[0] != 'u': s = 'u' + s else: s = repr(self.path) if s[0] != 'b': s = 'b' + s return '%s(%s)' % (self.__class__.__name__, s) def __bytes__(self): """Gives a bytestring version of the path. Note that if the path is unicode and contains international characters, this function will not raise, but the pathname will not be valid. It is meant for display purposes only; use the ``path`` attribute for a correct path (which might be bytes or unicode, depending on the system). """ if self._backend is unicode: return self.path.encode(self._encoding, 'replace') else: return self.path def __unicode__(self): """Gives a unicode version of the path. Note that if the path is binary and contains invalid byte sequences, this function will not raise, but the pathname will not be valid. It is meant for display purposes only; use the ``path`` attribute for a correct path (which might be bytes or unicode, depending on the system). """ if self._backend is bytes: if PY3: return self.path.decode(self._encoding, 'surrogateescape') else: return self.path.decode(self._encoding, 'replace') else: return self.path if PY3: __str__ = __unicode__ else: __str__ = __bytes__ def expand_user(self): """Replaces ``~`` or ``~user`` by that user's home directory. """ return self.__class__(self._lib.expanduser(self.path)) def expand_vars(self): """Expands environment variables in the path. They might be of the form ``$name`` or ``${name}``; references to non-existing variables are kept unchanged. """ return self.__class__(self._lib.expandvars(self.path)) @property def parent(self): """The parent directory of this path. """ p = self._lib.dirname(self.path) p = self.__class__(p) return p @property def name(self): """The name of this path, i.e. the final component without directories. """ return self._lib.basename(self.path) @property def unicodename(self): """The name of this path as unicode. """ n = self._lib.basename(self.path) if self._backend is unicode: return n else: return n.decode(self._encoding, 'replace') @property def stem(self): """The name of this path without the extension. """ return self._lib.splitext(self.name)[0] @property def ext(self): """The extension of this path. """ return self._lib.splitext(self.path)[1] def split_root(self): """Splits this path into a pair (drive, location). Note that, because all paths are normalized, a root of ``'.'`` will be returned for relative paths. """ if not PY3 and hasattr(self._lib, 'splitunc'): root, rest = self._lib.splitunc(self.path) if root: if rest.startswith(self._sep): root += self._sep rest = rest[1:] return self.__class__(root), self.__class__(rest) root, rest = self._lib.splitdrive(self.path) if root: if rest.startswith(self._sep): root += self._sep rest = rest[1:] return self.__class__(root), self.__class__(rest) if self.path.startswith(self._sep): return self.__class__(self._sep), self.__class__(rest[1:]) return self.__class__(''), self @property def root(self): """The root of this path. This will be either a root (with optionally a drive name or UNC share) or ``'.'`` for relative paths. """ return self.split_root()[0] @property def components(self): """Splits this path into its components. The first component will be the root if this path is relative, then each component leading to the filename. """ return [self.__class__(p) for p in self._components()] def _components(self): root, loc = self.split_root() if root.path != self._to_backend('.'): components = [root.path] else: components = [] if loc.path != self._to_backend('.'): components.extend(loc.path.split(self._sep)) return components def ancestor(self, n): """Goes up `n` directories. """ p = self for i in range(n): p = p.parent return p def norm_case(self): """Removes the case if this flavor of paths is case insensitive. """ return self.__class__(self._normcase(self.path)) @property def is_absolute(self): """Indicates whether this path is absolute or relative. """ return self.root.path != self._to_backend('.') def rel_path_to(self, dest): """Builds a relative path leading from this one to the given `dest`. Note that these paths might be both relative, in which case they'll be assumed to start from the same directory. """ dest = self.__class__(dest) orig_list = self.norm_case()._components() dest_list = dest._components() i = -1 for i, (orig_part, dest_part) in enumerate(zip(orig_list, dest_list)): if orig_part != self._normcase(dest_part): up = ['..'] * (len(orig_list) - i) return self.__class__(*(up + dest_list[i:])) if len(orig_list) <= len(dest_list): if len(dest_list) > i + 1: return self.__class__(*dest_list[i + 1:]) else: return self.__class__('') else: up = ['..'] * (len(orig_list) - i - 1) return self.__class__(*up) def lies_under(self, prefix): """Indicates if the `prefix` is a parent of this path. """ orig_list = self.norm_case()._components() pref_list = self.__class__(prefix).norm_case()._components() return (len(orig_list) >= len(pref_list) and orig_list[:len(pref_list)] == pref_list) class WindowsPath(AbstractPath): """An abstract representation of a Windows path. It is safe to build and use objects of this class even when not running on Windows. """ _lib = ntpath _encoding = 'windows-1252' WindowsPath._cmp_base = WindowsPath class PosixPath(AbstractPath): """An abstract representation of a POSIX path. It is safe to build and use objects of this class even when running on Windows. """ _lib = posixpath _encoding = 'utf-8' PosixPath._cmp_base = PosixPath DefaultAbstractPath = WindowsPath if os.name == 'nt' else PosixPath try: import unicodedata except ImportError: pass else: class MacOSPath(PosixPath): """An abstract representation of a path on Mac OS X. The filesystem on Mac OS X (HFS) normalizes unicode sequences (NFC). """ @classmethod def _normpath(cls, p): return unicodedata.normalize('NFC', p.decode('utf-8')).encode('utf-8') if sys.platform == 'darwin': DefaultAbstractPath = MacOSPath class Path(DefaultAbstractPath): """A concrete representation of an actual path on this system. This extends either :class:`~rpaths.WindowsPath` or :class:`~rpaths.PosixPath` depending on the current system. It adds concrete filesystem operations. """ @property def _encoding(self): return sys.getfilesystemencoding() @classmethod def cwd(cls): """Returns the current directory. """ return cls(os.getcwd()) def chdir(self): """Changes the current directory to this path. """ os.chdir(self.path) @contextlib.contextmanager def in_dir(self): """Context manager that changes to this directory then changes back. """ previous_dir = self.cwd() self.chdir() try: yield finally: previous_dir.chdir() @classmethod def tempfile(cls, suffix='', prefix=None, dir=None, text=False): """Returns a new temporary file. The return value is a pair (fd, path) where fd is the file descriptor returned by :func:`os.open`, and path is a :class:`~rpaths.Path` to it. :param suffix: If specified, the file name will end with that suffix, otherwise there will be no suffix. :param prefix: Is specified, the file name will begin with that prefix, otherwise a default prefix is used. :param dir: If specified, the file will be created in that directory, otherwise a default directory is used. :param text: If true, the file is opened in text mode. Else (the default) the file is opened in binary mode. On some operating systems, this makes no difference. The file is readable and writable only by the creating user ID. If the operating system uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by children of this process. The caller is responsible for deleting the file when done with it. """ if prefix is None: prefix = tempfile.template if dir is not None: # Note that this is not safe on Python 2 # There is no work around, apart from not using the tempfile module dir = str(Path(dir)) fd, filename = tempfile.mkstemp(suffix, prefix, dir, text) return fd, cls(filename).absolute() @classmethod def tempdir(cls, suffix='', prefix=None, dir=None): """Returns a new temporary directory. Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the `text` argument is not accepted. The directory is readable, writable, and searchable only by the creating user. The caller is responsible for deleting the directory when done with it. """ if prefix is None: prefix = tempfile.template if dir is not None: # Note that this is not safe on Python 2 # There is no work around, apart from not using the tempfile module dir = str(Path(dir)) dirname = tempfile.mkdtemp(suffix, prefix, dir) return cls(dirname).absolute() def absolute(self): """Returns a normalized absolutized version of the path. """ return self.__class__(self._lib.abspath(self.path)) def rel_path_to(self, dest): """Builds a relative path leading from this one to another. Note that these paths might be both relative, in which case they'll be assumed to be considered starting from the same directory. Contrary to :class:`~rpaths.AbstractPath`'s version, this will also work if one path is relative and the other absolute. """ return super(Path, self.absolute()).rel_path_to(Path(dest).absolute()) def relative(self): """Builds a relative version of this path from the current directory. This is the same as ``Path.cwd().rel_path_to(thispath)``. """ return self.cwd().rel_path_to(self) def resolve(self): """Expands the symbolic links in the path. """ return self.__class__(self._lib.realpath(self.path)) def listdir(self, pattern=None): """Returns a list of all the files in this directory. The special entries ``'.'`` and ``'..'`` will not be returned. :param pattern: A pattern to match directory entries against. :type pattern: NoneType | Callable | Pattern | unicode | bytes """ files = [self / self.__class__(p) for p in os.listdir(self.path)] if pattern is None: pass elif callable(pattern): files = filter(pattern, files) else: if isinstance(pattern, backend_types): if isinstance(pattern, bytes): pattern = pattern.decode(self._encoding, 'replace') start, full_re, _int_re = pattern2re(pattern) elif isinstance(pattern, Pattern): start, full_re = pattern.start_dir, pattern.full_regex else: raise TypeError("listdir() expects pattern to be a callable, " "a regular expression or a string pattern, " "got %r" % type(pattern)) # If pattern contains slashes (other than first and last chars), # listdir() will never match anything if start: return [] files = [f for f in files if full_re.search(f.unicodename)] return files def recursedir(self, pattern=None, top_down=True, follow_links=False, handle_errors=None): """Recursively lists all files under this directory. :param pattern: An extended patterns, where: * a slash '/' always represents the path separator * a backslash '\' escapes other special characters * an initial slash '/' anchors the match at the beginning of the (relative) path * a trailing '/' suffix is removed * an asterisk '*' matches a sequence of any length (including 0) of any characters (except the path separator) * a '?' matches exactly one character (except the path separator) * '[abc]' matches characters 'a', 'b' or 'c' * two asterisks '**' matches one or more path components (might match '/' characters) :type pattern: NoneType | Callable | Pattern | unicode | bytes :param follow_links: If False, symbolic links will not be followed (the default). Else, they will be followed, but directories reached through different names will *not* be listed multiple times. :param handle_errors: Can be set to a callback that will be called when an error is encountered while accessing the filesystem (such as a permission issue). If set to None (the default), exceptions will be propagated. """ if not self.is_dir(): raise ValueError("recursedir() called on non-directory %s" % self) start = '' int_pattern = None if pattern is None: pattern = lambda p: True elif callable(pattern): pass else: if isinstance(pattern, backend_types): if isinstance(pattern, bytes): pattern = pattern.decode(self._encoding, 'replace') start, full_re, int_re = pattern2re(pattern) elif isinstance(pattern, Pattern): start, full_re, int_re = \ pattern.start_dir, pattern.full_regex, pattern.int_regex else: raise TypeError("recursedir() expects pattern to be a " "callable, a regular expression or a string " "pattern, got %r" % type(pattern)) if self._lib.sep != '/': pattern = lambda p: full_re.search( unicode(p).replace(self._lib.sep, '/')) if int_re is not None: int_pattern = lambda p: int_re.search( unicode(p).replace(self._lib.sep, '/')) else: pattern = lambda p: full_re.search(unicode(p)) if int_re is not None: int_pattern = lambda p: int_re.search(unicode(p)) if not start: path = self else: path = self / start if not path.exists(): return [] elif not path.is_dir(): return [path] return path._recursedir(pattern=pattern, int_pattern=int_pattern, top_down=top_down, seen=set(), path=self.__class__(start), follow_links=follow_links, handle_errors=handle_errors) def _recursedir(self, pattern, int_pattern, top_down, seen, path, follow_links=False, handle_errors=None): real_dir = self.resolve() if real_dir in seen: return seen.add(real_dir) try: dir_list = os.listdir(self.path) except OSError: if handle_errors is not None: handle_errors(self.path) return raise for child in dir_list: newpath = path / child child = self / child is_dir = child.is_dir() and (not child.is_link() or follow_links) # Fast failing thanks to int_pattern here: if we don't match # int_pattern, don't try inner files either matches_pattern = pattern(newpath) if (not matches_pattern and int_pattern is not None and not int_pattern(newpath)): continue if is_dir and not top_down: for grandkid in child._recursedir(pattern, int_pattern, top_down, seen, newpath, follow_links, handle_errors): yield grandkid if matches_pattern: yield child if is_dir and top_down: for grandkid in child._recursedir(pattern, int_pattern, top_down, seen, newpath, follow_links, handle_errors): yield grandkid def exists(self): """True if the file exists, except for broken symlinks where it's False. """ return self._lib.exists(self.path) def lexists(self): """True if the file exists, even if it's a broken symbolic link. """ return self._lib.lexists(self.path) def is_file(self): """True if this file exists and is a regular file. """ return self._lib.isfile(self.path) def is_dir(self): """True if this file exists and is a directory. """ return self._lib.isdir(self.path) def is_link(self): """True if this file exists and is a symbolic link. """ return self._lib.islink(self.path) def is_mount(self): """True if this file is a mount point. """ return self._lib.ismount(self.path) def atime(self): """Returns the time of last access to this path. This returns a number of seconds since the epoch. """ return self._lib.getatime(self.path) def ctime(self): """Returns the ctime of this path. On some systems, this is the time of last metadata change, and on others (like Windows), it is the creation time for path. In any case, it is a number of seconds since the epoch. """ return self._lib.getctime(self.path) def mtime(self): """Returns the time of last modification of this path. This returns a number of seconds since the epoch. """ return self._lib.getmtime(self.path) def size(self): """Returns the size, in bytes, of the file. """ return self._lib.getsize(self.path) if hasattr(os.path, 'samefile'): def same_file(self, other): """Returns True if both paths refer to the same file or directory. In particular, this identifies hard links. """ return self._lib.samefile(self.path, self._to_backend(other)) def stat(self): return os.stat(self.path) def lstat(self): return os.lstat(self.path) if hasattr(os, 'statvfs'): def statvfs(self): return os.statvfs(self.path) if hasattr(os, 'chmod'): def chmod(self, mode): """Changes the mode of the path to the given numeric `mode`. """ return os.chmod(self.path, mode) if hasattr(os, 'chown'): def chown(self, uid=-1, gid=-1): """Changes the owner and group id of the path. """ return os.chown(self.path, uid, gid) def mkdir(self, name=None, parents=False, mode=0o777): """Creates that directory, or a directory under this one. ``path.mkdir(name)`` is a shortcut for ``(path/name).mkdir()``. :param name: Path component to append to this path before creating the directory. :param parents: If True, missing directories leading to the path will be created too, recursively. If False (the default), the parent of that path needs to exist already. :param mode: Permissions associated with the directory on creation, without race conditions. """ if name is not None: return (self / name).mkdir(parents=parents, mode=mode) if self.exists(): return if parents: os.makedirs(self.path, mode) else: os.mkdir(self.path, mode) return self def rmdir(self, parents=False): """Removes this directory, provided it is empty. Use :func:`~rpaths.Path.rmtree` if it might still contain files. :param parents: If set to True, it will also destroy every empty directory above it until an error is encountered. """ if parents: os.removedirs(self.path) else: os.rmdir(self.path) def remove(self): """Removes this file. """ os.remove(self.path) def rename(self, new, parents=False): """Renames this path to the given new location. :param new: New path where to move this one. :param parents: If set to True, it will create the parent directories of the target if they don't exist. """ if parents: os.renames(self.path, self._to_backend(new)) else: os.rename(self.path, self._to_backend(new)) if hasattr(os, 'link'): def hardlink(self, newpath): """Creates a hard link to this path at the given `newpath`. """ os.link(self.path, self._to_backend(newpath)) if hasattr(os, 'symlink'): def symlink(self, target): """Create a symbolic link here, pointing to the given `target`. """ os.symlink(self._to_backend(target), self.path) if hasattr(os, 'readlink'): def read_link(self, absolute=False): """Returns the path this link points to. If `absolute` is True, the target is made absolute. """ p = self.__class__(os.readlink(self.path)) if absolute: return (self.parent / p).absolute() else: return p def copyfile(self, target): """Copies this file to the given `target` location. """ shutil.copyfile(self.path, self._to_backend(target)) def copymode(self, target): """Copies the mode of this file on the `target` file. The owner is not copied. """ shutil.copymode(self.path, self._to_backend(target)) def copystat(self, target): """Copies the permissions, times and flags from this to the `target`. The owner is not copied. """ shutil.copystat(self.path, self._to_backend(target)) def copy(self, target): """Copies this file the `target`, which might be a directory. The permissions are copied. """ shutil.copy(self.path, self._to_backend(target)) def copytree(self, target, symlinks=False): """Recursively copies this directory to the `target` location. The permissions and times are copied (like :meth:`~rpaths.Path.copystat`). If the optional `symlinks` flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. """ shutil.copytree(self.path, self._to_backend(target), symlinks) def rmtree(self, ignore_errors=False): """Deletes an entire directory. If ignore_errors is True, failed removals will be ignored; else, an exception will be raised. """ shutil.rmtree(self.path, ignore_errors) def move(self, target): """Recursively moves a file or directory to the given target location. """ shutil.move(self.path, self._to_backend(target)) def open(self, mode='r', name=None, **kwargs): """Opens this file, or a file under this directory. ``path.open(mode, name)`` is a shortcut for ``(path/name).open(mode)``. Note that this uses :func:`io.open()` which behaves differently from :func:`open()` on Python 2; see the appropriate documentation. :param name: Path component to append to this path before opening the file. """ if name is not None: return io.open((self / name).path, mode=mode, **kwargs) else: return io.open(self.path, mode=mode, **kwargs) @contextlib.contextmanager def rewrite(self, mode='r', name=None, temp=None, tempext='~', **kwargs): r"""Replaces this file with new content. This context manager gives you two file objects, (r, w), where r is readable and has the current content of the file, and w is writable and will replace the file at the end of the context (unless an exception is raised, in which case it is rolled back). Keyword arguments will be used for both files, unless they are prefixed with ``read_`` or ``write_``. For instance:: with Path('test.txt').rewrite(read_newline='\n', write_newline='\r\n') as (r, w): w.write(r.read()) :param name: Path component to append to this path before opening the file. :param temp: Temporary file name to write, and then move over this one. By default it's this filename with a ``~`` suffix. :param tempext: Extension to add to this file to get the temporary file to write then move over this one. Defaults to ``~``. """ if name is not None: pathr = self / name else: pathr = self for m in 'war+': mode = mode.replace(m, '') # Build options common_kwargs = {} readable_kwargs = {} writable_kwargs = {} for key, value in kwargs.items(): if key.startswith('read_'): readable_kwargs[key[5:]] = value elif key.startswith('write_'): writable_kwargs[key[6:]] = value else: common_kwargs[key] = value readable_kwargs = dict_union(common_kwargs, readable_kwargs) writable_kwargs = dict_union(common_kwargs, writable_kwargs) with pathr.open('r' + mode, **readable_kwargs) as readable: if temp is not None: pathw = Path(temp) else: pathw = pathr + tempext try: pathw.remove() except OSError: pass writable = pathw.open('w' + mode, **writable_kwargs) try: yield readable, writable except Exception: # Problem, delete writable writable.close() pathw.remove() raise else: writable.close() # Alright, replace pathr.copymode(pathw) pathr.remove() pathw.rename(pathr) class Pattern(object): """A pattern that paths can be matched against. You can check if a filename matches this pattern by using `matches()`, or pass it to the `Path.listdir` and `Path.recursedir` methods. `may_contain_matches()` is a special method which you can feed directories to; if it returns False, no path under that one will match the pattern. >>> pattern = Pattern('/usr/l*/**.so') >>> pattern.matches('/usr/local/irc/mod_user.so') True >>> pattern.matches('/usr/bin/thing.so') False >>> pattern.may_contain_matches('/usr') True >>> pattern.may_contain_matches('/usr/lib') True >>> pattern.may_contain_matches('/usr/bin') False """ def __init__(self, pattern): if isinstance(pattern, bytes): pattern = pattern.decode(sys.getfilesystemencoding()) self.start_dir, self.full_regex, self.int_regex = pattern2re(pattern) @staticmethod def _prepare_path(path): # Here we want to force the use of replacement characters. # The __unicode__ implementation might use 'surrogateescape' replace = False if isinstance(path, AbstractPath): replace = path._lib.sep if path._lib.sep != '/' else None path = path.path else: replace = Path._lib.sep if Path._lib.sep != '/' else None if isinstance(path, bytes): path = path.decode(sys.getfilesystemencoding(), 'replace') elif not isinstance(path, unicode): raise TypeError("Expected a path, got %r" % type(path)) if path.startswith('/'): path = path[1:] if replace is not None: path = path.replace(replace, '/') return path def matches(self, path): """Tests if the given path matches the pattern. Note that the unicode translation of the patch is matched, so replacement characters might have been added. """ path = self._prepare_path(path) return self.full_regex.search(path) is not None def may_contain_matches(self, path): """Tests whether it's possible for paths under the given one to match. If this method returns None, no path under the given one will match the pattern. """ path = self._prepare_path(path) return self.int_regex.search(path) is not None no_special_chars = re.compile(r'^(?:[^\\*?\[\]]|\\.)*$') def patterncomp2re(component): if component == '**': return '.*' i, n = 0, len(component) regex = '' while i < n: c = component[i] if c == '\\': i += 1 if i < n: regex += re.escape(component[i]) elif c == '*': regex += '[^/]*' elif c == '?': regex += '[^/]' elif c == '[': i += 1 regex += '[' c = component[i] while c != ']': if c == '/': raise ValueError("Slashes not accepted in [] classes") regex += re.escape(c) i += 1 c = component[i] regex += ']' else: regex += re.escape(c) i += 1 return regex @memoize1 def pattern2re(pattern): """Makes a unicode regular expression from a pattern. Returns ``(start, full_re, int_re)`` where: * `start` is either empty or the subdirectory in which to start searching, * `full_re` is a regular expression object that matches the requested files, i.e. a translation of the pattern * `int_re` is either None of a regular expression object that matches the requested paths or their ancestors (i.e. if a path doesn't match `int_re`, no path under it will match `full_re`) This uses extended patterns, where: * a slash '/' always represents the path separator * a backslash '\' escapes other special characters * an initial slash '/' anchors the match at the beginning of the (relative) path * a trailing '/' suffix is removed * an asterisk '*' matches a sequence of any length (including 0) of any characters (except the path separator) * a '?' matches exactly one character (except the path separator) * '[abc]' matches characters 'a', 'b' or 'c' * two asterisks '**' matches one or more path components (might match '/' characters) """ pattern_segs = filter(None, pattern.split('/')) # This anchors the first component either at the start of the string or at # the start of a path component if not pattern: return '', re.compile(''), None elif '/' in pattern: full_regex = '^' # Start at beginning of path int_regex = [] int_regex_done = False start_dir = [] start_dir_done = False else: full_regex = '(?:^|/)' # Skip any number of full components int_regex = None int_regex_done = True start_dir = [] start_dir_done = True # Handles each component for pnum, pat in enumerate(pattern_segs): comp = patterncomp2re(pat) # The first component is already anchored if pnum > 0: full_regex += '/' full_regex += comp if not int_regex_done: if pat == '**': int_regex_done = True else: int_regex.append(comp) if not start_dir_done and no_special_chars.match(pat): start_dir.append(pat) else: start_dir_done = True full_regex = re.compile(full_regex.rstrip('/') + '$') if int_regex is not None: n = len(int_regex) int_regex_s = '' for i, c in enumerate(reversed(int_regex)): if i == n - 1: # Last iteration (first component) int_regex_s = '^(?:%s%s)?' % (c, int_regex_s) elif int_regex_s: int_regex_s = '(?:/%s%s)?' % (c, int_regex_s) else: # First iteration (last component) int_regex_s = '(?:/%s)?' % c int_regex = re.compile(int_regex_s + '$') start_dir = '/'.join(start_dir) return start_dir, full_regex, int_regex rpaths-0.13/setup.cfg0000644000175000017500000000010313075176241015347 0ustar remramremram00000000000000[bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 rpaths-0.13/setup.py0000644000175000017500000000212613075175703015251 0ustar remramremram00000000000000from setuptools import setup description = """\ rpaths is another path manipulation library. It is heavily inspired by Unipath and pathlib. It aims at total Python 2/3 and Windows/POSIX compatibility. To my knowledge, no other library can handle all the possible paths on every platform. """ setup(name='rpaths', version='0.13', py_modules=['rpaths'], description='Path manipulation library', author="Remi Rampin", author_email='remirampin@gmail.com', url='http://github.com/remram44/rpaths', long_description=description, license='BSD', keywords=['path', 'file', 'filename', 'pattern', 'fnmatch'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: System :: Filesystems']) rpaths-0.13/PKG-INFO0000644000175000017500000000172313075176241014634 0ustar remramremram00000000000000Metadata-Version: 1.1 Name: rpaths Version: 0.13 Summary: Path manipulation library Home-page: http://github.com/remram44/rpaths Author: Remi Rampin Author-email: remirampin@gmail.com License: BSD Description: rpaths is another path manipulation library. It is heavily inspired by Unipath and pathlib. It aims at total Python 2/3 and Windows/POSIX compatibility. To my knowledge, no other library can handle all the possible paths on every platform. Keywords: path,file,filename,pattern,fnmatch Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: System :: Filesystems